reenabling disconnect on timeout for iodevice connections
[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 protected:
123   void customEvent(QEvent *event);
124
125 private slots:
126   void dataAvailable();
127   void detachSender();
128   void removePeerBySender();
129   void objectRenamed(const QString &newname, const QString &oldname);
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 signals:
136   void peerRemoved(QIODevice *dev);
137   void connected();
138   void disconnected();
139   void objectInitialized(SyncableObject *);
140   void lagUpdated(int lag);
141   
142 private:
143   void init();
144   void initServer();
145   void initClient();
146   
147   const QMetaObject *metaObject(QObject *obj);
148   void createClassInfo(QObject *obj);
149   void setArgTypes(QObject *obj, int methodId);
150   void setReturnType(QObject *obj, int methodId);
151   void setMinArgCount(QObject *obj, int methodId);
152   void setMethodName(QObject *obj, int methodId);
153   void setSyncMap(SyncableObject *obj);
154   void setReceiveMap(SyncableObject *obj);
155   void setUpdatedRemotelyId(SyncableObject *obj);
156
157   bool methodsMatch(const QMetaMethod &signal, const QMetaMethod &slot) const;
158
159   void dispatchSignal(QIODevice *receiver, const RequestType &requestType, const QVariantList &params);
160   void dispatchSignal(const RequestType &requestType, const QVariantList &params);
161
162   void receivePackedFunc(AbstractPeer *sender, const QVariant &packedFunc);
163   void receivePeerSignal(AbstractPeer *sender, const RequestType &requestType, const QVariantList &params);
164   void receivePeerSignal(SignalProxy *sender, const RequestType &requestType, const QVariantList &params);
165   void handleSync(AbstractPeer *sender, QVariantList params);
166   void handleInitRequest(AbstractPeer *sender, const QVariantList &params);
167   void handleInitData(AbstractPeer *sender, const QVariantList &params);
168   void handleSignal(const QVariantList &data);
169
170   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue);
171   bool invokeSlot(QObject *receiver, int methodId, const QVariantList &params = QVariantList());
172
173   QVariantMap initData(SyncableObject *obj) const;
174   void setInitData(SyncableObject *obj, const QVariantMap &properties);
175
176   void updateLag(IODevicePeer *peer, int lag);
177
178 public:
179   void dumpSyncMap(SyncableObject *object);
180   inline int peerCount() const { return _peers.size(); }
181   
182 private:
183   class AbstractPeer {
184   public:
185     enum PeerType {
186       NotAPeer = 0,
187       IODevicePeer = 1,
188       SignalProxyPeer = 2
189     };
190     AbstractPeer() : _type(NotAPeer) {}
191     AbstractPeer(PeerType type) : _type(type) {}
192     virtual ~AbstractPeer() {}
193     inline PeerType type() const { return _type; }
194     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params) = 0;
195   private:
196     PeerType _type;
197   };
198
199   class IODevicePeer : public AbstractPeer {
200   public:
201     IODevicePeer(QIODevice *device, bool compress) : AbstractPeer(AbstractPeer::IODevicePeer), _device(device), byteCount(0), usesCompression(compress), sentHeartBeats(0), lag(0) {}
202     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
203     inline void dispatchPackedFunc(const QVariant &packedFunc) { SignalProxy::writeDataToDevice(_device, packedFunc, usesCompression); }
204     QString address() const;
205     inline bool isOpen() const { return _device->isOpen(); }
206     inline void close() const { _device->close(); }
207     inline bool readData(QVariant &item) { return SignalProxy::readDataFromDevice(_device, byteCount, item, usesCompression); }
208   private:
209     QIODevice *_device;
210     quint32 byteCount;
211     bool usesCompression;
212   public:
213     int sentHeartBeats;
214     int lag;
215   };
216
217   class SignalProxyPeer : public AbstractPeer {
218   public:
219     SignalProxyPeer(SignalProxy *sender, SignalProxy *receiver) : AbstractPeer(AbstractPeer::SignalProxyPeer), sender(sender), receiver(receiver) {}
220     virtual void dispatchSignal(const RequestType &requestType, const QVariantList &params);
221   private:
222     SignalProxy *sender;
223     SignalProxy *receiver;
224   };
225
226   // a Hash of the actual used communication object to it's corresponding peer
227   // currently a communication object can either be an arbitrary QIODevice or another SignalProxy
228   typedef QHash<QObject *, AbstractPeer *> PeerHash;
229   PeerHash _peers;
230   
231 //   // Hash of used QIODevices
232 //   struct peerInfo {
233 //     quint32 byteCount;
234 //     bool usesCompression;
235 //     int sentHeartBeats;
236 //     int lag;
237 //     peerInfo() : byteCount(0), usesCompression(false), sentHeartBeats(0) {}
238 //   };
239 //   QHash<QIODevice*, peerInfo> _peers;
240
241   // containg a list of argtypes for fast access
242   QHash<const QMetaObject *, ClassInfo*> _classInfo;
243
244   // we use one SignalRelay per QObject
245   QHash<QObject*, SignalRelay *> _relayHash;
246
247   // RPC function -> (object, slot ID)
248   typedef QPair<QObject*, int> MethodId;
249   typedef QMultiHash<QByteArray, MethodId> SlotHash;
250   SlotHash _attachedSlots;
251
252   // slaves for sync
253   typedef QHash<QString, SyncableObject *> ObjectId;
254   QHash<QByteArray, ObjectId> _syncSlave;
255
256
257   ProxyMode _proxyMode;
258   QTimer _heartBeatTimer;
259   
260   friend class SignalRelay;
261 };
262
263 #endif