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