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