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