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