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