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