76ed4d54d5008a14ab49b22dc01022b900ba9e3e
[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   enum ClientConnectionType {
59     SignalProxyConnection,
60     IODeviceConnection
61   };
62
63   SignalProxy(QObject *parent);
64   SignalProxy(ProxyMode mode, QObject *parent);
65   SignalProxy(ProxyMode mode, QIODevice *device, QObject *parent);
66   virtual ~SignalProxy();
67
68   void setProxyMode(ProxyMode mode);
69   inline ProxyMode proxyMode() const { return _proxyMode; }
70
71   bool addPeer(QIODevice *iodev);
72   bool addPeer(SignalProxy *proxy);
73   void removePeer(QObject *peer);
74   void removeAllPeers();
75   
76   bool attachSignal(QObject *sender, const char *signal, const QByteArray& sigName = QByteArray());
77   bool attachSlot(const QByteArray& sigName, QObject *recv, const char *slot);
78
79   void synchronize(SyncableObject *obj);
80
81 //   void setInitialized(SyncableObject *obj);
82 //   bool isInitialized(SyncableObject *obj) const;
83   void requestInit(SyncableObject *obj);
84
85   void detachObject(QObject *obj);
86   void detachSignals(QObject *sender);
87   void detachSlots(QObject *receiver);
88   void stopSync(SyncableObject *obj);
89
90   //! Writes a QVariant to a device.
91   /** The data item is prefixed with the resulting blocksize,
92    *  so the corresponding function readDataFromDevice() can check if enough data is available
93    *  at the device to reread the item.
94    */
95   static void writeDataToDevice(QIODevice *dev, const QVariant &item, bool compressed = false);
96
97   //! Reads a data item from a device that has been written by writeDataToDevice().
98   /** If not enough data bytes are available, the function returns false and the QVariant reference
99    *  remains untouched.
100    */
101   static bool readDataFromDevice(QIODevice *dev, quint32 &blockSize, QVariant &item, bool compressed = false);
102
103   static QString methodBaseName(const QMetaMethod &method);
104
105   const QList<int> &argTypes(QObject *obj, int methodId);
106   const int &returnType(QObject *obj, int methodId);
107   const int &minArgCount(QObject *obj, int methodId);
108   const QByteArray &methodName(QObject *obj, int methodId);
109   const QHash<QByteArray, int> &syncMap(SyncableObject *obj);
110   const QHash<int, int> &receiveMap(SyncableObject *obj);
111   int updatedRemotelyId(SyncableObject *obj);
112
113   typedef QHash<int, QList<int> > ArgHash;
114   typedef QHash<int, QByteArray> MethodNameHash;
115   struct ClassInfo {
116     ArgHash argTypes;
117     QHash<int, int> returnType;
118     QHash<int, int> minArgCount;
119     MethodNameHash methodNames;
120     int updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster
121     QHash<QByteArray, int> syncMap;
122     QHash<int, int> receiveMap;
123   };
124
125   void dumpProxyStats();
126   
127 protected:
128   void customEvent(QEvent *event);
129
130 private slots:
131   void dataAvailable();
132   void detachSender();
133   void removePeerBySender();
134   void objectRenamed(const QString &newname, const QString &oldname);
135   void objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname);
136   void sendHeartBeat();
137   void receiveHeartBeat(AbstractPeer *peer, const QVariantList &params);
138   void receiveHeartBeatReply(AbstractPeer *peer, const QVariantList &params);
139   
140 signals:
141   void peerRemoved(QIODevice *dev);
142   void connected();
143   void disconnected();
144   void objectInitialized(SyncableObject *);
145   void lagUpdated(int lag);
146   
147 private:
148   void init();
149   void initServer();
150   void initClient();
151   
152   const QMetaObject *metaObject(QObject *obj);
153   void createClassInfo(QObject *obj);
154   void setArgTypes(QObject *obj, int methodId);
155   void setReturnType(QObject *obj, int methodId);
156   void setMinArgCount(QObject *obj, int methodId);
157   void setMethodName(QObject *obj, int methodId);
158   void setSyncMap(SyncableObject *obj);
159   void setReceiveMap(SyncableObject *obj);
160   void setUpdatedRemotelyId(SyncableObject *obj);
161
162   bool methodsMatch(const QMetaMethod &signal, const QMetaMethod &slot) const;
163
164   void dispatchSignal(QIODevice *receiver, const RequestType &requestType, const QVariantList &params);
165   void dispatchSignal(const RequestType &requestType, const QVariantList &params);
166
167   void receivePackedFunc(AbstractPeer *sender, const QVariant &packedFunc);
168   void receivePeerSignal(AbstractPeer *sender, const RequestType &requestType, const QVariantList &params);
169   void receivePeerSignal(SignalProxy *sender, const RequestType &requestType, const QVariantList &params);
170   void handleSync(AbstractPeer *sender, QVariantList params);
171   void handleInitRequest(AbstractPeer *sender, const QVariantList &params);
172   void handleInitData(AbstractPeer *sender, const QVariantList &params);
173   void handleSignal(const QVariantList &data);
174
175   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue);
176   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params = QVariantList());
177
178   QVariantMap initData(SyncableObject *obj) const;
179   void setInitData(SyncableObject *obj, const QVariantMap &properties);
180
181   void updateLag(IODevicePeer *peer, int lag);
182
183 public:
184   void dumpSyncMap(SyncableObject *object);
185   inline int peerCount() const { return _peers.size(); }
186   
187 private:
188   static void disconnectDevice(QIODevice *dev, const QString &reason = QString());
189
190   class AbstractPeer {
191   public:
192     enum PeerType {
193       NotAPeer = 0,
194       IODevicePeer = 1,
195       SignalProxyPeer = 2
196     };
197     AbstractPeer() : _type(NotAPeer) {}
198     AbstractPeer(PeerType type) : _type(type) {}
199     virtual ~AbstractPeer() {}
200     inline PeerType type() const { return _type; }
201     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params) = 0;
202   private:
203     PeerType _type;
204   };
205
206   class IODevicePeer : public AbstractPeer {
207   public:
208     IODevicePeer(QIODevice *device, bool compress) : AbstractPeer(AbstractPeer::IODevicePeer), _device(device), byteCount(0), usesCompression(compress), sentHeartBeats(0), lag(0) {}
209     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
210     inline void dispatchPackedFunc(const QVariant &packedFunc) { SignalProxy::writeDataToDevice(_device, packedFunc, usesCompression); }
211     QString address() const;
212     inline bool isOpen() const { return _device->isOpen(); }
213     inline void close() const { _device->close(); }
214     inline bool readData(QVariant &item) { return SignalProxy::readDataFromDevice(_device, byteCount, item, usesCompression); }
215   private:
216     QIODevice *_device;
217     quint32 byteCount;
218     bool usesCompression;
219   public:
220     int sentHeartBeats;
221     int lag;
222   };
223
224   class SignalProxyPeer : public AbstractPeer {
225   public:
226     SignalProxyPeer(SignalProxy *sender, SignalProxy *receiver) : AbstractPeer(AbstractPeer::SignalProxyPeer), sender(sender), receiver(receiver) {}
227     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
228   private:
229     SignalProxy *sender;
230     SignalProxy *receiver;
231   };
232
233   // a Hash of the actual used communication object to it's corresponding peer
234   // currently a communication object can either be an arbitrary QIODevice or another SignalProxy
235   typedef QHash<QObject *, AbstractPeer *> PeerHash;
236   PeerHash _peers;
237
238   // containg a list of argtypes for fast access
239   QHash<const QMetaObject *, ClassInfo*> _classInfo;
240
241   // we use one SignalRelay per QObject
242   QHash<QObject*, SignalRelay *> _relayHash;
243
244   // RPC function -> (object, slot ID)
245   typedef QPair<QObject*, int> MethodId;
246   typedef QMultiHash<QByteArray, MethodId> SlotHash;
247   SlotHash _attachedSlots;
248
249   // slaves for sync
250   typedef QHash<QString, SyncableObject *> ObjectId;
251   QHash<QByteArray, ObjectId> _syncSlave;
252
253
254   ProxyMode _proxyMode;
255   QTimer _heartBeatTimer;
256   
257   friend class SignalRelay;
258 };
259
260 #endif