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