Allow peer-specific sending and receiving of remote signals
[quassel.git] / src / common / signalproxy.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2013 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include <QCoreApplication>
22 #include <QHostAddress>
23 #include <QMetaMethod>
24 #include <QMetaProperty>
25 #include <QThread>
26
27 #ifdef HAVE_SSL
28     #include <QSslSocket>
29 #endif
30
31 #include "signalproxy.h"
32
33 #include "peer.h"
34 #include "protocol.h"
35 #include "syncableobject.h"
36 #include "util.h"
37 #include "types.h"
38
39 using namespace Protocol;
40
41 class RemovePeerEvent : public QEvent
42 {
43 public:
44     RemovePeerEvent(Peer *peer) : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)), peer(peer) {}
45     Peer *peer;
46 };
47
48
49 // ==================================================
50 //  SignalRelay
51 // ==================================================
52 class SignalProxy::SignalRelay : public QObject
53 {
54 /* Q_OBJECT is not necessary or even allowed, because we implement
55    qt_metacall ourselves (and don't use any other features of the meta
56    object system)
57 */
58 public:
59     SignalRelay(SignalProxy *parent) : QObject(parent), _proxy(parent) {}
60     inline SignalProxy *proxy() const { return _proxy; }
61
62     int qt_metacall(QMetaObject::Call _c, int _id, void **_a);
63
64     void attachSignal(QObject *sender, int signalId, const QByteArray &funcName);
65     void detachSignal(QObject *sender, int signalId = -1);
66
67 private:
68     struct Signal {
69         QObject *sender;
70         int signalId;
71         QByteArray signature;
72         Signal(QObject *sender, int sigId, const QByteArray &signature) : sender(sender), signalId(sigId), signature(signature) {}
73         Signal() : sender(0), signalId(-1) {}
74     };
75
76     SignalProxy *_proxy;
77     QHash<int, Signal> _slots;
78 };
79
80
81 void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QByteArray &funcName)
82 {
83     // we ride without safetybelts here... all checking for valid method etc pp has to be done by the caller
84     // all connected methodIds are offset by the standard methodCount of QObject
85     int slotId;
86     for (int i = 0;; i++) {
87         if (!_slots.contains(i)) {
88             slotId = i;
89             break;
90         }
91     }
92
93     QByteArray fn;
94     if (!funcName.isEmpty()) {
95         fn = QMetaObject::normalizedSignature(funcName);
96     }
97     else {
98         fn = SIGNAL(fakeMethodSignature());
99         fn = fn.replace("fakeMethodSignature()", sender->metaObject()->method(signalId).signature());
100     }
101
102     _slots[slotId] = Signal(sender, signalId, fn);
103
104     QMetaObject::connect(sender, signalId, this, QObject::staticMetaObject.methodCount() + slotId);
105 }
106
107
108 void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId)
109 {
110     QHash<int, Signal>::iterator slotIter = _slots.begin();
111     while (slotIter != _slots.end()) {
112         if (slotIter->sender == sender && (signalId == -1 || slotIter->signalId == signalId)) {
113             slotIter = _slots.erase(slotIter);
114             if (signalId != -1)
115                 break;
116         }
117         else {
118             slotIter++;
119         }
120     }
121 }
122
123
124 int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
125 {
126     _id = QObject::qt_metacall(_c, _id, _a);
127     if (_id < 0)
128         return _id;
129
130     if (_c == QMetaObject::InvokeMetaMethod) {
131         if (_slots.contains(_id)) {
132             QObject *caller = sender();
133
134             SignalProxy::ExtendedMetaObject *eMeta = proxy()->extendedMetaObject(caller->metaObject());
135             Q_ASSERT(eMeta);
136
137             const Signal &signal = _slots[_id];
138
139             QVariantList params;
140
141             const QList<int> &argTypes = eMeta->argTypes(signal.signalId);
142             for (int i = 0; i < argTypes.size(); i++) {
143                 if (argTypes[i] == 0) {
144                     qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(caller->metaObject()->className()).arg(caller->metaObject()->method(_id).signature());
145                     qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
146                     return _id;
147                 }
148                 params << QVariant(argTypes[i], _a[i+1]);
149             }
150
151             if (argTypes.size() >= 1 && argTypes[0] == qMetaTypeId<PeerPtr>() && proxy()->proxyMode() == SignalProxy::Server) {
152                 Peer *peer = params[0].value<PeerPtr>();
153                 proxy()->dispatch(peer, RpcCall(signal.signature, params));
154             } else
155                 proxy()->dispatch(RpcCall(signal.signature, params));
156         }
157         _id -= _slots.count();
158     }
159     return _id;
160 }
161
162
163 // ==================================================
164 //  SignalProxy
165 // ==================================================
166 SignalProxy::SignalProxy(QObject *parent)
167     : QObject(parent)
168 {
169     setProxyMode(Client);
170     init();
171 }
172
173
174 SignalProxy::SignalProxy(ProxyMode mode, QObject *parent)
175     : QObject(parent)
176 {
177     setProxyMode(mode);
178     init();
179 }
180
181
182 SignalProxy::~SignalProxy()
183 {
184     QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
185     while (classIter != _syncSlave.end()) {
186         ObjectId::iterator objIter = classIter->begin();
187         while (objIter != classIter->end()) {
188             SyncableObject *obj = objIter.value();
189             objIter = classIter->erase(objIter);
190             obj->stopSynchronize(this);
191         }
192         classIter++;
193     }
194     _syncSlave.clear();
195
196     removeAllPeers();
197 }
198
199
200 void SignalProxy::setProxyMode(ProxyMode mode)
201 {
202     if (_peers.count()) {
203         qWarning() << Q_FUNC_INFO << "Cannot change proxy mode while connected";
204         return;
205     }
206
207     _proxyMode = mode;
208     if (mode == Server)
209         initServer();
210     else
211         initClient();
212 }
213
214
215 void SignalProxy::init()
216 {
217     _heartBeatInterval = 0;
218     _maxHeartBeatCount = 0;
219     _signalRelay = new SignalRelay(this);
220     setHeartBeatInterval(30);
221     setMaxHeartBeatCount(2);
222     _secure = false;
223     updateSecureState();
224 }
225
226
227 void SignalProxy::initServer()
228 {
229 }
230
231
232 void SignalProxy::initClient()
233 {
234     attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray,QString,QString)));
235 }
236
237
238 void SignalProxy::setHeartBeatInterval(int secs)
239 {
240     if (_heartBeatInterval != secs) {
241         _heartBeatInterval = secs;
242         emit heartBeatIntervalChanged(secs);
243     }
244 }
245
246
247 void SignalProxy::setMaxHeartBeatCount(int max)
248 {
249     if (_maxHeartBeatCount != max) {
250         _maxHeartBeatCount = max;
251         emit maxHeartBeatCountChanged(max);
252     }
253 }
254
255
256 bool SignalProxy::addPeer(Peer *peer)
257 {
258     if (!peer)
259         return false;
260
261     if (_peers.contains(peer))
262         return true;
263
264     if (!peer->isOpen()) {
265         qWarning("SignalProxy: peer needs to be open!");
266         return false;
267     }
268
269     if (proxyMode() == Client) {
270         if (!_peers.isEmpty()) {
271             qWarning("SignalProxy: only one peer allowed in client mode!");
272             return false;
273         }
274         connect(peer, SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
275     }
276
277     connect(peer, SIGNAL(disconnected()), SLOT(removePeerBySender()));
278     connect(peer, SIGNAL(secureStateChanged(bool)), SLOT(updateSecureState()));
279
280     if (!peer->parent())
281         peer->setParent(this);
282
283     _peers.insert(peer);
284
285     peer->setSignalProxy(this);
286
287     if (_peers.count() == 1)
288         emit connected();
289
290     updateSecureState();
291     return true;
292 }
293
294
295 void SignalProxy::removeAllPeers()
296 {
297     Q_ASSERT(proxyMode() == Server || _peers.count() <= 1);
298     // wee need to copy that list since we modify it in the loop
299     QSet<Peer *> peers = _peers;
300     foreach(Peer *peer, peers) {
301         removePeer(peer);
302     }
303 }
304
305
306 void SignalProxy::removePeer(Peer *peer)
307 {
308     if (!peer) {
309         qWarning() << Q_FUNC_INFO << "Trying to remove a null peer!";
310         return;
311     }
312
313     if (_peers.isEmpty()) {
314         qWarning() << "SignalProxy::removePeer(): No peers in use!";
315         return;
316     }
317
318     if (!_peers.contains(peer)) {
319         qWarning() << "SignalProxy: unknown Peer" << peer;
320         return;
321     }
322
323     disconnect(peer, 0, this, 0);
324     peer->setSignalProxy(0);
325
326     _peers.remove(peer);
327     emit peerRemoved(peer);
328
329     if (peer->parent() == this)
330         peer->deleteLater();
331
332     updateSecureState();
333
334     if (_peers.isEmpty())
335         emit disconnected();
336 }
337
338
339 void SignalProxy::removePeerBySender()
340 {
341     removePeer(qobject_cast<Peer *>(sender()));
342 }
343
344
345 void SignalProxy::renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname)
346 {
347     if (proxyMode() == Client)
348         return;
349
350     const QMetaObject *meta = obj->syncMetaObject();
351     const QByteArray className(meta->className());
352     objectRenamed(className, newname, oldname);
353
354     dispatch(RpcCall("__objectRenamed__", QVariantList() << className << newname << oldname));
355 }
356
357
358 void SignalProxy::objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname)
359 {
360     if (_syncSlave.contains(classname) && _syncSlave[classname].contains(oldname) && oldname != newname) {
361         SyncableObject *obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname);
362         requestInit(obj);
363     }
364 }
365
366
367 const QMetaObject *SignalProxy::metaObject(const QObject *obj)
368 {
369     if (const SyncableObject *syncObject = qobject_cast<const SyncableObject *>(obj))
370         return syncObject->syncMetaObject();
371     else
372         return obj->metaObject();
373 }
374
375
376 SignalProxy::ExtendedMetaObject *SignalProxy::extendedMetaObject(const QMetaObject *meta) const
377 {
378     if (_extendedMetaObjects.contains(meta))
379         return _extendedMetaObjects[meta];
380     else
381         return 0;
382 }
383
384
385 SignalProxy::ExtendedMetaObject *SignalProxy::createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
386 {
387     if (!_extendedMetaObjects.contains(meta)) {
388         _extendedMetaObjects[meta] = new ExtendedMetaObject(meta, checkConflicts);
389     }
390     return _extendedMetaObjects[meta];
391 }
392
393
394 bool SignalProxy::attachSignal(QObject *sender, const char *signal, const QByteArray &sigName)
395 {
396     const QMetaObject *meta = sender->metaObject();
397     QByteArray sig(meta->normalizedSignature(signal).mid(1));
398     int methodId = meta->indexOfMethod(sig.constData());
399     if (methodId == -1 || meta->method(methodId).methodType() != QMetaMethod::Signal) {
400         qWarning() << "SignalProxy::attachSignal(): No such signal" << signal;
401         return false;
402     }
403
404     createExtendedMetaObject(meta);
405     _signalRelay->attachSignal(sender, methodId, sigName);
406
407     disconnect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
408     connect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
409     return true;
410 }
411
412
413 bool SignalProxy::attachSlot(const QByteArray &sigName, QObject *recv, const char *slot)
414 {
415     const QMetaObject *meta = recv->metaObject();
416     int methodId = meta->indexOfMethod(meta->normalizedSignature(slot).mid(1));
417     if (methodId == -1 || meta->method(methodId).methodType() == QMetaMethod::Method) {
418         qWarning() << "SignalProxy::attachSlot(): No such slot" << slot;
419         return false;
420     }
421
422     createExtendedMetaObject(meta);
423
424     QByteArray funcName = QMetaObject::normalizedSignature(sigName.constData());
425     _attachedSlots.insert(funcName, qMakePair(recv, methodId));
426
427     disconnect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
428     connect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
429     return true;
430 }
431
432
433 void SignalProxy::synchronize(SyncableObject *obj)
434 {
435     createExtendedMetaObject(obj, true);
436
437     // attaching as slave to receive sync Calls
438     QByteArray className(obj->syncMetaObject()->className());
439     _syncSlave[className][obj->objectName()] = obj;
440
441     if (proxyMode() == Server) {
442         obj->setInitialized();
443         emit objectInitialized(obj);
444     }
445     else {
446         if (obj->isInitialized())
447             emit objectInitialized(obj);
448         else
449             requestInit(obj);
450     }
451
452     obj->synchronize(this);
453 }
454
455
456 void SignalProxy::detachObject(QObject *obj)
457 {
458     detachSignals(obj);
459     detachSlots(obj);
460 }
461
462
463 void SignalProxy::detachSignals(QObject *sender)
464 {
465     _signalRelay->detachSignal(sender);
466 }
467
468
469 void SignalProxy::detachSlots(QObject *receiver)
470 {
471     SlotHash::iterator slotIter = _attachedSlots.begin();
472     while (slotIter != _attachedSlots.end()) {
473         if (slotIter.value().first == receiver) {
474             slotIter = _attachedSlots.erase(slotIter);
475         }
476         else
477             slotIter++;
478     }
479 }
480
481
482 void SignalProxy::stopSynchronize(SyncableObject *obj)
483 {
484     // we can't use a className here, since it might be effed up, if we receive the call as a result of a decon
485     // gladly the objectName() is still valid. So we have only to iterate over the classes not each instance! *sigh*
486     QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
487     while (classIter != _syncSlave.end()) {
488         if (classIter->contains(obj->objectName()) && classIter.value()[obj->objectName()] == obj) {
489             classIter->remove(obj->objectName());
490             break;
491         }
492         classIter++;
493     }
494     obj->stopSynchronize(this);
495 }
496
497
498 template<class T>
499 void SignalProxy::dispatch(const T &protoMessage)
500 {
501     foreach (Peer *peer, _peers) {
502         if (peer->isOpen())
503             peer->dispatch(protoMessage);
504         else
505             QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
506     }
507 }
508
509
510 void SignalProxy::dispatch(Peer *peer, const RpcCall &rpcCall)
511 {
512     if (peer && peer->isOpen())
513         peer->dispatch(rpcCall);
514     else
515         QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
516 }
517
518
519 void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage)
520 {
521     if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) {
522         qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
523                    << syncMessage.params;
524         return;
525     }
526
527     SyncableObject *receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
528     ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
529     if (!eMeta->slotMap().contains(syncMessage.slotName)) {
530         qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
531                    << syncMessage.params;
532         return;
533     }
534
535     int slotId = eMeta->slotMap()[syncMessage.slotName];
536     if (proxyMode() != eMeta->receiverMode(slotId)) {
537         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed. Wrong ProxyMode!", eMeta->methodName(slotId).constData());
538         return;
539     }
540
541     QVariant returnValue((QVariant::Type)eMeta->returnType(slotId));
542     if (!invokeSlot(receiver, slotId, syncMessage.params, returnValue)) {
543         qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed ", eMeta->methodName(slotId).constData());
544         return;
545     }
546
547     if (returnValue.type() != QVariant::Invalid && eMeta->receiveMap().contains(slotId)) {
548         int receiverId = eMeta->receiveMap()[slotId];
549         QVariantList returnParams;
550         if (eMeta->argTypes(receiverId).count() > 1)
551             returnParams << syncMessage.params;
552         returnParams << returnValue;
553         peer->dispatch(SyncMessage(syncMessage.className, syncMessage.objectName, eMeta->methodName(receiverId), returnParams));
554     }
555
556     // send emit update signal
557     invokeSlot(receiver, eMeta->updatedRemotelyId());
558 }
559
560
561 void SignalProxy::handle(Peer *peer, const InitRequest &initRequest)
562 {
563    if (!_syncSlave.contains(initRequest.className)) {
564         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:"
565                    << initRequest.className;
566         return;
567     }
568
569     if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) {
570         qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:"
571                    << initRequest.className << initRequest.objectName;
572         return;
573     }
574
575     SyncableObject *obj = _syncSlave[initRequest.className][initRequest.objectName];
576     peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj)));
577 }
578
579
580 void SignalProxy::handle(Peer *peer, const InitData &initData)
581 {
582     Q_UNUSED(peer)
583
584     if (!_syncSlave.contains(initData.className)) {
585         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:"
586                    << initData.className;
587         return;
588     }
589
590     if (!_syncSlave[initData.className].contains(initData.objectName)) {
591         qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:"
592                    << initData.className << initData.objectName;
593         return;
594     }
595
596     SyncableObject *obj = _syncSlave[initData.className][initData.objectName];
597     setInitData(obj, initData.initData);
598 }
599
600
601 void SignalProxy::handle(Peer *peer, const RpcCall &rpcCall)
602 {
603     QObject *receiver;
604     int methodId;
605     SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName);
606     while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) {
607         receiver = (*slot).first;
608         methodId = (*slot).second;
609         if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) {
610             ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
611             qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData());
612         }
613         ++slot;
614     }
615 }
616
617
618 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, QVariant &returnValue, Peer *peer)
619 {
620     ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
621     const QList<int> args = eMeta->argTypes(methodId);
622     const int numArgs = params.count() < args.count()
623                         ? params.count()
624                         : args.count();
625
626     if (eMeta->minArgCount(methodId) > params.count()) {
627         qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId);
628         return false;
629     }
630
631     void *_a[] = { 0,           // return type...
632                    0, 0, 0, 0, 0, // and 10 args - that's the max size qt can handle with signals and slots
633                    0, 0, 0, 0, 0 };
634
635     // check for argument compatibility and build params array
636     for (int i = 0; i < numArgs; i++) {
637         if (!params[i].isValid()) {
638             qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method" << QString("%1::%2()").arg(receiver->metaObject()->className()).arg(receiver->metaObject()->method(methodId).signature());
639             qWarning() << "                            - make sure all your data types are known by the Qt MetaSystem";
640             return false;
641         }
642         if (args[i] != QMetaType::type(params[i].typeName())) {
643             qWarning() << "SignalProxy::invokeSlot(): incompatible param types to invoke" << eMeta->methodName(methodId);
644             return false;
645         }
646         // if first arg is a PeerPtr, replace it by the address of the peer originally receiving the RpcCall
647         if (peer && i == 0 && args[0] == qMetaTypeId<PeerPtr>()) {
648             QVariant v = QVariant::fromValue<PeerPtr>(peer);
649             _a[1] = const_cast<void*>(v.constData());
650         } else
651             _a[i+1] = const_cast<void *>(params[i].constData());
652     }
653
654     if (returnValue.type() != QVariant::Invalid)
655         _a[0] = const_cast<void *>(returnValue.constData());
656
657     Qt::ConnectionType type = QThread::currentThread() == receiver->thread()
658                               ? Qt::DirectConnection
659                               : Qt::QueuedConnection;
660
661     if (type == Qt::DirectConnection) {
662         return receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
663     }
664     else {
665         qWarning() << "Queued Connections are not implemented yet";
666         // note to self: qmetaobject.cpp:990 ff
667         return false;
668     }
669 }
670
671
672 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList &params, Peer *peer)
673 {
674     QVariant ret;
675     return invokeSlot(receiver, methodId, params, ret, peer);
676 }
677
678
679 void SignalProxy::requestInit(SyncableObject *obj)
680 {
681     if (proxyMode() == Server || obj->isInitialized())
682         return;
683
684     dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
685 }
686
687
688 QVariantMap SignalProxy::initData(SyncableObject *obj) const
689 {
690     return obj->toVariantMap();
691 }
692
693
694 void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties)
695 {
696     if (obj->isInitialized())
697         return;
698     obj->fromVariantMap(properties);
699     obj->setInitialized();
700     emit objectInitialized(obj);
701     invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
702 }
703
704
705 void SignalProxy::customEvent(QEvent *event)
706 {
707     switch ((int)event->type()) {
708     case RemovePeerEvent: {
709         ::RemovePeerEvent *e = static_cast< ::RemovePeerEvent *>(event);
710         removePeer(e->peer);
711         event->accept();
712         break;
713     }
714
715     default:
716         qWarning() << Q_FUNC_INFO << "Received unknown custom event:" << event->type();
717         return;
718     }
719 }
720
721
722 void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap)
723 {
724     // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
725     if (modeType != _proxyMode)
726         return;
727
728     ExtendedMetaObject *eMeta = extendedMetaObject(obj);
729
730     QVariantList params;
731
732     const QList<int> &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
733
734     for (int i = 0; i < argTypes.size(); i++) {
735         if (argTypes[i] == 0) {
736             qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
737             qWarning() << "        - make sure all your data types are known by the Qt MetaSystem";
738             return;
739         }
740         params << QVariant(argTypes[i], va_arg(ap, void *));
741     }
742
743     dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
744 }
745
746
747 void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason)
748 {
749     if (!reason.isEmpty())
750         qWarning() << qPrintable(reason);
751     QAbstractSocket *sock  = qobject_cast<QAbstractSocket *>(dev);
752     if (sock)
753         qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
754     dev->close();
755 }
756
757
758 void SignalProxy::dumpProxyStats()
759 {
760     QString mode;
761     if (proxyMode() == Server)
762         mode = "Server";
763     else
764         mode = "Client";
765
766     int slaveCount = 0;
767     foreach(ObjectId oid, _syncSlave.values())
768     slaveCount += oid.count();
769
770     qDebug() << this;
771     qDebug() << "              Proxy Mode:" << mode;
772     qDebug() << "          attached Slots:" << _attachedSlots.count();
773     qDebug() << " number of synced Slaves:" << slaveCount;
774     qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
775 }
776
777
778 void SignalProxy::updateSecureState()
779 {
780     bool wasSecure = _secure;
781
782     _secure = !_peers.isEmpty();
783     foreach (const Peer *peer,  _peers) {
784         _secure &= peer->isSecure();
785     }
786
787     if (wasSecure != _secure)
788         emit secureStateChanged(_secure);
789 }
790
791
792 // ==================================================
793 //  ExtendedMetaObject
794 // ==================================================
795 SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
796     : _meta(meta),
797     _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
798 {
799     for (int i = 0; i < _meta->methodCount(); i++) {
800         if (_meta->method(i).methodType() != QMetaMethod::Slot)
801             continue;
802
803         if (QByteArray(_meta->method(i).signature()).contains('*'))
804             continue;  // skip methods with ptr params
805
806         QByteArray method = methodName(_meta->method(i));
807         if (method.startsWith("init"))
808             continue;  // skip initializers
809
810         if (_methodIds.contains(method)) {
811             /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
812                we don't care... we just need the full fledged version
813              */
814             const QMetaMethod &current = _meta->method(_methodIds[method]);
815             const QMetaMethod &candidate = _meta->method(i);
816             if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
817                 int minCount = candidate.parameterTypes().count();
818                 QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
819                 if (commonParams == candidate.parameterTypes())
820                     continue;  // we already got the full featured version
821             }
822             else {
823                 int minCount = current.parameterTypes().count();
824                 QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
825                 if (commonParams == current.parameterTypes()) {
826                     _methodIds[method] = i; // use the new one
827                     continue;
828                 }
829             }
830             if (checkConflicts) {
831                 qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
832                 qWarning() << " - " << _meta->method(i).signature() << "conflicts with" << _meta->method(_methodIds[method]).signature();
833             }
834             continue;
835         }
836         _methodIds[method] = i;
837     }
838 }
839
840
841 const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
842 {
843     if (!_methods.contains(methodId)) {
844         _methods[methodId] = MethodDescriptor(_meta->method(methodId));
845     }
846     return _methods[methodId];
847 }
848
849
850 const QHash<int, int> &SignalProxy::ExtendedMetaObject::receiveMap()
851 {
852     if (_receiveMap.isEmpty()) {
853         QHash<int, int> receiveMap;
854
855         QMetaMethod requestSlot;
856         QByteArray returnTypeName;
857         QByteArray signature;
858         QByteArray methodName;
859         QByteArray params;
860         int paramsPos;
861         int receiverId;
862         const int methodCount = _meta->methodCount();
863         for (int i = 0; i < methodCount; i++) {
864             requestSlot = _meta->method(i);
865             if (requestSlot.methodType() != QMetaMethod::Slot)
866                 continue;
867
868             returnTypeName = requestSlot.typeName();
869             if (QMetaType::Void == (QMetaType::Type)returnType(i))
870                 continue;
871
872             signature = QByteArray(requestSlot.signature());
873             if (!signature.startsWith("request"))
874                 continue;
875
876             paramsPos = signature.indexOf('(');
877             if (paramsPos == -1)
878                 continue;
879
880             methodName = signature.left(paramsPos);
881             params = signature.mid(paramsPos);
882
883             methodName = methodName.replace("request", "receive");
884             params = params.left(params.count() - 1) + ", " + returnTypeName + ")";
885
886             signature = QMetaObject::normalizedSignature(methodName + params);
887             receiverId = _meta->indexOfSlot(signature);
888
889             if (receiverId == -1) {
890                 signature = QMetaObject::normalizedSignature(methodName + "(" + returnTypeName + ")");
891                 receiverId = _meta->indexOfSlot(signature);
892             }
893
894             if (receiverId != -1) {
895                 receiveMap[i] = receiverId;
896             }
897         }
898         _receiveMap = receiveMap;
899     }
900     return _receiveMap;
901 }
902
903
904 QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method)
905 {
906     QByteArray sig(method.signature());
907     return sig.left(sig.indexOf("("));
908 }
909
910
911 QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method)
912 {
913     QString methodname = QString(method.signature()).section("(", 0, 0);
914
915     // determine where we have to chop:
916     int upperCharPos;
917     if (method.methodType() == QMetaMethod::Slot) {
918         // we take evertyhing from the first uppercase char if it's slot
919         upperCharPos = methodname.indexOf(QRegExp("[A-Z]"));
920         if (upperCharPos == -1)
921             return QString();
922         methodname = methodname.mid(upperCharPos);
923     }
924     else {
925         // and if it's a signal we discard everything from the last uppercase char
926         upperCharPos = methodname.lastIndexOf(QRegExp("[A-Z]"));
927         if (upperCharPos == -1)
928             return QString();
929         methodname = methodname.left(upperCharPos);
930     }
931
932     methodname[0] = methodname[0].toUpper();
933
934     return methodname;
935 }
936
937
938 SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method)
939     : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)),
940     _returnType(QMetaType::type(method.typeName()))
941 {
942     // determine argTypes
943     QList<QByteArray> paramTypes = method.parameterTypes();
944     QList<int> argTypes;
945     for (int i = 0; i < paramTypes.count(); i++) {
946         argTypes.append(QMetaType::type(paramTypes[i]));
947     }
948     _argTypes = argTypes;
949
950     // determine minArgCount
951     QString signature(method.signature());
952     _minArgCount = method.parameterTypes().count() - signature.count("=");
953
954     _receiverMode = (_methodName.startsWith("request"))
955                     ? SignalProxy::Server
956                     : SignalProxy::Client;
957 }