76397b4b89e5977bfe61d020b220e134f9288f5d
[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: (allow-none): 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   if (proxy->priv->expected_interface != NULL)
759     {
760       const GDBusSignalInfo *info;
761       GVariantType *expected_type;
762       info = g_dbus_interface_info_lookup_signal (proxy->priv->expected_interface, signal_name);
763       if (info == NULL)
764         goto out;
765       expected_type = _g_dbus_compute_complete_signature (info->args);
766       if (!g_variant_type_equal (expected_type, g_variant_get_type (parameters)))
767         {
768           g_variant_type_free (expected_type);
769           goto out;
770         }
771       g_variant_type_free (expected_type);
772     }
773
774   g_signal_emit (proxy,
775                  signals[SIGNAL_SIGNAL],
776                  0,
777                  sender_name,
778                  signal_name,
779                  parameters);
780  out:
781   ;
782 }
783
784 /* ---------------------------------------------------------------------------------------------------- */
785
786 static void
787 insert_property_checked (GDBusProxy  *proxy,
788                          gchar *property_name,
789                          GVariant *value)
790 {
791   if (proxy->priv->expected_interface != NULL)
792     {
793       const GDBusPropertyInfo *info;
794
795       info = g_dbus_interface_info_lookup_property (proxy->priv->expected_interface, property_name);
796       /* Ignore unknown properties */
797       if (info == NULL)
798         goto invalid;
799
800       /* Ignore properties with the wrong type */
801       if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
802         goto invalid;
803     }
804
805   g_hash_table_insert (proxy->priv->properties,
806                        property_name, /* adopts string */
807                        value); /* adopts value */
808
809   return;
810
811  invalid:
812   g_variant_unref (value);
813   g_free (property_name);
814 }
815
816 static void
817 on_properties_changed (GDBusConnection *connection,
818                        const gchar     *sender_name,
819                        const gchar     *object_path,
820                        const gchar     *interface_name,
821                        const gchar     *signal_name,
822                        GVariant        *parameters,
823                        gpointer         user_data)
824 {
825   GDBusProxy *proxy = G_DBUS_PROXY (user_data);
826   GError *error;
827   const gchar *interface_name_for_signal;
828   GVariant *changed_properties;
829   gchar **invalidated_properties;
830   GVariantIter iter;
831   gchar *key;
832   GVariant *value;
833   guint n;
834
835   error = NULL;
836   changed_properties = NULL;
837   invalidated_properties = NULL;
838
839   if (!proxy->priv->initialized)
840     goto out;
841
842   if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
843     goto out;
844
845   if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(sa{sv}as)")))
846     {
847       g_warning ("Value for PropertiesChanged signal with type `%s' does not match `(sa{sv}as)'",
848                  g_variant_get_type_string (parameters));
849       goto out;
850     }
851
852   g_variant_get (parameters,
853                  "(&s@a{sv}^a&s)",
854                  &interface_name_for_signal,
855                  &changed_properties,
856                  &invalidated_properties);
857
858   if (g_strcmp0 (interface_name_for_signal, proxy->priv->interface_name) != 0)
859     goto out;
860
861   g_variant_iter_init (&iter, changed_properties);
862   while (g_variant_iter_next (&iter, "{sv}", &key, &value))
863     {
864       insert_property_checked (proxy,
865                                key, /* adopts string */
866                                value); /* adopts value */
867     }
868
869   for (n = 0; invalidated_properties[n] != NULL; n++)
870     {
871       g_hash_table_remove (proxy->priv->properties, invalidated_properties[n]);
872     }
873
874   /* emit signal */
875   g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
876                  0,
877                  changed_properties,
878                  invalidated_properties);
879
880  out:
881   if (changed_properties != NULL)
882     g_variant_unref (changed_properties);
883   g_free (invalidated_properties);
884 }
885
886 /* ---------------------------------------------------------------------------------------------------- */
887
888 static void
889 process_get_all_reply (GDBusProxy *proxy,
890                        GVariant   *result)
891 {
892   GVariantIter *iter;
893   gchar *key;
894   GVariant *value;
895
896   if (!g_variant_is_of_type (result, G_VARIANT_TYPE ("(a{sv})")))
897     {
898       g_warning ("Value for GetAll reply with type `%s' does not match `(a{sv})'",
899                  g_variant_get_type_string (result));
900       goto out;
901     }
902
903   g_variant_get (result, "(a{sv})", &iter);
904   while (g_variant_iter_next (iter, "{sv}", &key, &value))
905     {
906       insert_property_checked (proxy,
907                                key, /* adopts string */
908                                value); /* adopts value */
909     }
910   g_variant_iter_free (iter);
911
912   /* Synthesize ::g-properties-changed changed */
913   if (g_hash_table_size (proxy->priv->properties) > 0)
914     {
915       GVariant *changed_properties;
916       const gchar *invalidated_properties[1] = {NULL};
917
918       g_variant_get (result,
919                      "(@a{sv})",
920                      &changed_properties);
921       g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
922                      0,
923                      changed_properties,
924                      invalidated_properties);
925       g_variant_unref (changed_properties);
926     }
927
928  out:
929   ;
930 }
931
932 typedef struct
933 {
934   GDBusProxy *proxy;
935   GCancellable *cancellable;
936   gchar *name_owner;
937 } LoadPropertiesOnNameOwnerChangedData;
938
939 static void
940 on_name_owner_changed_get_all_cb (GDBusConnection *connection,
941                                   GAsyncResult    *res,
942                                   gpointer         user_data)
943 {
944   LoadPropertiesOnNameOwnerChangedData *data = user_data;
945   GVariant *result;
946   GError *error;
947   gboolean cancelled;
948
949   cancelled = FALSE;
950
951   error = NULL;
952   result = g_dbus_connection_call_finish (connection,
953                                           res,
954                                           &error);
955   if (result == NULL)
956     {
957       if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_CANCELLED)
958         cancelled = TRUE;
959       /* We just ignore if GetAll() is failing. Because this might happen
960        * if the object has no properties at all. Or if the caller is
961        * not authorized to see the properties.
962        *
963        * Either way, apps can know about this by using
964        * get_cached_property_names() or get_cached_property().
965        *
966        * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
967        * fact that GetAll() failed
968        */
969       //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
970       g_error_free (error);
971     }
972
973   /* and finally we can notify */
974   if (!cancelled)
975     {
976       g_free (data->proxy->priv->name_owner);
977       data->proxy->priv->name_owner = data->name_owner;
978       data->name_owner = NULL; /* to avoid an extra copy, we steal the string */
979
980       g_hash_table_remove_all (data->proxy->priv->properties);
981       if (result != NULL)
982         {
983           process_get_all_reply (data->proxy, result);
984           g_variant_unref (result);
985         }
986
987       g_object_notify (G_OBJECT (data->proxy), "g-name-owner");
988     }
989
990   if (data->cancellable == data->proxy->priv->get_all_cancellable)
991     data->proxy->priv->get_all_cancellable = NULL;
992
993   g_object_unref (data->proxy);
994   g_object_unref (data->cancellable);
995   g_free (data->name_owner);
996   g_free (data);
997 }
998
999 static void
1000 on_name_owner_changed (GDBusConnection *connection,
1001                        const gchar      *sender_name,
1002                        const gchar      *object_path,
1003                        const gchar      *interface_name,
1004                        const gchar      *signal_name,
1005                        GVariant         *parameters,
1006                        gpointer          user_data)
1007 {
1008   GDBusProxy *proxy = G_DBUS_PROXY (user_data);
1009   const gchar *old_owner;
1010   const gchar *new_owner;
1011
1012   /* if we are already trying to load properties, cancel that */
1013   if (proxy->priv->get_all_cancellable != NULL)
1014     {
1015       g_cancellable_cancel (proxy->priv->get_all_cancellable);
1016       proxy->priv->get_all_cancellable = NULL;
1017     }
1018
1019   g_variant_get (parameters,
1020                  "(&s&s&s)",
1021                  NULL,
1022                  &old_owner,
1023                  &new_owner);
1024
1025   if (strlen (new_owner) == 0)
1026     {
1027       g_free (proxy->priv->name_owner);
1028       proxy->priv->name_owner = NULL;
1029
1030       /* Synthesize ::g-properties-changed changed */
1031       if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES) &&
1032           g_hash_table_size (proxy->priv->properties) > 0)
1033         {
1034           GVariantBuilder builder;
1035           GVariant *changed_properties;
1036           GPtrArray *invalidated_properties;
1037           GHashTableIter iter;
1038           const gchar *key;
1039
1040           /* Build changed_properties (always empty) and invalidated_properties ... */
1041           g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
1042           changed_properties = g_variant_builder_end (&builder);
1043           invalidated_properties = g_ptr_array_new_with_free_func (g_free);
1044           g_hash_table_iter_init (&iter, proxy->priv->properties);
1045           while (g_hash_table_iter_next (&iter, (gpointer) &key, NULL))
1046             g_ptr_array_add (invalidated_properties, g_strdup (key));
1047           g_ptr_array_add (invalidated_properties, NULL);
1048
1049           /* ... throw out the properties ... */
1050           g_hash_table_remove_all (proxy->priv->properties);
1051
1052           /* ... and finally emit the ::g-properties-changed signal */
1053           g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
1054                          0,
1055                          changed_properties,
1056                          (const gchar* const *) invalidated_properties->pdata);
1057           g_variant_unref (changed_properties);
1058           g_ptr_array_unref (invalidated_properties);
1059         }
1060       g_object_notify (G_OBJECT (proxy), "g-name-owner");
1061     }
1062   else
1063     {
1064       /* ignore duplicates - this can happen when activating the service */
1065       if (g_strcmp0 (new_owner, proxy->priv->name_owner) == 0)
1066         goto out;
1067
1068       if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES)
1069         {
1070           g_free (proxy->priv->name_owner);
1071           proxy->priv->name_owner = g_strdup (new_owner);
1072           g_hash_table_remove_all (proxy->priv->properties);
1073           g_object_notify (G_OBJECT (proxy), "g-name-owner");
1074         }
1075       else
1076         {
1077           LoadPropertiesOnNameOwnerChangedData *data;
1078
1079           /* start loading properties.. only then emit notify::g-name-owner .. we
1080            * need to be able to cancel this in the event another NameOwnerChanged
1081            * signal suddenly happens
1082            */
1083
1084           g_assert (proxy->priv->get_all_cancellable == NULL);
1085           proxy->priv->get_all_cancellable = g_cancellable_new ();
1086           data = g_new0 (LoadPropertiesOnNameOwnerChangedData, 1);
1087           data->proxy = g_object_ref (proxy);
1088           data->cancellable = proxy->priv->get_all_cancellable;
1089           data->name_owner = g_strdup (new_owner);
1090           g_dbus_connection_call (proxy->priv->connection,
1091                                   data->name_owner,
1092                                   proxy->priv->object_path,
1093                                   "org.freedesktop.DBus.Properties",
1094                                   "GetAll",
1095                                   g_variant_new ("(s)", proxy->priv->interface_name),
1096                                   G_VARIANT_TYPE ("(a{sv})"),
1097                                   G_DBUS_CALL_FLAGS_NONE,
1098                                   -1,           /* timeout */
1099                                   proxy->priv->get_all_cancellable,
1100                                   (GAsyncReadyCallback) on_name_owner_changed_get_all_cb,
1101                                   data);
1102         }
1103     }
1104
1105  out:
1106   ;
1107 }
1108
1109 /* ---------------------------------------------------------------------------------------------------- */
1110
1111 typedef struct
1112 {
1113   GDBusProxy *proxy;
1114   GCancellable *cancellable;
1115   GSimpleAsyncResult *simple;
1116 } AsyncInitData;
1117
1118 static void
1119 async_init_data_free (AsyncInitData *data)
1120 {
1121   g_object_unref (data->proxy);
1122   if (data->cancellable != NULL)
1123     g_object_unref (data->cancellable);
1124   g_object_unref (data->simple);
1125   g_free (data);
1126 }
1127
1128 static void
1129 async_init_get_all_cb (GDBusConnection *connection,
1130                        GAsyncResult    *res,
1131                        gpointer         user_data)
1132 {
1133   AsyncInitData *data = user_data;
1134   GVariant *result;
1135   GError *error;
1136
1137   error = NULL;
1138   result = g_dbus_connection_call_finish (connection,
1139                                           res,
1140                                           &error);
1141   if (result == NULL)
1142     {
1143       /* We just ignore if GetAll() is failing. Because this might happen
1144        * if the object has no properties at all. Or if the caller is
1145        * not authorized to see the properties.
1146        *
1147        * Either way, apps can know about this by using
1148        * get_cached_property_names() or get_cached_property().
1149        *
1150        * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
1151        * fact that GetAll() failed
1152        */
1153       //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
1154       g_error_free (error);
1155     }
1156   else
1157     {
1158       g_simple_async_result_set_op_res_gpointer (data->simple,
1159                                                  result,
1160                                                  (GDestroyNotify) g_variant_unref);
1161     }
1162
1163   g_simple_async_result_complete_in_idle (data->simple);
1164   async_init_data_free (data);
1165 }
1166
1167
1168 static void
1169 async_init_get_name_owner_cb (GDBusConnection *connection,
1170                               GAsyncResult    *res,
1171                               gpointer         user_data)
1172 {
1173   AsyncInitData *data = user_data;
1174
1175   if (res != NULL)
1176     {
1177       GError *error;
1178       GVariant *result;
1179
1180       error = NULL;
1181       result = g_dbus_connection_call_finish (connection,
1182                                               res,
1183                                               &error);
1184       if (result == NULL)
1185         {
1186           if (error->domain == G_DBUS_ERROR &&
1187               error->code == G_DBUS_ERROR_NAME_HAS_NO_OWNER)
1188             {
1189               g_error_free (error);
1190             }
1191           else
1192             {
1193               g_simple_async_result_take_error (data->simple, error);
1194               g_simple_async_result_complete_in_idle (data->simple);
1195               async_init_data_free (data);
1196               goto out;
1197             }
1198         }
1199       else
1200         {
1201           g_variant_get (result,
1202                          "(s)",
1203                          &data->proxy->priv->name_owner);
1204           g_variant_unref (result);
1205         }
1206     }
1207
1208   if (!(data->proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES))
1209     {
1210       /* load all properties asynchronously */
1211       g_dbus_connection_call (data->proxy->priv->connection,
1212                               data->proxy->priv->name_owner,
1213                               data->proxy->priv->object_path,
1214                               "org.freedesktop.DBus.Properties",
1215                               "GetAll",
1216                               g_variant_new ("(s)", data->proxy->priv->interface_name),
1217                               G_VARIANT_TYPE ("(a{sv})"),
1218                               G_DBUS_CALL_FLAGS_NONE,
1219                               -1,           /* timeout */
1220                               data->cancellable,
1221                               (GAsyncReadyCallback) async_init_get_all_cb,
1222                               data);
1223     }
1224   else
1225     {
1226       g_simple_async_result_complete_in_idle (data->simple);
1227       async_init_data_free (data);
1228     }
1229
1230  out:
1231   ;
1232 }
1233
1234 static void
1235 async_init_call_get_name_owner (AsyncInitData *data)
1236 {
1237   g_dbus_connection_call (data->proxy->priv->connection,
1238                           "org.freedesktop.DBus",  /* name */
1239                           "/org/freedesktop/DBus", /* object path */
1240                           "org.freedesktop.DBus",  /* interface */
1241                           "GetNameOwner",
1242                           g_variant_new ("(s)",
1243                                          data->proxy->priv->name),
1244                           G_VARIANT_TYPE ("(s)"),
1245                           G_DBUS_CALL_FLAGS_NONE,
1246                           -1,           /* timeout */
1247                           data->cancellable,
1248                           (GAsyncReadyCallback) async_init_get_name_owner_cb,
1249                           data);
1250 }
1251
1252 static void
1253 async_init_start_service_by_name_cb (GDBusConnection *connection,
1254                                      GAsyncResult    *res,
1255                                      gpointer         user_data)
1256 {
1257   AsyncInitData *data = user_data;
1258   GError *error;
1259   GVariant *result;
1260
1261   error = NULL;
1262   result = g_dbus_connection_call_finish (connection,
1263                                           res,
1264                                           &error);
1265   if (result == NULL)
1266     {
1267       /* Errors are not unexpected; the bus will reply e.g.
1268        *
1269        *   org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
1270        *   was not provided by any .service files
1271        *
1272        * This doesn't mean that the name doesn't have an owner, just
1273        * that it's not provided by a .service file. So just proceed to
1274        * invoke GetNameOwner() if dealing with that error.
1275        */
1276       if (error->domain == G_DBUS_ERROR &&
1277           error->code == G_DBUS_ERROR_SERVICE_UNKNOWN)
1278         {
1279           g_error_free (error);
1280         }
1281       else
1282         {
1283           g_prefix_error (&error,
1284                           _("Error calling StartServiceByName for %s: "),
1285                           data->proxy->priv->name);
1286           goto failed;
1287         }
1288     }
1289   else
1290     {
1291       guint32 start_service_result;
1292       g_variant_get (result,
1293                      "(u)",
1294                      &start_service_result);
1295       g_variant_unref (result);
1296       if (start_service_result == 1 ||  /* DBUS_START_REPLY_SUCCESS */
1297           start_service_result == 2)    /* DBUS_START_REPLY_ALREADY_RUNNING */
1298         {
1299           /* continue to invoke GetNameOwner() */
1300         }
1301       else
1302         {
1303           error = g_error_new (G_IO_ERROR,
1304                                G_IO_ERROR_FAILED,
1305                                _("Unexpected reply %d from StartServiceByName(\"%s\") method"),
1306                                start_service_result,
1307                                data->proxy->priv->name);
1308           goto failed;
1309         }
1310     }
1311
1312   async_init_call_get_name_owner (data);
1313   return;
1314
1315  failed:
1316   g_warn_if_fail (error != NULL);
1317   g_simple_async_result_take_error (data->simple, error);
1318   g_simple_async_result_complete_in_idle (data->simple);
1319   async_init_data_free (data);
1320 }
1321
1322 static void
1323 async_init_call_start_service_by_name (AsyncInitData *data)
1324 {
1325   g_dbus_connection_call (data->proxy->priv->connection,
1326                           "org.freedesktop.DBus",  /* name */
1327                           "/org/freedesktop/DBus", /* object path */
1328                           "org.freedesktop.DBus",  /* interface */
1329                           "StartServiceByName",
1330                           g_variant_new ("(su)",
1331                                          data->proxy->priv->name,
1332                                          0),
1333                           G_VARIANT_TYPE ("(u)"),
1334                           G_DBUS_CALL_FLAGS_NONE,
1335                           -1,           /* timeout */
1336                           data->cancellable,
1337                           (GAsyncReadyCallback) async_init_start_service_by_name_cb,
1338                           data);
1339 }
1340
1341 static void
1342 async_initable_init_second_async (GAsyncInitable      *initable,
1343                                   gint                 io_priority,
1344                                   GCancellable        *cancellable,
1345                                   GAsyncReadyCallback  callback,
1346                                   gpointer             user_data)
1347 {
1348   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1349   AsyncInitData *data;
1350
1351   data = g_new0 (AsyncInitData, 1);
1352   data->proxy = g_object_ref (proxy);
1353   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1354   data->simple = g_simple_async_result_new (G_OBJECT (proxy),
1355                                             callback,
1356                                             user_data,
1357                                             NULL);
1358
1359   /* Check name ownership asynchronously - possibly also start the service */
1360   if (proxy->priv->name == NULL)
1361     {
1362       /* Do nothing */
1363       async_init_get_name_owner_cb (proxy->priv->connection, NULL, data);
1364     }
1365   else if (g_dbus_is_unique_name (proxy->priv->name))
1366     {
1367       proxy->priv->name_owner = g_strdup (proxy->priv->name);
1368       async_init_get_name_owner_cb (proxy->priv->connection, NULL, data);
1369     }
1370   else
1371     {
1372       if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
1373         {
1374           async_init_call_get_name_owner (data);
1375         }
1376       else
1377         {
1378           async_init_call_start_service_by_name (data);
1379         }
1380     }
1381 }
1382
1383 static gboolean
1384 async_initable_init_second_finish (GAsyncInitable  *initable,
1385                                    GAsyncResult    *res,
1386                                    GError         **error)
1387 {
1388   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1389   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1390   GVariant *result;
1391   gboolean ret;
1392
1393   ret = FALSE;
1394
1395   if (g_simple_async_result_propagate_error (simple, error))
1396     goto out;
1397
1398   result = g_simple_async_result_get_op_res_gpointer (simple);
1399   if (result != NULL)
1400     {
1401       process_get_all_reply (proxy, result);
1402     }
1403
1404   ret = TRUE;
1405
1406  out:
1407   proxy->priv->initialized = TRUE;
1408   return ret;
1409 }
1410
1411 /* ---------------------------------------------------------------------------------------------------- */
1412
1413 static void
1414 async_initable_init_first (GAsyncInitable *initable)
1415 {
1416   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1417
1418   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES))
1419     {
1420       /* subscribe to PropertiesChanged() */
1421       proxy->priv->properties_changed_subscriber_id =
1422         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1423                                             proxy->priv->name,
1424                                             "org.freedesktop.DBus.Properties",
1425                                             "PropertiesChanged",
1426                                             proxy->priv->object_path,
1427                                             proxy->priv->interface_name,
1428                                             G_DBUS_SIGNAL_FLAGS_NONE,
1429                                             on_properties_changed,
1430                                             proxy,
1431                                             NULL);
1432     }
1433
1434   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS))
1435     {
1436       /* subscribe to all signals for the object */
1437       proxy->priv->signals_subscriber_id =
1438         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1439                                             proxy->priv->name,
1440                                             proxy->priv->interface_name,
1441                                             NULL,                        /* member */
1442                                             proxy->priv->object_path,
1443                                             NULL,                        /* arg0 */
1444                                             G_DBUS_SIGNAL_FLAGS_NONE,
1445                                             on_signal_received,
1446                                             proxy,
1447                                             NULL);
1448     }
1449
1450   if (proxy->priv->name != NULL && !g_dbus_is_unique_name (proxy->priv->name))
1451     {
1452       proxy->priv->name_owner_changed_subscription_id =
1453         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1454                                             "org.freedesktop.DBus",  /* name */
1455                                             "org.freedesktop.DBus",  /* interface */
1456                                             "NameOwnerChanged",      /* signal name */
1457                                             "/org/freedesktop/DBus", /* path */
1458                                             proxy->priv->name,       /* arg0 */
1459                                             G_DBUS_SIGNAL_FLAGS_NONE,
1460                                             on_name_owner_changed,
1461                                             proxy,
1462                                             NULL);
1463     }
1464 }
1465
1466 /* ---------------------------------------------------------------------------------------------------- */
1467
1468 /* initialization is split into two parts - the first is the
1469  * non-blocing part that requires the callers GMainContext - the
1470  * second is a blocking part async part that doesn't require the
1471  * callers GMainContext.. we do this split so the code can be reused
1472  * in the GInitable implementation below.
1473  *
1474  * Note that obtaining a GDBusConnection is not shared between the two
1475  * paths.
1476  */
1477
1478 typedef struct
1479 {
1480   GDBusProxy          *proxy;
1481   gint                 io_priority;
1482   GCancellable        *cancellable;
1483   GAsyncReadyCallback  callback;
1484   gpointer             user_data;
1485 } GetConnectionData;
1486
1487 static void
1488 get_connection_cb (GObject       *source_object,
1489                    GAsyncResult  *res,
1490                    gpointer       user_data)
1491 {
1492   GetConnectionData *data = user_data;
1493   GError *error;
1494
1495   error = NULL;
1496   data->proxy->priv->connection = g_bus_get_finish (res, &error);
1497   if (data->proxy->priv->connection == NULL)
1498     {
1499       GSimpleAsyncResult *simple;
1500       simple = g_simple_async_result_new (G_OBJECT (data->proxy),
1501                                           data->callback,
1502                                           data->user_data,
1503                                           NULL);
1504       g_simple_async_result_take_error (simple, error);
1505       g_simple_async_result_complete_in_idle (simple);
1506       g_object_unref (simple);
1507     }
1508   else
1509     {
1510       async_initable_init_first (G_ASYNC_INITABLE (data->proxy));
1511       async_initable_init_second_async (G_ASYNC_INITABLE (data->proxy),
1512                                         data->io_priority,
1513                                         data->cancellable,
1514                                         data->callback,
1515                                         data->user_data);
1516     }
1517
1518   if (data->cancellable != NULL)
1519     g_object_unref (data->cancellable);
1520   if (data->proxy != NULL)
1521     g_object_unref (data->proxy);
1522   g_free (data);
1523 }
1524
1525 static void
1526 async_initable_init_async (GAsyncInitable      *initable,
1527                            gint                 io_priority,
1528                            GCancellable        *cancellable,
1529                            GAsyncReadyCallback  callback,
1530                            gpointer             user_data)
1531 {
1532   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1533
1534   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1535     {
1536       GetConnectionData *data;
1537
1538       g_assert (proxy->priv->connection == NULL);
1539
1540       data = g_new0 (GetConnectionData, 1);
1541       data->proxy = g_object_ref (proxy);
1542       data->io_priority = io_priority;
1543       data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1544       data->callback = callback;
1545       data->user_data = user_data;
1546       g_bus_get (proxy->priv->bus_type,
1547                  cancellable,
1548                  get_connection_cb,
1549                  data);
1550     }
1551   else
1552     {
1553       async_initable_init_first (initable);
1554       async_initable_init_second_async (initable, io_priority, cancellable, callback, user_data);
1555     }
1556 }
1557
1558 static gboolean
1559 async_initable_init_finish (GAsyncInitable  *initable,
1560                             GAsyncResult    *res,
1561                             GError         **error)
1562 {
1563   return async_initable_init_second_finish (initable, res, error);
1564 }
1565
1566 static void
1567 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1568 {
1569   async_initable_iface->init_async = async_initable_init_async;
1570   async_initable_iface->init_finish = async_initable_init_finish;
1571 }
1572
1573 /* ---------------------------------------------------------------------------------------------------- */
1574
1575 typedef struct
1576 {
1577   GMainContext *context;
1578   GMainLoop *loop;
1579   GAsyncResult *res;
1580 } InitableAsyncInitableData;
1581
1582 static void
1583 async_initable_init_async_cb (GObject      *source_object,
1584                               GAsyncResult *res,
1585                               gpointer      user_data)
1586 {
1587   InitableAsyncInitableData *data = user_data;
1588   data->res = g_object_ref (res);
1589   g_main_loop_quit (data->loop);
1590 }
1591
1592 /* Simply reuse the GAsyncInitable implementation but run the first
1593  * part (that is non-blocking and requires the callers GMainContext)
1594  * with the callers GMainContext.. and the second with a private
1595  * GMainContext (bug 621310 is slightly related).
1596  *
1597  * Note that obtaining a GDBusConnection is not shared between the two
1598  * paths.
1599  */
1600 static gboolean
1601 initable_init (GInitable     *initable,
1602                GCancellable  *cancellable,
1603                GError       **error)
1604 {
1605   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1606   InitableAsyncInitableData *data;
1607   gboolean ret;
1608
1609   ret = FALSE;
1610
1611   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1612     {
1613       g_assert (proxy->priv->connection == NULL);
1614       proxy->priv->connection = g_bus_get_sync (proxy->priv->bus_type,
1615                                                 cancellable,
1616                                                 error);
1617       if (proxy->priv->connection == NULL)
1618         goto out;
1619     }
1620
1621   async_initable_init_first (G_ASYNC_INITABLE (initable));
1622
1623   data = g_new0 (InitableAsyncInitableData, 1);
1624   data->context = g_main_context_new ();
1625   data->loop = g_main_loop_new (data->context, FALSE);
1626
1627   g_main_context_push_thread_default (data->context);
1628
1629   async_initable_init_second_async (G_ASYNC_INITABLE (initable),
1630                                     G_PRIORITY_DEFAULT,
1631                                     cancellable,
1632                                     async_initable_init_async_cb,
1633                                     data);
1634
1635   g_main_loop_run (data->loop);
1636
1637   ret = async_initable_init_second_finish (G_ASYNC_INITABLE (initable),
1638                                            data->res,
1639                                            error);
1640
1641   g_main_context_pop_thread_default (data->context);
1642
1643   g_main_context_unref (data->context);
1644   g_main_loop_unref (data->loop);
1645   g_object_unref (data->res);
1646   g_free (data);
1647
1648  out:
1649
1650   return ret;
1651 }
1652
1653 static void
1654 initable_iface_init (GInitableIface *initable_iface)
1655 {
1656   initable_iface->init = initable_init;
1657 }
1658
1659 /* ---------------------------------------------------------------------------------------------------- */
1660
1661 /**
1662  * g_dbus_proxy_new:
1663  * @connection: A #GDBusConnection.
1664  * @flags: Flags used when constructing the proxy.
1665  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1666  * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
1667  * @object_path: An object path.
1668  * @interface_name: A D-Bus interface name.
1669  * @cancellable: A #GCancellable or %NULL.
1670  * @callback: Callback function to invoke when the proxy is ready.
1671  * @user_data: User data to pass to @callback.
1672  *
1673  * Creates a proxy for accessing @interface_name on the remote object
1674  * at @object_path owned by @name at @connection and asynchronously
1675  * loads D-Bus properties unless the
1676  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used. Connect to
1677  * the #GDBusProxy::g-properties-changed signal to get notified about
1678  * property changes.
1679  *
1680  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
1681  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
1682  * to handle signals from the remote object.
1683  *
1684  * If @name is a well-known name and the
1685  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag isn't set and no name
1686  * owner currently exists, the message bus will be requested to launch
1687  * a name owner for the name.
1688  *
1689  * This is a failable asynchronous constructor - when the proxy is
1690  * ready, @callback will be invoked and you can use
1691  * g_dbus_proxy_new_finish() to get the result.
1692  *
1693  * See g_dbus_proxy_new_sync() and for a synchronous version of this constructor.
1694  *
1695  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1696  *
1697  * Since: 2.26
1698  */
1699 void
1700 g_dbus_proxy_new (GDBusConnection     *connection,
1701                   GDBusProxyFlags      flags,
1702                   GDBusInterfaceInfo  *info,
1703                   const gchar         *name,
1704                   const gchar         *object_path,
1705                   const gchar         *interface_name,
1706                   GCancellable        *cancellable,
1707                   GAsyncReadyCallback  callback,
1708                   gpointer             user_data)
1709 {
1710   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1711   g_return_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) || g_dbus_is_name (name));
1712   g_return_if_fail (g_variant_is_object_path (object_path));
1713   g_return_if_fail (g_dbus_is_interface_name (interface_name));
1714
1715   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
1716                               G_PRIORITY_DEFAULT,
1717                               cancellable,
1718                               callback,
1719                               user_data,
1720                               "g-flags", flags,
1721                               "g-interface-info", info,
1722                               "g-name", name,
1723                               "g-connection", connection,
1724                               "g-object-path", object_path,
1725                               "g-interface-name", interface_name,
1726                               NULL);
1727 }
1728
1729 /**
1730  * g_dbus_proxy_new_finish:
1731  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new().
1732  * @error: Return location for error or %NULL.
1733  *
1734  * Finishes creating a #GDBusProxy.
1735  *
1736  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
1737  *
1738  * Since: 2.26
1739  */
1740 GDBusProxy *
1741 g_dbus_proxy_new_finish (GAsyncResult  *res,
1742                          GError       **error)
1743 {
1744   GObject *object;
1745   GObject *source_object;
1746
1747   source_object = g_async_result_get_source_object (res);
1748   g_assert (source_object != NULL);
1749
1750   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1751                                         res,
1752                                         error);
1753   g_object_unref (source_object);
1754
1755   if (object != NULL)
1756     return G_DBUS_PROXY (object);
1757   else
1758     return NULL;
1759 }
1760
1761 /**
1762  * g_dbus_proxy_new_sync:
1763  * @connection: A #GDBusConnection.
1764  * @flags: Flags used when constructing the proxy.
1765  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1766  * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
1767  * @object_path: An object path.
1768  * @interface_name: A D-Bus interface name.
1769  * @cancellable: (allow-none): A #GCancellable or %NULL.
1770  * @error: (allow-none): Return location for error or %NULL.
1771  *
1772  * Creates a proxy for accessing @interface_name on the remote object
1773  * at @object_path owned by @name at @connection and synchronously
1774  * loads D-Bus properties unless the
1775  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used.
1776  *
1777  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
1778  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
1779  * to handle signals from the remote object.
1780  *
1781  * If @name is a well-known name and the
1782  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag isn't set and no name
1783  * owner currently exists, the message bus will be requested to launch
1784  * a name owner for the name.
1785  *
1786  * This is a synchronous failable constructor. See g_dbus_proxy_new()
1787  * and g_dbus_proxy_new_finish() for the asynchronous version.
1788  *
1789  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1790  *
1791  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
1792  *
1793  * Since: 2.26
1794  */
1795 GDBusProxy *
1796 g_dbus_proxy_new_sync (GDBusConnection     *connection,
1797                        GDBusProxyFlags      flags,
1798                        GDBusInterfaceInfo  *info,
1799                        const gchar         *name,
1800                        const gchar         *object_path,
1801                        const gchar         *interface_name,
1802                        GCancellable        *cancellable,
1803                        GError             **error)
1804 {
1805   GInitable *initable;
1806
1807   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1808   g_return_val_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) ||
1809                         g_dbus_is_name (name), NULL);
1810   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1811   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
1812
1813   initable = g_initable_new (G_TYPE_DBUS_PROXY,
1814                              cancellable,
1815                              error,
1816                              "g-flags", flags,
1817                              "g-interface-info", info,
1818                              "g-name", name,
1819                              "g-connection", connection,
1820                              "g-object-path", object_path,
1821                              "g-interface-name", interface_name,
1822                              NULL);
1823   if (initable != NULL)
1824     return G_DBUS_PROXY (initable);
1825   else
1826     return NULL;
1827 }
1828
1829 /* ---------------------------------------------------------------------------------------------------- */
1830
1831 /**
1832  * g_dbus_proxy_new_for_bus:
1833  * @bus_type: A #GBusType.
1834  * @flags: Flags used when constructing the proxy.
1835  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1836  * @name: A bus name (well-known or unique).
1837  * @object_path: An object path.
1838  * @interface_name: A D-Bus interface name.
1839  * @cancellable: A #GCancellable or %NULL.
1840  * @callback: Callback function to invoke when the proxy is ready.
1841  * @user_data: User data to pass to @callback.
1842  *
1843  * Like g_dbus_proxy_new() but takes a #GBusType instead of a #GDBusConnection.
1844  *
1845  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1846  *
1847  * Since: 2.26
1848  */
1849 void
1850 g_dbus_proxy_new_for_bus (GBusType             bus_type,
1851                           GDBusProxyFlags      flags,
1852                           GDBusInterfaceInfo  *info,
1853                           const gchar         *name,
1854                           const gchar         *object_path,
1855                           const gchar         *interface_name,
1856                           GCancellable        *cancellable,
1857                           GAsyncReadyCallback  callback,
1858                           gpointer             user_data)
1859 {
1860   g_return_if_fail (g_dbus_is_name (name));
1861   g_return_if_fail (g_variant_is_object_path (object_path));
1862   g_return_if_fail (g_dbus_is_interface_name (interface_name));
1863
1864   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
1865                               G_PRIORITY_DEFAULT,
1866                               cancellable,
1867                               callback,
1868                               user_data,
1869                               "g-flags", flags,
1870                               "g-interface-info", info,
1871                               "g-name", name,
1872                               "g-bus-type", bus_type,
1873                               "g-object-path", object_path,
1874                               "g-interface-name", interface_name,
1875                               NULL);
1876 }
1877
1878 /**
1879  * g_dbus_proxy_new_for_bus_finish:
1880  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new_for_bus().
1881  * @error: Return location for error or %NULL.
1882  *
1883  * Finishes creating a #GDBusProxy.
1884  *
1885  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
1886  *
1887  * Since: 2.26
1888  */
1889 GDBusProxy *
1890 g_dbus_proxy_new_for_bus_finish (GAsyncResult  *res,
1891                                  GError       **error)
1892 {
1893   return g_dbus_proxy_new_finish (res, error);
1894 }
1895
1896 /**
1897  * g_dbus_proxy_new_for_bus_sync:
1898  * @bus_type: A #GBusType.
1899  * @flags: Flags used when constructing the proxy.
1900  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface
1901  *        that @proxy conforms to or %NULL.
1902  * @name: A bus name (well-known or unique).
1903  * @object_path: An object path.
1904  * @interface_name: A D-Bus interface name.
1905  * @cancellable: A #GCancellable or %NULL.
1906  * @error: Return location for error or %NULL.
1907  *
1908  * Like g_dbus_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection.
1909  *
1910  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1911  *
1912  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
1913  *
1914  * Since: 2.26
1915  */
1916 GDBusProxy *
1917 g_dbus_proxy_new_for_bus_sync (GBusType             bus_type,
1918                                GDBusProxyFlags      flags,
1919                                GDBusInterfaceInfo  *info,
1920                                const gchar         *name,
1921                                const gchar         *object_path,
1922                                const gchar         *interface_name,
1923                                GCancellable        *cancellable,
1924                                GError             **error)
1925 {
1926   GInitable *initable;
1927
1928   g_return_val_if_fail (g_dbus_is_name (name), NULL);
1929   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1930   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
1931
1932   initable = g_initable_new (G_TYPE_DBUS_PROXY,
1933                              cancellable,
1934                              error,
1935                              "g-flags", flags,
1936                              "g-interface-info", info,
1937                              "g-name", name,
1938                              "g-bus-type", bus_type,
1939                              "g-object-path", object_path,
1940                              "g-interface-name", interface_name,
1941                              NULL);
1942   if (initable != NULL)
1943     return G_DBUS_PROXY (initable);
1944   else
1945     return NULL;
1946 }
1947
1948 /* ---------------------------------------------------------------------------------------------------- */
1949
1950 /**
1951  * g_dbus_proxy_get_connection:
1952  * @proxy: A #GDBusProxy.
1953  *
1954  * Gets the connection @proxy is for.
1955  *
1956  * Returns: (transfer none): A #GDBusConnection owned by @proxy. Do not free.
1957  *
1958  * Since: 2.26
1959  */
1960 GDBusConnection *
1961 g_dbus_proxy_get_connection (GDBusProxy *proxy)
1962 {
1963   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
1964   return proxy->priv->connection;
1965 }
1966
1967 /**
1968  * g_dbus_proxy_get_flags:
1969  * @proxy: A #GDBusProxy.
1970  *
1971  * Gets the flags that @proxy was constructed with.
1972  *
1973  * Returns: Flags from the #GDBusProxyFlags enumeration.
1974  *
1975  * Since: 2.26
1976  */
1977 GDBusProxyFlags
1978 g_dbus_proxy_get_flags (GDBusProxy *proxy)
1979 {
1980   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), 0);
1981   return proxy->priv->flags;
1982 }
1983
1984 /**
1985  * g_dbus_proxy_get_name:
1986  * @proxy: A #GDBusProxy.
1987  *
1988  * Gets the name that @proxy was constructed for.
1989  *
1990  * Returns: A string owned by @proxy. Do not free.
1991  *
1992  * Since: 2.26
1993  */
1994 const gchar *
1995 g_dbus_proxy_get_name (GDBusProxy *proxy)
1996 {
1997   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
1998   return proxy->priv->name;
1999 }
2000
2001 /**
2002  * g_dbus_proxy_get_name_owner:
2003  * @proxy: A #GDBusProxy.
2004  *
2005  * The unique name that owns the name that @proxy is for or %NULL if
2006  * no-one currently owns that name. You may connect to the
2007  * #GObject::notify signal to track changes to the
2008  * #GDBusProxy:g-name-owner property.
2009  *
2010  * Returns: The name owner or %NULL if no name owner exists. Free with g_free().
2011  *
2012  * Since: 2.26
2013  */
2014 gchar *
2015 g_dbus_proxy_get_name_owner (GDBusProxy *proxy)
2016 {
2017   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2018   return g_strdup (proxy->priv->name_owner);
2019 }
2020
2021 /**
2022  * g_dbus_proxy_get_object_path:
2023  * @proxy: A #GDBusProxy.
2024  *
2025  * Gets the object path @proxy is for.
2026  *
2027  * Returns: A string owned by @proxy. Do not free.
2028  *
2029  * Since: 2.26
2030  */
2031 const gchar *
2032 g_dbus_proxy_get_object_path (GDBusProxy *proxy)
2033 {
2034   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2035   return proxy->priv->object_path;
2036 }
2037
2038 /**
2039  * g_dbus_proxy_get_interface_name:
2040  * @proxy: A #GDBusProxy.
2041  *
2042  * Gets the D-Bus interface name @proxy is for.
2043  *
2044  * Returns: A string owned by @proxy. Do not free.
2045  *
2046  * Since: 2.26
2047  */
2048 const gchar *
2049 g_dbus_proxy_get_interface_name (GDBusProxy *proxy)
2050 {
2051   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2052   return proxy->priv->interface_name;
2053 }
2054
2055 /**
2056  * g_dbus_proxy_get_default_timeout:
2057  * @proxy: A #GDBusProxy.
2058  *
2059  * Gets the timeout to use if -1 (specifying default timeout) is
2060  * passed as @timeout_msec in the g_dbus_proxy_call() and
2061  * g_dbus_proxy_call_sync() functions.
2062  *
2063  * See the #GDBusProxy:g-default-timeout property for more details.
2064  *
2065  * Returns: Timeout to use for @proxy.
2066  *
2067  * Since: 2.26
2068  */
2069 gint
2070 g_dbus_proxy_get_default_timeout (GDBusProxy *proxy)
2071 {
2072   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), -1);
2073   return proxy->priv->timeout_msec;
2074 }
2075
2076 /**
2077  * g_dbus_proxy_set_default_timeout:
2078  * @proxy: A #GDBusProxy.
2079  * @timeout_msec: Timeout in milliseconds.
2080  *
2081  * Sets the timeout to use if -1 (specifying default timeout) is
2082  * passed as @timeout_msec in the g_dbus_proxy_call() and
2083  * g_dbus_proxy_call_sync() functions.
2084  *
2085  * See the #GDBusProxy:g-default-timeout property for more details.
2086  *
2087  * Since: 2.26
2088  */
2089 void
2090 g_dbus_proxy_set_default_timeout (GDBusProxy *proxy,
2091                                   gint        timeout_msec)
2092 {
2093   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2094   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2095
2096   /* TODO: locking? */
2097   if (proxy->priv->timeout_msec != timeout_msec)
2098     {
2099       proxy->priv->timeout_msec = timeout_msec;
2100       g_object_notify (G_OBJECT (proxy), "g-default-timeout");
2101     }
2102 }
2103
2104 /**
2105  * g_dbus_proxy_get_interface_info:
2106  * @proxy: A #GDBusProxy
2107  *
2108  * Returns the #GDBusInterfaceInfo, if any, specifying the minimal
2109  * interface that @proxy conforms to.
2110  *
2111  * See the #GDBusProxy:g-interface-info property for more details.
2112  *
2113  * Returns: A #GDBusInterfaceInfo or %NULL. Do not unref the returned
2114  * object, it is owned by @proxy.
2115  *
2116  * Since: 2.26
2117  */
2118 GDBusInterfaceInfo *
2119 g_dbus_proxy_get_interface_info (GDBusProxy *proxy)
2120 {
2121   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2122   return proxy->priv->expected_interface;
2123 }
2124
2125 /**
2126  * g_dbus_proxy_set_interface_info:
2127  * @proxy: A #GDBusProxy
2128  * @info: (allow-none): Minimum interface this proxy conforms to or %NULL to unset.
2129  *
2130  * Ensure that interactions with @proxy conform to the given
2131  * interface.  For example, when completing a method call, if the type
2132  * signature of the message isn't what's expected, the given #GError
2133  * is set.  Signals that have a type signature mismatch are simply
2134  * dropped.
2135  *
2136  * See the #GDBusProxy:g-interface-info property for more details.
2137  *
2138  * Since: 2.26
2139  */
2140 void
2141 g_dbus_proxy_set_interface_info (GDBusProxy         *proxy,
2142                                  GDBusInterfaceInfo *info)
2143 {
2144   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2145   if (proxy->priv->expected_interface != NULL)
2146     {
2147       g_dbus_interface_info_cache_release (proxy->priv->expected_interface);
2148       g_dbus_interface_info_unref (proxy->priv->expected_interface);
2149     }
2150   proxy->priv->expected_interface = info != NULL ? g_dbus_interface_info_ref (info) : NULL;
2151   if (proxy->priv->expected_interface != NULL)
2152     g_dbus_interface_info_cache_build (proxy->priv->expected_interface);
2153 }
2154
2155 /* ---------------------------------------------------------------------------------------------------- */
2156
2157 static gboolean
2158 maybe_split_method_name (const gchar  *method_name,
2159                          gchar       **out_interface_name,
2160                          const gchar **out_method_name)
2161 {
2162   gboolean was_split;
2163
2164   was_split = FALSE;
2165   g_assert (out_interface_name != NULL);
2166   g_assert (out_method_name != NULL);
2167   *out_interface_name = NULL;
2168   *out_method_name = NULL;
2169
2170   if (strchr (method_name, '.') != NULL)
2171     {
2172       gchar *p;
2173       gchar *last_dot;
2174
2175       p = g_strdup (method_name);
2176       last_dot = strrchr (p, '.');
2177       *last_dot = '\0';
2178
2179       *out_interface_name = p;
2180       *out_method_name = last_dot + 1;
2181
2182       was_split = TRUE;
2183     }
2184
2185   return was_split;
2186 }
2187
2188
2189 static void
2190 reply_cb (GDBusConnection *connection,
2191           GAsyncResult    *res,
2192           gpointer         user_data)
2193 {
2194   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
2195   GVariant *value;
2196   GError *error;
2197
2198   error = NULL;
2199   value = g_dbus_connection_call_finish (connection,
2200                                          res,
2201                                          &error);
2202   if (error != NULL)
2203     {
2204       g_simple_async_result_take_error (simple, error);
2205     }
2206   else
2207     {
2208       g_simple_async_result_set_op_res_gpointer (simple,
2209                                                  value,
2210                                                  (GDestroyNotify) g_variant_unref);
2211     }
2212
2213   /* no need to complete in idle since the method GDBusConnection already does */
2214   g_simple_async_result_complete (simple);
2215   g_object_unref (simple);
2216 }
2217
2218 static const GDBusMethodInfo *
2219 lookup_method_info_or_warn (GDBusProxy  *proxy,
2220                             const gchar *method_name)
2221 {
2222   const GDBusMethodInfo *info;
2223
2224   if (proxy->priv->expected_interface == NULL)
2225     return NULL;
2226
2227   info = g_dbus_interface_info_lookup_method (proxy->priv->expected_interface, method_name);
2228   if (info == NULL)
2229     {
2230       g_warning ("Trying to invoke method %s which isn't in expected interface %s",
2231                  method_name, proxy->priv->expected_interface->name);
2232     }
2233
2234   return info;
2235 }
2236
2237 static const gchar *
2238 get_destination_for_call (GDBusProxy *proxy)
2239 {
2240   const gchar *ret;
2241
2242   ret = NULL;
2243
2244   /* If proxy->priv->name is a unique name, then proxy->priv->name_owner
2245    * is never NULL and always the same as proxy->priv->name. We use this
2246    * knowledge to avoid checking if proxy->priv->name is a unique or
2247    * well-known name.
2248    */
2249   ret = proxy->priv->name_owner;
2250   if (ret != NULL)
2251     goto out;
2252
2253   if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
2254     goto out;
2255
2256   ret = proxy->priv->name;
2257
2258  out:
2259   return ret;
2260 }
2261
2262 /**
2263  * g_dbus_proxy_call:
2264  * @proxy: A #GDBusProxy.
2265  * @method_name: Name of method to invoke.
2266  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
2267  * @flags: Flags from the #GDBusCallFlags enumeration.
2268  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
2269  *                "infinite") or -1 to use the proxy default timeout.
2270  * @cancellable: A #GCancellable or %NULL.
2271  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
2272  * care about the result of the method invocation.
2273  * @user_data: The data to pass to @callback.
2274  *
2275  * Asynchronously invokes the @method_name method on @proxy.
2276  *
2277  * If @method_name contains any dots, then @name is split into interface and
2278  * method name parts. This allows using @proxy for invoking methods on
2279  * other interfaces.
2280  *
2281  * If the #GDBusConnection associated with @proxy is closed then
2282  * the operation will fail with %G_IO_ERROR_CLOSED. If
2283  * @cancellable is canceled, the operation will fail with
2284  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
2285  * compatible with the D-Bus protocol, the operation fails with
2286  * %G_IO_ERROR_INVALID_ARGUMENT.
2287  *
2288  * If the @parameters #GVariant is floating, it is consumed. This allows
2289  * convenient 'inline' use of g_variant_new(), e.g.:
2290  * |[
2291  *  g_dbus_proxy_call (proxy,
2292  *                     "TwoStrings",
2293  *                     g_variant_new ("(ss)",
2294  *                                    "Thing One",
2295  *                                    "Thing Two"),
2296  *                     G_DBUS_CALL_FLAGS_NONE,
2297  *                     -1,
2298  *                     NULL,
2299  *                     (GAsyncReadyCallback) two_strings_done,
2300  *                     &amp;data);
2301  * ]|
2302  *
2303  * This is an asynchronous method. When the operation is finished,
2304  * @callback will be invoked in the
2305  * <link linkend="g-main-context-push-thread-default">thread-default
2306  * main loop</link> of the thread you are calling this method from.
2307  * You can then call g_dbus_proxy_call_finish() to get the result of
2308  * the operation. See g_dbus_proxy_call_sync() for the synchronous
2309  * version of this method.
2310  *
2311  * Since: 2.26
2312  */
2313 void
2314 g_dbus_proxy_call (GDBusProxy          *proxy,
2315                    const gchar         *method_name,
2316                    GVariant            *parameters,
2317                    GDBusCallFlags       flags,
2318                    gint                 timeout_msec,
2319                    GCancellable        *cancellable,
2320                    GAsyncReadyCallback  callback,
2321                    gpointer             user_data)
2322 {
2323   GSimpleAsyncResult *simple;
2324   gboolean was_split;
2325   gchar *split_interface_name;
2326   const gchar *split_method_name;
2327   const gchar *target_method_name;
2328   const gchar *target_interface_name;
2329   const gchar *destination;
2330   GVariantType *reply_type;
2331
2332   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2333   g_return_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name));
2334   g_return_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
2335   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2336
2337   reply_type = NULL;
2338   split_interface_name = NULL;
2339
2340   simple = g_simple_async_result_new (G_OBJECT (proxy),
2341                                       callback,
2342                                       user_data,
2343                                       g_dbus_proxy_call);
2344
2345   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2346   target_method_name = was_split ? split_method_name : method_name;
2347   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2348
2349   /* Warn if method is unexpected (cf. :g-interface-info) */
2350   if (!was_split)
2351     {
2352       const GDBusMethodInfo *expected_method_info;
2353       expected_method_info = lookup_method_info_or_warn (proxy, target_method_name);
2354       if (expected_method_info != NULL)
2355         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2356     }
2357
2358   destination = NULL;
2359   if (proxy->priv->name != NULL)
2360     {
2361       destination = get_destination_for_call (proxy);
2362       if (destination == NULL)
2363         {
2364           g_simple_async_result_set_error (simple,
2365                                            G_IO_ERROR,
2366                                            G_IO_ERROR_FAILED,
2367                                            _("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"));
2368           goto out;
2369         }
2370     }
2371
2372   g_dbus_connection_call (proxy->priv->connection,
2373                           destination,
2374                           proxy->priv->object_path,
2375                           target_interface_name,
2376                           target_method_name,
2377                           parameters,
2378                           reply_type,
2379                           flags,
2380                           timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2381                           cancellable,
2382                           (GAsyncReadyCallback) reply_cb,
2383                           simple);
2384
2385  out:
2386   if (reply_type != NULL)
2387     g_variant_type_free (reply_type);
2388
2389   g_free (split_interface_name);
2390 }
2391
2392 /**
2393  * g_dbus_proxy_call_finish:
2394  * @proxy: A #GDBusProxy.
2395  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_proxy_call().
2396  * @error: Return location for error or %NULL.
2397  *
2398  * Finishes an operation started with g_dbus_proxy_call().
2399  *
2400  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
2401  * return values. Free with g_variant_unref().
2402  *
2403  * Since: 2.26
2404  */
2405 GVariant *
2406 g_dbus_proxy_call_finish (GDBusProxy    *proxy,
2407                           GAsyncResult  *res,
2408                           GError       **error)
2409 {
2410   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2411   GVariant *value;
2412
2413   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2414   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2415   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2416
2417   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_proxy_call);
2418
2419   value = NULL;
2420
2421   if (g_simple_async_result_propagate_error (simple, error))
2422     goto out;
2423
2424   value = g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
2425
2426  out:
2427   return value;
2428 }
2429
2430 /**
2431  * g_dbus_proxy_call_sync:
2432  * @proxy: A #GDBusProxy.
2433  * @method_name: Name of method to invoke.
2434  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
2435  *              or %NULL if not passing parameters.
2436  * @flags: Flags from the #GDBusCallFlags enumeration.
2437  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
2438  *                "infinite") or -1 to use the proxy default timeout.
2439  * @cancellable: A #GCancellable or %NULL.
2440  * @error: Return location for error or %NULL.
2441  *
2442  * Synchronously invokes the @method_name method on @proxy.
2443  *
2444  * If @method_name contains any dots, then @name is split into interface and
2445  * method name parts. This allows using @proxy for invoking methods on
2446  * other interfaces.
2447  *
2448  * If the #GDBusConnection associated with @proxy is disconnected then
2449  * the operation will fail with %G_IO_ERROR_CLOSED. If
2450  * @cancellable is canceled, the operation will fail with
2451  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
2452  * compatible with the D-Bus protocol, the operation fails with
2453  * %G_IO_ERROR_INVALID_ARGUMENT.
2454  *
2455  * If the @parameters #GVariant is floating, it is consumed. This allows
2456  * convenient 'inline' use of g_variant_new(), e.g.:
2457  * |[
2458  *  g_dbus_proxy_call_sync (proxy,
2459  *                          "TwoStrings",
2460  *                          g_variant_new ("(ss)",
2461  *                                         "Thing One",
2462  *                                         "Thing Two"),
2463  *                          G_DBUS_CALL_FLAGS_NONE,
2464  *                          -1,
2465  *                          NULL,
2466  *                          &amp;error);
2467  * ]|
2468  *
2469  * The calling thread is blocked until a reply is received. See
2470  * g_dbus_proxy_call() for the asynchronous version of this
2471  * method.
2472  *
2473  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
2474  * return values. Free with g_variant_unref().
2475  *
2476  * Since: 2.26
2477  */
2478 GVariant *
2479 g_dbus_proxy_call_sync (GDBusProxy      *proxy,
2480                         const gchar     *method_name,
2481                         GVariant        *parameters,
2482                         GDBusCallFlags   flags,
2483                         gint             timeout_msec,
2484                         GCancellable    *cancellable,
2485                         GError         **error)
2486 {
2487   GVariant *ret;
2488   gboolean was_split;
2489   gchar *split_interface_name;
2490   const gchar *split_method_name;
2491   const gchar *target_method_name;
2492   const gchar *target_interface_name;
2493   const gchar *destination;
2494   GVariantType *reply_type;
2495
2496   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2497   g_return_val_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name), NULL);
2498   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
2499   g_return_val_if_fail (timeout_msec == -1 || timeout_msec >= 0, NULL);
2500   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2501
2502   reply_type = NULL;
2503
2504   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2505   target_method_name = was_split ? split_method_name : method_name;
2506   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2507
2508   /* Warn if method is unexpected (cf. :g-interface-info) */
2509   if (!was_split)
2510     {
2511       const GDBusMethodInfo *expected_method_info;
2512       expected_method_info = lookup_method_info_or_warn (proxy, target_method_name);
2513       if (expected_method_info != NULL)
2514         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2515     }
2516
2517   destination = NULL;
2518   if (proxy->priv->name != NULL)
2519     {
2520       destination = get_destination_for_call (proxy);
2521       if (destination == NULL)
2522         {
2523           g_set_error_literal (error,
2524                                G_IO_ERROR,
2525                                G_IO_ERROR_FAILED,
2526                                _("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"));
2527           ret = NULL;
2528           goto out;
2529         }
2530     }
2531
2532   ret = g_dbus_connection_call_sync (proxy->priv->connection,
2533                                      destination,
2534                                      proxy->priv->object_path,
2535                                      target_interface_name,
2536                                      target_method_name,
2537                                      parameters,
2538                                      reply_type,
2539                                      flags,
2540                                      timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2541                                      cancellable,
2542                                      error);
2543
2544  out:
2545   if (reply_type != NULL)
2546     g_variant_type_free (reply_type);
2547
2548   g_free (split_interface_name);
2549
2550   return ret;
2551 }
2552
2553 /* ---------------------------------------------------------------------------------------------------- */