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