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"
63 Q_GLOBAL_STATIC(QDBusConnectionManager, _q_manager)
65 QDBusConnectionPrivate *QDBusConnectionManager::sender() const
67 QMutexLocker locker(&senderMutex);
68 return connection(senderName);
71 void QDBusConnectionManager::setSender(const QDBusConnectionPrivate *s)
73 QMutexLocker locker(&senderMutex);
74 senderName = (s ? s->name : QString());
77 QDBusConnectionPrivate *QDBusConnectionManager::connection(const QString &name) const
79 return connectionHash.value(name, 0);
82 void QDBusConnectionManager::removeConnection(const QString &name)
84 QDBusConnectionPrivate *d = 0;
85 d = connectionHash.take(name);
86 if (d && !d->ref.deref())
89 // Static objects may be keeping the connection open.
90 // However, it is harmless to have outstanding references to a connection that is
91 // closing as long as those references will be soon dropped without being used.
93 // ### Output a warning if connections are being used after they have been removed.
96 QDBusConnectionManager::~QDBusConnectionManager()
98 for (QHash<QString, QDBusConnectionPrivate *>::const_iterator it = connectionHash.constBegin();
99 it != connectionHash.constEnd(); ++it) {
100 QDBusConnectionPrivate *d = it.value();
104 d->closeConnection();
106 connectionHash.clear();
109 QDBusConnectionManager* QDBusConnectionManager::instance()
114 Q_DBUS_EXPORT void qDBusBindToApplication();
115 void qDBusBindToApplication()
119 void QDBusConnectionManager::setConnection(const QString &name, QDBusConnectionPrivate *c)
121 connectionHash[name] = c;
126 \class QDBusConnection
130 \brief The QDBusConnection class represents a connection to the D-Bus bus daemon.
132 This class is the initial point in a D-Bus session. Using it, you
133 can get access to remote objects, interfaces; connect remote
134 signals to your object's slots; register objects, etc.
136 D-Bus connections are created using the connectToBus() function,
137 which opens a connection to the server daemon and does the initial
138 handshaking, associating that connection with a name. Further
139 attempts to connect using the same name will return the same
142 The connection is then torn down using the disconnectFromBus()
145 Once disconnected, calling connectToBus() will not reestablish a
146 connection, you must create a new QDBusConnection instance.
148 As a convenience for the two most common connection types, the
149 sessionBus() and systemBus() functions return open connections to
150 the session server daemon and the system server daemon,
151 respectively. Those connections are opened when first used and are
152 closed when the QCoreApplication destructor is run.
154 D-Bus also supports peer-to-peer connections, without the need for
155 a bus server daemon. Using this facility, two applications can
156 talk to each other and exchange messages. This can be achieved by
157 passing an address to connectToBus() function, which was opened by
158 another D-Bus application using QDBusServer.
162 \enum QDBusConnection::BusType
163 Specifies the type of the bus connection. The valid bus types are:
165 \value SessionBus the session bus, associated with the running desktop session
166 \value SystemBus the system bus, used to communicate with system-wide processes
167 \value ActivationBus the activation bus, the "alias" for the bus that started the
170 On the Session Bus, one can find other applications by the same user that are sharing the same
171 desktop session (hence the name). On the System Bus, however, processes shared for the whole
172 system are usually found.
176 \enum QDBusConnection::RegisterOption
177 Specifies the options for registering objects with the connection. The possible values are:
179 \value ExportAdaptors export the contents of adaptors found in this object
181 \value ExportScriptableSlots export this object's scriptable slots
182 \value ExportScriptableSignals export this object's scriptable signals
183 \value ExportScriptableProperties export this object's scriptable properties
184 \value ExportScriptableInvokables export this object's scriptable invokables
185 \value ExportScriptableContents shorthand form for ExportScriptableSlots |
186 ExportScriptableSignals |
187 ExportScriptableProperties
189 \value ExportNonScriptableSlots export this object's non-scriptable slots
190 \value ExportNonScriptableSignals export this object's non-scriptable signals
191 \value ExportNonScriptableProperties export this object's non-scriptable properties
192 \value ExportNonScriptableInvokables export this object's non-scriptable invokables
193 \value ExportNonScriptableContents shorthand form for ExportNonScriptableSlots |
194 ExportNonScriptableSignals |
195 ExportNonScriptableProperties
197 \value ExportAllSlots export all of this object's slots
198 \value ExportAllSignals export all of this object's signals
199 \value ExportAllProperties export all of this object's properties
200 \value ExportAllInvokables export all of this object's invokables
201 \value ExportAllContents export all of this object's contents
202 \value ExportChildObjects export this object's child objects
204 \sa registerObject(), QDBusAbstractAdaptor, {usingadaptors.html}{Using adaptors}
210 \enum QDBusConnection::VirtualObjectRegisterOption
211 Specifies the options for registering virtual objects with the connection. The possible values are:
213 \value SingleNode register a virtual object to handle one path only
214 \value SubPath register a virtual object so that it handles all sub paths
216 \sa registerVirtualObject(), QDBusVirtualObject
220 \enum QDBusConnection::UnregisterMode
221 The mode for unregistering an object path:
223 \value UnregisterNode unregister this node only: do not unregister child objects
224 \value UnregisterTree unregister this node and all its sub-tree
226 Note, however, if this object was registered with the ExportChildObjects option, UnregisterNode
227 will unregister the child objects too.
232 \enum QDBusConnection::ConnectionCapability
234 This enum describes the available capabilities for a D-Bus connection.
236 \value UnixFileDescriptorPassing enables passing of Unix file descriptors to other processes
237 (see QDBusUnixFileDescriptor)
239 \sa connectionCapabilities()
243 Creates a QDBusConnection object attached to the connection with name \a name.
245 This does not open the connection. You have to call connectToBus() to open it.
247 QDBusConnection::QDBusConnection(const QString &name)
249 if (name.isEmpty()) {
252 QMutexLocker locker(&_q_manager()->mutex);
253 d = _q_manager()->connection(name);
260 Creates a copy of the \a other connection.
262 QDBusConnection::QDBusConnection(const QDBusConnection &other)
271 Creates a connection object with the given \a dd as private object.
273 QDBusConnection::QDBusConnection(QDBusConnectionPrivate *dd)
281 Disposes of this object. This does not close the connection: you
282 have to call disconnectFromBus() to do that.
284 QDBusConnection::~QDBusConnection()
286 if (d && !d->ref.deref())
291 Creates a copy of the connection \a other in this object. Note
292 that the connection this object referenced before the copy, is not
293 spontaneously disconnected.
295 \sa disconnectFromBus()
297 QDBusConnection &QDBusConnection::operator=(const QDBusConnection &other)
301 if (d && !d->ref.deref())
308 Opens a connection of type \a type to one of the known busses and
309 associate with it the connection name \a name. Returns a
310 QDBusConnection object associated with that connection.
312 QDBusConnection QDBusConnection::connectToBus(BusType type, const QString &name)
314 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
315 // "Cannot create connection without a Q[Core]Application instance");
316 if (!qdbus_loadLibDBus()) {
317 QDBusConnectionPrivate *d = 0;
318 return QDBusConnection(d);
321 QMutexLocker locker(&_q_manager()->mutex);
323 QDBusConnectionPrivate *d = _q_manager()->connection(name);
324 if (d || name.isEmpty())
325 return QDBusConnection(d);
327 d = new QDBusConnectionPrivate;
328 DBusConnection *c = 0;
329 QDBusErrorInternal error;
332 c = q_dbus_bus_get_private(DBUS_BUS_SYSTEM, error);
335 c = q_dbus_bus_get_private(DBUS_BUS_SESSION, error);
338 c = q_dbus_bus_get_private(DBUS_BUS_STARTER, error);
341 d->setConnection(c, error); //setConnection does the error handling for us
343 _q_manager()->setConnection(name, d);
345 QDBusConnection retval(d);
347 // create the bus service
348 // will lock in QDBusConnectionPrivate::connectRelay()
349 d->setBusService(retval);
355 Opens a connection to a private bus on address \a address and associate with it the
356 connection name \a name. Returns a QDBusConnection object associated with that connection.
358 QDBusConnection QDBusConnection::connectToBus(const QString &address,
361 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
362 // "Cannot create connection without a Q[Core]Application instance");
363 if (!qdbus_loadLibDBus()) {
364 QDBusConnectionPrivate *d = 0;
365 return QDBusConnection(d);
368 QMutexLocker locker(&_q_manager()->mutex);
370 QDBusConnectionPrivate *d = _q_manager()->connection(name);
371 if (d || name.isEmpty())
372 return QDBusConnection(d);
374 d = new QDBusConnectionPrivate;
375 // setConnection does the error handling for us
376 QDBusErrorInternal error;
377 DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
379 if (!q_dbus_bus_register(c, error)) {
380 q_dbus_connection_unref(c);
384 d->setConnection(c, error);
385 _q_manager()->setConnection(name, d);
387 QDBusConnection retval(d);
389 // create the bus service
390 // will lock in QDBusConnectionPrivate::connectRelay()
391 d->setBusService(retval);
398 Opens a peer-to-peer connection on address \a address and associate with it the
399 connection name \a name. Returns a QDBusConnection object associated with that connection.
401 QDBusConnection QDBusConnection::connectToPeer(const QString &address,
404 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
405 // "Cannot create connection without a Q[Core]Application instance");
406 if (!qdbus_loadLibDBus()) {
407 QDBusConnectionPrivate *d = 0;
408 return QDBusConnection(d);
411 QMutexLocker locker(&_q_manager()->mutex);
413 QDBusConnectionPrivate *d = _q_manager()->connection(name);
414 if (d || name.isEmpty())
415 return QDBusConnection(d);
417 d = new QDBusConnectionPrivate;
418 // setPeer does the error handling for us
419 QDBusErrorInternal error;
420 DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
422 d->setPeer(c, error);
423 _q_manager()->setConnection(name, d);
425 QDBusConnection retval(d);
431 Closes the bus connection of name \a name.
433 Note that if there are still QDBusConnection objects associated
434 with the same connection, the connection will not be closed until
435 all references are dropped. However, no further references can be
436 created using the QDBusConnection constructor.
438 void QDBusConnection::disconnectFromBus(const QString &name)
441 QMutexLocker locker(&_q_manager()->mutex);
442 QDBusConnectionPrivate *d = _q_manager()->connection(name);
443 if (d && d->mode != QDBusConnectionPrivate::ClientMode)
445 _q_manager()->removeConnection(name);
452 Closes the peer connection of name \a name.
454 Note that if there are still QDBusConnection objects associated
455 with the same connection, the connection will not be closed until
456 all references are dropped. However, no further references can be
457 created using the QDBusConnection constructor.
459 void QDBusConnection::disconnectFromPeer(const QString &name)
462 QMutexLocker locker(&_q_manager()->mutex);
463 QDBusConnectionPrivate *d = _q_manager()->connection(name);
464 if (d && d->mode != QDBusConnectionPrivate::PeerMode)
466 _q_manager()->removeConnection(name);
471 Sends the \a message over this connection, without waiting for a
472 reply. This is suitable for errors, signals, and return values as
473 well as calls whose return values are not necessary.
475 Returns true if the message was queued successfully, false otherwise.
477 bool QDBusConnection::send(const QDBusMessage &message) const
479 if (!d || !d->connection) {
480 QDBusError err = QDBusError(QDBusError::Disconnected,
481 QLatin1String("Not connected to D-BUS server"));
486 return d->send(message) != 0;
490 Sends the \a message over this connection and returns immediately.
491 When the reply is received, the method \a returnMethod is called in
492 the \a receiver object. If an error occurs, the method \a errorMethod
493 will be called instead.
495 If no reply is received within \a timeout milliseconds, an automatic
496 error will be delivered indicating the expiration of the call.
497 The default \a timeout is -1, which will be replaced with an
498 implementation-defined value that is suitable for inter-process
499 communications (generally, 25 seconds).
501 This function is suitable for method calls only. It is guaranteed
502 that the slot will be called exactly once with the reply, as long
503 as the parameter types match and no error occurs.
505 Returns true if the message was sent, or false if the message could
508 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
509 const char *returnMethod, const char *errorMethod,
512 if (!d || !d->connection) {
513 QDBusError err = QDBusError(QDBusError::Disconnected,
514 QLatin1String("Not connected to D-BUS server"));
519 return d->sendWithReplyAsync(message, receiver, returnMethod, errorMethod, timeout) != 0;
525 Sends the \a message over this connection and returns immediately.
526 When the reply is received, the method \a returnMethod is called in
527 the \a receiver object.
529 This function is suitable for method calls only. It is guaranteed
530 that the slot will be called exactly once with the reply, as long
531 as the parameter types match and no error occurs.
533 This function is dangerous because it cannot report errors, including
534 the expiration of the timeout.
536 Returns true if the message was sent, or false if the message could
539 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
540 const char *returnMethod, int timeout) const
542 return callWithCallback(message, receiver, returnMethod, 0, timeout);
546 Sends the \a message over this connection and blocks, waiting for
547 a reply, for at most \a timeout milliseconds. This function is
548 suitable for method calls only. It returns the reply message as
549 its return value, which will be either of type
550 QDBusMessage::ReplyMessage or QDBusMessage::ErrorMessage.
552 If no reply is received within \a timeout milliseconds, an automatic
553 error will be delivered indicating the expiration of the call.
554 The default \a timeout is -1, which will be replaced with an
555 implementation-defined value that is suitable for inter-process
556 communications (generally, 25 seconds).
558 See the QDBusInterface::call() function for a more friendly way
561 \warning If \a mode is QDBus::BlockWithGui, this function will
562 reenter the Qt event loop in order to wait for the
563 reply. During the wait, it may deliver signals and other
564 method calls to your application. Therefore, it must be
565 prepared to handle a reentrancy whenever a call is
568 QDBusMessage QDBusConnection::call(const QDBusMessage &message, QDBus::CallMode mode, int timeout) const
570 if (!d || !d->connection) {
571 QDBusError err = QDBusError(QDBusError::Disconnected,
572 QLatin1String("Not connected to D-Bus server"));
576 return QDBusMessage::createError(err);
579 if (mode != QDBus::NoBlock)
580 return d->sendWithReply(message, mode, timeout);
584 retval << QVariant(); // add one argument (to avoid .at(0) problems)
590 Sends the \a message over this connection and returns
591 immediately. This function is suitable for method calls only. It
592 returns an object of type QDBusPendingCall which can be used to
593 track the status of the reply.
595 If no reply is received within \a timeout milliseconds, an automatic
596 error will be delivered indicating the expiration of the call. The
597 default \a timeout is -1, which will be replaced with an
598 implementation-defined value that is suitable for inter-process
599 communications (generally, 25 seconds). This timeout is also the
600 upper limit for waiting in QDBusPendingCall::waitForFinished().
602 See the QDBusInterface::asyncCall() function for a more friendly way
605 QDBusPendingCall QDBusConnection::asyncCall(const QDBusMessage &message, int timeout) const
607 if (!d || !d->connection) {
608 return QDBusPendingCall(0); // null pointer -> disconnected
611 QDBusPendingCallPrivate *priv = d->sendWithReplyAsync(message, timeout);
612 return QDBusPendingCall(priv);
616 Connects the signal specified by the \a service, \a path, \a interface and \a name parameters to
617 the slot \a slot in object \a receiver. The arguments \a service and \a path can be empty,
618 denoting a connection to any signal of the (\a interface, \a name) pair, from any remote
621 Returns true if the connection was successful.
623 \warning The signal will only be delivered to the slot if the parameters match. This verification
624 can be done only when the signal is received, not at connection time.
626 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
627 const QString &name, QObject *receiver, const char *slot)
629 return connect(service, path, interface, name, QStringList(), QString(), receiver, slot);
635 Connects the signal to the slot \a slot in object \a
636 receiver. Unlike the previous connect() overload, this function
637 allows one to specify the parameter signature to be connected
638 using the \a signature variable. The function will then verify
639 that this signature can be delivered to the slot specified by \a
640 slot and return false otherwise.
642 Returns true if the connection was successful.
644 \note This function verifies that the signal signature matches the
645 slot's parameters, but it does not verify that the actual
646 signal exists with the given signature in the remote
649 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
650 const QString &name, const QString &signature,
651 QObject *receiver, const char *slot)
653 return connect(service, path, interface, name, QStringList(), signature, receiver, slot);
660 Connects the signal to the slot \a slot in object \a
661 receiver. Unlike the previous connect() overload, this function
662 allows one to specify the parameter signature to be connected
663 using the \a signature variable. The function will then verify
664 that this signature can be delivered to the slot specified by \a
665 slot and return false otherwise.
667 The \a argumentMatch parameter lists the string parameters to be matched,
668 in sequential order. Note that, to match an empty string, you need to
669 pass a QString that is empty but not null (i.e., QString("")). A null
670 QString skips matching at that position.
672 Returns true if the connection was successful.
674 \note This function verifies that the signal signature matches the
675 slot's parameters, but it does not verify that the actual
676 signal exists with the given signature in the remote
679 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
680 const QString &name, const QStringList &argumentMatch, const QString &signature,
681 QObject *receiver, const char *slot)
684 if (!receiver || !slot || !d || !d->connection)
686 if (interface.isEmpty() && name.isEmpty())
688 if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface)) {
690 qWarning("QDBusConnection::connect: interface name '%s' is not valid", interface.toLatin1().constData());
694 if (!service.isEmpty() && !QDBusUtil::isValidBusName(service)) {
696 qWarning("QDBusConnection::connect: service name '%s' is not valid", service.toLatin1().constData());
700 if (!path.isEmpty() && !QDBusUtil::isValidObjectPath(path)) {
702 qWarning("QDBusConnection::connect: object path '%s' is not valid", path.toLatin1().constData());
707 QDBusWriteLocker locker(ConnectAction, d);
708 return d->connectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
712 Disconnects the signal specified by the \a service, \a path, \a interface
713 and \a name parameters from the slot \a slot in object \a receiver. The
714 arguments must be the same as passed to the connect() function.
716 Returns true if the disconnection was successful.
718 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString &interface,
719 const QString &name, QObject *receiver, const char *slot)
721 return disconnect(service, path, interface, name, QStringList(), QString(), receiver, slot);
727 Disconnects the signal specified by the \a service, \a path, \a
728 interface, \a name, and \a signature parameters from the slot \a slot in
729 object \a receiver. The arguments must be the same as passed to the
732 Returns true if the disconnection was successful.
734 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
735 const QString &name, const QString &signature,
736 QObject *receiver, const char *slot)
738 return disconnect(service, path, interface, name, QStringList(), signature, receiver, slot);
745 Disconnects the signal specified by the \a service, \a path, \a
746 interface, \a name, \a argumentMatch, and \a signature parameters from
747 the slot \a slot in object \a receiver. The arguments must be the same as
748 passed to the connect() function.
750 Returns true if the disconnection was successful.
752 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
753 const QString &name, const QStringList &argumentMatch, const QString &signature,
754 QObject *receiver, const char *slot)
756 if (!receiver || !slot || !d || !d->connection)
758 if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface))
760 if (interface.isEmpty() && name.isEmpty())
763 QDBusWriteLocker locker(DisconnectAction, d);
764 return d->disconnectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
768 Registers the object \a object at path \a path and returns true if
769 the registration was successful. The \a options parameter
770 specifies how much of the object \a object will be exposed through
773 This function does not replace existing objects: if there is already an object registered at
774 path \a path, this function will return false. Use unregisterObject() to unregister it first.
776 You cannot register an object as a child object of an object that
777 was registered with QDBusConnection::ExportChildObjects.
779 bool QDBusConnection::registerObject(const QString &path, QObject *object, RegisterOptions options)
781 Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registerObject",
782 "Invalid object path given");
783 if (!d || !d->connection || !object || !options || !QDBusUtil::isValidObjectPath(path))
786 QStringList pathComponents = path.split(QLatin1Char('/'));
787 if (pathComponents.last().isEmpty())
788 pathComponents.removeLast();
789 QDBusWriteLocker locker(RegisterObjectAction, d);
791 // lower-bound search for where this object should enter in the tree
792 QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
795 if (pathComponents.count() == i) {
797 // consider it free if there's no object here and the user is not trying to
798 // replace the object sub-tree
802 if (options & QDBusConnectionPrivate::VirtualObject) {
803 // technically the check for children needs to go even deeper
804 if (options & SubPath) {
805 foreach (const QDBusConnectionPrivate::ObjectTreeNode &child, node->children) {
811 if ((options & ExportChildObjects && !node->children.isEmpty()))
814 // we can add the object here
816 node->flags = options;
818 d->registerObject(node);
819 //qDebug("REGISTERED FOR %s", path.toLocal8Bit().constData());
823 // if a virtual object occupies this path, return false
824 if (node->obj && (node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath)) {
825 qDebug("Cannot register object at %s because QDBusVirtualObject handles all sub-paths.",
830 // find the position where we'd insert the node
831 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
832 qLowerBound(node->children.begin(), node->children.end(), pathComponents.at(i));
833 if (it != node->children.end() && it->name == pathComponents.at(i)) {
834 // match: this node exists
837 // are we allowed to go deeper?
838 if (node->flags & ExportChildObjects) {
840 qDebug("Cannot register object at %s because %s exports its own child objects",
841 qPrintable(path), qPrintable(pathComponents.at(i)));
846 node = node->children.insert(it, pathComponents.at(i));
853 Q_ASSERT_X(false, "QDBusConnection::registerObject", "The impossible happened");
860 Registers a QDBusTreeNode for a path. It can handle a path including all child paths, thus
861 handling multiple DBus nodes.
863 To unregister a QDBusTreeNode use the unregisterObject() function with its path.
865 bool QDBusConnection::registerVirtualObject(const QString &path, QDBusVirtualObject *treeNode,
866 VirtualObjectRegisterOption options)
868 int opts = options | QDBusConnectionPrivate::VirtualObject;
869 return registerObject(path, (QObject*) treeNode, (RegisterOptions) opts);
873 Unregisters an object that was registered with the registerObject() at the object path given by
874 \a path and, if \a mode is QDBusConnection::UnregisterTree, all of its sub-objects too.
876 Note that you cannot unregister objects that were not registered with registerObject().
878 void QDBusConnection::unregisterObject(const QString &path, UnregisterMode mode)
880 if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
883 QStringList pathComponents = path.split(QLatin1Char('/'));
884 QDBusWriteLocker locker(UnregisterObjectAction, d);
885 QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
890 if (pathComponents.count() == i || !path.compare(QLatin1String("/"))) {
895 if (mode == UnregisterTree) {
896 // clear the sub-tree as well
897 node->children.clear(); // can't disconnect the objects because we really don't know if they can
898 // be found somewhere else in the path too
904 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
905 qLowerBound(node->children.begin(), node->children.end(), pathComponents.at(i));
906 if (it == node->children.end() || it->name != pathComponents.at(i))
907 break; // node not found
915 Return the object that was registered with the registerObject() at the object path given by
918 QObject *QDBusConnection::objectRegisteredAt(const QString &path) const
920 Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registeredObject",
921 "Invalid object path given");
922 if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
925 QStringList pathComponents = path.split(QLatin1Char('/'));
926 if (pathComponents.last().isEmpty())
927 pathComponents.removeLast();
929 // lower-bound search for where this object should enter in the tree
930 QDBusReadLocker lock(ObjectRegisteredAtAction, d);
931 const QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
935 if (pathComponents.count() == i)
937 if ((node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath))
940 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
941 qLowerBound(node->children.constBegin(), node->children.constEnd(), pathComponents.at(i));
942 if (it == node->children.constEnd() || it->name != pathComponents.at(i))
943 break; // node not found
954 Returns a QDBusConnectionInterface object that represents the
955 D-Bus server interface on this connection.
957 QDBusConnectionInterface *QDBusConnection::interface() const
961 return d->busService;
968 Returns the internal, implementation-defined pointer for this
969 connection. Currently, this returns a DBusConnection* pointer,
970 without changing the reference count. It is the responsibility of
971 the caller to call dbus_connection_ref if it wants to store the
974 void *QDBusConnection::internalPointer() const
976 return d ? d->connection : 0;
980 Returns true if this QDBusConnection object is connected.
982 bool QDBusConnection::isConnected() const
984 return d && d->connection && q_dbus_connection_get_is_connected(d->connection);
988 Returns the last error that happened in this connection.
990 This function is provided for low-level code. If you're using
991 QDBusInterface::call(), error codes are reported by its return
994 \sa QDBusInterface, QDBusMessage
996 QDBusError QDBusConnection::lastError() const
998 return d ? d->lastError : QDBusError();
1002 Returns the unique connection name for this connection, if this QDBusConnection object is
1003 connected, or an empty QString otherwise.
1005 A Unique Connection Name is a string in the form ":x.xxx" (where x
1006 are decimal digits) that is assigned by the D-Bus server daemon
1007 upon connection. It uniquely identifies this client in the bus.
1009 This function returns an empty QString for peer-to-peer connections.
1011 QString QDBusConnection::baseService() const
1013 return d ? d->baseService : QString();
1019 Returns the connection name for this connection, as given as the
1020 name parameter to connectToBus().
1022 The connection name can be used to uniquely identify actual
1023 underlying connections to buses. Copies made from a single
1024 connection will always implicitly share the underlying connection,
1025 and hence will have the same connection name.
1027 Inversely, two connections having different connection names will
1028 always either be connected to different buses, or have a different
1029 unique name (as returned by baseService()) on that bus.
1031 \sa connectToBus(), disconnectFromBus()
1033 QString QDBusConnection::name() const
1035 return d ? d->name : QString();
1041 Returns the capabilities of this connection as negotiated with the bus
1042 server or peer. If this QDBusConnection is not connected, this function
1043 returns no capabilities.
1045 QDBusConnection::ConnectionCapabilities QDBusConnection::connectionCapabilities() const
1047 return d ? d->capabilities : ConnectionCapabilities(0);
1051 Attempts to register the \a serviceName on the D-Bus server and
1052 returns true if the registration succeeded. The registration will
1053 fail if the name is already registered by another application.
1055 \sa unregisterService(), QDBusConnectionInterface::registerService()
1057 bool QDBusConnection::registerService(const QString &serviceName)
1059 if (interface() && interface()->registerService(serviceName)) {
1060 if (d) d->registerService(serviceName);
1067 Unregisters the service \a serviceName that was previously
1068 registered with registerService() and returns true if it
1071 \sa registerService(), QDBusConnectionInterface::unregisterService()
1073 bool QDBusConnection::unregisterService(const QString &serviceName)
1075 if (interface()->unregisterService(serviceName)) {
1076 if (d) d->unregisterService(serviceName);
1082 static const char _q_sessionBusName[] = "qt_default_session_bus";
1083 static const char _q_systemBusName[] = "qt_default_system_bus";
1085 class QDBusDefaultConnection: public QDBusConnection
1087 const char *ownName;
1089 inline QDBusDefaultConnection(BusType type, const char *name)
1090 : QDBusConnection(connectToBus(type, QString::fromLatin1(name))), ownName(name)
1092 // make sure this connection is running on the main thread
1093 QCoreApplication *instance = QCoreApplication::instance();
1095 qWarning("QDBusConnection: %s D-Bus connection created before QCoreApplication. Application may misbehave.",
1096 type == SessionBus ? "session" : type == SystemBus ? "system" : "generic");
1097 } else if (QDBusConnectionPrivate::d(*this)) {
1098 QDBusConnectionPrivate::d(*this)->moveToThread(instance->thread());
1102 inline ~QDBusDefaultConnection()
1103 { disconnectFromBus(QString::fromLatin1(ownName)); }
1106 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_sessionBus,
1107 (QDBusConnection::SessionBus, _q_sessionBusName))
1108 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_systemBus,
1109 (QDBusConnection::SystemBus, _q_systemBusName))
1112 \fn QDBusConnection QDBusConnection::sessionBus()
1114 Returns a QDBusConnection object opened with the session bus. The object
1115 reference returned by this function is valid until the application terminates,
1116 at which point the connection will be closed and the object deleted.
1118 QDBusConnection QDBusConnection::sessionBus()
1120 return *_q_sessionBus();
1124 \fn QDBusConnection QDBusConnection::systemBus()
1126 Returns a QDBusConnection object opened with the system bus. The object reference returned
1127 by this function is valid until the QCoreApplication's destructor is run, when the
1128 connection will be closed and the object, deleted.
1130 QDBusConnection QDBusConnection::systemBus()
1132 return *_q_systemBus();
1138 Returns the connection that sent the signal, if called in a slot activated
1139 by QDBus; otherwise it returns 0.
1141 \note Please avoid this function. This function is not thread-safe, so if
1142 there's any other thread delivering a D-Bus call, this function may return
1143 the wrong connection. In new code, please use QDBusContext::connection()
1144 (see that class for a description on how to use it).
1146 QDBusConnection QDBusConnection::sender()
1148 return QDBusConnection(_q_manager()->sender());
1154 void QDBusConnectionPrivate::setSender(const QDBusConnectionPrivate *s)
1156 _q_manager()->setSender(s);
1162 void QDBusConnectionPrivate::setBusService(const QDBusConnection &connection)
1164 busService = new QDBusConnectionInterface(connection, this);
1165 ref.deref(); // busService has increased the refcounting to us
1166 // avoid cyclic refcounting
1168 QObject::connect(this, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1169 busService, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1170 Qt::QueuedConnection);
1175 Returns the local machine ID as known to the D-Bus system. Each
1176 node or host that runs D-Bus has a unique identifier that can be
1177 used to distinguish it from other hosts if they are sharing
1178 resources like the filesystem.
1180 Note that the local machine ID is not guaranteed to be persistent
1181 across boots of the system, so this identifier should not be
1182 stored in persistent storage (like the filesystem). It is
1183 guaranteed to remain constant only during the lifetime of this
1186 QByteArray QDBusConnection::localMachineId()
1188 char *dbus_machine_id = q_dbus_get_local_machine_id();
1189 QByteArray result = dbus_machine_id;
1190 q_dbus_free(dbus_machine_id);
1198 \brief The QDBus namespace contains miscellaneous identifiers used
1199 throughout the QtDBus library.
1203 \enum QDBus::CallMode
1205 This enum describes the various ways of placing a function call. The valid modes are:
1207 \value NoBlock Place the call but don't wait for the reply (the reply's contents
1209 \value Block Don't use an event loop to wait for a reply, but instead block on
1210 network operations while waiting. This means the
1211 user-interface may not be updated until the function returns.
1212 \value BlockWithGui Use the Qt event loop to wait for a reply. This means that the
1213 user-interface will stay responsive (processing input events),
1214 but it also means other events may happen, like signal delivery
1215 and other D-Bus method calls.
1216 \value AutoDetect Automatically detect if the called function has a reply.
1218 When using BlockWithGui, applications must be prepared for reentrancy in any function.
1223 #endif // QT_NO_DBUS