GDBusProxy: Store GDBusObject in private struct instead of qdata
[platform/upstream/glib.git] / gio / gdbusproxy.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser 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  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "gdbusutils.h"
29 #include "gdbusproxy.h"
30 #include "gioenumtypes.h"
31 #include "gdbusconnection.h"
32 #include "gdbuserror.h"
33 #include "gdbusprivate.h"
34 #include "gio-marshal.h"
35 #include "ginitable.h"
36 #include "gasyncinitable.h"
37 #include "gioerror.h"
38 #include "gasyncresult.h"
39 #include "gsimpleasyncresult.h"
40 #include "gcancellable.h"
41 #include "gdbusinterface.h"
42
43 #include "glibintl.h"
44
45 /**
46  * SECTION:gdbusproxy
47  * @short_description: Client-side D-Bus interface proxy
48  * @include: gio/gio.h
49  *
50  * #GDBusProxy is a base class used for proxies to access a D-Bus
51  * interface on a remote object. A #GDBusProxy can be constructed for
52  * both well-known and unique names.
53  *
54  * By default, #GDBusProxy will cache all properties (and listen to
55  * changes) of the remote object, and proxy all signals that gets
56  * emitted. This behaviour can be changed by passing suitable
57  * #GDBusProxyFlags when the proxy is created. If the proxy is for a
58  * well-known name, the property cache is flushed when the name owner
59  * vanishes and reloaded when a name owner appears.
60  *
61  * If a #GDBusProxy is used for a well-known name, the owner of the
62  * name is tracked and can be read from
63  * #GDBusProxy:g-name-owner. Connect to the #GObject::notify signal to
64  * get notified of changes. Additionally, only signals and property
65  * changes emitted from the current name owner are considered and
66  * calls are always sent to the current name owner. This avoids a
67  * number of race conditions when the name is lost by one owner and
68  * claimed by another. However, if no name owner currently exists,
69  * then calls will be sent to the well-known name which may result in
70  * the message bus launching an owner (unless
71  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START is set).
72  *
73  * The generic #GDBusProxy::g-properties-changed and #GDBusProxy::g-signal
74  * signals are not very convenient to work with. Therefore, the recommended
75  * way of working with proxies is to subclass #GDBusProxy, and have
76  * more natural properties and signals in your derived class.
77  *
78  * See <xref linkend="gdbus-example-proxy-subclass"/> for an example.
79  *
80  * <example id="gdbus-wellknown-proxy"><title>GDBusProxy for a well-known-name</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-watch-proxy.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
81  */
82
83 struct _GDBusProxyPrivate
84 {
85   GBusType bus_type;
86   GDBusConnection *connection;
87
88   GDBusProxyFlags flags;
89   gchar *name;
90   gchar *name_owner;
91   gchar *object_path;
92   gchar *interface_name;
93   gint timeout_msec;
94
95   guint name_owner_changed_subscription_id;
96
97   GCancellable *get_all_cancellable;
98
99   /* gchar* -> GVariant* */
100   GHashTable *properties;
101
102   GDBusInterfaceInfo *expected_interface;
103
104   guint properties_changed_subscriber_id;
105   guint signals_subscriber_id;
106
107   gboolean initialized;
108
109   GDBusObject *object;
110 };
111
112 enum
113 {
114   PROP_0,
115   PROP_G_CONNECTION,
116   PROP_G_BUS_TYPE,
117   PROP_G_NAME,
118   PROP_G_NAME_OWNER,
119   PROP_G_FLAGS,
120   PROP_G_OBJECT_PATH,
121   PROP_G_INTERFACE_NAME,
122   PROP_G_DEFAULT_TIMEOUT,
123   PROP_G_INTERFACE_INFO
124 };
125
126 enum
127 {
128   PROPERTIES_CHANGED_SIGNAL,
129   SIGNAL_SIGNAL,
130   LAST_SIGNAL,
131 };
132
133 guint signals[LAST_SIGNAL] = {0};
134
135 static void dbus_interface_iface_init (GDBusInterfaceIface *dbus_interface_iface);
136 static void initable_iface_init       (GInitableIface *initable_iface);
137 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
138
139 G_DEFINE_TYPE_WITH_CODE (GDBusProxy, g_dbus_proxy, G_TYPE_OBJECT,
140                          G_IMPLEMENT_INTERFACE (G_TYPE_DBUS_INTERFACE, dbus_interface_iface_init)
141                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
142                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
143                          );
144
145 static void
146 g_dbus_proxy_finalize (GObject *object)
147 {
148   GDBusProxy *proxy = G_DBUS_PROXY (object);
149
150   g_warn_if_fail (proxy->priv->get_all_cancellable == NULL);
151
152   if (proxy->priv->name_owner_changed_subscription_id > 0)
153     g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
154                                           proxy->priv->name_owner_changed_subscription_id);
155
156   if (proxy->priv->properties_changed_subscriber_id > 0)
157     g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
158                                           proxy->priv->properties_changed_subscriber_id);
159
160   if (proxy->priv->signals_subscriber_id > 0)
161     g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
162                                           proxy->priv->signals_subscriber_id);
163
164   if (proxy->priv->connection != NULL)
165     g_object_unref (proxy->priv->connection);
166   g_free (proxy->priv->name);
167   g_free (proxy->priv->name_owner);
168   g_free (proxy->priv->object_path);
169   g_free (proxy->priv->interface_name);
170   if (proxy->priv->properties != NULL)
171     g_hash_table_unref (proxy->priv->properties);
172
173   if (proxy->priv->expected_interface != NULL)
174     {
175       g_dbus_interface_info_cache_release (proxy->priv->expected_interface);
176       g_dbus_interface_info_unref (proxy->priv->expected_interface);
177     }
178
179   if (proxy->priv->object != NULL)
180     g_object_remove_weak_pointer (G_OBJECT (proxy->priv->object), (gpointer *) &proxy->priv->object);
181
182   G_OBJECT_CLASS (g_dbus_proxy_parent_class)->finalize (object);
183 }
184
185 static void
186 g_dbus_proxy_get_property (GObject    *object,
187                            guint       prop_id,
188                            GValue     *value,
189                            GParamSpec *pspec)
190 {
191   GDBusProxy *proxy = G_DBUS_PROXY (object);
192
193   switch (prop_id)
194     {
195     case PROP_G_CONNECTION:
196       g_value_set_object (value, proxy->priv->connection);
197       break;
198
199     case PROP_G_FLAGS:
200       g_value_set_flags (value, proxy->priv->flags);
201       break;
202
203     case PROP_G_NAME:
204       g_value_set_string (value, proxy->priv->name);
205       break;
206
207     case PROP_G_NAME_OWNER:
208       g_value_set_string (value, proxy->priv->name_owner);
209       break;
210
211     case PROP_G_OBJECT_PATH:
212       g_value_set_string (value, proxy->priv->object_path);
213       break;
214
215     case PROP_G_INTERFACE_NAME:
216       g_value_set_string (value, proxy->priv->interface_name);
217       break;
218
219     case PROP_G_DEFAULT_TIMEOUT:
220       g_value_set_int (value, proxy->priv->timeout_msec);
221       break;
222
223     case PROP_G_INTERFACE_INFO:
224       g_value_set_boxed (value, g_dbus_proxy_get_interface_info (proxy));
225       break;
226
227     default:
228       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
229       break;
230     }
231 }
232
233 static void
234 g_dbus_proxy_set_property (GObject      *object,
235                            guint         prop_id,
236                            const GValue *value,
237                            GParamSpec   *pspec)
238 {
239   GDBusProxy *proxy = G_DBUS_PROXY (object);
240
241   switch (prop_id)
242     {
243     case PROP_G_CONNECTION:
244       proxy->priv->connection = g_value_dup_object (value);
245       break;
246
247     case PROP_G_FLAGS:
248       proxy->priv->flags = g_value_get_flags (value);
249       break;
250
251     case PROP_G_NAME:
252       proxy->priv->name = g_value_dup_string (value);
253       break;
254
255     case PROP_G_OBJECT_PATH:
256       proxy->priv->object_path = g_value_dup_string (value);
257       break;
258
259     case PROP_G_INTERFACE_NAME:
260       proxy->priv->interface_name = g_value_dup_string (value);
261       break;
262
263     case PROP_G_DEFAULT_TIMEOUT:
264       g_dbus_proxy_set_default_timeout (proxy, g_value_get_int (value));
265       break;
266
267     case PROP_G_INTERFACE_INFO:
268       g_dbus_proxy_set_interface_info (proxy, g_value_get_boxed (value));
269       break;
270
271     case PROP_G_BUS_TYPE:
272       proxy->priv->bus_type = g_value_get_enum (value);
273       break;
274
275     default:
276       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
277       break;
278     }
279 }
280
281 static void
282 g_dbus_proxy_class_init (GDBusProxyClass *klass)
283 {
284   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
285
286   gobject_class->finalize     = g_dbus_proxy_finalize;
287   gobject_class->set_property = g_dbus_proxy_set_property;
288   gobject_class->get_property = g_dbus_proxy_get_property;
289
290   /* Note that all property names are prefixed to avoid collisions with D-Bus property names
291    * in derived classes */
292
293   /**
294    * GDBusProxy:g-interface-info:
295    *
296    * Ensure that interactions with this proxy conform to the given
297    * interface.  For example, when completing a method call, if the
298    * type signature of the message isn't what's expected, the given
299    * #GError is set.  Signals that have a type signature mismatch are
300    * simply dropped.
301    *
302    * Since: 2.26
303    */
304   g_object_class_install_property (gobject_class,
305                                    PROP_G_INTERFACE_INFO,
306                                    g_param_spec_boxed ("g-interface-info",
307                                                        P_("Interface Information"),
308                                                        P_("Interface Information"),
309                                                        G_TYPE_DBUS_INTERFACE_INFO,
310                                                        G_PARAM_READABLE |
311                                                        G_PARAM_WRITABLE |
312                                                        G_PARAM_STATIC_NAME |
313                                                        G_PARAM_STATIC_BLURB |
314                                                        G_PARAM_STATIC_NICK));
315
316   /**
317    * GDBusProxy:g-connection:
318    *
319    * The #GDBusConnection the proxy is for.
320    *
321    * Since: 2.26
322    */
323   g_object_class_install_property (gobject_class,
324                                    PROP_G_CONNECTION,
325                                    g_param_spec_object ("g-connection",
326                                                         P_("g-connection"),
327                                                         P_("The connection the proxy is for"),
328                                                         G_TYPE_DBUS_CONNECTION,
329                                                         G_PARAM_READABLE |
330                                                         G_PARAM_WRITABLE |
331                                                         G_PARAM_CONSTRUCT_ONLY |
332                                                         G_PARAM_STATIC_NAME |
333                                                         G_PARAM_STATIC_BLURB |
334                                                         G_PARAM_STATIC_NICK));
335
336   /**
337    * GDBusProxy:g-bus-type:
338    *
339    * If this property is not %G_BUS_TYPE_NONE, then
340    * #GDBusProxy:g-connection must be %NULL and will be set to the
341    * #GDBusConnection obtained by calling g_bus_get() with the value
342    * of this property.
343    *
344    * Since: 2.26
345    */
346   g_object_class_install_property (gobject_class,
347                                    PROP_G_BUS_TYPE,
348                                    g_param_spec_enum ("g-bus-type",
349                                                       P_("Bus Type"),
350                                                       P_("The bus to connect to, if any"),
351                                                       G_TYPE_BUS_TYPE,
352                                                       G_BUS_TYPE_NONE,
353                                                       G_PARAM_WRITABLE |
354                                                       G_PARAM_CONSTRUCT_ONLY |
355                                                       G_PARAM_STATIC_NAME |
356                                                       G_PARAM_STATIC_BLURB |
357                                                       G_PARAM_STATIC_NICK));
358
359   /**
360    * GDBusProxy:g-flags:
361    *
362    * Flags from the #GDBusProxyFlags enumeration.
363    *
364    * Since: 2.26
365    */
366   g_object_class_install_property (gobject_class,
367                                    PROP_G_FLAGS,
368                                    g_param_spec_flags ("g-flags",
369                                                        P_("g-flags"),
370                                                        P_("Flags for the proxy"),
371                                                        G_TYPE_DBUS_PROXY_FLAGS,
372                                                        G_DBUS_PROXY_FLAGS_NONE,
373                                                        G_PARAM_READABLE |
374                                                        G_PARAM_WRITABLE |
375                                                        G_PARAM_CONSTRUCT_ONLY |
376                                                        G_PARAM_STATIC_NAME |
377                                                        G_PARAM_STATIC_BLURB |
378                                                        G_PARAM_STATIC_NICK));
379
380   /**
381    * GDBusProxy:g-name:
382    *
383    * The well-known or unique name that the proxy is for.
384    *
385    * Since: 2.26
386    */
387   g_object_class_install_property (gobject_class,
388                                    PROP_G_NAME,
389                                    g_param_spec_string ("g-name",
390                                                         P_("g-name"),
391                                                         P_("The well-known or unique name that the proxy is for"),
392                                                         NULL,
393                                                         G_PARAM_READABLE |
394                                                         G_PARAM_WRITABLE |
395                                                         G_PARAM_CONSTRUCT_ONLY |
396                                                         G_PARAM_STATIC_NAME |
397                                                         G_PARAM_STATIC_BLURB |
398                                                         G_PARAM_STATIC_NICK));
399
400   /**
401    * GDBusProxy:g-name-owner:
402    *
403    * The unique name that owns #GDBusProxy:name or %NULL if no-one
404    * currently owns that name. You may connect to #GObject::notify signal to
405    * track changes to this property.
406    *
407    * Since: 2.26
408    */
409   g_object_class_install_property (gobject_class,
410                                    PROP_G_NAME_OWNER,
411                                    g_param_spec_string ("g-name-owner",
412                                                         P_("g-name-owner"),
413                                                         P_("The unique name for the owner"),
414                                                         NULL,
415                                                         G_PARAM_READABLE |
416                                                         G_PARAM_STATIC_NAME |
417                                                         G_PARAM_STATIC_BLURB |
418                                                         G_PARAM_STATIC_NICK));
419
420   /**
421    * GDBusProxy:g-object-path:
422    *
423    * The object path the proxy is for.
424    *
425    * Since: 2.26
426    */
427   g_object_class_install_property (gobject_class,
428                                    PROP_G_OBJECT_PATH,
429                                    g_param_spec_string ("g-object-path",
430                                                         P_("g-object-path"),
431                                                         P_("The object path the proxy is for"),
432                                                         NULL,
433                                                         G_PARAM_READABLE |
434                                                         G_PARAM_WRITABLE |
435                                                         G_PARAM_CONSTRUCT_ONLY |
436                                                         G_PARAM_STATIC_NAME |
437                                                         G_PARAM_STATIC_BLURB |
438                                                         G_PARAM_STATIC_NICK));
439
440   /**
441    * GDBusProxy:g-interface-name:
442    *
443    * The D-Bus interface name the proxy is for.
444    *
445    * Since: 2.26
446    */
447   g_object_class_install_property (gobject_class,
448                                    PROP_G_INTERFACE_NAME,
449                                    g_param_spec_string ("g-interface-name",
450                                                         P_("g-interface-name"),
451                                                         P_("The D-Bus interface name the proxy is for"),
452                                                         NULL,
453                                                         G_PARAM_READABLE |
454                                                         G_PARAM_WRITABLE |
455                                                         G_PARAM_CONSTRUCT_ONLY |
456                                                         G_PARAM_STATIC_NAME |
457                                                         G_PARAM_STATIC_BLURB |
458                                                         G_PARAM_STATIC_NICK));
459
460   /**
461    * GDBusProxy:g-default-timeout:
462    *
463    * The timeout to use if -1 (specifying default timeout) is passed
464    * as @timeout_msec in the g_dbus_proxy_call() and
465    * g_dbus_proxy_call_sync() functions.
466    *
467    * This allows applications to set a proxy-wide timeout for all
468    * remote method invocations on the proxy. If this property is -1,
469    * the default timeout (typically 25 seconds) is used. If set to
470    * %G_MAXINT, then no timeout is used.
471    *
472    * Since: 2.26
473    */
474   g_object_class_install_property (gobject_class,
475                                    PROP_G_DEFAULT_TIMEOUT,
476                                    g_param_spec_int ("g-default-timeout",
477                                                      P_("Default Timeout"),
478                                                      P_("Timeout for remote method invocation"),
479                                                      -1,
480                                                      G_MAXINT,
481                                                      -1,
482                                                      G_PARAM_READABLE |
483                                                      G_PARAM_WRITABLE |
484                                                      G_PARAM_CONSTRUCT |
485                                                      G_PARAM_STATIC_NAME |
486                                                      G_PARAM_STATIC_BLURB |
487                                                      G_PARAM_STATIC_NICK));
488
489   /**
490    * GDBusProxy::g-properties-changed:
491    * @proxy: The #GDBusProxy emitting the signal.
492    * @changed_properties: A #GVariant containing the properties that changed
493    * @invalidated_properties: A %NULL terminated array of properties that was invalidated
494    *
495    * Emitted when one or more D-Bus properties on @proxy changes. The
496    * local cache has already been updated when this signal fires. Note
497    * that both @changed_properties and @invalidated_properties are
498    * guaranteed to never be %NULL (either may be empty though).
499    *
500    * This signal corresponds to the
501    * <literal>PropertiesChanged</literal> D-Bus signal on the
502    * <literal>org.freedesktop.DBus.Properties</literal> interface.
503    *
504    * Since: 2.26
505    */
506   signals[PROPERTIES_CHANGED_SIGNAL] = g_signal_new ("g-properties-changed",
507                                                      G_TYPE_DBUS_PROXY,
508                                                      G_SIGNAL_RUN_LAST,
509                                                      G_STRUCT_OFFSET (GDBusProxyClass, g_properties_changed),
510                                                      NULL,
511                                                      NULL,
512                                                      _gio_marshal_VOID__VARIANT_BOXED,
513                                                      G_TYPE_NONE,
514                                                      2,
515                                                      G_TYPE_VARIANT,
516                                                      G_TYPE_STRV | G_SIGNAL_TYPE_STATIC_SCOPE);
517
518   /**
519    * GDBusProxy::g-signal:
520    * @proxy: The #GDBusProxy emitting the signal.
521    * @sender_name: The sender of the signal or %NULL if the connection is not a bus connection.
522    * @signal_name: The name of the signal.
523    * @parameters: A #GVariant tuple with parameters for the signal.
524    *
525    * Emitted when a signal from the remote object and interface that @proxy is for, has been received.
526    *
527    * Since: 2.26
528    */
529   signals[SIGNAL_SIGNAL] = g_signal_new ("g-signal",
530                                          G_TYPE_DBUS_PROXY,
531                                          G_SIGNAL_RUN_LAST,
532                                          G_STRUCT_OFFSET (GDBusProxyClass, g_signal),
533                                          NULL,
534                                          NULL,
535                                          _gio_marshal_VOID__STRING_STRING_VARIANT,
536                                          G_TYPE_NONE,
537                                          3,
538                                          G_TYPE_STRING,
539                                          G_TYPE_STRING,
540                                          G_TYPE_VARIANT);
541
542
543   g_type_class_add_private (klass, sizeof (GDBusProxyPrivate));
544 }
545
546 static void
547 g_dbus_proxy_init (GDBusProxy *proxy)
548 {
549   proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, G_TYPE_DBUS_PROXY, GDBusProxyPrivate);
550   proxy->priv->properties = g_hash_table_new_full (g_str_hash,
551                                                    g_str_equal,
552                                                    g_free,
553                                                    (GDestroyNotify) g_variant_unref);
554 }
555
556 /* ---------------------------------------------------------------------------------------------------- */
557
558 static gint
559 property_name_sort_func (const gchar **a,
560                          const gchar **b)
561 {
562   return g_strcmp0 (*a, *b);
563 }
564
565 /**
566  * g_dbus_proxy_get_cached_property_names:
567  * @proxy: A #GDBusProxy.
568  *
569  * Gets the names of all cached properties on @proxy.
570  *
571  * Returns: A %NULL-terminated array of strings or %NULL if @proxy has
572  * no cached properties. Free the returned array with g_strfreev().
573  *
574  * Since: 2.26
575  */
576 gchar **
577 g_dbus_proxy_get_cached_property_names (GDBusProxy  *proxy)
578 {
579   gchar **names;
580   GPtrArray *p;
581   GHashTableIter iter;
582   const gchar *key;
583
584   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
585
586   names = NULL;
587   if (g_hash_table_size (proxy->priv->properties) == 0)
588     goto out;
589
590   p = g_ptr_array_new ();
591
592   g_hash_table_iter_init (&iter, proxy->priv->properties);
593   while (g_hash_table_iter_next (&iter, (gpointer) &key, NULL))
594     g_ptr_array_add (p, g_strdup (key));
595   g_ptr_array_sort (p, (GCompareFunc) property_name_sort_func);
596   g_ptr_array_add (p, NULL);
597
598   names = (gchar **) g_ptr_array_free (p, FALSE);
599
600  out:
601   return names;
602 }
603
604 static const GDBusPropertyInfo *
605 lookup_property_info_or_warn (GDBusProxy  *proxy,
606                               const gchar *property_name)
607 {
608   const GDBusPropertyInfo *info;
609
610   if (proxy->priv->expected_interface == NULL)
611     return NULL;
612
613   info = g_dbus_interface_info_lookup_property (proxy->priv->expected_interface, property_name);
614   if (info == NULL)
615     {
616       g_warning ("Trying to lookup property %s which isn't in expected interface %s",
617                  property_name,
618                  proxy->priv->expected_interface->name);
619     }
620
621   return info;
622 }
623
624 /**
625  * g_dbus_proxy_get_cached_property:
626  * @proxy: A #GDBusProxy.
627  * @property_name: Property name.
628  *
629  * Looks up the value for a property from the cache. This call does no
630  * blocking IO.
631  *
632  * If @proxy has an expected interface (see
633  * #GDBusProxy:g-interface-info), then @property_name (for existence)
634  * is checked against it.
635  *
636  * Returns: A reference to the #GVariant instance that holds the value
637  * for @property_name or %NULL if the value is not in the cache. The
638  * returned reference must be freed with g_variant_unref().
639  *
640  * Since: 2.26
641  */
642 GVariant *
643 g_dbus_proxy_get_cached_property (GDBusProxy   *proxy,
644                                   const gchar  *property_name)
645 {
646   GVariant *value;
647
648   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
649   g_return_val_if_fail (property_name != NULL, NULL);
650
651   value = g_hash_table_lookup (proxy->priv->properties, property_name);
652   if (value == NULL)
653     {
654       lookup_property_info_or_warn (proxy, property_name);
655       /* no difference */
656       goto out;
657     }
658
659   g_variant_ref (value);
660
661  out:
662   return value;
663 }
664
665 /**
666  * g_dbus_proxy_set_cached_property:
667  * @proxy: A #GDBusProxy
668  * @property_name: Property name.
669  * @value: (allow-none): Value for the property or %NULL to remove it from the cache.
670  *
671  * If @value is not %NULL, sets the cached value for the property with
672  * name @property_name to the value in @value.
673  *
674  * If @value is %NULL, then the cached value is removed from the
675  * property cache.
676  *
677  * If @proxy has an expected interface (see
678  * #GDBusProxy:g-interface-info), then @property_name (for existence)
679  * and @value (for the type) is checked against it.
680  *
681  * If the @value #GVariant is floating, it is consumed. This allows
682  * convenient 'inline' use of g_variant_new(), e.g.
683  * |[
684  *  g_dbus_proxy_set_cached_property (proxy,
685  *                                    "SomeProperty",
686  *                                    g_variant_new ("(si)",
687  *                                                  "A String",
688  *                                                  42));
689  * ]|
690  *
691  * Normally you will not need to use this method since @proxy is
692  * tracking changes using the
693  * <literal>org.freedesktop.DBus.Properties.PropertiesChanged</literal>
694  * D-Bus signal. However, for performance reasons an object may decide
695  * to not use this signal for some properties and instead use a
696  * proprietary out-of-band mechanism to transmit changes.
697  *
698  * As a concrete example, consider an object with a property
699  * <literal>ChatroomParticipants</literal> which is an array of
700  * strings. Instead of transmitting the same (long) array every time
701  * the property changes, it is more efficient to only transmit the
702  * delta using e.g. signals <literal>ChatroomParticipantJoined(String
703  * name)</literal> and <literal>ChatroomParticipantParted(String
704  * name)</literal>.
705  *
706  * Since: 2.26
707  */
708 void
709 g_dbus_proxy_set_cached_property (GDBusProxy   *proxy,
710                                   const gchar  *property_name,
711                                   GVariant     *value)
712 {
713   const GDBusPropertyInfo *info;
714
715   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
716   g_return_if_fail (property_name != NULL);
717
718   if (value != NULL)
719     {
720       info = lookup_property_info_or_warn (proxy, property_name);
721       if (info != NULL)
722         {
723           if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
724             {
725               g_warning (_("Trying to set property %s of type %s but according to the expected "
726                            "interface the type is %s"),
727                          property_name,
728                          g_variant_get_type_string (value),
729                          info->signature);
730               goto out;
731             }
732         }
733       g_hash_table_insert (proxy->priv->properties,
734                            g_strdup (property_name),
735                            g_variant_ref_sink (value));
736     }
737   else
738     {
739       g_hash_table_remove (proxy->priv->properties, property_name);
740     }
741
742  out:
743   ;
744 }
745
746 /* ---------------------------------------------------------------------------------------------------- */
747
748 static void
749 on_signal_received (GDBusConnection *connection,
750                     const gchar     *sender_name,
751                     const gchar     *object_path,
752                     const gchar     *interface_name,
753                     const gchar     *signal_name,
754                     GVariant        *parameters,
755                     gpointer         user_data)
756 {
757   GDBusProxy *proxy = G_DBUS_PROXY (user_data);
758
759   if (!proxy->priv->initialized)
760     goto out;
761
762   if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
763     goto out;
764
765   if (proxy->priv->expected_interface != NULL)
766     {
767       const GDBusSignalInfo *info;
768       GVariantType *expected_type;
769       info = g_dbus_interface_info_lookup_signal (proxy->priv->expected_interface, signal_name);
770       if (info == NULL)
771         goto out;
772       expected_type = _g_dbus_compute_complete_signature (info->args);
773       if (!g_variant_type_equal (expected_type, g_variant_get_type (parameters)))
774         {
775           g_variant_type_free (expected_type);
776           goto out;
777         }
778       g_variant_type_free (expected_type);
779     }
780
781   g_signal_emit (proxy,
782                  signals[SIGNAL_SIGNAL],
783                  0,
784                  sender_name,
785                  signal_name,
786                  parameters);
787  out:
788   ;
789 }
790
791 /* ---------------------------------------------------------------------------------------------------- */
792
793 static void
794 insert_property_checked (GDBusProxy  *proxy,
795                          gchar *property_name,
796                          GVariant *value)
797 {
798   if (proxy->priv->expected_interface != NULL)
799     {
800       const GDBusPropertyInfo *info;
801
802       info = g_dbus_interface_info_lookup_property (proxy->priv->expected_interface, property_name);
803       /* Ignore unknown properties */
804       if (info == NULL)
805         goto invalid;
806
807       /* Ignore properties with the wrong type */
808       if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
809         goto invalid;
810     }
811
812   g_hash_table_insert (proxy->priv->properties,
813                        property_name, /* adopts string */
814                        value); /* adopts value */
815
816   return;
817
818  invalid:
819   g_variant_unref (value);
820   g_free (property_name);
821 }
822
823 static void
824 on_properties_changed (GDBusConnection *connection,
825                        const gchar     *sender_name,
826                        const gchar     *object_path,
827                        const gchar     *interface_name,
828                        const gchar     *signal_name,
829                        GVariant        *parameters,
830                        gpointer         user_data)
831 {
832   GDBusProxy *proxy = G_DBUS_PROXY (user_data);
833   const gchar *interface_name_for_signal;
834   GVariant *changed_properties;
835   gchar **invalidated_properties;
836   GVariantIter iter;
837   gchar *key;
838   GVariant *value;
839   guint n;
840
841   changed_properties = NULL;
842   invalidated_properties = NULL;
843
844   if (!proxy->priv->initialized)
845     goto out;
846
847   if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
848     goto out;
849
850   if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(sa{sv}as)")))
851     {
852       g_warning ("Value for PropertiesChanged signal with type `%s' does not match `(sa{sv}as)'",
853                  g_variant_get_type_string (parameters));
854       goto out;
855     }
856
857   g_variant_get (parameters,
858                  "(&s@a{sv}^a&s)",
859                  &interface_name_for_signal,
860                  &changed_properties,
861                  &invalidated_properties);
862
863   if (g_strcmp0 (interface_name_for_signal, proxy->priv->interface_name) != 0)
864     goto out;
865
866   g_variant_iter_init (&iter, changed_properties);
867   while (g_variant_iter_next (&iter, "{sv}", &key, &value))
868     {
869       insert_property_checked (proxy,
870                                key, /* adopts string */
871                                value); /* adopts value */
872     }
873
874   for (n = 0; invalidated_properties[n] != NULL; n++)
875     {
876       g_hash_table_remove (proxy->priv->properties, invalidated_properties[n]);
877     }
878
879   /* emit signal */
880   g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
881                  0,
882                  changed_properties,
883                  invalidated_properties);
884
885  out:
886   if (changed_properties != NULL)
887     g_variant_unref (changed_properties);
888   g_free (invalidated_properties);
889 }
890
891 /* ---------------------------------------------------------------------------------------------------- */
892
893 static void
894 process_get_all_reply (GDBusProxy *proxy,
895                        GVariant   *result)
896 {
897   GVariantIter *iter;
898   gchar *key;
899   GVariant *value;
900
901   if (!g_variant_is_of_type (result, G_VARIANT_TYPE ("(a{sv})")))
902     {
903       g_warning ("Value for GetAll reply with type `%s' does not match `(a{sv})'",
904                  g_variant_get_type_string (result));
905       goto out;
906     }
907
908   g_variant_get (result, "(a{sv})", &iter);
909   while (g_variant_iter_next (iter, "{sv}", &key, &value))
910     {
911       insert_property_checked (proxy,
912                                key, /* adopts string */
913                                value); /* adopts value */
914     }
915   g_variant_iter_free (iter);
916
917   /* Synthesize ::g-properties-changed changed */
918   if (g_hash_table_size (proxy->priv->properties) > 0)
919     {
920       GVariant *changed_properties;
921       const gchar *invalidated_properties[1] = {NULL};
922
923       g_variant_get (result,
924                      "(@a{sv})",
925                      &changed_properties);
926       g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
927                      0,
928                      changed_properties,
929                      invalidated_properties);
930       g_variant_unref (changed_properties);
931     }
932
933  out:
934   ;
935 }
936
937 typedef struct
938 {
939   GDBusProxy *proxy;
940   GCancellable *cancellable;
941   gchar *name_owner;
942 } LoadPropertiesOnNameOwnerChangedData;
943
944 static void
945 on_name_owner_changed_get_all_cb (GDBusConnection *connection,
946                                   GAsyncResult    *res,
947                                   gpointer         user_data)
948 {
949   LoadPropertiesOnNameOwnerChangedData *data = user_data;
950   GVariant *result;
951   GError *error;
952   gboolean cancelled;
953
954   cancelled = FALSE;
955
956   error = NULL;
957   result = g_dbus_connection_call_finish (connection,
958                                           res,
959                                           &error);
960   if (result == NULL)
961     {
962       if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_CANCELLED)
963         cancelled = TRUE;
964       /* We just ignore if GetAll() is failing. Because this might happen
965        * if the object has no properties at all. Or if the caller is
966        * not authorized to see the properties.
967        *
968        * Either way, apps can know about this by using
969        * get_cached_property_names() or get_cached_property().
970        *
971        * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
972        * fact that GetAll() failed
973        */
974       //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
975       g_error_free (error);
976     }
977
978   /* and finally we can notify */
979   if (!cancelled)
980     {
981       g_free (data->proxy->priv->name_owner);
982       data->proxy->priv->name_owner = data->name_owner;
983       data->name_owner = NULL; /* to avoid an extra copy, we steal the string */
984
985       g_hash_table_remove_all (data->proxy->priv->properties);
986       if (result != NULL)
987         {
988           process_get_all_reply (data->proxy, result);
989           g_variant_unref (result);
990         }
991
992       g_object_notify (G_OBJECT (data->proxy), "g-name-owner");
993     }
994
995   if (data->cancellable == data->proxy->priv->get_all_cancellable)
996     data->proxy->priv->get_all_cancellable = NULL;
997
998   g_object_unref (data->proxy);
999   g_object_unref (data->cancellable);
1000   g_free (data->name_owner);
1001   g_free (data);
1002 }
1003
1004 static void
1005 on_name_owner_changed (GDBusConnection *connection,
1006                        const gchar      *sender_name,
1007                        const gchar      *object_path,
1008                        const gchar      *interface_name,
1009                        const gchar      *signal_name,
1010                        GVariant         *parameters,
1011                        gpointer          user_data)
1012 {
1013   GDBusProxy *proxy = G_DBUS_PROXY (user_data);
1014   const gchar *old_owner;
1015   const gchar *new_owner;
1016
1017   /* if we are already trying to load properties, cancel that */
1018   if (proxy->priv->get_all_cancellable != NULL)
1019     {
1020       g_cancellable_cancel (proxy->priv->get_all_cancellable);
1021       proxy->priv->get_all_cancellable = NULL;
1022     }
1023
1024   g_variant_get (parameters,
1025                  "(&s&s&s)",
1026                  NULL,
1027                  &old_owner,
1028                  &new_owner);
1029
1030   if (strlen (new_owner) == 0)
1031     {
1032       g_free (proxy->priv->name_owner);
1033       proxy->priv->name_owner = NULL;
1034
1035       /* Synthesize ::g-properties-changed changed */
1036       if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES) &&
1037           g_hash_table_size (proxy->priv->properties) > 0)
1038         {
1039           GVariantBuilder builder;
1040           GVariant *changed_properties;
1041           GPtrArray *invalidated_properties;
1042           GHashTableIter iter;
1043           const gchar *key;
1044
1045           /* Build changed_properties (always empty) and invalidated_properties ... */
1046           g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
1047           changed_properties = g_variant_builder_end (&builder);
1048           invalidated_properties = g_ptr_array_new_with_free_func (g_free);
1049           g_hash_table_iter_init (&iter, proxy->priv->properties);
1050           while (g_hash_table_iter_next (&iter, (gpointer) &key, NULL))
1051             g_ptr_array_add (invalidated_properties, g_strdup (key));
1052           g_ptr_array_add (invalidated_properties, NULL);
1053
1054           /* ... throw out the properties ... */
1055           g_hash_table_remove_all (proxy->priv->properties);
1056
1057           /* ... and finally emit the ::g-properties-changed signal */
1058           g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
1059                          0,
1060                          changed_properties,
1061                          (const gchar* const *) invalidated_properties->pdata);
1062           g_variant_unref (changed_properties);
1063           g_ptr_array_unref (invalidated_properties);
1064         }
1065       g_object_notify (G_OBJECT (proxy), "g-name-owner");
1066     }
1067   else
1068     {
1069       /* ignore duplicates - this can happen when activating the service */
1070       if (g_strcmp0 (new_owner, proxy->priv->name_owner) == 0)
1071         goto out;
1072
1073       if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES)
1074         {
1075           g_free (proxy->priv->name_owner);
1076           proxy->priv->name_owner = g_strdup (new_owner);
1077           g_hash_table_remove_all (proxy->priv->properties);
1078           g_object_notify (G_OBJECT (proxy), "g-name-owner");
1079         }
1080       else
1081         {
1082           LoadPropertiesOnNameOwnerChangedData *data;
1083
1084           /* start loading properties.. only then emit notify::g-name-owner .. we
1085            * need to be able to cancel this in the event another NameOwnerChanged
1086            * signal suddenly happens
1087            */
1088
1089           g_assert (proxy->priv->get_all_cancellable == NULL);
1090           proxy->priv->get_all_cancellable = g_cancellable_new ();
1091           data = g_new0 (LoadPropertiesOnNameOwnerChangedData, 1);
1092           data->proxy = g_object_ref (proxy);
1093           data->cancellable = proxy->priv->get_all_cancellable;
1094           data->name_owner = g_strdup (new_owner);
1095           g_dbus_connection_call (proxy->priv->connection,
1096                                   data->name_owner,
1097                                   proxy->priv->object_path,
1098                                   "org.freedesktop.DBus.Properties",
1099                                   "GetAll",
1100                                   g_variant_new ("(s)", proxy->priv->interface_name),
1101                                   G_VARIANT_TYPE ("(a{sv})"),
1102                                   G_DBUS_CALL_FLAGS_NONE,
1103                                   -1,           /* timeout */
1104                                   proxy->priv->get_all_cancellable,
1105                                   (GAsyncReadyCallback) on_name_owner_changed_get_all_cb,
1106                                   data);
1107         }
1108     }
1109
1110  out:
1111   ;
1112 }
1113
1114 /* ---------------------------------------------------------------------------------------------------- */
1115
1116 typedef struct
1117 {
1118   GDBusProxy *proxy;
1119   GCancellable *cancellable;
1120   GSimpleAsyncResult *simple;
1121 } AsyncInitData;
1122
1123 static void
1124 async_init_data_free (AsyncInitData *data)
1125 {
1126   g_object_unref (data->proxy);
1127   if (data->cancellable != NULL)
1128     g_object_unref (data->cancellable);
1129   g_object_unref (data->simple);
1130   g_free (data);
1131 }
1132
1133 static void
1134 async_init_get_all_cb (GDBusConnection *connection,
1135                        GAsyncResult    *res,
1136                        gpointer         user_data)
1137 {
1138   AsyncInitData *data = user_data;
1139   GVariant *result;
1140   GError *error;
1141
1142   error = NULL;
1143   result = g_dbus_connection_call_finish (connection,
1144                                           res,
1145                                           &error);
1146   if (result == NULL)
1147     {
1148       /* We just ignore if GetAll() is failing. Because this might happen
1149        * if the object has no properties at all. Or if the caller is
1150        * not authorized to see the properties.
1151        *
1152        * Either way, apps can know about this by using
1153        * get_cached_property_names() or get_cached_property().
1154        *
1155        * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
1156        * fact that GetAll() failed
1157        */
1158       //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
1159       g_error_free (error);
1160     }
1161   else
1162     {
1163       g_simple_async_result_set_op_res_gpointer (data->simple,
1164                                                  result,
1165                                                  (GDestroyNotify) g_variant_unref);
1166     }
1167
1168   g_simple_async_result_complete_in_idle (data->simple);
1169   async_init_data_free (data);
1170 }
1171
1172
1173 static void
1174 async_init_get_name_owner_cb (GDBusConnection *connection,
1175                               GAsyncResult    *res,
1176                               gpointer         user_data)
1177 {
1178   AsyncInitData *data = user_data;
1179
1180   if (res != NULL)
1181     {
1182       GError *error;
1183       GVariant *result;
1184
1185       error = NULL;
1186       result = g_dbus_connection_call_finish (connection,
1187                                               res,
1188                                               &error);
1189       if (result == NULL)
1190         {
1191           if (error->domain == G_DBUS_ERROR &&
1192               error->code == G_DBUS_ERROR_NAME_HAS_NO_OWNER)
1193             {
1194               g_error_free (error);
1195             }
1196           else
1197             {
1198               g_simple_async_result_take_error (data->simple, error);
1199               g_simple_async_result_complete_in_idle (data->simple);
1200               async_init_data_free (data);
1201               goto out;
1202             }
1203         }
1204       else
1205         {
1206           g_variant_get (result,
1207                          "(s)",
1208                          &data->proxy->priv->name_owner);
1209           g_variant_unref (result);
1210         }
1211     }
1212
1213   if (!(data->proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES))
1214     {
1215       /* load all properties asynchronously */
1216       g_dbus_connection_call (data->proxy->priv->connection,
1217                               data->proxy->priv->name_owner,
1218                               data->proxy->priv->object_path,
1219                               "org.freedesktop.DBus.Properties",
1220                               "GetAll",
1221                               g_variant_new ("(s)", data->proxy->priv->interface_name),
1222                               G_VARIANT_TYPE ("(a{sv})"),
1223                               G_DBUS_CALL_FLAGS_NONE,
1224                               -1,           /* timeout */
1225                               data->cancellable,
1226                               (GAsyncReadyCallback) async_init_get_all_cb,
1227                               data);
1228     }
1229   else
1230     {
1231       g_simple_async_result_complete_in_idle (data->simple);
1232       async_init_data_free (data);
1233     }
1234
1235  out:
1236   ;
1237 }
1238
1239 static void
1240 async_init_call_get_name_owner (AsyncInitData *data)
1241 {
1242   g_dbus_connection_call (data->proxy->priv->connection,
1243                           "org.freedesktop.DBus",  /* name */
1244                           "/org/freedesktop/DBus", /* object path */
1245                           "org.freedesktop.DBus",  /* interface */
1246                           "GetNameOwner",
1247                           g_variant_new ("(s)",
1248                                          data->proxy->priv->name),
1249                           G_VARIANT_TYPE ("(s)"),
1250                           G_DBUS_CALL_FLAGS_NONE,
1251                           -1,           /* timeout */
1252                           data->cancellable,
1253                           (GAsyncReadyCallback) async_init_get_name_owner_cb,
1254                           data);
1255 }
1256
1257 static void
1258 async_init_start_service_by_name_cb (GDBusConnection *connection,
1259                                      GAsyncResult    *res,
1260                                      gpointer         user_data)
1261 {
1262   AsyncInitData *data = user_data;
1263   GError *error;
1264   GVariant *result;
1265
1266   error = NULL;
1267   result = g_dbus_connection_call_finish (connection,
1268                                           res,
1269                                           &error);
1270   if (result == NULL)
1271     {
1272       /* Errors are not unexpected; the bus will reply e.g.
1273        *
1274        *   org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
1275        *   was not provided by any .service files
1276        *
1277        * This doesn't mean that the name doesn't have an owner, just
1278        * that it's not provided by a .service file. So just proceed to
1279        * invoke GetNameOwner() if dealing with that error.
1280        */
1281       if (error->domain == G_DBUS_ERROR &&
1282           error->code == G_DBUS_ERROR_SERVICE_UNKNOWN)
1283         {
1284           g_error_free (error);
1285         }
1286       else
1287         {
1288           g_prefix_error (&error,
1289                           _("Error calling StartServiceByName for %s: "),
1290                           data->proxy->priv->name);
1291           goto failed;
1292         }
1293     }
1294   else
1295     {
1296       guint32 start_service_result;
1297       g_variant_get (result,
1298                      "(u)",
1299                      &start_service_result);
1300       g_variant_unref (result);
1301       if (start_service_result == 1 ||  /* DBUS_START_REPLY_SUCCESS */
1302           start_service_result == 2)    /* DBUS_START_REPLY_ALREADY_RUNNING */
1303         {
1304           /* continue to invoke GetNameOwner() */
1305         }
1306       else
1307         {
1308           error = g_error_new (G_IO_ERROR,
1309                                G_IO_ERROR_FAILED,
1310                                _("Unexpected reply %d from StartServiceByName(\"%s\") method"),
1311                                start_service_result,
1312                                data->proxy->priv->name);
1313           goto failed;
1314         }
1315     }
1316
1317   async_init_call_get_name_owner (data);
1318   return;
1319
1320  failed:
1321   g_warn_if_fail (error != NULL);
1322   g_simple_async_result_take_error (data->simple, error);
1323   g_simple_async_result_complete_in_idle (data->simple);
1324   async_init_data_free (data);
1325 }
1326
1327 static void
1328 async_init_call_start_service_by_name (AsyncInitData *data)
1329 {
1330   g_dbus_connection_call (data->proxy->priv->connection,
1331                           "org.freedesktop.DBus",  /* name */
1332                           "/org/freedesktop/DBus", /* object path */
1333                           "org.freedesktop.DBus",  /* interface */
1334                           "StartServiceByName",
1335                           g_variant_new ("(su)",
1336                                          data->proxy->priv->name,
1337                                          0),
1338                           G_VARIANT_TYPE ("(u)"),
1339                           G_DBUS_CALL_FLAGS_NONE,
1340                           -1,           /* timeout */
1341                           data->cancellable,
1342                           (GAsyncReadyCallback) async_init_start_service_by_name_cb,
1343                           data);
1344 }
1345
1346 static void
1347 async_initable_init_second_async (GAsyncInitable      *initable,
1348                                   gint                 io_priority,
1349                                   GCancellable        *cancellable,
1350                                   GAsyncReadyCallback  callback,
1351                                   gpointer             user_data)
1352 {
1353   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1354   AsyncInitData *data;
1355
1356   data = g_new0 (AsyncInitData, 1);
1357   data->proxy = g_object_ref (proxy);
1358   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1359   data->simple = g_simple_async_result_new (G_OBJECT (proxy),
1360                                             callback,
1361                                             user_data,
1362                                             NULL);
1363
1364   /* Check name ownership asynchronously - possibly also start the service */
1365   if (proxy->priv->name == NULL)
1366     {
1367       /* Do nothing */
1368       async_init_get_name_owner_cb (proxy->priv->connection, NULL, data);
1369     }
1370   else if (g_dbus_is_unique_name (proxy->priv->name))
1371     {
1372       proxy->priv->name_owner = g_strdup (proxy->priv->name);
1373       async_init_get_name_owner_cb (proxy->priv->connection, NULL, data);
1374     }
1375   else
1376     {
1377       if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
1378         {
1379           async_init_call_get_name_owner (data);
1380         }
1381       else
1382         {
1383           async_init_call_start_service_by_name (data);
1384         }
1385     }
1386 }
1387
1388 static gboolean
1389 async_initable_init_second_finish (GAsyncInitable  *initable,
1390                                    GAsyncResult    *res,
1391                                    GError         **error)
1392 {
1393   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1394   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1395   GVariant *result;
1396   gboolean ret;
1397
1398   ret = FALSE;
1399
1400   if (g_simple_async_result_propagate_error (simple, error))
1401     goto out;
1402
1403   result = g_simple_async_result_get_op_res_gpointer (simple);
1404   if (result != NULL)
1405     {
1406       process_get_all_reply (proxy, result);
1407     }
1408
1409   ret = TRUE;
1410
1411  out:
1412   proxy->priv->initialized = TRUE;
1413   return ret;
1414 }
1415
1416 /* ---------------------------------------------------------------------------------------------------- */
1417
1418 static void
1419 async_initable_init_first (GAsyncInitable *initable)
1420 {
1421   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1422
1423   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES))
1424     {
1425       /* subscribe to PropertiesChanged() */
1426       proxy->priv->properties_changed_subscriber_id =
1427         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1428                                             proxy->priv->name,
1429                                             "org.freedesktop.DBus.Properties",
1430                                             "PropertiesChanged",
1431                                             proxy->priv->object_path,
1432                                             proxy->priv->interface_name,
1433                                             G_DBUS_SIGNAL_FLAGS_NONE,
1434                                             on_properties_changed,
1435                                             proxy,
1436                                             NULL);
1437     }
1438
1439   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS))
1440     {
1441       /* subscribe to all signals for the object */
1442       proxy->priv->signals_subscriber_id =
1443         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1444                                             proxy->priv->name,
1445                                             proxy->priv->interface_name,
1446                                             NULL,                        /* member */
1447                                             proxy->priv->object_path,
1448                                             NULL,                        /* arg0 */
1449                                             G_DBUS_SIGNAL_FLAGS_NONE,
1450                                             on_signal_received,
1451                                             proxy,
1452                                             NULL);
1453     }
1454
1455   if (proxy->priv->name != NULL && !g_dbus_is_unique_name (proxy->priv->name))
1456     {
1457       proxy->priv->name_owner_changed_subscription_id =
1458         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1459                                             "org.freedesktop.DBus",  /* name */
1460                                             "org.freedesktop.DBus",  /* interface */
1461                                             "NameOwnerChanged",      /* signal name */
1462                                             "/org/freedesktop/DBus", /* path */
1463                                             proxy->priv->name,       /* arg0 */
1464                                             G_DBUS_SIGNAL_FLAGS_NONE,
1465                                             on_name_owner_changed,
1466                                             proxy,
1467                                             NULL);
1468     }
1469 }
1470
1471 /* ---------------------------------------------------------------------------------------------------- */
1472
1473 /* initialization is split into two parts - the first is the
1474  * non-blocing part that requires the callers GMainContext - the
1475  * second is a blocking part async part that doesn't require the
1476  * callers GMainContext.. we do this split so the code can be reused
1477  * in the GInitable implementation below.
1478  *
1479  * Note that obtaining a GDBusConnection is not shared between the two
1480  * paths.
1481  */
1482
1483 typedef struct
1484 {
1485   GDBusProxy          *proxy;
1486   gint                 io_priority;
1487   GCancellable        *cancellable;
1488   GAsyncReadyCallback  callback;
1489   gpointer             user_data;
1490 } GetConnectionData;
1491
1492 static void
1493 get_connection_cb (GObject       *source_object,
1494                    GAsyncResult  *res,
1495                    gpointer       user_data)
1496 {
1497   GetConnectionData *data = user_data;
1498   GError *error;
1499
1500   error = NULL;
1501   data->proxy->priv->connection = g_bus_get_finish (res, &error);
1502   if (data->proxy->priv->connection == NULL)
1503     {
1504       GSimpleAsyncResult *simple;
1505       simple = g_simple_async_result_new (G_OBJECT (data->proxy),
1506                                           data->callback,
1507                                           data->user_data,
1508                                           NULL);
1509       g_simple_async_result_take_error (simple, error);
1510       g_simple_async_result_complete_in_idle (simple);
1511       g_object_unref (simple);
1512     }
1513   else
1514     {
1515       async_initable_init_first (G_ASYNC_INITABLE (data->proxy));
1516       async_initable_init_second_async (G_ASYNC_INITABLE (data->proxy),
1517                                         data->io_priority,
1518                                         data->cancellable,
1519                                         data->callback,
1520                                         data->user_data);
1521     }
1522
1523   if (data->cancellable != NULL)
1524     g_object_unref (data->cancellable);
1525   if (data->proxy != NULL)
1526     g_object_unref (data->proxy);
1527   g_free (data);
1528 }
1529
1530 static void
1531 async_initable_init_async (GAsyncInitable      *initable,
1532                            gint                 io_priority,
1533                            GCancellable        *cancellable,
1534                            GAsyncReadyCallback  callback,
1535                            gpointer             user_data)
1536 {
1537   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1538
1539   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1540     {
1541       GetConnectionData *data;
1542
1543       g_assert (proxy->priv->connection == NULL);
1544
1545       data = g_new0 (GetConnectionData, 1);
1546       data->proxy = g_object_ref (proxy);
1547       data->io_priority = io_priority;
1548       data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1549       data->callback = callback;
1550       data->user_data = user_data;
1551       g_bus_get (proxy->priv->bus_type,
1552                  cancellable,
1553                  get_connection_cb,
1554                  data);
1555     }
1556   else
1557     {
1558       async_initable_init_first (initable);
1559       async_initable_init_second_async (initable, io_priority, cancellable, callback, user_data);
1560     }
1561 }
1562
1563 static gboolean
1564 async_initable_init_finish (GAsyncInitable  *initable,
1565                             GAsyncResult    *res,
1566                             GError         **error)
1567 {
1568   return async_initable_init_second_finish (initable, res, error);
1569 }
1570
1571 static void
1572 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1573 {
1574   async_initable_iface->init_async = async_initable_init_async;
1575   async_initable_iface->init_finish = async_initable_init_finish;
1576 }
1577
1578 /* ---------------------------------------------------------------------------------------------------- */
1579
1580 typedef struct
1581 {
1582   GMainContext *context;
1583   GMainLoop *loop;
1584   GAsyncResult *res;
1585 } InitableAsyncInitableData;
1586
1587 static void
1588 async_initable_init_async_cb (GObject      *source_object,
1589                               GAsyncResult *res,
1590                               gpointer      user_data)
1591 {
1592   InitableAsyncInitableData *data = user_data;
1593   data->res = g_object_ref (res);
1594   g_main_loop_quit (data->loop);
1595 }
1596
1597 /* Simply reuse the GAsyncInitable implementation but run the first
1598  * part (that is non-blocking and requires the callers GMainContext)
1599  * with the callers GMainContext.. and the second with a private
1600  * GMainContext (bug 621310 is slightly related).
1601  *
1602  * Note that obtaining a GDBusConnection is not shared between the two
1603  * paths.
1604  */
1605 static gboolean
1606 initable_init (GInitable     *initable,
1607                GCancellable  *cancellable,
1608                GError       **error)
1609 {
1610   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1611   InitableAsyncInitableData *data;
1612   gboolean ret;
1613
1614   ret = FALSE;
1615
1616   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1617     {
1618       g_assert (proxy->priv->connection == NULL);
1619       proxy->priv->connection = g_bus_get_sync (proxy->priv->bus_type,
1620                                                 cancellable,
1621                                                 error);
1622       if (proxy->priv->connection == NULL)
1623         goto out;
1624     }
1625
1626   async_initable_init_first (G_ASYNC_INITABLE (initable));
1627
1628   data = g_new0 (InitableAsyncInitableData, 1);
1629   data->context = g_main_context_new ();
1630   data->loop = g_main_loop_new (data->context, FALSE);
1631
1632   g_main_context_push_thread_default (data->context);
1633
1634   async_initable_init_second_async (G_ASYNC_INITABLE (initable),
1635                                     G_PRIORITY_DEFAULT,
1636                                     cancellable,
1637                                     async_initable_init_async_cb,
1638                                     data);
1639
1640   g_main_loop_run (data->loop);
1641
1642   ret = async_initable_init_second_finish (G_ASYNC_INITABLE (initable),
1643                                            data->res,
1644                                            error);
1645
1646   g_main_context_pop_thread_default (data->context);
1647
1648   g_main_context_unref (data->context);
1649   g_main_loop_unref (data->loop);
1650   g_object_unref (data->res);
1651   g_free (data);
1652
1653  out:
1654
1655   return ret;
1656 }
1657
1658 static void
1659 initable_iface_init (GInitableIface *initable_iface)
1660 {
1661   initable_iface->init = initable_init;
1662 }
1663
1664 /* ---------------------------------------------------------------------------------------------------- */
1665
1666 /**
1667  * g_dbus_proxy_new:
1668  * @connection: A #GDBusConnection.
1669  * @flags: Flags used when constructing the proxy.
1670  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1671  * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
1672  * @object_path: An object path.
1673  * @interface_name: A D-Bus interface name.
1674  * @cancellable: A #GCancellable or %NULL.
1675  * @callback: Callback function to invoke when the proxy is ready.
1676  * @user_data: User data to pass to @callback.
1677  *
1678  * Creates a proxy for accessing @interface_name on the remote object
1679  * at @object_path owned by @name at @connection and asynchronously
1680  * loads D-Bus properties unless the
1681  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used. Connect to
1682  * the #GDBusProxy::g-properties-changed signal to get notified about
1683  * property changes.
1684  *
1685  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
1686  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
1687  * to handle signals from the remote object.
1688  *
1689  * If @name is a well-known name and the
1690  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag isn't set and no name
1691  * owner currently exists, the message bus will be requested to launch
1692  * a name owner for the name.
1693  *
1694  * This is a failable asynchronous constructor - when the proxy is
1695  * ready, @callback will be invoked and you can use
1696  * g_dbus_proxy_new_finish() to get the result.
1697  *
1698  * See g_dbus_proxy_new_sync() and for a synchronous version of this constructor.
1699  *
1700  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1701  *
1702  * Since: 2.26
1703  */
1704 void
1705 g_dbus_proxy_new (GDBusConnection     *connection,
1706                   GDBusProxyFlags      flags,
1707                   GDBusInterfaceInfo  *info,
1708                   const gchar         *name,
1709                   const gchar         *object_path,
1710                   const gchar         *interface_name,
1711                   GCancellable        *cancellable,
1712                   GAsyncReadyCallback  callback,
1713                   gpointer             user_data)
1714 {
1715   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1716   g_return_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) || g_dbus_is_name (name));
1717   g_return_if_fail (g_variant_is_object_path (object_path));
1718   g_return_if_fail (g_dbus_is_interface_name (interface_name));
1719
1720   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
1721                               G_PRIORITY_DEFAULT,
1722                               cancellable,
1723                               callback,
1724                               user_data,
1725                               "g-flags", flags,
1726                               "g-interface-info", info,
1727                               "g-name", name,
1728                               "g-connection", connection,
1729                               "g-object-path", object_path,
1730                               "g-interface-name", interface_name,
1731                               NULL);
1732 }
1733
1734 /**
1735  * g_dbus_proxy_new_finish:
1736  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new().
1737  * @error: Return location for error or %NULL.
1738  *
1739  * Finishes creating a #GDBusProxy.
1740  *
1741  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
1742  *
1743  * Since: 2.26
1744  */
1745 GDBusProxy *
1746 g_dbus_proxy_new_finish (GAsyncResult  *res,
1747                          GError       **error)
1748 {
1749   GObject *object;
1750   GObject *source_object;
1751
1752   source_object = g_async_result_get_source_object (res);
1753   g_assert (source_object != NULL);
1754
1755   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1756                                         res,
1757                                         error);
1758   g_object_unref (source_object);
1759
1760   if (object != NULL)
1761     return G_DBUS_PROXY (object);
1762   else
1763     return NULL;
1764 }
1765
1766 /**
1767  * g_dbus_proxy_new_sync:
1768  * @connection: A #GDBusConnection.
1769  * @flags: Flags used when constructing the proxy.
1770  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1771  * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
1772  * @object_path: An object path.
1773  * @interface_name: A D-Bus interface name.
1774  * @cancellable: (allow-none): A #GCancellable or %NULL.
1775  * @error: (allow-none): Return location for error or %NULL.
1776  *
1777  * Creates a proxy for accessing @interface_name on the remote object
1778  * at @object_path owned by @name at @connection and synchronously
1779  * loads D-Bus properties unless the
1780  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used.
1781  *
1782  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
1783  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
1784  * to handle signals from the remote object.
1785  *
1786  * If @name is a well-known name and the
1787  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag isn't set and no name
1788  * owner currently exists, the message bus will be requested to launch
1789  * a name owner for the name.
1790  *
1791  * This is a synchronous failable constructor. See g_dbus_proxy_new()
1792  * and g_dbus_proxy_new_finish() for the asynchronous version.
1793  *
1794  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1795  *
1796  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
1797  *
1798  * Since: 2.26
1799  */
1800 GDBusProxy *
1801 g_dbus_proxy_new_sync (GDBusConnection     *connection,
1802                        GDBusProxyFlags      flags,
1803                        GDBusInterfaceInfo  *info,
1804                        const gchar         *name,
1805                        const gchar         *object_path,
1806                        const gchar         *interface_name,
1807                        GCancellable        *cancellable,
1808                        GError             **error)
1809 {
1810   GInitable *initable;
1811
1812   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1813   g_return_val_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) ||
1814                         g_dbus_is_name (name), NULL);
1815   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1816   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
1817
1818   initable = g_initable_new (G_TYPE_DBUS_PROXY,
1819                              cancellable,
1820                              error,
1821                              "g-flags", flags,
1822                              "g-interface-info", info,
1823                              "g-name", name,
1824                              "g-connection", connection,
1825                              "g-object-path", object_path,
1826                              "g-interface-name", interface_name,
1827                              NULL);
1828   if (initable != NULL)
1829     return G_DBUS_PROXY (initable);
1830   else
1831     return NULL;
1832 }
1833
1834 /* ---------------------------------------------------------------------------------------------------- */
1835
1836 /**
1837  * g_dbus_proxy_new_for_bus:
1838  * @bus_type: A #GBusType.
1839  * @flags: Flags used when constructing the proxy.
1840  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1841  * @name: A bus name (well-known or unique).
1842  * @object_path: An object path.
1843  * @interface_name: A D-Bus interface name.
1844  * @cancellable: A #GCancellable or %NULL.
1845  * @callback: Callback function to invoke when the proxy is ready.
1846  * @user_data: User data to pass to @callback.
1847  *
1848  * Like g_dbus_proxy_new() but takes a #GBusType instead of a #GDBusConnection.
1849  *
1850  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1851  *
1852  * Since: 2.26
1853  */
1854 void
1855 g_dbus_proxy_new_for_bus (GBusType             bus_type,
1856                           GDBusProxyFlags      flags,
1857                           GDBusInterfaceInfo  *info,
1858                           const gchar         *name,
1859                           const gchar         *object_path,
1860                           const gchar         *interface_name,
1861                           GCancellable        *cancellable,
1862                           GAsyncReadyCallback  callback,
1863                           gpointer             user_data)
1864 {
1865   g_return_if_fail (g_dbus_is_name (name));
1866   g_return_if_fail (g_variant_is_object_path (object_path));
1867   g_return_if_fail (g_dbus_is_interface_name (interface_name));
1868
1869   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
1870                               G_PRIORITY_DEFAULT,
1871                               cancellable,
1872                               callback,
1873                               user_data,
1874                               "g-flags", flags,
1875                               "g-interface-info", info,
1876                               "g-name", name,
1877                               "g-bus-type", bus_type,
1878                               "g-object-path", object_path,
1879                               "g-interface-name", interface_name,
1880                               NULL);
1881 }
1882
1883 /**
1884  * g_dbus_proxy_new_for_bus_finish:
1885  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new_for_bus().
1886  * @error: Return location for error or %NULL.
1887  *
1888  * Finishes creating a #GDBusProxy.
1889  *
1890  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
1891  *
1892  * Since: 2.26
1893  */
1894 GDBusProxy *
1895 g_dbus_proxy_new_for_bus_finish (GAsyncResult  *res,
1896                                  GError       **error)
1897 {
1898   return g_dbus_proxy_new_finish (res, error);
1899 }
1900
1901 /**
1902  * g_dbus_proxy_new_for_bus_sync:
1903  * @bus_type: A #GBusType.
1904  * @flags: Flags used when constructing the proxy.
1905  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface
1906  *        that @proxy conforms to or %NULL.
1907  * @name: A bus name (well-known or unique).
1908  * @object_path: An object path.
1909  * @interface_name: A D-Bus interface name.
1910  * @cancellable: A #GCancellable or %NULL.
1911  * @error: Return location for error or %NULL.
1912  *
1913  * Like g_dbus_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection.
1914  *
1915  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1916  *
1917  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
1918  *
1919  * Since: 2.26
1920  */
1921 GDBusProxy *
1922 g_dbus_proxy_new_for_bus_sync (GBusType             bus_type,
1923                                GDBusProxyFlags      flags,
1924                                GDBusInterfaceInfo  *info,
1925                                const gchar         *name,
1926                                const gchar         *object_path,
1927                                const gchar         *interface_name,
1928                                GCancellable        *cancellable,
1929                                GError             **error)
1930 {
1931   GInitable *initable;
1932
1933   g_return_val_if_fail (g_dbus_is_name (name), NULL);
1934   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1935   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
1936
1937   initable = g_initable_new (G_TYPE_DBUS_PROXY,
1938                              cancellable,
1939                              error,
1940                              "g-flags", flags,
1941                              "g-interface-info", info,
1942                              "g-name", name,
1943                              "g-bus-type", bus_type,
1944                              "g-object-path", object_path,
1945                              "g-interface-name", interface_name,
1946                              NULL);
1947   if (initable != NULL)
1948     return G_DBUS_PROXY (initable);
1949   else
1950     return NULL;
1951 }
1952
1953 /* ---------------------------------------------------------------------------------------------------- */
1954
1955 /**
1956  * g_dbus_proxy_get_connection:
1957  * @proxy: A #GDBusProxy.
1958  *
1959  * Gets the connection @proxy is for.
1960  *
1961  * Returns: (transfer none): A #GDBusConnection owned by @proxy. Do not free.
1962  *
1963  * Since: 2.26
1964  */
1965 GDBusConnection *
1966 g_dbus_proxy_get_connection (GDBusProxy *proxy)
1967 {
1968   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
1969   return proxy->priv->connection;
1970 }
1971
1972 /**
1973  * g_dbus_proxy_get_flags:
1974  * @proxy: A #GDBusProxy.
1975  *
1976  * Gets the flags that @proxy was constructed with.
1977  *
1978  * Returns: Flags from the #GDBusProxyFlags enumeration.
1979  *
1980  * Since: 2.26
1981  */
1982 GDBusProxyFlags
1983 g_dbus_proxy_get_flags (GDBusProxy *proxy)
1984 {
1985   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), 0);
1986   return proxy->priv->flags;
1987 }
1988
1989 /**
1990  * g_dbus_proxy_get_name:
1991  * @proxy: A #GDBusProxy.
1992  *
1993  * Gets the name that @proxy was constructed for.
1994  *
1995  * Returns: A string owned by @proxy. Do not free.
1996  *
1997  * Since: 2.26
1998  */
1999 const gchar *
2000 g_dbus_proxy_get_name (GDBusProxy *proxy)
2001 {
2002   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2003   return proxy->priv->name;
2004 }
2005
2006 /**
2007  * g_dbus_proxy_get_name_owner:
2008  * @proxy: A #GDBusProxy.
2009  *
2010  * The unique name that owns the name that @proxy is for or %NULL if
2011  * no-one currently owns that name. You may connect to the
2012  * #GObject::notify signal to track changes to the
2013  * #GDBusProxy:g-name-owner property.
2014  *
2015  * Returns: The name owner or %NULL if no name owner exists. Free with g_free().
2016  *
2017  * Since: 2.26
2018  */
2019 gchar *
2020 g_dbus_proxy_get_name_owner (GDBusProxy *proxy)
2021 {
2022   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2023   return g_strdup (proxy->priv->name_owner);
2024 }
2025
2026 /**
2027  * g_dbus_proxy_get_object_path:
2028  * @proxy: A #GDBusProxy.
2029  *
2030  * Gets the object path @proxy is for.
2031  *
2032  * Returns: A string owned by @proxy. Do not free.
2033  *
2034  * Since: 2.26
2035  */
2036 const gchar *
2037 g_dbus_proxy_get_object_path (GDBusProxy *proxy)
2038 {
2039   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2040   return proxy->priv->object_path;
2041 }
2042
2043 /**
2044  * g_dbus_proxy_get_interface_name:
2045  * @proxy: A #GDBusProxy.
2046  *
2047  * Gets the D-Bus interface name @proxy is for.
2048  *
2049  * Returns: A string owned by @proxy. Do not free.
2050  *
2051  * Since: 2.26
2052  */
2053 const gchar *
2054 g_dbus_proxy_get_interface_name (GDBusProxy *proxy)
2055 {
2056   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2057   return proxy->priv->interface_name;
2058 }
2059
2060 /**
2061  * g_dbus_proxy_get_default_timeout:
2062  * @proxy: A #GDBusProxy.
2063  *
2064  * Gets the timeout to use if -1 (specifying default timeout) is
2065  * passed as @timeout_msec in the g_dbus_proxy_call() and
2066  * g_dbus_proxy_call_sync() functions.
2067  *
2068  * See the #GDBusProxy:g-default-timeout property for more details.
2069  *
2070  * Returns: Timeout to use for @proxy.
2071  *
2072  * Since: 2.26
2073  */
2074 gint
2075 g_dbus_proxy_get_default_timeout (GDBusProxy *proxy)
2076 {
2077   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), -1);
2078   return proxy->priv->timeout_msec;
2079 }
2080
2081 /**
2082  * g_dbus_proxy_set_default_timeout:
2083  * @proxy: A #GDBusProxy.
2084  * @timeout_msec: Timeout in milliseconds.
2085  *
2086  * Sets the timeout to use if -1 (specifying default timeout) is
2087  * passed as @timeout_msec in the g_dbus_proxy_call() and
2088  * g_dbus_proxy_call_sync() functions.
2089  *
2090  * See the #GDBusProxy:g-default-timeout property for more details.
2091  *
2092  * Since: 2.26
2093  */
2094 void
2095 g_dbus_proxy_set_default_timeout (GDBusProxy *proxy,
2096                                   gint        timeout_msec)
2097 {
2098   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2099   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2100
2101   /* TODO: locking? */
2102   if (proxy->priv->timeout_msec != timeout_msec)
2103     {
2104       proxy->priv->timeout_msec = timeout_msec;
2105       g_object_notify (G_OBJECT (proxy), "g-default-timeout");
2106     }
2107 }
2108
2109 /**
2110  * g_dbus_proxy_get_interface_info:
2111  * @proxy: A #GDBusProxy
2112  *
2113  * Returns the #GDBusInterfaceInfo, if any, specifying the minimal
2114  * interface that @proxy conforms to.
2115  *
2116  * See the #GDBusProxy:g-interface-info property for more details.
2117  *
2118  * Returns: A #GDBusInterfaceInfo or %NULL. Do not unref the returned
2119  * object, it is owned by @proxy.
2120  *
2121  * Since: 2.26
2122  */
2123 GDBusInterfaceInfo *
2124 g_dbus_proxy_get_interface_info (GDBusProxy *proxy)
2125 {
2126   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2127   return proxy->priv->expected_interface;
2128 }
2129
2130 /**
2131  * g_dbus_proxy_set_interface_info:
2132  * @proxy: A #GDBusProxy
2133  * @info: (allow-none): Minimum interface this proxy conforms to or %NULL to unset.
2134  *
2135  * Ensure that interactions with @proxy conform to the given
2136  * interface.  For example, when completing a method call, if the type
2137  * signature of the message isn't what's expected, the given #GError
2138  * is set.  Signals that have a type signature mismatch are simply
2139  * dropped.
2140  *
2141  * See the #GDBusProxy:g-interface-info property for more details.
2142  *
2143  * Since: 2.26
2144  */
2145 void
2146 g_dbus_proxy_set_interface_info (GDBusProxy         *proxy,
2147                                  GDBusInterfaceInfo *info)
2148 {
2149   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2150   if (proxy->priv->expected_interface != NULL)
2151     {
2152       g_dbus_interface_info_cache_release (proxy->priv->expected_interface);
2153       g_dbus_interface_info_unref (proxy->priv->expected_interface);
2154     }
2155   proxy->priv->expected_interface = info != NULL ? g_dbus_interface_info_ref (info) : NULL;
2156   if (proxy->priv->expected_interface != NULL)
2157     g_dbus_interface_info_cache_build (proxy->priv->expected_interface);
2158 }
2159
2160 /* ---------------------------------------------------------------------------------------------------- */
2161
2162 static gboolean
2163 maybe_split_method_name (const gchar  *method_name,
2164                          gchar       **out_interface_name,
2165                          const gchar **out_method_name)
2166 {
2167   gboolean was_split;
2168
2169   was_split = FALSE;
2170   g_assert (out_interface_name != NULL);
2171   g_assert (out_method_name != NULL);
2172   *out_interface_name = NULL;
2173   *out_method_name = NULL;
2174
2175   if (strchr (method_name, '.') != NULL)
2176     {
2177       gchar *p;
2178       gchar *last_dot;
2179
2180       p = g_strdup (method_name);
2181       last_dot = strrchr (p, '.');
2182       *last_dot = '\0';
2183
2184       *out_interface_name = p;
2185       *out_method_name = last_dot + 1;
2186
2187       was_split = TRUE;
2188     }
2189
2190   return was_split;
2191 }
2192
2193
2194 static void
2195 reply_cb (GDBusConnection *connection,
2196           GAsyncResult    *res,
2197           gpointer         user_data)
2198 {
2199   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
2200   GVariant *value;
2201   GError *error;
2202
2203   error = NULL;
2204   value = g_dbus_connection_call_finish (connection,
2205                                          res,
2206                                          &error);
2207   if (error != NULL)
2208     {
2209       g_simple_async_result_take_error (simple, error);
2210     }
2211   else
2212     {
2213       g_simple_async_result_set_op_res_gpointer (simple,
2214                                                  value,
2215                                                  (GDestroyNotify) g_variant_unref);
2216     }
2217
2218   /* no need to complete in idle since the method GDBusConnection already does */
2219   g_simple_async_result_complete (simple);
2220   g_object_unref (simple);
2221 }
2222
2223 static const GDBusMethodInfo *
2224 lookup_method_info_or_warn (GDBusProxy  *proxy,
2225                             const gchar *method_name)
2226 {
2227   const GDBusMethodInfo *info;
2228
2229   if (proxy->priv->expected_interface == NULL)
2230     return NULL;
2231
2232   info = g_dbus_interface_info_lookup_method (proxy->priv->expected_interface, method_name);
2233   if (info == NULL)
2234     {
2235       g_warning ("Trying to invoke method %s which isn't in expected interface %s",
2236                  method_name, proxy->priv->expected_interface->name);
2237     }
2238
2239   return info;
2240 }
2241
2242 static const gchar *
2243 get_destination_for_call (GDBusProxy *proxy)
2244 {
2245   const gchar *ret;
2246
2247   ret = NULL;
2248
2249   /* If proxy->priv->name is a unique name, then proxy->priv->name_owner
2250    * is never NULL and always the same as proxy->priv->name. We use this
2251    * knowledge to avoid checking if proxy->priv->name is a unique or
2252    * well-known name.
2253    */
2254   ret = proxy->priv->name_owner;
2255   if (ret != NULL)
2256     goto out;
2257
2258   if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
2259     goto out;
2260
2261   ret = proxy->priv->name;
2262
2263  out:
2264   return ret;
2265 }
2266
2267 /**
2268  * g_dbus_proxy_call:
2269  * @proxy: A #GDBusProxy.
2270  * @method_name: Name of method to invoke.
2271  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
2272  * @flags: Flags from the #GDBusCallFlags enumeration.
2273  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
2274  *                "infinite") or -1 to use the proxy default timeout.
2275  * @cancellable: A #GCancellable or %NULL.
2276  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
2277  * care about the result of the method invocation.
2278  * @user_data: The data to pass to @callback.
2279  *
2280  * Asynchronously invokes the @method_name method on @proxy.
2281  *
2282  * If @method_name contains any dots, then @name is split into interface and
2283  * method name parts. This allows using @proxy for invoking methods on
2284  * other interfaces.
2285  *
2286  * If the #GDBusConnection associated with @proxy is closed then
2287  * the operation will fail with %G_IO_ERROR_CLOSED. If
2288  * @cancellable is canceled, the operation will fail with
2289  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
2290  * compatible with the D-Bus protocol, the operation fails with
2291  * %G_IO_ERROR_INVALID_ARGUMENT.
2292  *
2293  * If the @parameters #GVariant is floating, it is consumed. This allows
2294  * convenient 'inline' use of g_variant_new(), e.g.:
2295  * |[
2296  *  g_dbus_proxy_call (proxy,
2297  *                     "TwoStrings",
2298  *                     g_variant_new ("(ss)",
2299  *                                    "Thing One",
2300  *                                    "Thing Two"),
2301  *                     G_DBUS_CALL_FLAGS_NONE,
2302  *                     -1,
2303  *                     NULL,
2304  *                     (GAsyncReadyCallback) two_strings_done,
2305  *                     &amp;data);
2306  * ]|
2307  *
2308  * This is an asynchronous method. When the operation is finished,
2309  * @callback will be invoked in the
2310  * <link linkend="g-main-context-push-thread-default">thread-default
2311  * main loop</link> of the thread you are calling this method from.
2312  * You can then call g_dbus_proxy_call_finish() to get the result of
2313  * the operation. See g_dbus_proxy_call_sync() for the synchronous
2314  * version of this method.
2315  *
2316  * Since: 2.26
2317  */
2318 void
2319 g_dbus_proxy_call (GDBusProxy          *proxy,
2320                    const gchar         *method_name,
2321                    GVariant            *parameters,
2322                    GDBusCallFlags       flags,
2323                    gint                 timeout_msec,
2324                    GCancellable        *cancellable,
2325                    GAsyncReadyCallback  callback,
2326                    gpointer             user_data)
2327 {
2328   GSimpleAsyncResult *simple;
2329   gboolean was_split;
2330   gchar *split_interface_name;
2331   const gchar *split_method_name;
2332   const gchar *target_method_name;
2333   const gchar *target_interface_name;
2334   const gchar *destination;
2335   GVariantType *reply_type;
2336
2337   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2338   g_return_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name));
2339   g_return_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
2340   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2341
2342   reply_type = NULL;
2343   split_interface_name = NULL;
2344
2345   simple = g_simple_async_result_new (G_OBJECT (proxy),
2346                                       callback,
2347                                       user_data,
2348                                       g_dbus_proxy_call);
2349
2350   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2351   target_method_name = was_split ? split_method_name : method_name;
2352   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2353
2354   /* Warn if method is unexpected (cf. :g-interface-info) */
2355   if (!was_split)
2356     {
2357       const GDBusMethodInfo *expected_method_info;
2358       expected_method_info = lookup_method_info_or_warn (proxy, target_method_name);
2359       if (expected_method_info != NULL)
2360         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2361     }
2362
2363   destination = NULL;
2364   if (proxy->priv->name != NULL)
2365     {
2366       destination = get_destination_for_call (proxy);
2367       if (destination == NULL)
2368         {
2369           g_simple_async_result_set_error (simple,
2370                                            G_IO_ERROR,
2371                                            G_IO_ERROR_FAILED,
2372                                            _("Cannot invoke method; proxy is for a well-known name without an owner and proxy was constructed with the G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag"));
2373           goto out;
2374         }
2375     }
2376
2377   g_dbus_connection_call (proxy->priv->connection,
2378                           destination,
2379                           proxy->priv->object_path,
2380                           target_interface_name,
2381                           target_method_name,
2382                           parameters,
2383                           reply_type,
2384                           flags,
2385                           timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2386                           cancellable,
2387                           (GAsyncReadyCallback) reply_cb,
2388                           simple);
2389
2390  out:
2391   if (reply_type != NULL)
2392     g_variant_type_free (reply_type);
2393
2394   g_free (split_interface_name);
2395 }
2396
2397 /**
2398  * g_dbus_proxy_call_finish:
2399  * @proxy: A #GDBusProxy.
2400  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_proxy_call().
2401  * @error: Return location for error or %NULL.
2402  *
2403  * Finishes an operation started with g_dbus_proxy_call().
2404  *
2405  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
2406  * return values. Free with g_variant_unref().
2407  *
2408  * Since: 2.26
2409  */
2410 GVariant *
2411 g_dbus_proxy_call_finish (GDBusProxy    *proxy,
2412                           GAsyncResult  *res,
2413                           GError       **error)
2414 {
2415   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2416   GVariant *value;
2417
2418   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2419   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2420   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2421
2422   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_proxy_call);
2423
2424   value = NULL;
2425
2426   if (g_simple_async_result_propagate_error (simple, error))
2427     goto out;
2428
2429   value = g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
2430
2431  out:
2432   return value;
2433 }
2434
2435 /**
2436  * g_dbus_proxy_call_sync:
2437  * @proxy: A #GDBusProxy.
2438  * @method_name: Name of method to invoke.
2439  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
2440  *              or %NULL if not passing parameters.
2441  * @flags: Flags from the #GDBusCallFlags enumeration.
2442  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
2443  *                "infinite") or -1 to use the proxy default timeout.
2444  * @cancellable: A #GCancellable or %NULL.
2445  * @error: Return location for error or %NULL.
2446  *
2447  * Synchronously invokes the @method_name method on @proxy.
2448  *
2449  * If @method_name contains any dots, then @name is split into interface and
2450  * method name parts. This allows using @proxy for invoking methods on
2451  * other interfaces.
2452  *
2453  * If the #GDBusConnection associated with @proxy is disconnected then
2454  * the operation will fail with %G_IO_ERROR_CLOSED. If
2455  * @cancellable is canceled, the operation will fail with
2456  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
2457  * compatible with the D-Bus protocol, the operation fails with
2458  * %G_IO_ERROR_INVALID_ARGUMENT.
2459  *
2460  * If the @parameters #GVariant is floating, it is consumed. This allows
2461  * convenient 'inline' use of g_variant_new(), e.g.:
2462  * |[
2463  *  g_dbus_proxy_call_sync (proxy,
2464  *                          "TwoStrings",
2465  *                          g_variant_new ("(ss)",
2466  *                                         "Thing One",
2467  *                                         "Thing Two"),
2468  *                          G_DBUS_CALL_FLAGS_NONE,
2469  *                          -1,
2470  *                          NULL,
2471  *                          &amp;error);
2472  * ]|
2473  *
2474  * The calling thread is blocked until a reply is received. See
2475  * g_dbus_proxy_call() for the asynchronous version of this
2476  * method.
2477  *
2478  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
2479  * return values. Free with g_variant_unref().
2480  *
2481  * Since: 2.26
2482  */
2483 GVariant *
2484 g_dbus_proxy_call_sync (GDBusProxy      *proxy,
2485                         const gchar     *method_name,
2486                         GVariant        *parameters,
2487                         GDBusCallFlags   flags,
2488                         gint             timeout_msec,
2489                         GCancellable    *cancellable,
2490                         GError         **error)
2491 {
2492   GVariant *ret;
2493   gboolean was_split;
2494   gchar *split_interface_name;
2495   const gchar *split_method_name;
2496   const gchar *target_method_name;
2497   const gchar *target_interface_name;
2498   const gchar *destination;
2499   GVariantType *reply_type;
2500
2501   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2502   g_return_val_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name), NULL);
2503   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
2504   g_return_val_if_fail (timeout_msec == -1 || timeout_msec >= 0, NULL);
2505   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2506
2507   reply_type = NULL;
2508
2509   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2510   target_method_name = was_split ? split_method_name : method_name;
2511   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2512
2513   /* Warn if method is unexpected (cf. :g-interface-info) */
2514   if (!was_split)
2515     {
2516       const GDBusMethodInfo *expected_method_info;
2517       expected_method_info = lookup_method_info_or_warn (proxy, target_method_name);
2518       if (expected_method_info != NULL)
2519         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2520     }
2521
2522   destination = NULL;
2523   if (proxy->priv->name != NULL)
2524     {
2525       destination = get_destination_for_call (proxy);
2526       if (destination == NULL)
2527         {
2528           g_set_error_literal (error,
2529                                G_IO_ERROR,
2530                                G_IO_ERROR_FAILED,
2531                                _("Cannot invoke method; proxy is for a well-known name without an owner and proxy was constructed with the G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag"));
2532           ret = NULL;
2533           goto out;
2534         }
2535     }
2536
2537   ret = g_dbus_connection_call_sync (proxy->priv->connection,
2538                                      destination,
2539                                      proxy->priv->object_path,
2540                                      target_interface_name,
2541                                      target_method_name,
2542                                      parameters,
2543                                      reply_type,
2544                                      flags,
2545                                      timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2546                                      cancellable,
2547                                      error);
2548
2549  out:
2550   if (reply_type != NULL)
2551     g_variant_type_free (reply_type);
2552
2553   g_free (split_interface_name);
2554
2555   return ret;
2556 }
2557
2558 /* ---------------------------------------------------------------------------------------------------- */
2559
2560 static GDBusInterfaceInfo *
2561 _g_dbus_proxy_get_info (GDBusInterface *interface)
2562 {
2563   GDBusProxy *proxy = G_DBUS_PROXY (interface);
2564   return g_dbus_proxy_get_interface_info (proxy);
2565 }
2566
2567 static GDBusObject *
2568 _g_dbus_proxy_get_object (GDBusInterface *interface)
2569 {
2570   GDBusProxy *proxy = G_DBUS_PROXY (interface);
2571   return proxy->priv->object;
2572 }
2573
2574 static void
2575 _g_dbus_proxy_set_object (GDBusInterface *interface,
2576                           GDBusObject    *object)
2577 {
2578   GDBusProxy *proxy = G_DBUS_PROXY (interface);
2579   if (proxy->priv->object != NULL)
2580     g_object_remove_weak_pointer (G_OBJECT (proxy->priv->object), (gpointer *) &proxy->priv->object);
2581   proxy->priv->object = object;
2582   if (proxy->priv->object != NULL)
2583     g_object_add_weak_pointer (G_OBJECT (proxy->priv->object), (gpointer *) &proxy->priv->object);
2584 }
2585
2586 static void
2587 dbus_interface_iface_init (GDBusInterfaceIface *dbus_interface_iface)
2588 {
2589   dbus_interface_iface->get_info   = _g_dbus_proxy_get_info;
2590   dbus_interface_iface->get_object = _g_dbus_proxy_get_object;
2591   dbus_interface_iface->set_object = _g_dbus_proxy_set_object;
2592 }
2593
2594 /* ---------------------------------------------------------------------------------------------------- */