1 | /* |
2 | * Copyright (C) 2010 Sebastian Trueg <trueg@kde.org> |
3 | * Copyright (C) 2010 David Faure <faure@kde.org> |
4 | * |
5 | * This library is free software; you can redistribute it and/or |
6 | * modify it under the terms of the GNU Library General Public |
7 | * License as published by the Free Software Foundation; either |
8 | * version 2 of the License, or (at your option) any later version. |
9 | * |
10 | * This library is distributed in the hope that it will be useful, |
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
13 | * Library General Public License for more details. |
14 | * |
15 | * You should have received a copy of the GNU Library General Public License |
16 | * along with this library; see the file COPYING.LIB. If not, write to |
17 | * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, |
18 | * Boston, MA 02110-1301, USA. |
19 | */ |
20 | |
21 | #include "dbusconnectionpool.h" |
22 | #include <QCoreApplication> |
23 | #include <QThread> |
24 | #include <QThreadStorage> |
25 | |
26 | namespace { |
27 | QAtomicInt s_connectionCounter; |
28 | |
29 | class DBusConnectionPoolPrivate |
30 | { |
31 | public: |
32 | DBusConnectionPoolPrivate() |
33 | : m_connection(QDBusConnection::connectToBus( |
34 | QDBusConnection::SessionBus, |
35 | QString::fromLatin1("AkonadiKde%1" ).arg(newNumber()))) |
36 | { |
37 | } |
38 | ~DBusConnectionPoolPrivate() { |
39 | QDBusConnection::disconnectFromBus(m_connection.name()); |
40 | } |
41 | |
42 | QDBusConnection connection() const { |
43 | return m_connection; |
44 | } |
45 | |
46 | private: |
47 | static int newNumber() { |
48 | return s_connectionCounter.fetchAndAddAcquire(1); |
49 | } |
50 | QDBusConnection m_connection; |
51 | }; |
52 | } |
53 | |
54 | QThreadStorage<DBusConnectionPoolPrivate *> s_perThreadConnection; |
55 | |
56 | QDBusConnection Akonadi::DBusConnectionPool::threadConnection() |
57 | { |
58 | if (!QCoreApplication::instance() || QCoreApplication::instance()->thread() == QThread::currentThread()) { |
59 | return QDBusConnection::sessionBus(); // main thread, use the default session bus, breaks unported resources otherwise |
60 | } |
61 | if (!s_perThreadConnection.hasLocalData()) { |
62 | s_perThreadConnection.setLocalData(new DBusConnectionPoolPrivate); |
63 | } |
64 | return s_perThreadConnection.localData()->connection(); |
65 | } |
66 | |