f2490ba52c275c1e31eabd2d7a68372c079dd44b
[quassel.git] / src / common / signalproxy.h
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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 <QList>
25 #include <QHash>
26 #include <QVariant>
27 #include <QVariantMap>
28 #include <QPair>
29 #include <QString>
30 #include <QByteArray>
31 #include <QTimer>
32
33 class SignalRelay;
34 class SyncableObject;
35 struct QMetaObject;
36
37 class SignalProxy : public QObject {
38   Q_OBJECT
39
40   class AbstractPeer;
41   class IODevicePeer;
42
43 public:
44   enum ProxyMode {
45     Server,
46     Client
47   };
48
49   enum RequestType {
50     Sync = 1,
51     RpcCall,
52     InitRequest,
53     InitData,
54     HeartBeat,
55     HeartBeatReply
56   };
57
58   SignalProxy(QObject *parent);
59   SignalProxy(ProxyMode mode, QObject *parent);
60   SignalProxy(ProxyMode mode, QIODevice *device, QObject *parent);
61   virtual ~SignalProxy();
62
63   void setProxyMode(ProxyMode mode);
64   inline ProxyMode proxyMode() const { return _proxyMode; }
65
66   bool addPeer(QIODevice *iodev);
67   bool addPeer(SignalProxy *proxy);
68   void removePeer(QObject *peer);
69   void removeAllPeers();
70   
71   bool attachSignal(QObject *sender, const char *signal, const QByteArray& sigName = QByteArray());
72   bool attachSlot(const QByteArray& sigName, QObject *recv, const char *slot);
73
74   void synchronize(SyncableObject *obj);
75
76 //   void setInitialized(SyncableObject *obj);
77 //   bool isInitialized(SyncableObject *obj) const;
78   void requestInit(SyncableObject *obj);
79
80   void detachObject(QObject *obj);
81   void detachSignals(QObject *sender);
82   void detachSlots(QObject *receiver);
83   void stopSync(SyncableObject *obj);
84
85   //! Writes a QVariant to a device.
86   /** The data item is prefixed with the resulting blocksize,
87    *  so the corresponding function readDataFromDevice() can check if enough data is available
88    *  at the device to reread the item.
89    */
90   static void writeDataToDevice(QIODevice *dev, const QVariant &item, bool compressed = false);
91
92   //! Reads a data item from a device that has been written by writeDataToDevice().
93   /** If not enough data bytes are available, the function returns false and the QVariant reference
94    *  remains untouched.
95    */
96   static bool readDataFromDevice(QIODevice *dev, quint32 &blockSize, QVariant &item, bool compressed = false);
97
98   static QString methodBaseName(const QMetaMethod &method);
99
100   const QList<int> &argTypes(QObject *obj, int methodId);
101   const int &returnType(QObject *obj, int methodId);
102   const int &minArgCount(QObject *obj, int methodId);
103   const QByteArray &methodName(QObject *obj, int methodId);
104   const QHash<QByteArray, int> &syncMap(SyncableObject *obj);
105   const QHash<int, int> &receiveMap(SyncableObject *obj);
106   int updatedRemotelyId(SyncableObject *obj);
107
108   typedef QHash<int, QList<int> > ArgHash;
109   typedef QHash<int, QByteArray> MethodNameHash;
110   struct ClassInfo {
111     ArgHash argTypes;
112     QHash<int, int> returnType;
113     QHash<int, int> minArgCount;
114     MethodNameHash methodNames;
115     int updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster
116     QHash<QByteArray, int> syncMap;
117     QHash<int, int> receiveMap;
118   };
119
120   void dumpProxyStats();
121   
122 private slots:
123   void dataAvailable();
124   void detachSender();
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 signals:
133   void peerRemoved(QIODevice *dev);
134   void connected();
135   void disconnected();
136   void objectInitialized(SyncableObject *);
137   void lagUpdated(int lag);
138   
139 private:
140   void init();
141   void initServer();
142   void initClient();
143   
144   const QMetaObject *metaObject(QObject *obj);
145   void createClassInfo(QObject *obj);
146   void setArgTypes(QObject *obj, int methodId);
147   void setReturnType(QObject *obj, int methodId);
148   void setMinArgCount(QObject *obj, int methodId);
149   void setMethodName(QObject *obj, int methodId);
150   void setSyncMap(SyncableObject *obj);
151   void setReceiveMap(SyncableObject *obj);
152   void setUpdatedRemotelyId(SyncableObject *obj);
153
154   bool methodsMatch(const QMetaMethod &signal, const QMetaMethod &slot) const;
155
156   void dispatchSignal(QIODevice *receiver, const RequestType &requestType, const QVariantList &params);
157   void dispatchSignal(const RequestType &requestType, const QVariantList &params);
158
159   void receivePackedFunc(AbstractPeer *sender, const QVariant &packedFunc);
160   void receivePeerSignal(AbstractPeer *sender, const RequestType &requestType, const QVariantList &params);
161   void handleSync(AbstractPeer *sender, QVariantList params);
162   void handleInitRequest(AbstractPeer *sender, const QVariantList &params);
163   void handleInitData(AbstractPeer *sender, const QVariantList &params);
164   void handleSignal(const QVariantList &data);
165
166   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue);
167   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params = QVariantList());
168
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   class AbstractPeer {
180   public:
181     enum PeerType {
182       NotAPeer = 0,
183       IODevicePeer = 1,
184       SignalProxyPeer = 2
185     };
186     AbstractPeer() : _type(NotAPeer) {}
187     AbstractPeer(PeerType type) : _type(type) {}
188     virtual ~AbstractPeer() {}
189     inline PeerType type() const { return _type; }
190     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params) = 0;
191   private:
192     PeerType _type;
193   };
194
195   class IODevicePeer : public AbstractPeer {
196   public:
197     IODevicePeer(QIODevice *device, bool compress) : AbstractPeer(AbstractPeer::IODevicePeer), _device(device), byteCount(0), usesCompression(compress), sentHeartBeats(0), lag(0) {}
198     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
199     inline void dispatchPackedFunc(const QVariant &packedFunc) { SignalProxy::writeDataToDevice(_device, packedFunc, usesCompression); }
200     inline QIODevice *device() const { return _device; }
201     inline bool isOpen() const { return _device->isOpen(); }
202     inline bool readData(QVariant &item) { return SignalProxy::readDataFromDevice(_device, byteCount, item, usesCompression); }
203   private:
204     QIODevice *_device;
205     quint32 byteCount;
206     bool usesCompression;
207   public:
208     int sentHeartBeats;
209     int lag;
210   };
211
212   class SignalProxyPeer : public AbstractPeer {
213   public:
214     SignalProxyPeer(SignalProxy *proxy) : AbstractPeer(AbstractPeer::SignalProxyPeer), proxy(proxy) {}
215     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
216   private:
217     SignalProxy *proxy;
218   };
219
220   // a Hash of the actual used communication object to it's corresponding peer
221   // currently a communication object can either be an arbitrary QIODevice or another SignalProxy
222   typedef QHash<QObject *, AbstractPeer *> PeerHash;
223   PeerHash _peers;
224   
225 //   // Hash of used QIODevices
226 //   struct peerInfo {
227 //     quint32 byteCount;
228 //     bool usesCompression;
229 //     int sentHeartBeats;
230 //     int lag;
231 //     peerInfo() : byteCount(0), usesCompression(false), sentHeartBeats(0) {}
232 //   };
233 //   QHash<QIODevice*, peerInfo> _peers;
234
235   // containg a list of argtypes for fast access
236   QHash<const QMetaObject *, ClassInfo*> _classInfo;
237
238   // we use one SignalRelay per QObject
239   QHash<QObject*, SignalRelay *> _relayHash;
240
241   // RPC function -> (object, slot ID)
242   typedef QPair<QObject*, int> MethodId;
243   typedef QMultiHash<QByteArray, MethodId> SlotHash;
244   SlotHash _attachedSlots;
245
246   // slaves for sync
247   typedef QHash<QString, SyncableObject *> ObjectId;
248   QHash<QByteArray, ObjectId> _syncSlave;
249
250
251   ProxyMode _proxyMode;
252   QTimer _heartBeatTimer;
253   
254   friend class SignalRelay;
255 };
256
257 #endif