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 ****************************************************************************/
42 #include "qdbusconnection.h"
43 #include "qdbusconnection_p.h"
46 #include <qcoreapplication.h>
47 #include <qstringlist.h>
50 #include "qdbusconnectioninterface.h"
51 #include "qdbuserror.h"
52 #include "qdbusmessage.h"
53 #include "qdbusmessage_p.h"
54 #include "qdbusinterface_p.h"
55 #include "qdbusutil_p.h"
56 #include "qdbusconnectionmanager_p.h"
58 #include "qdbusthreaddebug_p.h"
66 Q_GLOBAL_STATIC(QDBusConnectionManager, _q_manager)
68 QDBusConnectionPrivate *QDBusConnectionManager::sender() const
70 QMutexLocker locker(&senderMutex);
71 return connection(senderName);
74 void QDBusConnectionManager::setSender(const QDBusConnectionPrivate *s)
76 QMutexLocker locker(&senderMutex);
77 senderName = (s ? s->name : QString());
80 QDBusConnectionPrivate *QDBusConnectionManager::connection(const QString &name) const
82 return connectionHash.value(name, 0);
85 void QDBusConnectionManager::removeConnection(const QString &name)
87 QDBusConnectionPrivate *d = 0;
88 d = connectionHash.take(name);
89 if (d && !d->ref.deref())
92 // Static objects may be keeping the connection open.
93 // However, it is harmless to have outstanding references to a connection that is
94 // closing as long as those references will be soon dropped without being used.
96 // ### Output a warning if connections are being used after they have been removed.
99 QDBusConnectionManager::~QDBusConnectionManager()
101 for (QHash<QString, QDBusConnectionPrivate *>::const_iterator it = connectionHash.constBegin();
102 it != connectionHash.constEnd(); ++it) {
103 QDBusConnectionPrivate *d = it.value();
107 d->closeConnection();
109 connectionHash.clear();
112 QDBusConnectionManager* QDBusConnectionManager::instance()
117 Q_DBUS_EXPORT void qDBusBindToApplication();
118 void qDBusBindToApplication()
122 void QDBusConnectionManager::setConnection(const QString &name, QDBusConnectionPrivate *c)
124 connectionHash[name] = c;
129 \class QDBusConnection
133 \brief The QDBusConnection class represents a connection to the D-Bus bus daemon.
135 This class is the initial point in a D-Bus session. Using it, you
136 can get access to remote objects, interfaces; connect remote
137 signals to your object's slots; register objects, etc.
139 D-Bus connections are created using the connectToBus() function,
140 which opens a connection to the server daemon and does the initial
141 handshaking, associating that connection with a name. Further
142 attempts to connect using the same name will return the same
145 The connection is then torn down using the disconnectFromBus()
148 Once disconnected, calling connectToBus() will not reestablish a
149 connection, you must create a new QDBusConnection instance.
151 As a convenience for the two most common connection types, the
152 sessionBus() and systemBus() functions return open connections to
153 the session server daemon and the system server daemon,
154 respectively. Those connections are opened when first used and are
155 closed when the QCoreApplication destructor is run.
157 D-Bus also supports peer-to-peer connections, without the need for
158 a bus server daemon. Using this facility, two applications can
159 talk to each other and exchange messages. This can be achieved by
160 passing an address to connectToBus() function, which was opened by
161 another D-Bus application using QDBusServer.
165 \enum QDBusConnection::BusType
166 Specifies the type of the bus connection. The valid bus types are:
168 \value SessionBus the session bus, associated with the running desktop session
169 \value SystemBus the system bus, used to communicate with system-wide processes
170 \value ActivationBus the activation bus, the "alias" for the bus that started the
173 On the Session Bus, one can find other applications by the same user that are sharing the same
174 desktop session (hence the name). On the System Bus, however, processes shared for the whole
175 system are usually found.
179 \enum QDBusConnection::RegisterOption
180 Specifies the options for registering objects with the connection. The possible values are:
182 \value ExportAdaptors export the contents of adaptors found in this object
184 \value ExportScriptableSlots export this object's scriptable slots
185 \value ExportScriptableSignals export this object's scriptable signals
186 \value ExportScriptableProperties export this object's scriptable properties
187 \value ExportScriptableInvokables export this object's scriptable invokables
188 \value ExportScriptableContents shorthand form for ExportScriptableSlots |
189 ExportScriptableSignals |
190 ExportScriptableProperties
192 \value ExportNonScriptableSlots export this object's non-scriptable slots
193 \value ExportNonScriptableSignals export this object's non-scriptable signals
194 \value ExportNonScriptableProperties export this object's non-scriptable properties
195 \value ExportNonScriptableInvokables export this object's non-scriptable invokables
196 \value ExportNonScriptableContents shorthand form for ExportNonScriptableSlots |
197 ExportNonScriptableSignals |
198 ExportNonScriptableProperties
200 \value ExportAllSlots export all of this object's slots
201 \value ExportAllSignals export all of this object's signals
202 \value ExportAllProperties export all of this object's properties
203 \value ExportAllInvokables export all of this object's invokables
204 \value ExportAllContents export all of this object's contents
205 \value ExportChildObjects export this object's child objects
207 \sa registerObject(), QDBusAbstractAdaptor, {usingadaptors.html}{Using adaptors}
213 \enum QDBusConnection::VirtualObjectRegisterOption
214 Specifies the options for registering virtual objects with the connection. The possible values are:
216 \value SingleNode register a virtual object to handle one path only
217 \value SubPath register a virtual object so that it handles all sub paths
219 \sa registerVirtualObject(), QDBusVirtualObject
223 \enum QDBusConnection::UnregisterMode
224 The mode for unregistering an object path:
226 \value UnregisterNode unregister this node only: do not unregister child objects
227 \value UnregisterTree unregister this node and all its sub-tree
229 Note, however, if this object was registered with the ExportChildObjects option, UnregisterNode
230 will unregister the child objects too.
235 \enum QDBusConnection::ConnectionCapability
237 This enum describes the available capabilities for a D-Bus connection.
239 \value UnixFileDescriptorPassing enables passing of Unix file descriptors to other processes
240 (see QDBusUnixFileDescriptor)
242 \sa connectionCapabilities()
246 Creates a QDBusConnection object attached to the connection with name \a name.
248 This does not open the connection. You have to call connectToBus() to open it.
250 QDBusConnection::QDBusConnection(const QString &name)
252 if (name.isEmpty()) {
255 QMutexLocker locker(&_q_manager()->mutex);
256 d = _q_manager()->connection(name);
263 Creates a copy of the \a other connection.
265 QDBusConnection::QDBusConnection(const QDBusConnection &other)
274 Creates a connection object with the given \a dd as private object.
276 QDBusConnection::QDBusConnection(QDBusConnectionPrivate *dd)
284 Disposes of this object. This does not close the connection: you
285 have to call disconnectFromBus() to do that.
287 QDBusConnection::~QDBusConnection()
289 if (d && !d->ref.deref())
294 Creates a copy of the connection \a other in this object. Note
295 that the connection this object referenced before the copy, is not
296 spontaneously disconnected.
298 \sa disconnectFromBus()
300 QDBusConnection &QDBusConnection::operator=(const QDBusConnection &other)
304 if (d && !d->ref.deref())
311 Opens a connection of type \a type to one of the known busses and
312 associate with it the connection name \a name. Returns a
313 QDBusConnection object associated with that connection.
315 QDBusConnection QDBusConnection::connectToBus(BusType type, const QString &name)
317 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
318 // "Cannot create connection without a Q[Core]Application instance");
319 if (!qdbus_loadLibDBus()) {
320 QDBusConnectionPrivate *d = 0;
321 return QDBusConnection(d);
324 QMutexLocker locker(&_q_manager()->mutex);
326 QDBusConnectionPrivate *d = _q_manager()->connection(name);
327 if (d || name.isEmpty())
328 return QDBusConnection(d);
330 d = new QDBusConnectionPrivate;
331 DBusConnection *c = 0;
332 QDBusErrorInternal error;
335 c = q_dbus_bus_get_private(DBUS_BUS_SYSTEM, error);
338 c = q_dbus_bus_get_private(DBUS_BUS_SESSION, error);
341 c = q_dbus_bus_get_private(DBUS_BUS_STARTER, error);
344 d->setConnection(c, error); //setConnection does the error handling for us
346 _q_manager()->setConnection(name, d);
348 QDBusConnection retval(d);
350 // create the bus service
351 // will lock in QDBusConnectionPrivate::connectRelay()
352 d->setBusService(retval);
358 Opens a connection to a private bus on address \a address and associate with it the
359 connection name \a name. Returns a QDBusConnection object associated with that connection.
361 QDBusConnection QDBusConnection::connectToBus(const QString &address,
364 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
365 // "Cannot create connection without a Q[Core]Application instance");
366 if (!qdbus_loadLibDBus()) {
367 QDBusConnectionPrivate *d = 0;
368 return QDBusConnection(d);
371 QMutexLocker locker(&_q_manager()->mutex);
373 QDBusConnectionPrivate *d = _q_manager()->connection(name);
374 if (d || name.isEmpty())
375 return QDBusConnection(d);
377 d = new QDBusConnectionPrivate;
378 // setConnection does the error handling for us
379 QDBusErrorInternal error;
380 DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
382 if (!q_dbus_bus_register(c, error)) {
383 q_dbus_connection_unref(c);
387 d->setConnection(c, error);
388 _q_manager()->setConnection(name, d);
390 QDBusConnection retval(d);
392 // create the bus service
393 // will lock in QDBusConnectionPrivate::connectRelay()
394 d->setBusService(retval);
401 Opens a peer-to-peer connection on address \a address and associate with it the
402 connection name \a name. Returns a QDBusConnection object associated with that connection.
404 QDBusConnection QDBusConnection::connectToPeer(const QString &address,
407 // Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
408 // "Cannot create connection without a Q[Core]Application instance");
409 if (!qdbus_loadLibDBus()) {
410 QDBusConnectionPrivate *d = 0;
411 return QDBusConnection(d);
414 QMutexLocker locker(&_q_manager()->mutex);
416 QDBusConnectionPrivate *d = _q_manager()->connection(name);
417 if (d || name.isEmpty())
418 return QDBusConnection(d);
420 d = new QDBusConnectionPrivate;
421 // setPeer does the error handling for us
422 QDBusErrorInternal error;
423 DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
425 d->setPeer(c, error);
426 _q_manager()->setConnection(name, d);
428 QDBusConnection retval(d);
434 Closes the bus connection of name \a name.
436 Note that if there are still QDBusConnection objects associated
437 with the same connection, the connection will not be closed until
438 all references are dropped. However, no further references can be
439 created using the QDBusConnection constructor.
441 void QDBusConnection::disconnectFromBus(const QString &name)
444 QMutexLocker locker(&_q_manager()->mutex);
445 QDBusConnectionPrivate *d = _q_manager()->connection(name);
446 if (d && d->mode != QDBusConnectionPrivate::ClientMode)
448 _q_manager()->removeConnection(name);
455 Closes the peer connection of name \a name.
457 Note that if there are still QDBusConnection objects associated
458 with the same connection, the connection will not be closed until
459 all references are dropped. However, no further references can be
460 created using the QDBusConnection constructor.
462 void QDBusConnection::disconnectFromPeer(const QString &name)
465 QMutexLocker locker(&_q_manager()->mutex);
466 QDBusConnectionPrivate *d = _q_manager()->connection(name);
467 if (d && d->mode != QDBusConnectionPrivate::PeerMode)
469 _q_manager()->removeConnection(name);
474 Sends the \a message over this connection, without waiting for a
475 reply. This is suitable for errors, signals, and return values as
476 well as calls whose return values are not necessary.
478 Returns true if the message was queued successfully, false otherwise.
480 bool QDBusConnection::send(const QDBusMessage &message) const
482 if (!d || !d->connection) {
483 QDBusError err = QDBusError(QDBusError::Disconnected,
484 QLatin1String("Not connected to D-BUS server"));
489 return d->send(message) != 0;
493 Sends the \a message over this connection and returns immediately.
494 When the reply is received, the method \a returnMethod is called in
495 the \a receiver object. If an error occurs, the method \a errorMethod
496 will be called instead.
498 If no reply is received within \a timeout milliseconds, an automatic
499 error will be delivered indicating the expiration of the call.
500 The default \a timeout is -1, which will be replaced with an
501 implementation-defined value that is suitable for inter-process
502 communications (generally, 25 seconds).
504 This function is suitable for method calls only. It is guaranteed
505 that the slot will be called exactly once with the reply, as long
506 as the parameter types match and no error occurs.
508 Returns true if the message was sent, or false if the message could
511 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
512 const char *returnMethod, const char *errorMethod,
515 if (!d || !d->connection) {
516 QDBusError err = QDBusError(QDBusError::Disconnected,
517 QLatin1String("Not connected to D-BUS server"));
522 return d->sendWithReplyAsync(message, receiver, returnMethod, errorMethod, timeout) != 0;
528 Sends the \a message over this connection and returns immediately.
529 When the reply is received, the method \a returnMethod is called in
530 the \a receiver object.
532 This function is suitable for method calls only. It is guaranteed
533 that the slot will be called exactly once with the reply, as long
534 as the parameter types match and no error occurs.
536 This function is dangerous because it cannot report errors, including
537 the expiration of the timeout.
539 Returns true if the message was sent, or false if the message could
542 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
543 const char *returnMethod, int timeout) const
545 return callWithCallback(message, receiver, returnMethod, 0, timeout);
549 Sends the \a message over this connection and blocks, waiting for
550 a reply, for at most \a timeout milliseconds. This function is
551 suitable for method calls only. It returns the reply message as
552 its return value, which will be either of type
553 QDBusMessage::ReplyMessage or QDBusMessage::ErrorMessage.
555 If no reply is received within \a timeout milliseconds, an automatic
556 error will be delivered indicating the expiration of the call.
557 The default \a timeout is -1, which will be replaced with an
558 implementation-defined value that is suitable for inter-process
559 communications (generally, 25 seconds).
561 See the QDBusInterface::call() function for a more friendly way
564 \warning If \a mode is QDBus::BlockWithGui, this function will
565 reenter the Qt event loop in order to wait for the
566 reply. During the wait, it may deliver signals and other
567 method calls to your application. Therefore, it must be
568 prepared to handle a reentrancy whenever a call is
571 QDBusMessage QDBusConnection::call(const QDBusMessage &message, QDBus::CallMode mode, int timeout) const
573 if (!d || !d->connection) {
574 QDBusError err = QDBusError(QDBusError::Disconnected,
575 QLatin1String("Not connected to D-Bus server"));
579 return QDBusMessage::createError(err);
582 if (mode != QDBus::NoBlock)
583 return d->sendWithReply(message, mode, timeout);
587 retval << QVariant(); // add one argument (to avoid .at(0) problems)
593 Sends the \a message over this connection and returns
594 immediately. This function is suitable for method calls only. It
595 returns an object of type QDBusPendingCall which can be used to
596 track the status of the reply.
598 If no reply is received within \a timeout milliseconds, an automatic
599 error will be delivered indicating the expiration of the call. The
600 default \a timeout is -1, which will be replaced with an
601 implementation-defined value that is suitable for inter-process
602 communications (generally, 25 seconds). This timeout is also the
603 upper limit for waiting in QDBusPendingCall::waitForFinished().
605 See the QDBusInterface::asyncCall() function for a more friendly way
608 QDBusPendingCall QDBusConnection::asyncCall(const QDBusMessage &message, int timeout) const
610 if (!d || !d->connection) {
611 return QDBusPendingCall(0); // null pointer -> disconnected
614 QDBusPendingCallPrivate *priv = d->sendWithReplyAsync(message, timeout);
615 return QDBusPendingCall(priv);
619 Connects the signal specified by the \a service, \a path, \a interface and \a name parameters to
620 the slot \a slot in object \a receiver. The arguments \a service and \a path can be empty,
621 denoting a connection to any signal of the (\a interface, \a name) pair, from any remote
624 Returns true if the connection was successful.
626 \warning The signal will only be delivered to the slot if the parameters match. This verification
627 can be done only when the signal is received, not at connection time.
629 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
630 const QString &name, QObject *receiver, const char *slot)
632 return connect(service, path, interface, name, QStringList(), QString(), receiver, slot);
638 Connects the signal to the slot \a slot in object \a
639 receiver. Unlike the previous connect() overload, this function
640 allows one to specify the parameter signature to be connected
641 using the \a signature variable. The function will then verify
642 that this signature can be delivered to the slot specified by \a
643 slot and return false otherwise.
645 Returns true if the connection was successful.
647 \note This function verifies that the signal signature matches the
648 slot's parameters, but it does not verify that the actual
649 signal exists with the given signature in the remote
652 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
653 const QString &name, const QString &signature,
654 QObject *receiver, const char *slot)
656 return connect(service, path, interface, name, QStringList(), signature, receiver, slot);
663 Connects the signal to the slot \a slot in object \a
664 receiver. Unlike the previous connect() overload, this function
665 allows one to specify the parameter signature to be connected
666 using the \a signature variable. The function will then verify
667 that this signature can be delivered to the slot specified by \a
668 slot and return false otherwise.
670 The \a argumentMatch parameter lists the string parameters to be matched,
671 in sequential order. Note that, to match an empty string, you need to
672 pass a QString that is empty but not null (i.e., QString("")). A null
673 QString skips matching at that position.
675 Returns true if the connection was successful.
677 \note This function verifies that the signal signature matches the
678 slot's parameters, but it does not verify that the actual
679 signal exists with the given signature in the remote
682 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
683 const QString &name, const QStringList &argumentMatch, const QString &signature,
684 QObject *receiver, const char *slot)
687 if (!receiver || !slot || !d || !d->connection)
689 if (interface.isEmpty() && name.isEmpty())
691 if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface)) {
693 qWarning("QDBusConnection::connect: interface name '%s' is not valid", interface.toLatin1().constData());
697 if (!service.isEmpty() && !QDBusUtil::isValidBusName(service)) {
699 qWarning("QDBusConnection::connect: service name '%s' is not valid", service.toLatin1().constData());
703 if (!path.isEmpty() && !QDBusUtil::isValidObjectPath(path)) {
705 qWarning("QDBusConnection::connect: object path '%s' is not valid", path.toLatin1().constData());
710 QDBusWriteLocker locker(ConnectAction, d);
711 return d->connectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
715 Disconnects the signal specified by the \a service, \a path, \a interface
716 and \a name parameters from the slot \a slot in object \a receiver. The
717 arguments must be the same as passed to the connect() function.
719 Returns true if the disconnection was successful.
721 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString &interface,
722 const QString &name, QObject *receiver, const char *slot)
724 return disconnect(service, path, interface, name, QStringList(), QString(), receiver, slot);
730 Disconnects the signal specified by the \a service, \a path, \a
731 interface, \a name, and \a signature parameters from the slot \a slot in
732 object \a receiver. The arguments must be the same as passed to the
735 Returns true if the disconnection was successful.
737 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
738 const QString &name, const QString &signature,
739 QObject *receiver, const char *slot)
741 return disconnect(service, path, interface, name, QStringList(), signature, receiver, slot);
748 Disconnects the signal specified by the \a service, \a path, \a
749 interface, \a name, \a argumentMatch, and \a signature parameters from
750 the slot \a slot in object \a receiver. The arguments must be the same as
751 passed to the connect() function.
753 Returns true if the disconnection was successful.
755 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
756 const QString &name, const QStringList &argumentMatch, const QString &signature,
757 QObject *receiver, const char *slot)
759 if (!receiver || !slot || !d || !d->connection)
761 if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface))
763 if (interface.isEmpty() && name.isEmpty())
766 QDBusWriteLocker locker(DisconnectAction, d);
767 return d->disconnectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
771 Registers the object \a object at path \a path and returns true if
772 the registration was successful. The \a options parameter
773 specifies how much of the object \a object will be exposed through
776 This function does not replace existing objects: if there is already an object registered at
777 path \a path, this function will return false. Use unregisterObject() to unregister it first.
779 You cannot register an object as a child object of an object that
780 was registered with QDBusConnection::ExportChildObjects.
782 bool QDBusConnection::registerObject(const QString &path, QObject *object, RegisterOptions options)
784 Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registerObject",
785 "Invalid object path given");
786 if (!d || !d->connection || !object || !options || !QDBusUtil::isValidObjectPath(path))
789 QStringList pathComponents = path.split(QLatin1Char('/'));
790 if (pathComponents.last().isEmpty())
791 pathComponents.removeLast();
792 QDBusWriteLocker locker(RegisterObjectAction, d);
794 // lower-bound search for where this object should enter in the tree
795 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator node = &d->rootNode;
798 if (pathComponents.count() == i) {
800 // consider it free if there's no object here and the user is not trying to
801 // replace the object sub-tree
805 if (options & QDBusConnectionPrivate::VirtualObject) {
806 // technically the check for children needs to go even deeper
807 if (options & SubPath) {
808 foreach (const QDBusConnectionPrivate::ObjectTreeNode &child, node->children) {
814 if ((options & ExportChildObjects && !node->children.isEmpty()))
817 // we can add the object here
819 node->flags = options;
821 d->registerObject(node);
822 //qDebug("REGISTERED FOR %s", path.toLocal8Bit().constData());
826 // if a virtual object occupies this path, return false
827 if (node->obj && (node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath)) {
828 qDebug("Cannot register object at %s because QDBusVirtualObject handles all sub-paths.",
833 // find the position where we'd insert the node
834 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
835 std::lower_bound(node->children.begin(), node->children.end(), pathComponents.at(i));
836 if (it != node->children.end() && it->name == pathComponents.at(i)) {
837 // match: this node exists
840 // are we allowed to go deeper?
841 if (node->flags & ExportChildObjects) {
843 qDebug("Cannot register object at %s because %s exports its own child objects",
844 qPrintable(path), qPrintable(pathComponents.at(i)));
849 node = node->children.insert(it, pathComponents.at(i));
856 Q_ASSERT_X(false, "QDBusConnection::registerObject", "The impossible happened");
863 Registers a QDBusTreeNode for a path. It can handle a path including all child paths, thus
864 handling multiple DBus nodes.
866 To unregister a QDBusTreeNode use the unregisterObject() function with its path.
868 bool QDBusConnection::registerVirtualObject(const QString &path, QDBusVirtualObject *treeNode,
869 VirtualObjectRegisterOption options)
871 int opts = options | QDBusConnectionPrivate::VirtualObject;
872 return registerObject(path, (QObject*) treeNode, (RegisterOptions) opts);
876 Unregisters an object that was registered with the registerObject() at the object path given by
877 \a path and, if \a mode is QDBusConnection::UnregisterTree, all of its sub-objects too.
879 Note that you cannot unregister objects that were not registered with registerObject().
881 void QDBusConnection::unregisterObject(const QString &path, UnregisterMode mode)
883 if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
886 QStringList pathComponents = path.split(QLatin1Char('/'));
887 QDBusWriteLocker locker(UnregisterObjectAction, d);
888 QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
893 if (pathComponents.count() == i || !path.compare(QLatin1String("/"))) {
898 if (mode == UnregisterTree) {
899 // clear the sub-tree as well
900 node->children.clear(); // can't disconnect the objects because we really don't know if they can
901 // be found somewhere else in the path too
907 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
908 std::lower_bound(node->children.begin(), node->children.end(), pathComponents.at(i));
909 if (it == node->children.end() || it->name != pathComponents.at(i))
910 break; // node not found
918 Return the object that was registered with the registerObject() at the object path given by
921 QObject *QDBusConnection::objectRegisteredAt(const QString &path) const
923 Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registeredObject",
924 "Invalid object path given");
925 if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
928 QStringList pathComponents = path.split(QLatin1Char('/'));
929 if (pathComponents.last().isEmpty())
930 pathComponents.removeLast();
932 // lower-bound search for where this object should enter in the tree
933 QDBusReadLocker lock(ObjectRegisteredAtAction, d);
934 const QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
938 if (pathComponents.count() == i)
940 if ((node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath))
943 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
944 std::lower_bound(node->children.constBegin(), node->children.constEnd(), pathComponents.at(i));
945 if (it == node->children.constEnd() || it->name != pathComponents.at(i))
946 break; // node not found
957 Returns a QDBusConnectionInterface object that represents the
958 D-Bus server interface on this connection.
960 QDBusConnectionInterface *QDBusConnection::interface() const
964 return d->busService;
971 Returns the internal, implementation-defined pointer for this
972 connection. Currently, this returns a DBusConnection* pointer,
973 without changing the reference count. It is the responsibility of
974 the caller to call dbus_connection_ref if it wants to store the
977 void *QDBusConnection::internalPointer() const
979 return d ? d->connection : 0;
983 Returns true if this QDBusConnection object is connected.
985 bool QDBusConnection::isConnected() const
987 return d && d->connection && q_dbus_connection_get_is_connected(d->connection);
991 Returns the last error that happened in this connection.
993 This function is provided for low-level code. If you're using
994 QDBusInterface::call(), error codes are reported by its return
997 \sa QDBusInterface, QDBusMessage
999 QDBusError QDBusConnection::lastError() const
1001 return d ? d->lastError : QDBusError();
1005 Returns the unique connection name for this connection, if this QDBusConnection object is
1006 connected, or an empty QString otherwise.
1008 A Unique Connection Name is a string in the form ":x.xxx" (where x
1009 are decimal digits) that is assigned by the D-Bus server daemon
1010 upon connection. It uniquely identifies this client in the bus.
1012 This function returns an empty QString for peer-to-peer connections.
1014 QString QDBusConnection::baseService() const
1016 return d ? d->baseService : QString();
1022 Returns the connection name for this connection, as given as the
1023 name parameter to connectToBus().
1025 The connection name can be used to uniquely identify actual
1026 underlying connections to buses. Copies made from a single
1027 connection will always implicitly share the underlying connection,
1028 and hence will have the same connection name.
1030 Inversely, two connections having different connection names will
1031 always either be connected to different buses, or have a different
1032 unique name (as returned by baseService()) on that bus.
1034 \sa connectToBus(), disconnectFromBus()
1036 QString QDBusConnection::name() const
1038 return d ? d->name : QString();
1044 Returns the capabilities of this connection as negotiated with the bus
1045 server or peer. If this QDBusConnection is not connected, this function
1046 returns no capabilities.
1048 QDBusConnection::ConnectionCapabilities QDBusConnection::connectionCapabilities() const
1050 return d ? d->capabilities : ConnectionCapabilities(0);
1054 Attempts to register the \a serviceName on the D-Bus server and
1055 returns true if the registration succeeded. The registration will
1056 fail if the name is already registered by another application.
1058 \sa unregisterService(), QDBusConnectionInterface::registerService()
1060 bool QDBusConnection::registerService(const QString &serviceName)
1062 if (interface() && interface()->registerService(serviceName)) {
1063 if (d) d->registerService(serviceName);
1070 Unregisters the service \a serviceName that was previously
1071 registered with registerService() and returns true if it
1074 \sa registerService(), QDBusConnectionInterface::unregisterService()
1076 bool QDBusConnection::unregisterService(const QString &serviceName)
1078 if (interface()->unregisterService(serviceName)) {
1079 if (d) d->unregisterService(serviceName);
1085 static const char _q_sessionBusName[] = "qt_default_session_bus";
1086 static const char _q_systemBusName[] = "qt_default_system_bus";
1088 class QDBusDefaultConnection: public QDBusConnection
1090 const char *ownName;
1092 inline QDBusDefaultConnection(BusType type, const char *name)
1093 : QDBusConnection(connectToBus(type, QString::fromLatin1(name))), ownName(name)
1095 // make sure this connection is running on the main thread
1096 QCoreApplication *instance = QCoreApplication::instance();
1098 qWarning("QDBusConnection: %s D-Bus connection created before QCoreApplication. Application may misbehave.",
1099 type == SessionBus ? "session" : type == SystemBus ? "system" : "generic");
1100 } else if (QDBusConnectionPrivate::d(*this)) {
1101 QDBusConnectionPrivate::d(*this)->moveToThread(instance->thread());
1105 inline ~QDBusDefaultConnection()
1106 { disconnectFromBus(QString::fromLatin1(ownName)); }
1109 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_sessionBus,
1110 (QDBusConnection::SessionBus, _q_sessionBusName))
1111 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_systemBus,
1112 (QDBusConnection::SystemBus, _q_systemBusName))
1115 \fn QDBusConnection QDBusConnection::sessionBus()
1117 Returns a QDBusConnection object opened with the session bus. The object
1118 reference returned by this function is valid until the application terminates,
1119 at which point the connection will be closed and the object deleted.
1121 QDBusConnection QDBusConnection::sessionBus()
1123 return *_q_sessionBus();
1127 \fn QDBusConnection QDBusConnection::systemBus()
1129 Returns a QDBusConnection object opened with the system bus. The object reference returned
1130 by this function is valid until the QCoreApplication's destructor is run, when the
1131 connection will be closed and the object, deleted.
1133 QDBusConnection QDBusConnection::systemBus()
1135 return *_q_systemBus();
1141 Returns the connection that sent the signal, if called in a slot activated
1142 by QDBus; otherwise it returns 0.
1144 \note Please avoid this function. This function is not thread-safe, so if
1145 there's any other thread delivering a D-Bus call, this function may return
1146 the wrong connection. In new code, please use QDBusContext::connection()
1147 (see that class for a description on how to use it).
1149 QDBusConnection QDBusConnection::sender()
1151 return QDBusConnection(_q_manager()->sender());
1157 void QDBusConnectionPrivate::setSender(const QDBusConnectionPrivate *s)
1159 _q_manager()->setSender(s);
1165 void QDBusConnectionPrivate::setBusService(const QDBusConnection &connection)
1167 busService = new QDBusConnectionInterface(connection, this);
1168 ref.deref(); // busService has increased the refcounting to us
1169 // avoid cyclic refcounting
1171 QObject::connect(this, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1172 busService, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1173 Qt::QueuedConnection);
1178 Returns the local machine ID as known to the D-Bus system. Each
1179 node or host that runs D-Bus has a unique identifier that can be
1180 used to distinguish it from other hosts if they are sharing
1181 resources like the filesystem.
1183 Note that the local machine ID is not guaranteed to be persistent
1184 across boots of the system, so this identifier should not be
1185 stored in persistent storage (like the filesystem). It is
1186 guaranteed to remain constant only during the lifetime of this
1189 QByteArray QDBusConnection::localMachineId()
1191 char *dbus_machine_id = q_dbus_get_local_machine_id();
1192 QByteArray result = dbus_machine_id;
1193 q_dbus_free(dbus_machine_id);
1201 \brief The QDBus namespace contains miscellaneous identifiers used
1202 throughout the QtDBus library.
1206 \enum QDBus::CallMode
1208 This enum describes the various ways of placing a function call. The valid modes are:
1210 \value NoBlock Place the call but don't wait for the reply (the reply's contents
1212 \value Block Don't use an event loop to wait for a reply, but instead block on
1213 network operations while waiting. This means the
1214 user-interface may not be updated until the function returns.
1215 \value BlockWithGui Use the Qt event loop to wait for a reply. This means that the
1216 user-interface will stay responsive (processing input events),
1217 but it also means other events may happen, like signal delivery
1218 and other D-Bus method calls.
1219 \value AutoDetect Automatically detect if the called function has a reply.
1221 When using BlockWithGui, applications must be prepared for reentrancy in any function.
1226 #endif // QT_NO_DBUS