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