1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include <QCoreApplication>
22 #include <QHostAddress>
23 #include <QMetaMethod>
24 #include <QMetaProperty>
31 #include "signalproxy.h"
35 #include "syncableobject.h"
39 using namespace Protocol;
41 class RemovePeerEvent : public QEvent
44 RemovePeerEvent(Peer *peer) : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)), peer(peer) {}
49 // ==================================================
51 // ==================================================
52 class SignalProxy::SignalRelay : public QObject
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
59 SignalRelay(SignalProxy *parent) : QObject(parent), _proxy(parent) {}
60 inline SignalProxy *proxy() const { return _proxy; }
62 int qt_metacall(QMetaObject::Call _c, int _id, void **_a);
64 void attachSignal(QObject *sender, int signalId, const QByteArray &funcName);
65 void detachSignal(QObject *sender, int signalId = -1);
72 Signal(QObject *sender, int sigId, const QByteArray &signature) : sender(sender), signalId(sigId), signature(signature) {}
73 Signal() : sender(0), signalId(-1) {}
77 QHash<int, Signal> _slots;
81 void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QByteArray &funcName)
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
86 for (int i = 0;; i++) {
87 if (!_slots.contains(i)) {
94 if (!funcName.isEmpty()) {
95 fn = QMetaObject::normalizedSignature(funcName);
98 fn = SIGNAL(fakeMethodSignature());
99 #if QT_VERSION >= 0x050000
100 fn = fn.replace("fakeMethodSignature()", sender->metaObject()->method(signalId).methodSignature());
102 fn = fn.replace("fakeMethodSignature()", sender->metaObject()->method(signalId).signature());
106 _slots[slotId] = Signal(sender, signalId, fn);
108 QMetaObject::connect(sender, signalId, this, QObject::staticMetaObject.methodCount() + slotId);
112 void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId)
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);
128 int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
130 _id = QObject::qt_metacall(_c, _id, _a);
134 if (_c == QMetaObject::InvokeMetaMethod) {
135 if (_slots.contains(_id)) {
136 QObject *caller = sender();
138 SignalProxy::ExtendedMetaObject *eMeta = proxy()->extendedMetaObject(caller->metaObject());
141 const Signal &signal = _slots[_id];
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());
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());
153 qWarning() << " - make sure all your data types are known by the Qt MetaSystem";
156 params << QVariant(argTypes[i], _a[i+1]);
159 if (proxy()->_restrictMessageTarget) {
160 for (auto peer : proxy()->_restrictedTargets) {
162 proxy()->dispatch(peer, RpcCall(signal.signature, params));
165 proxy()->dispatch(RpcCall(signal.signature, params));
167 _id -= _slots.count();
173 // ==================================================
175 // ==================================================
177 thread_local SignalProxy *SignalProxy::_current{nullptr};
179 SignalProxy::SignalProxy(QObject *parent)
182 setProxyMode(Client);
187 SignalProxy::SignalProxy(ProxyMode mode, QObject *parent)
195 SignalProxy::~SignalProxy()
197 QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
198 while (classIter != _syncSlave.end()) {
199 ObjectId::iterator objIter = classIter->begin();
200 while (objIter != classIter->end()) {
201 SyncableObject *obj = objIter.value();
202 objIter = classIter->erase(objIter);
203 obj->stopSynchronize(this);
215 void SignalProxy::setProxyMode(ProxyMode mode)
217 if (!_peerMap.empty()) {
218 qWarning() << Q_FUNC_INFO << "Cannot change proxy mode while connected";
229 void SignalProxy::init()
231 _heartBeatInterval = 0;
232 _maxHeartBeatCount = 0;
233 _signalRelay = new SignalRelay(this);
234 setHeartBeatInterval(30);
235 setMaxHeartBeatCount(2);
242 void SignalProxy::initServer()
247 void SignalProxy::initClient()
249 attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray,QString,QString)));
253 void SignalProxy::setHeartBeatInterval(int secs)
255 if (_heartBeatInterval != secs) {
256 _heartBeatInterval = secs;
257 emit heartBeatIntervalChanged(secs);
262 void SignalProxy::setMaxHeartBeatCount(int max)
264 if (_maxHeartBeatCount != max) {
265 _maxHeartBeatCount = max;
266 emit maxHeartBeatCountChanged(max);
271 bool SignalProxy::addPeer(Peer *peer)
276 if (_peerMap.values().contains(peer))
279 if (!peer->isOpen()) {
280 qWarning("SignalProxy: peer needs to be open!");
284 if (proxyMode() == Client) {
285 if (!_peerMap.isEmpty()) {
286 qWarning("SignalProxy: only one peer allowed in client mode!");
289 connect(peer, SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
292 connect(peer, SIGNAL(disconnected()), SLOT(removePeerBySender()));
293 connect(peer, SIGNAL(secureStateChanged(bool)), SLOT(updateSecureState()));
296 peer->setParent(this);
298 if (peer->id() < 0) {
299 peer->setId(nextPeerId());
300 peer->setConnectedSince(QDateTime::currentDateTimeUtc());
303 _peerMap[peer->id()] = peer;
305 peer->setSignalProxy(this);
307 if (peerCount() == 1)
315 void SignalProxy::removeAllPeers()
317 Q_ASSERT(proxyMode() == Server || peerCount() <= 1);
318 // wee need to copy that list since we modify it in the loop
319 QList<Peer *> peers = _peerMap.values();
320 for (auto peer : peers) {
326 void SignalProxy::removePeer(Peer *peer)
329 qWarning() << Q_FUNC_INFO << "Trying to remove a null peer!";
333 if (_peerMap.isEmpty()) {
334 qWarning() << "SignalProxy::removePeer(): No peers in use!";
338 if (!_peerMap.values().contains(peer)) {
339 qWarning() << "SignalProxy: unknown Peer" << peer;
343 disconnect(peer, 0, this, 0);
344 peer->setSignalProxy(0);
346 _peerMap.remove(peer->id());
347 emit peerRemoved(peer);
349 if (peer->parent() == this)
354 if (_peerMap.isEmpty())
359 void SignalProxy::removePeerBySender()
361 removePeer(qobject_cast<Peer *>(sender()));
365 void SignalProxy::renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname)
367 if (proxyMode() == Client)
370 const QMetaObject *meta = obj->syncMetaObject();
371 const QByteArray className(meta->className());
372 objectRenamed(className, newname, oldname);
374 dispatch(RpcCall("__objectRenamed__", QVariantList() << className << newname << oldname));
378 void SignalProxy::objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname)
380 if (_syncSlave.contains(classname) && _syncSlave[classname].contains(oldname) && oldname != newname) {
381 SyncableObject *obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname);
387 const QMetaObject *SignalProxy::metaObject(const QObject *obj)
389 if (const SyncableObject *syncObject = qobject_cast<const SyncableObject *>(obj))
390 return syncObject->syncMetaObject();
392 return obj->metaObject();
396 SignalProxy::ExtendedMetaObject *SignalProxy::extendedMetaObject(const QMetaObject *meta) const
398 if (_extendedMetaObjects.contains(meta))
399 return _extendedMetaObjects[meta];
405 SignalProxy::ExtendedMetaObject *SignalProxy::createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
407 if (!_extendedMetaObjects.contains(meta)) {
408 _extendedMetaObjects[meta] = new ExtendedMetaObject(meta, checkConflicts);
410 return _extendedMetaObjects[meta];
414 bool SignalProxy::attachSignal(QObject *sender, const char *signal, const QByteArray &sigName)
416 const QMetaObject *meta = sender->metaObject();
417 QByteArray sig(meta->normalizedSignature(signal).mid(1));
418 int methodId = meta->indexOfMethod(sig.constData());
419 if (methodId == -1 || meta->method(methodId).methodType() != QMetaMethod::Signal) {
420 qWarning() << "SignalProxy::attachSignal(): No such signal" << signal;
424 createExtendedMetaObject(meta);
425 _signalRelay->attachSignal(sender, methodId, sigName);
427 disconnect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
428 connect(sender, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
433 bool SignalProxy::attachSlot(const QByteArray &sigName, QObject *recv, const char *slot)
435 const QMetaObject *meta = recv->metaObject();
436 int methodId = meta->indexOfMethod(meta->normalizedSignature(slot).mid(1));
437 if (methodId == -1 || meta->method(methodId).methodType() == QMetaMethod::Method) {
438 qWarning() << "SignalProxy::attachSlot(): No such slot" << slot;
442 createExtendedMetaObject(meta);
444 QByteArray funcName = QMetaObject::normalizedSignature(sigName.constData());
445 _attachedSlots.insert(funcName, qMakePair(recv, methodId));
447 disconnect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
448 connect(recv, SIGNAL(destroyed(QObject *)), this, SLOT(detachObject(QObject *)));
453 void SignalProxy::synchronize(SyncableObject *obj)
455 createExtendedMetaObject(obj, true);
457 // attaching as slave to receive sync Calls
458 QByteArray className(obj->syncMetaObject()->className());
459 _syncSlave[className][obj->objectName()] = obj;
461 if (proxyMode() == Server) {
462 obj->setInitialized();
463 emit objectInitialized(obj);
466 if (obj->isInitialized())
467 emit objectInitialized(obj);
472 obj->synchronize(this);
476 void SignalProxy::detachObject(QObject *obj)
483 void SignalProxy::detachSignals(QObject *sender)
485 _signalRelay->detachSignal(sender);
489 void SignalProxy::detachSlots(QObject *receiver)
491 SlotHash::iterator slotIter = _attachedSlots.begin();
492 while (slotIter != _attachedSlots.end()) {
493 if (slotIter.value().first == receiver) {
494 slotIter = _attachedSlots.erase(slotIter);
502 void SignalProxy::stopSynchronize(SyncableObject *obj)
504 // we can't use a className here, since it might be effed up, if we receive the call as a result of a decon
505 // gladly the objectName() is still valid. So we have only to iterate over the classes not each instance! *sigh*
506 QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
507 while (classIter != _syncSlave.end()) {
508 if (classIter->contains(obj->objectName()) && classIter.value()[obj->objectName()] == obj) {
509 classIter->remove(obj->objectName());
514 obj->stopSynchronize(this);
519 void SignalProxy::dispatch(const T &protoMessage)
521 for (auto&& peer : _peerMap.values()) {
522 dispatch(peer, protoMessage);
528 void SignalProxy::dispatch(Peer *peer, const T &protoMessage)
532 if (peer && peer->isOpen())
533 peer->dispatch(protoMessage);
535 QCoreApplication::postEvent(this, new ::RemovePeerEvent(peer));
537 _targetPeer = nullptr;
541 void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage)
543 if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) {
544 qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
545 << syncMessage.params;
549 SyncableObject *receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
550 ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
551 if (!eMeta->slotMap().contains(syncMessage.slotName)) {
552 qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
553 << syncMessage.params;
557 int slotId = eMeta->slotMap()[syncMessage.slotName];
558 if (proxyMode() != eMeta->receiverMode(slotId)) {
559 qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed. Wrong ProxyMode!", eMeta->methodName(slotId).constData());
563 // We can no longer construct a QVariant from QMetaType::Void
564 QVariant returnValue;
565 int returnType = eMeta->returnType(slotId);
566 if (returnType != QMetaType::Void)
567 returnValue = QVariant(static_cast<QVariant::Type>(returnType));
569 if (!invokeSlot(receiver, slotId, syncMessage.params, returnValue, peer)) {
570 qWarning("SignalProxy::handleSync(): invokeMethod for \"%s\" failed ", eMeta->methodName(slotId).constData());
574 if (returnValue.type() != QVariant::Invalid && eMeta->receiveMap().contains(slotId)) {
575 int receiverId = eMeta->receiveMap()[slotId];
576 QVariantList returnParams;
577 if (eMeta->argTypes(receiverId).count() > 1)
578 returnParams << syncMessage.params;
579 returnParams << returnValue;
581 peer->dispatch(SyncMessage(syncMessage.className, syncMessage.objectName, eMeta->methodName(receiverId), returnParams));
582 _targetPeer = nullptr;
585 // send emit update signal
586 invokeSlot(receiver, eMeta->updatedRemotelyId());
590 void SignalProxy::handle(Peer *peer, const InitRequest &initRequest)
592 if (!_syncSlave.contains(initRequest.className)) {
593 qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:"
594 << initRequest.className;
598 if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) {
599 qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:"
600 << initRequest.className << initRequest.objectName;
604 SyncableObject *obj = _syncSlave[initRequest.className][initRequest.objectName];
606 peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj)));
607 _targetPeer = nullptr;
611 void SignalProxy::handle(Peer *peer, const InitData &initData)
615 if (!_syncSlave.contains(initData.className)) {
616 qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:"
617 << initData.className;
621 if (!_syncSlave[initData.className].contains(initData.objectName)) {
622 qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:"
623 << initData.className << initData.objectName;
627 SyncableObject *obj = _syncSlave[initData.className][initData.objectName];
628 setInitData(obj, initData.initData);
632 void SignalProxy::handle(Peer *peer, const RpcCall &rpcCall)
636 SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName);
637 while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) {
638 receiver = (*slot).first;
639 methodId = (*slot).second;
640 if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) {
641 ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
642 qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData());
649 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, QVariant &returnValue, Peer *peer)
651 ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
652 const QList<int> args = eMeta->argTypes(methodId);
653 const int numArgs = params.count() < args.count()
657 if (eMeta->minArgCount(methodId) > params.count()) {
658 qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId);
662 void *_a[] = { 0, // return type...
663 0, 0, 0, 0, 0, // and 10 args - that's the max size qt can handle with signals and slots
666 // check for argument compatibility and build params array
667 for (int i = 0; i < numArgs; i++) {
668 if (!params[i].isValid()) {
669 #if QT_VERSION >= 0x050000
670 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());
672 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());
674 qWarning() << " - make sure all your data types are known by the Qt MetaSystem";
677 if (args[i] != QMetaType::type(params[i].typeName())) {
678 qWarning() << "SignalProxy::invokeSlot(): incompatible param types to invoke" << eMeta->methodName(methodId);
682 _a[i+1] = const_cast<void *>(params[i].constData());
685 if (returnValue.type() != QVariant::Invalid)
686 _a[0] = const_cast<void *>(returnValue.constData());
688 Qt::ConnectionType type = QThread::currentThread() == receiver->thread()
689 ? Qt::DirectConnection
690 : Qt::QueuedConnection;
692 if (type == Qt::DirectConnection) {
694 auto result = receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
695 _sourcePeer = nullptr;
698 qWarning() << "Queued Connections are not implemented yet";
699 // note to self: qmetaobject.cpp:990 ff
705 bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, Peer *peer)
708 return invokeSlot(receiver, methodId, params, ret, peer);
712 void SignalProxy::requestInit(SyncableObject *obj)
714 if (proxyMode() == Server || obj->isInitialized())
717 dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
721 QVariantMap SignalProxy::initData(SyncableObject *obj) const
723 return obj->toVariantMap();
727 void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties)
729 if (obj->isInitialized())
731 obj->fromVariantMap(properties);
732 obj->setInitialized();
733 emit objectInitialized(obj);
734 invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
738 void SignalProxy::customEvent(QEvent *event)
740 switch ((int)event->type()) {
741 case RemovePeerEvent: {
742 ::RemovePeerEvent *e = static_cast< ::RemovePeerEvent *>(event);
749 qWarning() << Q_FUNC_INFO << "Received unknown custom event:" << event->type();
755 void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap)
757 // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
758 if (modeType != _proxyMode)
761 ExtendedMetaObject *eMeta = extendedMetaObject(obj);
765 const QList<int> &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
767 for (int i = 0; i < argTypes.size(); i++) {
768 if (argTypes[i] == 0) {
769 qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
770 qWarning() << " - make sure all your data types are known by the Qt MetaSystem";
773 params << QVariant(argTypes[i], va_arg(ap, void *));
776 if (_restrictMessageTarget) {
777 for (auto peer : _restrictedTargets) {
779 dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
782 dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
786 void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason)
788 if (!reason.isEmpty())
789 qWarning() << qPrintable(reason);
790 QAbstractSocket *sock = qobject_cast<QAbstractSocket *>(dev);
792 qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
797 void SignalProxy::dumpProxyStats()
800 if (proxyMode() == Server)
806 foreach(ObjectId oid, _syncSlave.values())
807 slaveCount += oid.count();
810 qDebug() << " Proxy Mode:" << mode;
811 qDebug() << " attached Slots:" << _attachedSlots.count();
812 qDebug() << " number of synced Slaves:" << slaveCount;
813 qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
817 void SignalProxy::updateSecureState()
819 bool wasSecure = _secure;
821 _secure = !_peerMap.isEmpty();
822 for (auto peer : _peerMap.values()) {
823 _secure &= peer->isSecure();
826 if (wasSecure != _secure)
827 emit secureStateChanged(_secure);
830 QVariantList SignalProxy::peerData() {
832 for (auto &&peer : _peerMap.values()) {
834 data["id"] = peer->id();
835 data["clientVersion"] = peer->clientVersion();
836 // We explicitly rename this, as, due to the Debian reproducability changes, buildDate isn’t actually the build
837 // date anymore, but on newer clients the date of the last git commit
838 data["clientVersionDate"] = peer->buildDate();
839 data["remoteAddress"] = peer->address();
840 data["connectedSince"] = peer->connectedSince();
841 data["secure"] = peer->isSecure();
842 data["features"] = static_cast<quint32>(peer->features().toLegacyFeatures());
843 data["featureList"] = peer->features().toStringList();
849 Peer *SignalProxy::peerById(int peerId) {
850 // We use ::value() here instead of the [] operator because the latter has the side-effect
851 // of automatically inserting a null value with the passed key into the map. See
852 // https://doc.qt.io/qt-5/qhash.html#operator-5b-5d and https://doc.qt.io/qt-5/qhash.html#value.
853 return _peerMap.value(peerId);
856 void SignalProxy::restrictTargetPeers(QSet<Peer*> peers, std::function<void()> closure)
858 auto previousRestrictMessageTarget = _restrictMessageTarget;
859 auto previousRestrictedTargets = _restrictedTargets;
860 _restrictMessageTarget = true;
861 _restrictedTargets = peers;
865 _restrictMessageTarget = previousRestrictMessageTarget;
866 _restrictedTargets = previousRestrictedTargets;
869 Peer *SignalProxy::sourcePeer() {
873 void SignalProxy::setSourcePeer(Peer *sourcePeer) {
874 _sourcePeer = sourcePeer;
877 Peer *SignalProxy::targetPeer() {
881 void SignalProxy::setTargetPeer(Peer *targetPeer) {
882 _targetPeer = targetPeer;
885 // ==================================================
886 // ExtendedMetaObject
887 // ==================================================
888 SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
890 _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
892 for (int i = 0; i < _meta->methodCount(); i++) {
893 if (_meta->method(i).methodType() != QMetaMethod::Slot)
896 #if QT_VERSION >= 0x050000
897 if (_meta->method(i).methodSignature().contains('*'))
899 if (QByteArray(_meta->method(i).signature()).contains('*'))
901 continue; // skip methods with ptr params
903 QByteArray method = methodName(_meta->method(i));
904 if (method.startsWith("init"))
905 continue; // skip initializers
907 if (_methodIds.contains(method)) {
908 /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
909 we don't care... we just need the full fledged version
911 const QMetaMethod ¤t = _meta->method(_methodIds[method]);
912 const QMetaMethod &candidate = _meta->method(i);
913 if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
914 int minCount = candidate.parameterTypes().count();
915 QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
916 if (commonParams == candidate.parameterTypes())
917 continue; // we already got the full featured version
920 int minCount = current.parameterTypes().count();
921 QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
922 if (commonParams == current.parameterTypes()) {
923 _methodIds[method] = i; // use the new one
927 if (checkConflicts) {
928 qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
929 #if QT_VERSION >= 0x050000
930 qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with" << _meta->method(_methodIds[method]).methodSignature();
932 qWarning() << " - " << _meta->method(i).signature() << "conflicts with" << _meta->method(_methodIds[method]).signature();
937 _methodIds[method] = i;
942 const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
944 if (!_methods.contains(methodId)) {
945 _methods[methodId] = MethodDescriptor(_meta->method(methodId));
947 return _methods[methodId];
951 const QHash<int, int> &SignalProxy::ExtendedMetaObject::receiveMap()
953 if (_receiveMap.isEmpty()) {
954 QHash<int, int> receiveMap;
956 QMetaMethod requestSlot;
957 QByteArray returnTypeName;
958 QByteArray signature;
959 QByteArray methodName;
963 const int methodCount = _meta->methodCount();
964 for (int i = 0; i < methodCount; i++) {
965 requestSlot = _meta->method(i);
966 if (requestSlot.methodType() != QMetaMethod::Slot)
969 returnTypeName = requestSlot.typeName();
970 if (QMetaType::Void == (QMetaType::Type)returnType(i))
973 #if QT_VERSION >= 0x050000
974 signature = requestSlot.methodSignature();
976 signature = QByteArray(requestSlot.signature());
978 if (!signature.startsWith("request"))
981 paramsPos = signature.indexOf('(');
985 methodName = signature.left(paramsPos);
986 params = signature.mid(paramsPos);
988 methodName = methodName.replace("request", "receive");
989 params = params.left(params.count() - 1) + ", " + returnTypeName + ")";
991 signature = QMetaObject::normalizedSignature(methodName + params);
992 receiverId = _meta->indexOfSlot(signature);
994 if (receiverId == -1) {
995 signature = QMetaObject::normalizedSignature(methodName + "(" + returnTypeName + ")");
996 receiverId = _meta->indexOfSlot(signature);
999 if (receiverId != -1) {
1000 receiveMap[i] = receiverId;
1003 _receiveMap = receiveMap;
1009 QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method)
1011 #if QT_VERSION >= 0x050000
1012 QByteArray sig(method.methodSignature());
1014 QByteArray sig(method.signature());
1016 return sig.left(sig.indexOf("("));
1020 QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method)
1022 #if QT_VERSION >= 0x050000
1023 QString methodname = QString(method.methodSignature()).section("(", 0, 0);
1025 QString methodname = QString(method.signature()).section("(", 0, 0);
1028 // determine where we have to chop:
1030 if (method.methodType() == QMetaMethod::Slot) {
1031 // we take evertyhing from the first uppercase char if it's slot
1032 upperCharPos = methodname.indexOf(QRegExp("[A-Z]"));
1033 if (upperCharPos == -1)
1035 methodname = methodname.mid(upperCharPos);
1038 // and if it's a signal we discard everything from the last uppercase char
1039 upperCharPos = methodname.lastIndexOf(QRegExp("[A-Z]"));
1040 if (upperCharPos == -1)
1042 methodname = methodname.left(upperCharPos);
1045 methodname[0] = methodname[0].toUpper();
1051 SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method)
1052 : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)),
1053 _returnType(QMetaType::type(method.typeName()))
1055 // determine argTypes
1056 QList<QByteArray> paramTypes = method.parameterTypes();
1057 QList<int> argTypes;
1058 for (int i = 0; i < paramTypes.count(); i++) {
1059 argTypes.append(QMetaType::type(paramTypes[i]));
1061 _argTypes = argTypes;
1063 // determine minArgCount
1064 #if QT_VERSION >= 0x050000
1065 QString signature(method.methodSignature());
1067 QString signature(method.signature());
1069 _minArgCount = method.parameterTypes().count() - signature.count("=");
1071 _receiverMode = (_methodName.startsWith("request"))
1072 ? SignalProxy::Server
1073 : SignalProxy::Client;