Strip newlines from 'reason' fields in settings
[quassel.git] / src / common / signalproxy.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2012 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 <QList>
26 #include <QHash>
27 #include <QVariant>
28 #include <QVariantMap>
29 #include <QPair>
30 #include <QString>
31 #include <QByteArray>
32 #include <QTimer>
33
34 class SyncableObject;
35 struct QMetaObject;
36
37 class SignalProxy : public QObject
38 {
39     Q_OBJECT
40
41     class AbstractPeer;
42     class IODevicePeer;
43     class SignalProxyPeer;
44
45     class SignalRelay;
46
47 public:
48     enum ProxyMode {
49         Server,
50         Client
51     };
52
53     enum RequestType {
54         Sync = 1,
55         RpcCall,
56         InitRequest,
57         InitData,
58         HeartBeat,
59         HeartBeatReply
60     };
61
62     enum ClientConnectionType {
63         SignalProxyConnection,
64         IODeviceConnection
65     };
66
67     enum CustomEvents {
68         PeerSignal = QEvent::User,
69         RemovePeer
70     };
71
72     SignalProxy(QObject *parent);
73     SignalProxy(ProxyMode mode, QObject *parent);
74     SignalProxy(ProxyMode mode, QIODevice *device, QObject *parent);
75     virtual ~SignalProxy();
76
77     void setProxyMode(ProxyMode mode);
78     inline ProxyMode proxyMode() const { return _proxyMode; }
79
80     void setHeartBeatInterval(int secs);
81     inline int heartBeatInterval() const { return _heartBeatInterval; }
82     void setMaxHeartBeatCount(int max);
83     inline int maxHeartBeatCount() const { return _maxHeartBeatCount; }
84
85     bool addPeer(QIODevice *iodev);
86     bool addPeer(SignalProxy *proxy);
87     void removePeer(QObject *peer);
88     void removeAllPeers();
89
90     bool attachSignal(QObject *sender, const char *signal, const QByteArray &sigName = QByteArray());
91     bool attachSlot(const QByteArray &sigName, QObject *recv, const char *slot);
92
93     void synchronize(SyncableObject *obj);
94     void stopSynchronize(SyncableObject *obj);
95
96     //! Writes a QVariant to a device.
97     /** The data item is prefixed with the resulting blocksize,
98      *  so the corresponding function readDataFromDevice() can check if enough data is available
99      *  at the device to reread the item.
100      */
101     static void writeDataToDevice(QIODevice *dev, const QVariant &item, bool compressed = false);
102
103     //! Reads a data item from a device that has been written by writeDataToDevice().
104     /** If not enough data bytes are available, the function returns false and the QVariant reference
105      *  remains untouched.
106      */
107     static bool readDataFromDevice(QIODevice *dev, quint32 &blockSize, QVariant &item, bool compressed = false);
108
109     class ExtendedMetaObject;
110     ExtendedMetaObject *extendedMetaObject(const QMetaObject *meta) const;
111     ExtendedMetaObject *createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts = false);
112     inline ExtendedMetaObject *extendedMetaObject(const QObject *obj) const { return extendedMetaObject(metaObject(obj)); }
113     inline ExtendedMetaObject *createExtendedMetaObject(const QObject *obj, bool checkConflicts = false) { return createExtendedMetaObject(metaObject(obj), checkConflicts); }
114
115     bool isSecure() const { return _secure; }
116     void dumpProxyStats();
117
118 public slots:
119     void detachObject(QObject *obj);
120     void detachSignals(QObject *sender);
121     void detachSlots(QObject *receiver);
122
123 protected:
124     void customEvent(QEvent *event);
125     void sync_call__(const SyncableObject *obj, ProxyMode modeType, const char *funcname, va_list ap);
126     void renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname);
127
128 private slots:
129     void dataAvailable();
130     void removePeerBySender();
131     void objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname);
132     void sendHeartBeat();
133     void receiveHeartBeat(AbstractPeer *peer, const QVariantList &params);
134     void receiveHeartBeatReply(AbstractPeer *peer, const QVariantList &params);
135
136     void updateSecureState();
137
138 signals:
139     void peerRemoved(QIODevice *dev);
140     void connected();
141     void disconnected();
142     void objectInitialized(SyncableObject *);
143     void lagUpdated(int lag);
144     void securityChanged(bool);
145     void secureStateChanged(bool);
146
147 private:
148     void init();
149     void initServer();
150     void initClient();
151
152     static const QMetaObject *metaObject(const QObject *obj);
153
154     void dispatchSignal(QIODevice *receiver, const RequestType &requestType, const QVariantList &params);
155     void dispatchSignal(const RequestType &requestType, const QVariantList &params);
156
157     void receivePackedFunc(AbstractPeer *sender, const QVariant &packedFunc);
158     void receivePeerSignal(AbstractPeer *sender, const RequestType &requestType, const QVariantList &params);
159     void receivePeerSignal(SignalProxy *sender, const RequestType &requestType, const QVariantList &params);
160     void handleSync(AbstractPeer *sender, QVariantList params);
161     void handleInitRequest(AbstractPeer *sender, const QVariantList &params);
162     void handleInitData(AbstractPeer *sender, const QVariantList &params);
163     void handleSignal(const QVariantList &data);
164
165     bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue);
166     bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params = QVariantList());
167
168     void requestInit(SyncableObject *obj);
169     QVariantMap initData(SyncableObject *obj) const;
170     void setInitData(SyncableObject *obj, const QVariantMap &properties);
171
172     void updateLag(IODevicePeer *peer, int lag);
173
174 public:
175     void dumpSyncMap(SyncableObject *object);
176     inline int peerCount() const { return _peers.size(); }
177
178 private:
179     static void disconnectDevice(QIODevice *dev, const QString &reason = QString());
180
181     // a Hash of the actual used communication object to it's corresponding peer
182     // currently a communication object can either be an arbitrary QIODevice or another SignalProxy
183     typedef QHash<QObject *, AbstractPeer *> PeerHash;
184     PeerHash _peers;
185
186     // containg a list of argtypes for fast access
187     QHash<const QMetaObject *, ExtendedMetaObject *> _extendedMetaObjects;
188
189     // SignalRelay for all manually attached signals
190     SignalRelay *_signalRelay;
191
192     // RPC function -> (object, slot ID)
193     typedef QPair<QObject *, int> MethodId;
194     typedef QMultiHash<QByteArray, MethodId> SlotHash;
195     SlotHash _attachedSlots;
196
197     // slaves for sync
198     typedef QHash<QString, SyncableObject *> ObjectId;
199     QHash<QByteArray, ObjectId> _syncSlave;
200
201     ProxyMode _proxyMode;
202     QTimer _heartBeatTimer;
203     int _heartBeatInterval;
204     int _maxHeartBeatCount;
205
206     bool _secure; // determines if all connections are in a secured state (using ssl or internal connections)
207
208     friend class SignalRelay;
209     friend class SyncableObject;
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
272 // ==================================================
273 //  Peers
274 // ==================================================
275 class SignalProxy::AbstractPeer
276 {
277 public:
278     enum PeerType {
279         NotAPeer = 0,
280         IODevicePeer = 1,
281         SignalProxyPeer = 2
282     };
283     AbstractPeer() : _type(NotAPeer) {}
284     AbstractPeer(PeerType type) : _type(type) {}
285     virtual ~AbstractPeer() {}
286     inline PeerType type() const { return _type; }
287     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params) = 0;
288     virtual bool isSecure() const = 0;
289 private:
290     PeerType _type;
291 };
292
293
294 class SignalProxy::IODevicePeer : public SignalProxy::AbstractPeer
295 {
296 public:
297     IODevicePeer(QIODevice *device, bool compress) : AbstractPeer(AbstractPeer::IODevicePeer), _device(device), byteCount(0), usesCompression(compress), sentHeartBeats(0), lag(0) {}
298     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
299     virtual bool isSecure() const;
300     inline void dispatchPackedFunc(const QVariant &packedFunc) { SignalProxy::writeDataToDevice(_device, packedFunc, usesCompression); }
301     QString address() const;
302     inline bool isOpen() const { return _device->isOpen(); }
303     inline void close() const { _device->close(); }
304     inline bool readData(QVariant &item) { return SignalProxy::readDataFromDevice(_device, byteCount, item, usesCompression); }
305 private:
306     QIODevice *_device;
307     quint32 byteCount;
308     bool usesCompression;
309 public:
310     int sentHeartBeats;
311     int lag;
312 };
313
314
315 class SignalProxy::SignalProxyPeer : public SignalProxy::AbstractPeer
316 {
317 public:
318     SignalProxyPeer(SignalProxy *sender, SignalProxy *receiver) : AbstractPeer(AbstractPeer::SignalProxyPeer), sender(sender), receiver(receiver) {}
319     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
320     virtual inline bool isSecure() const { return true; }
321 private:
322     SignalProxy *sender;
323     SignalProxy *receiver;
324 };
325
326
327 #endif