~timo-jyrinki/unity/ubuntu5180

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/*
 * Copyright (C) 2011 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Neil Jagdish Patel <neil.patel@canonical.com>
 */

#include "GLibDBusProxy.h"

#include <map>
#include <memory>
#include <NuxCore/Logger.h>
#include <vector>

#include "GLibWrapper.h"
#include "GLibSignal.h"

namespace unity
{
namespace glib
{

namespace
{
nux::logging::Logger logger("unity.glib.dbusproxy");
}

using std::string;

class DBusProxy::Impl
{
public:
  typedef std::vector<ReplyCallback> Callbacks;
  typedef std::map<string, Callbacks> SignalHandlers;

  Impl(DBusProxy* owner,
       string const& name,
       string const& object_path,
       string const& interface_name,
       GBusType bus_type,
       GDBusProxyFlags flags);
  ~Impl();

  void StartReconnectionTimeout();
  void Connect();

  void Call(string const& method_name,
            GVariant* parameters,
            ReplyCallback callback,
            GCancellable* cancellable,
            GDBusCallFlags flags,
            int timeout_msec);

  void Connect(string const& signal_name, ReplyCallback callback);
  bool IsConnected();

  void OnProxyNameOwnerChanged(GDBusProxy*, GParamSpec*);
  void OnProxySignal(GDBusProxy* proxy, char* sender_name, char* signal_name,
                     GVariant* parameters);

  static void OnProxyConnectCallback(GObject* source, GAsyncResult* res, gpointer impl);
  static void OnCallCallback(GObject* source, GAsyncResult* res, gpointer call_data);

  struct CallData
  {
    DBusProxy::ReplyCallback callback;
    DBusProxy::Impl* impl;
    std::string method_name;
  };

  DBusProxy* owner_;
  string name_;
  string object_path_;
  string interface_name_;
  GBusType bus_type_;
  GDBusProxyFlags flags_;

  glib::Object<GDBusProxy> proxy_;
  glib::Object<GCancellable> cancellable_;
  guint watcher_id_;
  guint reconnect_timeout_id_;
  bool connected_;

  glib::Signal<void, GDBusProxy*, char*, char*, GVariant*> g_signal_connection_;
  glib::Signal<void, GDBusProxy*, GParamSpec*> name_owner_signal_;

