Unity 8
 All Classes Functions
abstractdbusservicemonitor.cpp
1 /*
2  * Copyright (C) 2011-2014 Canonical, Ltd.
3  *
4  * Authors:
5  * Ugo Riboni <ugo.riboni@canonical.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; version 3.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "abstractdbusservicemonitor.h"
21 
22 #include <QDBusInterface>
23 #include <QDBusServiceWatcher>
24 #include <QDBusConnection>
25 #include <QDBusConnectionInterface>
26 #include <QDBusReply>
27 
28 AbstractDBusServiceMonitor::AbstractDBusServiceMonitor(const QString &service, const QString &path,
29  const QString &interface, const Bus bus,
30  QObject *parent)
31  : QObject(parent)
32  , m_service(service)
33  , m_path(path)
34  , m_interface(interface)
35  , m_watcher(new QDBusServiceWatcher(service,
36  (bus == SystemBus) ? QDBusConnection::systemBus()
37  : QDBusConnection::sessionBus()))
38  , m_dbusInterface(nullptr)
39 {
40  connect(m_watcher, &QDBusServiceWatcher::serviceRegistered, this, &AbstractDBusServiceMonitor::createInterface);
41  connect(m_watcher, &QDBusServiceWatcher::serviceUnregistered, this, &AbstractDBusServiceMonitor::destroyInterface);
42 
43  // Connect to the service if it's up already
44  QDBusConnectionInterface* sessionBus = QDBusConnection::sessionBus().interface();
45  QDBusReply<bool> reply = sessionBus->isServiceRegistered(m_service);
46  if (reply.isValid() && reply.value()) {
47  createInterface(m_service);
48  }
49 }
50 
51 AbstractDBusServiceMonitor::~AbstractDBusServiceMonitor()
52 {
53  delete m_watcher;
54  delete m_dbusInterface;
55 }
56 
57 void AbstractDBusServiceMonitor::createInterface(const QString &)
58 {
59  if (m_dbusInterface != nullptr) {
60  delete m_dbusInterface;
61  m_dbusInterface = nullptr;
62  }
63 
64  m_dbusInterface = new QDBusInterface(m_service, m_path, m_interface,
65  QDBusConnection::sessionBus());
66  Q_EMIT serviceAvailableChanged(true);
67 }
68 
69 void AbstractDBusServiceMonitor::destroyInterface(const QString &)
70 {
71  if (m_dbusInterface != nullptr) {
72  delete m_dbusInterface;
73  m_dbusInterface = nullptr;
74  }
75 
76  Q_EMIT serviceAvailableChanged(false);
77 }
78 
79 QDBusInterface* AbstractDBusServiceMonitor::dbusInterface() const
80 {
81  return m_dbusInterface;
82 }
83 
84 bool AbstractDBusServiceMonitor::serviceAvailable() const
85 {
86  return m_dbusInterface != nullptr;
87 }