1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtDBus module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
43 #include <qcoreapplication.h>
44 #include <qstringlist.h>
47 #include "qdbusconnection.h"
48 #include "qdbusconnectioninterface.h"
49 #include "qdbuserror.h"
50 #include "qdbusmessage.h"
51 #include "qdbusmessage_p.h"
52 #include "qdbusconnection_p.h"
53 #include "qdbusinterface_p.h"
54 #include "qdbusutil_p.h"
55 #include "qdbusconnectionmanager_p.h"
57 #include "qdbusthreaddebug_p.h"
65 Q_GLOBAL_STATIC(QDBusConnectionManager, _q_manager)
67 QDBusConnectionPrivate *QDBusConnectionManager::sender() const
69 QMutexLocker locker(&senderMutex);
70 return connection(senderName);
73 void QDBusConnectionManager::setSender(const QDBusConnectionPrivate *s)
75 QMutexLocker locker(&senderMutex);
76 senderName = (s ? s->name : QString());
79 QDBusConnectionPrivate *QDBusConnectionManager::connection(const QString &name) const
81 return connectionHash.value(name, 0);
84 void QDBusConnectionManager::removeConnection(const QString &name)
86 QDBusConnectionPrivate *d = 0;
87 d = connectionHash.take(name);
88 if (d && !d->ref.deref())
91 // Static objects may be keeping the connection open.
92 // However, it is harmless to have outstanding references to a connection that is
93 // closing as long as those references will be soon dropped without being used.
95 // ### Output a warning if connections are being used after they have been removed.
98 QDBusConnectionManager::~QDBusConnectionManager()
100 for (QHash<QString, QDBusConnectionPrivate *>::const_iterator it = connectionHash.constBegin();
101 it != connectionHash.constEnd(); ++it) {
102 QDBusConnectionPrivate *d = it.value();
106 d->closeConnection();
108 connectionHash.clear();
111 QDBusConnectionManager* QDBusConnectionManager::instance()
116 Q_DBUS_EXPORT void qDBusBindToApplication();
117 void qDBusBindToApplication()
121 void QDBusConnectionManager::setConnection(const QString &name, QDBusConnectionPrivate *c)
123 connectionHash[name] = c;
128 \class QDBusConnection
132 \brief The QDBusConnection class represents a connection to the D-Bus bus daemon.
134 This class is the initial point in a D-Bus session. Using it, you
135 can get access to remote objects, interfaces; connect remote
136 signals to your object's slots; register objects, etc.
138 D-Bus connections are created using the connectToBus() function,
139 which opens a connection to the server daemon and does the initial
140 handshaking, associating that connection with a name. Further
141 attempts to connect using the same name will return the same
144 The connection is then torn down using the disconnectFromBus()
147 Once disconnected, calling connectToBus() will not reestablish a
148 connection, you must create a new QDBusConnection instance.
150 As a convenience for the two most common connection types, the
151 sessionBus() and systemBus() functions return open connections to
152 the session server daemon and the system server daemon,
153 respectively. Those connections are opened when first used and are
154 closed when the QCoreApplication destructor is run.
156 D-Bus also supports peer-to-peer connections, without the need for
157 a bus server daemon. Using this facility, two applications can
158 talk to each other and exchange messages. This can be achieved by
159 passing an address to connectToBus() function, which was opened by
160 another D-Bus application using QDBusServer.
164 \enum QDBusConnection::BusType
165 Specifies the type of the bus connection. The valid bus types are:
167 \value SessionBus the session bus, associated with the running desktop session
168 \value SystemBus the system bus, used to communicate with system-wide processes
169 \value ActivationBus the activation bus, the "alias" for the bus that started the
172 On the Session Bus, one can find other applications by the same user that are sharing the same
173 desktop session (hence the name). On the System Bus, however, processes shared for the whole
174 system are usually found.
178 \enum QDBusConnection::RegisterOption
179 Specifies the options for registering objects with the connection. The possible values are:
181 \value ExportAdaptors export the contents of adaptors found in this object
183 \value ExportScriptableSlots export this object's scriptable slots
184 \value ExportScriptableSignals export this object's scriptable signals
185 \value ExportScriptableProperties export this object's scriptable properties
186 \value ExportScriptableInvokables export this object's scriptable invokables
187 \value ExportScriptableContents shorthand form for ExportScriptableSlots |
188 ExportScriptableSignals |
189 ExportScriptableProperties
191 \value ExportNonScriptableSlots export this object's non-scriptable slots
192 \value ExportNonScriptableSignals export this object's non-scriptable signals
193 \value ExportNonScriptableProperties export this object's non-scriptable properties
194 \value ExportNonScriptableInvokables export this object's non-scriptable invokables
195 \value ExportNonScriptableContents shorthand form for ExportNonScriptableSlots |
196 ExportNonScriptableSignals |
197 ExportNonScriptableProperties
199 \value ExportAllSlots export all of this object's slots
200 \value ExportAllSignals export all of this object's signals
201 \value ExportAllProperties export all of this object's properties
202 \value ExportAllInvokables export all of this object's invokables
203 \value ExportAllContents export all of this object's contents
204 \value ExportChildObjects export this object's child objects
206 \sa registerObject(), QDBusAbstractAdaptor, {usingadaptors.html}{Using adaptors}
212 \enum QDBusConnection::VirtualObjectRegisterOption
213 Specifies the options for registering virtual objects with the connection. The possible values are:
215 \value SingleNode register a virtual object to handle one path only
216 \value SubPath register a virtual object so that it handles all sub paths
218 \sa registerVirtualObject(), QDBusVirtualObject
222 \enum QDBusConnection::UnregisterMode
223 The mode for unregistering an object path:
225 \value UnregisterNode unregister this node only: do not unregister child objects
226 \value UnregisterTree unregister this node and all its sub-tree
228 Note, however, if this object was registered with the ExportChildObjects option, UnregisterNode
229 will unregister the child objects too.
234 \enum QDBusConnection::ConnectionCapability
236 This enum describes the available capabilities for a D-Bus connection.
238 \value UnixFileDescriptorPassing enables passing of Unix file descriptors to other processes
239 (see QDBusUnixFileDescriptor)
241 \sa connectionCapabilities()
245 Creates a QDBusConnection object attached to the connection with name \a name.
247 This does not open the connection. You have to call connectToBus() to open it.
249 QDBusConnection::QDBusConnection(const QString &name)
251 if (name.isEmpty()) {
254 QMutexLocker locker(&_q_manager()->mutex);
255 d = _q_manager()->connection(name);
262 Creates a copy of the \a other connection.
264 QDBusConnection::QDBusConnection(const QDBusConnection &other)
273 Creates a connection object with the given \a dd as private object.
275 QDBusConnection::QDBusConnection(QDBusConnectionPrivate *dd)
283 Disposes of this object. This does not close the connection: you
284 have to call disconnectFromBus() to do that.
286 QDBusConnection::~QDBusConnection()
288 if (d && !d->ref.deref())
293 Creates a copy of the connection \a other in this object. Note
294 that the connection this object referenced before the copy, is not
295 spontaneously disconnected.
297 \sa disconnectFromBus()
299 QDBusConnection &QDBusConnection::operator=(const QDBusConnection &other)
303 if (d && !d->ref.deref())
310 Opens a connection of type \a type to one of the known busses and
311 associate with it the connection name \a name. Returns a
312 QDBusConnection object associated with that connection.
314 QDBusConnection QDBusConnection::connectToBus(BusType type, const QString &name)
316 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
317 // "Cannot create connection without a Q[Core]Application instance");
318 if (!qdbus_loadLibDBus()) {
319 QDBusConnectionPrivate *d = 0;
320 return QDBusConnection(d);
323 QMutexLocker locker(&_q_manager()->mutex);
325 QDBusConnectionPrivate *d = _q_manager()->connection(name);
326 if (d || name.isEmpty())
327 return QDBusConnection(d);
329 d = new QDBusConnectionPrivate;
330 DBusConnection *c = 0;
331 QDBusErrorInternal error;
334 c = q_dbus_bus_get_private(DBUS_BUS_SYSTEM, error);
337 c = q_dbus_bus_get_private(DBUS_BUS_SESSION, error);
340 c = q_dbus_bus_get_private(DBUS_BUS_STARTER, error);
343 d->setConnection(c, error); //setConnection does the error handling for us
345 _q_manager()->setConnection(name, d);
347 QDBusConnection retval(d);
349 // create the bus service
350 // will lock in QDBusConnectionPrivate::connectRelay()
351 d->setBusService(retval);
357 Opens a connection to a private bus on address \a address and associate with it the
358 connection name \a name. Returns a QDBusConnection object associated with that connection.
360 QDBusConnection QDBusConnection::connectToBus(const QString &address,
363 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
364 // "Cannot create connection without a Q[Core]Application instance");
365 if (!qdbus_loadLibDBus()) {
366 QDBusConnectionPrivate *d = 0;
367 return QDBusConnection(d);
370 QMutexLocker locker(&_q_manager()->mutex);
372 QDBusConnectionPrivate *d = _q_manager()->connection(name);
373 if (d || name.isEmpty())
374 return QDBusConnection(d);
376 d = new QDBusConnectionPrivate;
377 // setConnection does the error handling for us
378 QDBusErrorInternal error;
379 DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
381 if (!q_dbus_bus_register(c, error)) {
382 q_dbus_connection_unref(c);
386 d->setConnection(c, error);
387 _q_manager()->setConnection(name, d);
389 QDBusConnection retval(d);
391 // create the bus service
392 // will lock in QDBusConnectionPrivate::connectRelay()
393 d->setBusService(retval);
400 Opens a peer-to-peer connection on address \a address and associate with it the
401 connection name \a name. Returns a QDBusConnection object associated with that connection.
403 QDBusConnection QDBusConnection::connectToPeer(const QString &address,
406 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
407 // "Cannot create connection without a Q[Core]Application instance");
408 if (!qdbus_loadLibDBus()) {
409 QDBusConnectionPrivate *d = 0;
410 return QDBusConnection(d);
413 QMutexLocker locker(&_q_manager()->mutex);
415 QDBusConnectionPrivate *d = _q_manager()->connection(name);
416 if (d || name.isEmpty())
417 return QDBusConnection(d);
419 d = new QDBusConnectionPrivate;
420 // setPeer does the error handling for us
421 QDBusErrorInternal error;
422 DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
424 d->setPeer(c, error);
425 _q_manager()->setConnection(name, d);
427 QDBusConnection retval(d);
433 Closes the bus connection of name \a name.
435 Note that if there are still QDBusConnection objects associated
436 with the same connection, the connection will not be closed until
437 all references are dropped. However, no further references can be
438 created using the QDBusConnection constructor.
440 void QDBusConnection::disconnectFromBus(const QString &name)
443 QMutexLocker locker(&_q_manager()->mutex);
444 QDBusConnectionPrivate *d = _q_manager()->connection(name);
445 if (d && d->mode != QDBusConnectionPrivate::ClientMode)
447 _q_manager()->removeConnection(name);
454 Closes the peer connection of name \a name.
456 Note that if there are still QDBusConnection objects associated
457 with the same connection, the connection will not be closed until
458 all references are dropped. However, no further references can be
459 created using the QDBusConnection constructor.
461 void QDBusConnection::disconnectFromPeer(const QString &name)
464 QMutexLocker locker(&_q_manager()->mutex);
465 QDBusConnectionPrivate *d = _q_manager()->connection(name);
466 if (d && d->mode != QDBusConnectionPrivate::PeerMode)
468 _q_manager()->removeConnection(name);
473 Sends the \a message over this connection, without waiting for a
474 reply. This is suitable for errors, signals, and return values as
475 well as calls whose return values are not necessary.
477 Returns true if the message was queued successfully, false otherwise.
479 bool QDBusConnection::send(const QDBusMessage &message) const
481 if (!d || !d->connection) {
482 QDBusError err = QDBusError(QDBusError::Disconnected,
483 QLatin1String("Not connected to D-BUS server"));
488 return d->send(message) != 0;
492 Sends the \a message over this connection and returns immediately.
493 When the reply is received, the method \a returnMethod is called in
494 the \a receiver object. If an error occurs, the method \a errorMethod
495 will be called instead.
497 If no reply is received within \a timeout milliseconds, an automatic
498 error will be delivered indicating the expiration of the call.
499 The default \a timeout is -1, which will be replaced with an
500 implementation-defined value that is suitable for inter-process
501 communications (generally, 25 seconds).
503 This function is suitable for method calls only. It is guaranteed
504 that the slot will be called exactly once with the reply, as long
505 as the parameter types match and no error occurs.
507 Returns true if the message was sent, or false if the message could
510 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
511 const char *returnMethod, const char *errorMethod,
514 if (!d || !d->connection) {
515 QDBusError err = QDBusError(QDBusError::Disconnected,
516 QLatin1String("Not connected to D-BUS server"));
521 return d->sendWithReplyAsync(message, receiver, returnMethod, errorMethod, timeout) != 0;
527 Sends the \a message over this connection and returns immediately.
528 When the reply is received, the method \a returnMethod is called in
529 the \a receiver object.
531 This function is suitable for method calls only. It is guaranteed
532 that the slot will be called exactly once with the reply, as long
533 as the parameter types match and no error occurs.
535 This function is dangerous because it cannot report errors, including
536 the expiration of the timeout.
538 Returns true if the message was sent, or false if the message could
541 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
542 const char *returnMethod, int timeout) const
544 return callWithCallback(message, receiver, returnMethod, 0, timeout);
548 Sends the \a message over this connection and blocks, waiting for
549 a reply, for at most \a timeout milliseconds. This function is
550 suitable for method calls only. It returns the reply message as
551 its return value, which will be either of type
552 QDBusMessage::ReplyMessage or QDBusMessage::ErrorMessage.
554 If no reply is received within \a timeout milliseconds, an automatic
555 error will be delivered indicating the expiration of the call.
556 The default \a timeout is -1, which will be replaced with an
557 implementation-defined value that is suitable for inter-process
558 communications (generally, 25 seconds).
560 See the QDBusInterface::call() function for a more friendly way
563 \warning If \a mode is QDBus::BlockWithGui, this function will
564 reenter the Qt event loop in order to wait for the
565 reply. During the wait, it may deliver signals and other
566 method calls to your application. Therefore, it must be
567 prepared to handle a reentrancy whenever a call is
570 QDBusMessage QDBusConnection::call(const QDBusMessage &message, QDBus::CallMode mode, int timeout) const
572 if (!d || !d->connection) {
573 QDBusError err = QDBusError(QDBusError::Disconnected,
574 QLatin1String("Not connected to D-Bus server"));
578 return QDBusMessage::createError(err);
581 if (mode != QDBus::NoBlock)
582 return d->sendWithReply(message, mode, timeout);
586 retval << QVariant(); // add one argument (to avoid .at(0) problems)
592 Sends the \a message over this connection and returns
593 immediately. This function is suitable for method calls only. It
594 returns an object of type QDBusPendingCall which can be used to
595 track the status of the reply.
597 If no reply is received within \a timeout milliseconds, an automatic
598 error will be delivered indicating the expiration of the call. The
599 default \a timeout is -1, which will be replaced with an
600 implementation-defined value that is suitable for inter-process
601 communications (generally, 25 seconds). This timeout is also the
602 upper limit for waiting in QDBusPendingCall::waitForFinished().
604 See the QDBusInterface::asyncCall() function for a more friendly way
607 QDBusPendingCall QDBusConnection::asyncCall(const QDBusMessage &message, int timeout) const
609 if (!d || !d->connection) {
610 return QDBusPendingCall(0); // null pointer -> disconnected
613 QDBusPendingCallPrivate *priv = d->sendWithReplyAsync(message, timeout);
614 return QDBusPendingCall(priv);
618 Connects the signal specified by the \a service, \a path, \a interface and \a name parameters to
619 the slot \a slot in object \a receiver. The arguments \a service and \a path can be empty,
620 denoting a connection to any signal of the (\a interface, \a name) pair, from any remote
623 Returns true if the connection was successful.
625 \warning The signal will only be delivered to the slot if the parameters match. This verification
626 can be done only when the signal is received, not at connection time.
628 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
629 const QString &name, QObject *receiver, const char *slot)
631 return connect(service, path, interface, name, QStringList(), QString(), receiver, slot);
637 Connects the signal to the slot \a slot in object \a
638 receiver. Unlike the previous connect() overload, this function
639 allows one to specify the parameter signature to be connected
640 using the \a signature variable. The function will then verify
641 that this signature can be delivered to the slot specified by \a
642 slot and return false otherwise.
644 Returns true if the connection was successful.
646 \note This function verifies that the signal signature matches the
647 slot's parameters, but it does not verify that the actual
648 signal exists with the given signature in the remote
651 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
652 const QString &name, const QString &signature,
653 QObject *receiver, const char *slot)
655 return connect(service, path, interface, name, QStringList(), signature, receiver, slot);
662 Connects the signal to the slot \a slot in object \a
663 receiver. Unlike the previous connect() overload, this function
664 allows one to specify the parameter signature to be connected
665 using the \a signature variable. The function will then verify
666 that this signature can be delivered to the slot specified by \a
667 slot and return false otherwise.
669 The \a argumentMatch parameter lists the string parameters to be matched,
670 in sequential order. Note that, to match an empty string, you need to
671 pass a QString that is empty but not null (i.e., QString("")). A null
672 QString skips matching at that position.
674 Returns true if the connection was successful.
676 \note This function verifies that the signal signature matches the
677 slot's parameters, but it does not verify that the actual
678 signal exists with the given signature in the remote
681 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
682 const QString &name, const QStringList &argumentMatch, const QString &signature,
683 QObject *receiver, const char *slot)
686 if (!receiver || !slot || !d || !d->connection)
688 if (interface.isEmpty() && name.isEmpty())
690 if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface)) {
692 qWarning("QDBusConnection::connect: interface name '%s' is not valid", interface.toLatin1().constData());
696 if (!service.isEmpty() && !QDBusUtil::isValidBusName(service)) {
698 qWarning("QDBusConnection::connect: service name '%s' is not valid", service.toLatin1().constData());
702 if (!path.isEmpty() && !QDBusUtil::isValidObjectPath(path)) {
704 qWarning("QDBusConnection::connect: object path '%s' is not valid", path.toLatin1().constData());
709 QDBusWriteLocker locker(ConnectAction, d);
710 return d->connectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
714 Disconnects the signal specified by the \a service, \a path, \a interface
715 and \a name parameters from the slot \a slot in object \a receiver. The
716 arguments must be the same as passed to the connect() function.
718 Returns true if the disconnection was successful.
720 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString &interface,
721 const QString &name, QObject *receiver, const char *slot)
723 return disconnect(service, path, interface, name, QStringList(), QString(), receiver, slot);
729 Disconnects the signal specified by the \a service, \a path, \a
730 interface, \a name, and \a signature parameters from the slot \a slot in
731 object \a receiver. The arguments must be the same as passed to the
734 Returns true if the disconnection was successful.
736 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
737 const QString &name, const QString &signature,
738 QObject *receiver, const char *slot)
740 return disconnect(service, path, interface, name, QStringList(), signature, receiver, slot);
747 Disconnects the signal specified by the \a service, \a path, \a
748 interface, \a name, \a argumentMatch, and \a signature parameters from
749 the slot \a slot in object \a receiver. The arguments must be the same as
750 passed to the connect() function.
752 Returns true if the disconnection was successful.
754 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
755 const QString &name, const QStringList &argumentMatch, const QString &signature,
756 QObject *receiver, const char *slot)
758 if (!receiver || !slot || !d || !d->connection)
760 if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface))
762 if (interface.isEmpty() && name.isEmpty())
765 QDBusWriteLocker locker(DisconnectAction, d);
766 return d->disconnectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
770 Registers the object \a object at path \a path and returns true if
771 the registration was successful. The \a options parameter
772 specifies how much of the object \a object will be exposed through
775 This function does not replace existing objects: if there is already an object registered at
776 path \a path, this function will return false. Use unregisterObject() to unregister it first.
778 You cannot register an object as a child object of an object that
779 was registered with QDBusConnection::ExportChildObjects.
781 bool QDBusConnection::registerObject(const QString &path, QObject *object, RegisterOptions options)
783 Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registerObject",
784 "Invalid object path given");
785 if (!d || !d->connection || !object || !options || !QDBusUtil::isValidObjectPath(path))
788 QStringList pathComponents = path.split(QLatin1Char('/'));
789 if (pathComponents.last().isEmpty())
790 pathComponents.removeLast();
791 QDBusWriteLocker locker(RegisterObjectAction, d);
793 // lower-bound search for where this object should enter in the tree
794 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator node = &d->rootNode;
797 if (pathComponents.count() == i) {
799 // consider it free if there's no object here and the user is not trying to
800 // replace the object sub-tree
804 if (options & QDBusConnectionPrivate::VirtualObject) {
805 // technically the check for children needs to go even deeper
806 if (options & SubPath) {
807 foreach (const QDBusConnectionPrivate::ObjectTreeNode &child, node->children) {
813 if ((options & ExportChildObjects && !node->children.isEmpty()))
816 // we can add the object here
818 node->flags = options;
820 d->registerObject(node);
821 //qDebug("REGISTERED FOR %s", path.toLocal8Bit().constData());
825 // if a virtual object occupies this path, return false
826 if (node->obj && (node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath)) {
827 qDebug("Cannot register object at %s because QDBusVirtualObject handles all sub-paths.",
832 // find the position where we'd insert the node
833 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
834 std::lower_bound(node->children.begin(), node->children.end(), pathComponents.at(i));
835 if (it != node->children.end() && it->name == pathComponents.at(i)) {
836 // match: this node exists
839 // are we allowed to go deeper?
840 if (node->flags & ExportChildObjects) {
842 qDebug("Cannot register object at %s because %s exports its own child objects",
843 qPrintable(path), qPrintable(pathComponents.at(i)));
848 node = node->children.insert(it, pathComponents.at(i));
855 Q_ASSERT_X(false, "QDBusConnection::registerObject", "The impossible happened");
862 Registers a QDBusTreeNode for a path. It can handle a path including all child paths, thus
863 handling multiple DBus nodes.
865 To unregister a QDBusTreeNode use the unregisterObject() function with its path.
867 bool QDBusConnection::registerVirtualObject(const QString &path, QDBusVirtualObject *treeNode,
868 VirtualObjectRegisterOption options)
870 int opts = options | QDBusConnectionPrivate::VirtualObject;
871 return registerObject(path, (QObject*) treeNode, (RegisterOptions) opts);
875 Unregisters an object that was registered with the registerObject() at the object path given by
876 \a path and, if \a mode is QDBusConnection::UnregisterTree, all of its sub-objects too.
878 Note that you cannot unregister objects that were not registered with registerObject().
880 void QDBusConnection::unregisterObject(const QString &path, UnregisterMode mode)
882 if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
885 QStringList pathComponents = path.split(QLatin1Char('/'));
886 QDBusWriteLocker locker(UnregisterObjectAction, d);
887 QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
892 if (pathComponents.count() == i || !path.compare(QLatin1String("/"))) {
897 if (mode == UnregisterTree) {
898 // clear the sub-tree as well
899 node->children.clear(); // can't disconnect the objects because we really don't know if they can
900 // be found somewhere else in the path too
906 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
907 std::lower_bound(node->children.begin(), node->children.end(), pathComponents.at(i));
908 if (it == node->children.end() || it->name != pathComponents.at(i))
909 break; // node not found
917 Return the object that was registered with the registerObject() at the object path given by
920 QObject *QDBusConnection::objectRegisteredAt(const QString &path) const
922 Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registeredObject",
923 "Invalid object path given");
924 if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
927 QStringList pathComponents = path.split(QLatin1Char('/'));
928 if (pathComponents.last().isEmpty())
929 pathComponents.removeLast();
931 // lower-bound search for where this object should enter in the tree
932 QDBusReadLocker lock(ObjectRegisteredAtAction, d);
933 const QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
937 if (pathComponents.count() == i)
939 if ((node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath))
942 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
943 std::lower_bound(node->children.constBegin(), node->children.constEnd(), pathComponents.at(i));
944 if (it == node->children.constEnd() || it->name != pathComponents.at(i))
945 break; // node not found
956 Returns a QDBusConnectionInterface object that represents the
957 D-Bus server interface on this connection.
959 QDBusConnectionInterface *QDBusConnection::interface() const
963 return d->busService;
970 Returns the internal, implementation-defined pointer for this
971 connection. Currently, this returns a DBusConnection* pointer,
972 without changing the reference count. It is the responsibility of
973 the caller to call dbus_connection_ref if it wants to store the
976 void *QDBusConnection::internalPointer() const
978 return d ? d->connection : 0;
982 Returns true if this QDBusConnection object is connected.
984 bool QDBusConnection::isConnected() const
986 return d && d->connection && q_dbus_connection_get_is_connected(d->connection);
990 Returns the last error that happened in this connection.
992 This function is provided for low-level code. If you're using
993 QDBusInterface::call(), error codes are reported by its return
996 \sa QDBusInterface, QDBusMessage
998 QDBusError QDBusConnection::lastError() const
1000 return d ? d->lastError : QDBusError();
1004 Returns the unique connection name for this connection, if this QDBusConnection object is
1005 connected, or an empty QString otherwise.
1007 A Unique Connection Name is a string in the form ":x.xxx" (where x
1008 are decimal digits) that is assigned by the D-Bus server daemon
1009 upon connection. It uniquely identifies this client in the bus.
1011 This function returns an empty QString for peer-to-peer connections.
1013 QString QDBusConnection::baseService() const
1015 return d ? d->baseService : QString();
1021 Returns the connection name for this connection, as given as the
1022 name parameter to connectToBus().
1024 The connection name can be used to uniquely identify actual
1025 underlying connections to buses. Copies made from a single
1026 connection will always implicitly share the underlying connection,
1027 and hence will have the same connection name.
1029 Inversely, two connections having different connection names will
1030 always either be connected to different buses, or have a different
1031 unique name (as returned by baseService()) on that bus.
1033 \sa connectToBus(), disconnectFromBus()
1035 QString QDBusConnection::name() const
1037 return d ? d->name : QString();
1043 Returns the capabilities of this connection as negotiated with the bus
1044 server or peer. If this QDBusConnection is not connected, this function
1045 returns no capabilities.
1047 QDBusConnection::ConnectionCapabilities QDBusConnection::connectionCapabilities() const
1049 return d ? d->capabilities : ConnectionCapabilities(0);
1053 Attempts to register the \a serviceName on the D-Bus server and
1054 returns true if the registration succeeded. The registration will
1055 fail if the name is already registered by another application.
1057 \sa unregisterService(), QDBusConnectionInterface::registerService()
1059 bool QDBusConnection::registerService(const QString &serviceName)
1061 if (interface() && interface()->registerService(serviceName)) {
1062 if (d) d->registerService(serviceName);
1069 Unregisters the service \a serviceName that was previously
1070 registered with registerService() and returns true if it
1073 \sa registerService(), QDBusConnectionInterface::unregisterService()
1075 bool QDBusConnection::unregisterService(const QString &serviceName)
1077 if (interface()->unregisterService(serviceName)) {
1078 if (d) d->unregisterService(serviceName);
1084 static const char _q_sessionBusName[] = "qt_default_session_bus";
1085 static const char _q_systemBusName[] = "qt_default_system_bus";
1087 class QDBusDefaultConnection: public QDBusConnection
1089 const char *ownName;
1091 inline QDBusDefaultConnection(BusType type, const char *name)
1092 : QDBusConnection(connectToBus(type, QString::fromLatin1(name))), ownName(name)
1094 // make sure this connection is running on the main thread
1095 QCoreApplication *instance = QCoreApplication::instance();
1097 qWarning("QDBusConnection: %s D-Bus connection created before QCoreApplication. Application may misbehave.",
1098 type == SessionBus ? "session" : type == SystemBus ? "system" : "generic");
1099 } else if (QDBusConnectionPrivate::d(*this)) {
1100 QDBusConnectionPrivate::d(*this)->moveToThread(instance->thread());
1104 inline ~QDBusDefaultConnection()
1105 { disconnectFromBus(QString::fromLatin1(ownName)); }
1108 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_sessionBus,
1109 (QDBusConnection::SessionBus, _q_sessionBusName))
1110 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_systemBus,
1111 (QDBusConnection::SystemBus, _q_systemBusName))
1114 \fn QDBusConnection QDBusConnection::sessionBus()
1116 Returns a QDBusConnection object opened with the session bus. The object
1117 reference returned by this function is valid until the application terminates,
1118 at which point the connection will be closed and the object deleted.
1120 QDBusConnection QDBusConnection::sessionBus()
1122 return *_q_sessionBus();
1126 \fn QDBusConnection QDBusConnection::systemBus()
1128 Returns a QDBusConnection object opened with the system bus. The object reference returned
1129 by this function is valid until the QCoreApplication's destructor is run, when the
1130 connection will be closed and the object, deleted.
1132 QDBusConnection QDBusConnection::systemBus()
1134 return *_q_systemBus();
1140 Returns the connection that sent the signal, if called in a slot activated
1141 by QDBus; otherwise it returns 0.
1143 \note Please avoid this function. This function is not thread-safe, so if
1144 there's any other thread delivering a D-Bus call, this function may return
1145 the wrong connection. In new code, please use QDBusContext::connection()
1146 (see that class for a description on how to use it).
1148 QDBusConnection QDBusConnection::sender()
1150 return QDBusConnection(_q_manager()->sender());
1156 void QDBusConnectionPrivate::setSender(const QDBusConnectionPrivate *s)
1158 _q_manager()->setSender(s);
1164 void QDBusConnectionPrivate::setBusService(const QDBusConnection &connection)
1166 busService = new QDBusConnectionInterface(connection, this);
1167 ref.deref(); // busService has increased the refcounting to us
1168 // avoid cyclic refcounting
1170 QObject::connect(this, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1171 busService, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1172 Qt::QueuedConnection);
1177 Returns the local machine ID as known to the D-Bus system. Each
1178 node or host that runs D-Bus has a unique identifier that can be
1179 used to distinguish it from other hosts if they are sharing
1180 resources like the filesystem.
1182 Note that the local machine ID is not guaranteed to be persistent
1183 across boots of the system, so this identifier should not be
1184 stored in persistent storage (like the filesystem). It is
1185 guaranteed to remain constant only during the lifetime of this
1188 QByteArray QDBusConnection::localMachineId()
1190 char *dbus_machine_id = q_dbus_get_local_machine_id();
1191 QByteArray result = dbus_machine_id;
1192 q_dbus_free(dbus_machine_id);
1200 \brief The QDBus namespace contains miscellaneous identifiers used
1201 throughout the QtDBus library.
1205 \enum QDBus::CallMode
1207 This enum describes the various ways of placing a function call. The valid modes are:
1209 \value NoBlock Place the call but don't wait for the reply (the reply's contents
1211 \value Block Don't use an event loop to wait for a reply, but instead block on
1212 network operations while waiting. This means the
1213 user-interface may not be updated until the function returns.
1214 \value BlockWithGui Use the Qt event loop to wait for a reply. This means that the
1215 user-interface will stay responsive (processing input events),
1216 but it also means other events may happen, like signal delivery
1217 and other D-Bus method calls.
1218 \value AutoDetect Automatically detect if the called function has a reply.
1220 When using BlockWithGui, applications must be prepared for reentrancy in any function.
1225 #endif // QT_NO_DBUS