qt4-b-gone: Remove all code supporting Qt < 5.5 and KDE4
[quassel.git] / src / common / signalproxy.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #pragma once
22
23 #include <QEvent>
24 #include <QSet>
25
26 #include <functional>
27 #include <initializer_list>
28
29 #include "protocol.h"
30
31 struct QMetaObject;
32 class QIODevice;
33
34 class Peer;
35 class SyncableObject;
36
37 class SignalProxy : public QObject
38 {
39     Q_OBJECT
40
41     class SignalRelay;
42
43 public:
44     enum ProxyMode {
45         Server,
46         Client
47     };
48
49     enum EventType {
50         RemovePeerEvent = QEvent::User
51     };
52
53     SignalProxy(QObject *parent);
54     SignalProxy(ProxyMode mode, QObject *parent);
55     virtual ~SignalProxy();
56
57     void setProxyMode(ProxyMode mode);
58     inline ProxyMode proxyMode() const { return _proxyMode; }
59
60     void setHeartBeatInterval(int secs);
61     inline int heartBeatInterval() const { return _heartBeatInterval; }
62     void setMaxHeartBeatCount(int max);
63     inline int maxHeartBeatCount() const { return _maxHeartBeatCount; }
64
65     bool addPeer(Peer *peer);
66
67     bool attachSignal(QObject *sender, const char *signal, const QByteArray &sigName = QByteArray());
68     bool attachSlot(const QByteArray &sigName, QObject *recv, const char *slot);
69
70     void synchronize(SyncableObject *obj);
71     void stopSynchronize(SyncableObject *obj);
72
73     class ExtendedMetaObject;
74     ExtendedMetaObject *extendedMetaObject(const QMetaObject *meta) const;
75     ExtendedMetaObject *createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts = false);
76     inline ExtendedMetaObject *extendedMetaObject(const QObject *obj) const { return extendedMetaObject(metaObject(obj)); }
77     inline ExtendedMetaObject *createExtendedMetaObject(const QObject *obj, bool checkConflicts = false) { return createExtendedMetaObject(metaObject(obj), checkConflicts); }
78
79     bool isSecure() const { return _secure; }
80     void dumpProxyStats();
81     void dumpSyncMap(SyncableObject *object);
82
83     static SignalProxy *current() {
84         return _current;
85     }
86
87     /**@{*/
88     /**
89      * This method allows to send a signal only to a limited set of peers
90      * @param peers A list of peers that should receive it
91      * @param closure Code you want to execute within of that restricted environment
92      */
93     void restrictTargetPeers(QSet<Peer*> peers, std::function<void()> closure);
94     void restrictTargetPeers(Peer *peer, std::function<void()> closure) {
95         QSet<Peer*> set;
96         set.insert(peer);
97         restrictTargetPeers(set, std::move(closure));
98     }
99
100     //A better version, but only implemented on Qt5 if Initializer Lists exist
101 #ifdef Q_COMPILER_INITIALIZER_LISTS
102     void restrictTargetPeers(std::initializer_list<Peer*> peers, std::function<void()> closure) {
103         restrictTargetPeers(QSet<Peer*>(peers), std::move(closure));
104     }
105 #endif
106     /**}@*/
107
108     inline int peerCount() const { return _peerMap.size(); }
109     QVariantList peerData();
110
111     Peer *peerById(int peerId);
112
113     /**
114      * @return If handling a signal, the Peer from which the current signal originates
115      */
116     Peer *sourcePeer();
117     void setSourcePeer(Peer *sourcePeer);
118
119     /**
120      * @return If sending a signal, the Peer to which the current signal is directed
121      */
122     Peer *targetPeer();
123     void setTargetPeer(Peer *targetPeer);
124
125 public slots:
126     void detachObject(QObject *obj);
127     void detachSignals(QObject *sender);
128     void detachSlots(QObject *receiver);
129
130 protected:
131     void customEvent(QEvent *event);
132     void sync_call__(const SyncableObject *obj, ProxyMode modeType, const char *funcname, va_list ap);
133     void renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname);
134
135 private slots:
136     void removePeerBySender();
137     void objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname);
138     void updateSecureState();
139
140 signals:
141     void peerRemoved(Peer *peer);
142     void connected();
143     void disconnected();
144     void objectInitialized(SyncableObject *);
145     void heartBeatIntervalChanged(int secs);
146     void maxHeartBeatCountChanged(int max);
147     void lagUpdated(int lag);
148     void secureStateChanged(bool);
149
150 private:
151     template<class T>
152     class PeerMessageEvent;
153
154     void init();
155     void initServer();
156     void initClient();
157
158     static const QMetaObject *metaObject(const QObject *obj);
159
160     void removePeer(Peer *peer);
161     void removeAllPeers();
162
163     int nextPeerId() {
164         return _lastPeerId++;
165     }
166
167     template<class T>
168     void dispatch(const T &protoMessage);
169     template<class T>
170     void dispatch(Peer *peer, const T &protoMessage);
171
172     void handle(Peer *peer, const Protocol::SyncMessage &syncMessage);
173     void handle(Peer *peer, const Protocol::RpcCall &rpcCall);
174     void handle(Peer *peer, const Protocol::InitRequest &initRequest);
175     void handle(Peer *peer, const Protocol::InitData &initData);
176
177     template<class T>
178     void handle(Peer *, T) { Q_ASSERT(0); }
179
180     bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue, Peer *peer = 0);
181     bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params = QVariantList(), Peer *peer = 0);
182
183     void requestInit(SyncableObject *obj);
184     QVariantMap initData(SyncableObject *obj) const;
185     void setInitData(SyncableObject *obj, const QVariantMap &properties);
186
187     static void disconnectDevice(QIODevice *dev, const QString &reason = QString());
188
189     QHash<int, Peer*> _peerMap;
190
191     // containg a list of argtypes for fast access
192     QHash<const QMetaObject *, ExtendedMetaObject *> _extendedMetaObjects;
193
194     // SignalRelay for all manually attached signals
195     SignalRelay *_signalRelay;
196
197     // RPC function -> (object, slot ID)
198     typedef QPair<QObject *, int> MethodId;
199     typedef QMultiHash<QByteArray, MethodId> SlotHash;
200     SlotHash _attachedSlots;
201
202     // slaves for sync
203     typedef QHash<QString, SyncableObject *> ObjectId;
204     QHash<QByteArray, ObjectId> _syncSlave;
205
206     ProxyMode _proxyMode;
207     int _heartBeatInterval;
208     int _maxHeartBeatCount;
209
210     bool _secure; // determines if all connections are in a secured state (using ssl or internal connections)
211
212     int _lastPeerId = 0;
213
214     QSet<Peer *> _restrictedTargets;
215     bool _restrictMessageTarget = false;
216
217     Peer *_sourcePeer = nullptr;
218     Peer *_targetPeer = nullptr;
219
220     thread_local static SignalProxy *_current;
221
222     friend class SignalRelay;
223     friend class SyncableObject;
224     friend class Peer;
225 };
226
227
228 // ==================================================
229 //  ExtendedMetaObject
230 // ==================================================
231 class SignalProxy::ExtendedMetaObject
232 {
233     class MethodDescriptor
234     {
235     public:
236         MethodDescriptor(const QMetaMethod &method);
237         MethodDescriptor() : _returnType(-1), _minArgCount(-1), _receiverMode(SignalProxy::Client) {}
238
239         inline const QByteArray &methodName() const { return _methodName; }
240         inline const QList<int> &argTypes() const { return _argTypes; }
241         inline int returnType() const { return _returnType; }
242         inline int minArgCount() const { return _minArgCount; }
243         inline SignalProxy::ProxyMode receiverMode() const { return _receiverMode; }
244
245     private:
246         QByteArray _methodName;
247         QList<int> _argTypes;
248         int _returnType;
249         int _minArgCount;
250         SignalProxy::ProxyMode _receiverMode; // Only acceptable as a Sync Call if the receiving SignalProxy is in this mode.
251     };
252
253
254 public:
255     ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts);
256
257     inline const QByteArray &methodName(int methodId) { return methodDescriptor(methodId).methodName(); }
258     inline const QList<int> &argTypes(int methodId) { return methodDescriptor(methodId).argTypes(); }
259     inline int returnType(int methodId) { return methodDescriptor(methodId).returnType(); }
260     inline int minArgCount(int methodId) { return methodDescriptor(methodId).minArgCount(); }
261     inline SignalProxy::ProxyMode receiverMode(int methodId) { return methodDescriptor(methodId).receiverMode(); }
262
263     inline int methodId(const QByteArray &methodName) { return _methodIds.contains(methodName) ? _methodIds[methodName] : -1; }
264
265     inline int updatedRemotelyId() { return _updatedRemotelyId; }
266
267     inline const QHash<QByteArray, int> &slotMap() { return _methodIds; }
268     const QHash<int, int> &receiveMap();
269
270     const QMetaObject *metaObject() const { return _meta; }
271
272     static QByteArray methodName(const QMetaMethod &method);
273     static QString methodBaseName(const QMetaMethod &method);
274
275 private:
276     const MethodDescriptor &methodDescriptor(int methodId);
277
278     const QMetaObject *_meta;
279     int _updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster
280
281     QHash<int, MethodDescriptor> _methods;
282     QHash<QByteArray, int> _methodIds;
283     QHash<int, int> _receiveMap; // if slot x is called then hand over the result to slot y
284 };