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