We hate uninitialized values
[quassel.git] / src / common / signalproxy.h
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, 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   Q_OBJECT
39
40   class AbstractPeer;
41   class IODevicePeer;
42   class SignalProxyPeer;
43
44   class SignalRelay;
45
46 public:
47   enum ProxyMode {
48     Server,
49     Client
50   };
51
52   enum RequestType {
53     Sync = 1,
54     RpcCall,
55     InitRequest,
56     InitData,
57     HeartBeat,
58     HeartBeatReply
59   };
60
61   enum ClientConnectionType {
62     SignalProxyConnection,
63     IODeviceConnection
64   };
65
66   enum CustomEvents {
67     PeerSignal = QEvent::User,
68     RemovePeer
69   };
70
71   SignalProxy(QObject *parent);
72   SignalProxy(ProxyMode mode, QObject *parent);
73   SignalProxy(ProxyMode mode, QIODevice *device, QObject *parent);
74   virtual ~SignalProxy();
75
76   void setProxyMode(ProxyMode mode);
77   inline ProxyMode proxyMode() const { return _proxyMode; }
78
79   void setHeartBeatInterval(int secs);
80   inline int heartBeatInterval() const { return _heartBeatInterval; }
81   void setMaxHeartBeatCount(int max);
82   inline int maxHeartBeatCount() const { return _maxHeartBeatCount; }
83
84   bool addPeer(QIODevice *iodev);
85   bool addPeer(SignalProxy *proxy);
86   void removePeer(QObject *peer);
87   void removeAllPeers();
88
89   bool attachSignal(QObject *sender, const char *signal, const QByteArray& sigName = QByteArray());
90   bool attachSlot(const QByteArray& sigName, QObject *recv, const char *slot);
91
92   void synchronize(SyncableObject *obj);
93   void stopSynchronize(SyncableObject *obj);
94
95   //! Writes a QVariant to a device.
96   /** The data item is prefixed with the resulting blocksize,
97    *  so the corresponding function readDataFromDevice() can check if enough data is available
98    *  at the device to reread the item.
99    */
100   static void writeDataToDevice(QIODevice *dev, const QVariant &item, bool compressed = false);
101
102   //! Reads a data item from a device that has been written by writeDataToDevice().
103   /** If not enough data bytes are available, the function returns false and the QVariant reference
104    *  remains untouched.
105    */
106   static bool readDataFromDevice(QIODevice *dev, quint32 &blockSize, QVariant &item, bool compressed = false);
107
108   class ExtendedMetaObject;
109   ExtendedMetaObject *extendedMetaObject(const QMetaObject *meta) const;
110   ExtendedMetaObject *createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts = false);
111   inline ExtendedMetaObject *extendedMetaObject(const QObject *obj) const { return extendedMetaObject(metaObject(obj)); }
112   inline ExtendedMetaObject *createExtendedMetaObject(const QObject *obj, bool checkConflicts = false) { return createExtendedMetaObject(metaObject(obj), checkConflicts); }
113
114   bool isSecure() const { return _secure; }
115   void dumpProxyStats();
116
117 public slots:
118   void detachObject(QObject *obj);
119   void detachSignals(QObject *sender);
120   void detachSlots(QObject *receiver);
121
122 protected:
123   void customEvent(QEvent *event);
124   void sync_call__(const SyncableObject *obj, ProxyMode modeType, const char *funcname, va_list ap);
125   void renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname);
126
127 private slots:
128   void dataAvailable();
129   void removePeerBySender();
130   void objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname);
131   void sendHeartBeat();
132   void receiveHeartBeat(AbstractPeer *peer, const QVariantList &params);
133   void receiveHeartBeatReply(AbstractPeer *peer, const QVariantList &params);
134
135   void updateSecureState();
136
137 signals:
138   void peerRemoved(QIODevice *dev);
139   void connected();
140   void disconnected();
141   void objectInitialized(SyncableObject *);
142   void lagUpdated(int lag);
143   void securityChanged(bool);
144   void secureStateChanged(bool);
145
146 private:
147   void init();
148   void initServer();
149   void initClient();
150
151   static const QMetaObject *metaObject(const QObject *obj);
152
153   void dispatchSignal(QIODevice *receiver, const RequestType &requestType, const QVariantList &params);
154   void dispatchSignal(const RequestType &requestType, const QVariantList &params);
155
156   void receivePackedFunc(AbstractPeer *sender, const QVariant &packedFunc);
157   void receivePeerSignal(AbstractPeer *sender, const RequestType &requestType, const QVariantList &params);
158   void receivePeerSignal(SignalProxy *sender, const RequestType &requestType, const QVariantList &params);
159   void handleSync(AbstractPeer *sender, QVariantList params);
160   void handleInitRequest(AbstractPeer *sender, const QVariantList &params);
161   void handleInitData(AbstractPeer *sender, const QVariantList &params);
162   void handleSignal(const QVariantList &data);
163
164   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue);
165   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params = QVariantList());
166
167   void requestInit(SyncableObject *obj);
168   QVariantMap initData(SyncableObject *obj) const;
169   void setInitData(SyncableObject *obj, const QVariantMap &properties);
170
171   void updateLag(IODevicePeer *peer, int lag);
172
173 public:
174   void dumpSyncMap(SyncableObject *object);
175   inline int peerCount() const { return _peers.size(); }
176
177 private:
178   static void disconnectDevice(QIODevice *dev, const QString &reason = QString());
179
180   // a Hash of the actual used communication object to it's corresponding peer
181   // currently a communication object can either be an arbitrary QIODevice or another SignalProxy
182   typedef QHash<QObject *, AbstractPeer *> PeerHash;
183   PeerHash _peers;
184
185   // containg a list of argtypes for fast access
186   QHash<const QMetaObject *, ExtendedMetaObject *> _extendedMetaObjects;
187
188   // SignalRelay for all manually attached signals
189   SignalRelay *_signalRelay;
190
191   // RPC function -> (object, slot ID)
192   typedef QPair<QObject*, int> MethodId;
193   typedef QMultiHash<QByteArray, MethodId> SlotHash;
194   SlotHash _attachedSlots;
195
196   // slaves for sync
197   typedef QHash<QString, SyncableObject *> ObjectId;
198   QHash<QByteArray, ObjectId> _syncSlave;
199
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   class MethodDescriptor {
218   public:
219     MethodDescriptor(const QMetaMethod &method);
220     MethodDescriptor() : _returnType(-1), _minArgCount(-1), _receiverMode(SignalProxy::Client) {}
221
222     inline const QByteArray &methodName() const { return _methodName; }
223     inline const QList<int> &argTypes() const { return _argTypes; }
224     inline int returnType() const { return _returnType; }
225     inline int minArgCount() const { return _minArgCount; }
226     inline SignalProxy::ProxyMode receiverMode() const { return _receiverMode; }
227
228   private:
229     QByteArray _methodName;
230     QList<int> _argTypes;
231     int _returnType;
232     int _minArgCount;
233     SignalProxy::ProxyMode _receiverMode; // Only acceptable as a Sync Call if the receiving SignalProxy is in this mode.
234   };
235
236 public:
237   ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts);
238
239   inline const QByteArray &methodName(int methodId) { return methodDescriptor(methodId).methodName(); }
240   inline const QList<int> &argTypes(int methodId) { return methodDescriptor(methodId).argTypes(); }
241   inline int returnType(int methodId) { return methodDescriptor(methodId).returnType(); }
242   inline int minArgCount(int methodId) { return methodDescriptor(methodId).minArgCount(); }
243   inline SignalProxy::ProxyMode receiverMode(int methodId) { return methodDescriptor(methodId).receiverMode(); }
244
245   inline int methodId(const QByteArray &methodName) { return _methodIds.contains(methodName) ? _methodIds[methodName] : -1; }
246
247   inline int updatedRemotelyId() { return _updatedRemotelyId; }
248
249   inline const QHash<QByteArray, int> &slotMap() { return _methodIds; }
250   const QHash<int, int> &receiveMap();
251
252   const QMetaObject *metaObject() const { return _meta; }
253
254   static QByteArray methodName(const QMetaMethod &method);
255   static QString methodBaseName(const QMetaMethod &method);
256
257 private:
258   const MethodDescriptor &methodDescriptor(int methodId);
259
260   const QMetaObject *_meta;
261   int _updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster
262
263   QHash<int, MethodDescriptor> _methods;
264   QHash<QByteArray, int> _methodIds;
265   QHash<int, int> _receiveMap; // if slot x is called then hand over the result to slot y
266 };
267
268
269 // ==================================================
270 //  Peers
271 // ==================================================
272 class SignalProxy::AbstractPeer {
273 public:
274   enum PeerType {
275     NotAPeer = 0,
276     IODevicePeer = 1,
277     SignalProxyPeer = 2
278   };
279   AbstractPeer() : _type(NotAPeer) {}
280   AbstractPeer(PeerType type) : _type(type) {}
281   virtual ~AbstractPeer() {}
282   inline PeerType type() const { return _type; }
283   virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params) = 0;
284   virtual bool isSecure() const = 0;
285 private:
286   PeerType _type;
287 };
288
289 class SignalProxy::IODevicePeer : public SignalProxy::AbstractPeer {
290 public:
291   IODevicePeer(QIODevice *device, bool compress) : AbstractPeer(AbstractPeer::IODevicePeer), _device(device), byteCount(0), usesCompression(compress), sentHeartBeats(0), lag(0) {}
292   virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
293   virtual bool isSecure() const;
294   inline void dispatchPackedFunc(const QVariant &packedFunc) { SignalProxy::writeDataToDevice(_device, packedFunc, usesCompression); }
295   QString address() const;
296   inline bool isOpen() const { return _device->isOpen(); }
297   inline void close() const { _device->close(); }
298   inline bool readData(QVariant &item) { return SignalProxy::readDataFromDevice(_device, byteCount, item, usesCompression); }
299 private:
300   QIODevice *_device;
301   quint32 byteCount;
302   bool usesCompression;
303 public:
304   int sentHeartBeats;
305   int lag;
306 };
307
308 class SignalProxy::SignalProxyPeer : public SignalProxy::AbstractPeer {
309 public:
310   SignalProxyPeer(SignalProxy *sender, SignalProxy *receiver) : AbstractPeer(AbstractPeer::SignalProxyPeer), sender(sender), receiver(receiver) {}
311   virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
312   virtual inline bool isSecure() const { return true; }
313 private:
314   SignalProxy *sender;
315   SignalProxy *receiver;
316 };
317
318 #endif