  SignalHandlers handlers_;
};

DBusProxy::Impl::Impl(DBusProxy* owner,
                      string const& name,
                      string const& object_path,
                      string const& interface_name,
                      GBusType bus_type,
                      GDBusProxyFlags flags)
  : owner_(owner)
  , name_(name)
  , object_path_(object_path)
  , interface_name_(interface_name)
  , bus_type_(bus_type)
  , flags_(flags)
  , cancellable_(g_cancellable_new())
  , watcher_id_(0)
  , reconnect_timeout_id_(0)
  , connected_(false)
{
  StartReconnectionTimeout();
}

DBusProxy::Impl::~Impl()
{
  g_cancellable_cancel(cancellable_);
  if (watcher_id_)
    g_bus_unwatch_name(watcher_id_);
  if (reconnect_timeout_id_)
    g_source_remove(reconnect_timeout_id_);
}

void DBusProxy::Impl::StartReconnectionTimeout()
{
  LOG_DEBUG(logger) << "Starting reconnection timeout for " << name_;

  if (reconnect_timeout_id_)
    g_source_remove(reconnect_timeout_id_);

  auto callback = [](gpointer user_data) -> gboolean
  {
    DBusProxy::Impl* self = static_cast<DBusProxy::Impl*>(user_data);
    if (!self->proxy_)
      self->Connect();

    self->reconnect_timeout_id_ = 0;
    return FALSE;
  };
  reconnect_timeout_id_ = g_timeout_add_seconds(1, callback, this);
}

void DBusProxy::Impl::Connect()
{
  LOG_DEBUG(logger) << "Attempting to connect to " << name_;
  g_dbus_proxy_new_for_bus(bus_type_,
                           flags_,
                           NULL,
                           name_.c_str(),
                           object_path_.c_str(),
                           interface_name_.c_str(),
                           cancellable_,
                           DBusProxy::Impl::OnProxyConnectCallback,
                           this);
}

bool DBusProxy::Impl::IsConnected()
{
  return connected_;
}

void DBusProxy::Impl::OnProxyConnectCallback(GObject* source,
                                             GAsyncResult* res,
                                             gpointer impl)
{
  DBusProxy::Impl* self = static_cast<DBusProxy::Impl*>(impl);

  glib::Error error;
  glib::Object<GDBusProxy> proxy(g_dbus_proxy_new_for_bus_finish(res, &error));

  // If the async operation was cancelled, this callback will still be called and
  // therefore we should deal with the error before touching the impl pointer
  if (!proxy || error)
  {
    LOG_WARNING(logger) << "Unable to connect to proxy: " << error;
    return;
  }

  LOG_DEBUG(logger) << "Sucessfully created proxy: " << self->object_path_;

  self->proxy_ = proxy;
  self->g_signal_connection_.Connect(self->proxy_, "g-signal",
                                     sigc::mem_fun(self, &Impl::OnProxySignal));
  self->name_owner_signal_.Connect(self->proxy_, "notify::g-name-owner",
                                   sigc::mem_fun(self, &Impl::OnProxyNameOwnerChanged));

  // If a proxy cannot autostart a service, it doesn't throw an error, but
  // sets name_owner to NULL
  if (glib::String(g_dbus_proxy_get_name_owner(proxy)))
  {
    self->connected_ = true;
    self->owner_->connected.emit();
  }
}

void DBusProxy::Impl::OnProxyNameOwnerChanged(GDBusProxy* proxy, GParamSpec* param)
{
  glib::String name_owner(g_dbus_proxy_get_name_owner(proxy));

  if (name_owner)
  {
    if (!connected_)
    {
      LOG_DEBUG(logger) << name_ << " appeared";

      connected_ = true;
      owner_->connected.emit();
    }
  }
  else if (connected_)
  {
    LOG_DEBUG(logger) << name_ << " vanished";

    connected_ = false;
    owner_->disconnected.emit();
  }
}

void DBusProxy::Impl::OnProxySignal(GDBusProxy* proxy,
                                    char* sender_name,
                                    char* signal_name,
                                    GVariant* parameters)
{
  LOG_DEBUG(logger) << "Signal Received for proxy (" << object_path_ << ") "
                    << "SenderName: " << sender_name << " "
                    << "SignalName: " << signal_name << " "
                    << "ParameterType: " << g_variant_get_type_string(parameters);

  for (ReplyCallback callback: handlers_[signal_name])
    callback(parameters);
}

void DBusProxy::Impl::Call(string const& method_name,
                           GVariant* parameters,
                           ReplyCallback callback,
                           GCancellable* cancellable,
                           GDBusCallFlags flags,
                           int timeout_msec)
{
  if (proxy_)
  {
    CallData* data = new CallData();
    data->callback = callback;
    data->impl = this;
    data->method_name = method_name;

    g_dbus_proxy_call(proxy_,
                      method_name.c_str(),
                      parameters,
                      flags,
                      timeout_msec,
                      cancellable != NULL ? cancellable : cancellable_,
                      DBusProxy::Impl::OnCallCallback,
                      data);
  }
  else
  {
    LOG_WARNING(logger) << "Cannot call method " << method_name
                        << " proxy " << object_path_ << " does not exist";
  }
}

void DBusProxy::Impl::OnCallCallback(GObject* source, GAsyncResult* res, gpointer call_data)
{
  glib::Error error;
  std::unique_ptr<CallData> data (static_cast<CallData*>(call_data));
  GVariant* result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);

  if (error && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
  {
    // silently ignore
  }
  else if (error)
  {
    // Do not touch the impl pointer as the operation may have been cancelled
    LOG_WARNING(logger) << "Calling method \"" << data->method_name
      << "\" on object path: \""
      << g_dbus_proxy_get_object_path (G_DBUS_PROXY (source))
      << "\" failed: " << error;
  }
  else
  {
    data->callback(result);
    g_variant_unref(result);
  }
}

void DBusProxy::Impl::Connect(std::string const& signal_name, ReplyCallback callback)
{
  handlers_[signal_name].push_back(callback);
}

DBusProxy::DBusProxy(string const& name,
                     string const& object_path,
                     string const& interface_name,
                     GBusType bus_type,
                     GDBusProxyFlags flags)
  : pimpl(new Impl(this, name, object_path, interface_name, bus_type, flags))
{}

DBusProxy::~DBusProxy()
{}

void DBusProxy::Call(string const& method_name,
                     GVariant* parameters,
                     ReplyCallback callback,
                     GCancellable* cancellable,
                     GDBusCallFlags flags,
                     int timeout_msec)
{
  pimpl->Call(method_name, parameters, callback, cancellable, flags,
              timeout_msec);
}

void DBusProxy::Connect(std::string const& signal_name, ReplyCallback callback)
{
  pimpl->Connect(signal_name, callback);
}

bool DBusProxy::IsConnected()
{
  return pimpl->IsConnected();
}

}
}