Unity 8
URLDispatcher.cpp
1 /*
2  * Copyright (C) 2016-2017 Canonical, Ltd.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 3.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 
17 #include "URLDispatcher.h"
18 
19 #include <QDBusConnection>
20 #include <QDebug>
21 
22 class URLDispatcherInterface : public QObject
23 {
24  Q_OBJECT
25  Q_CLASSINFO("D-Bus Interface", "com.canonical.URLDispatcher")
26 
27 public:
28  explicit URLDispatcherInterface(URLDispatcher *parent);
29 
30  Q_SCRIPTABLE void DispatchURL(const QString &url, const QString &package);
31 };
32 
33 URLDispatcherInterface::URLDispatcherInterface(URLDispatcher *parent)
34  : QObject(parent)
35 {
36 }
37 
38 void URLDispatcherInterface::DispatchURL(const QString &url, const QString &package)
39 {
40  Q_UNUSED(package);
41  Q_EMIT static_cast<URLDispatcher *>(parent())->urlRequested(url);
42 }
43 
44 URLDispatcher::URLDispatcher(QObject *parent)
45  : QObject(parent)
46  , m_dispatcher(nullptr)
47 {
48 }
49 
50 bool URLDispatcher::active() const
51 {
52  return m_dispatcher != nullptr;
53 }
54 
55 void URLDispatcher::setActive(bool value)
56 {
57  if (value == active())
58  return;
59 
60  QDBusConnection connection = QDBusConnection::sessionBus();
61 
62  if (value) {
63  URLDispatcherInterface *dispatcher = new URLDispatcherInterface(this);
64  connection.registerObject(QStringLiteral("/com/canonical/URLDispatcher"),
65  dispatcher,
66  QDBusConnection::ExportScriptableContents);
67  if (!connection.registerService(QStringLiteral("com.canonical.URLDispatcher"))) {
68  qWarning() << "Unable to register DBus service com.canonical.URLDispatcher";
69  }
70  m_dispatcher = dispatcher;
71  } else {
72  connection.unregisterService(QStringLiteral("com.canonical.URLDispatcher"));
73  delete m_dispatcher;
74  m_dispatcher = nullptr;
75  }
76 
77  Q_EMIT activeChanged();
78 }
79 
80 #include "URLDispatcher.moc"