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