98bd758547db733e84209d251a4e658f7f61369f
[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_take_error (data->simple, error);
1144               g_simple_async_result_complete_in_idle (data->simple);
1145               async_init_data_free (data);
1146               goto out;
1147             }
1148         }
1149       else
1150         {
1151           g_variant_get (result,
1152                          "(s)",
1153                          &data->proxy->priv->name_owner);
1154           g_variant_unref (result);
1155         }
1156     }
1157
1158   if (!(data->proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES))
1159     {
1160       /* load all properties asynchronously */
1161       g_dbus_connection_call (data->proxy->priv->connection,
1162                               data->proxy->priv->name_owner,
1163                               data->proxy->priv->object_path,
1164                               "org.freedesktop.DBus.Properties",
1165                               "GetAll",
1166                               g_variant_new ("(s)", data->proxy->priv->interface_name),
1167                               G_VARIANT_TYPE ("(a{sv})"),
1168                               G_DBUS_CALL_FLAGS_NONE,
1169                               -1,           /* timeout */
1170                               data->cancellable,
1171                               (GAsyncReadyCallback) async_init_get_all_cb,
1172                               data);
1173     }
1174   else
1175     {
1176       g_simple_async_result_complete_in_idle (data->simple);
1177       async_init_data_free (data);
1178     }
1179
1180  out:
1181   ;
1182 }
1183
1184 static void
1185 async_init_call_get_name_owner (AsyncInitData *data)
1186 {
1187   g_dbus_connection_call (data->proxy->priv->connection,
1188                           "org.freedesktop.DBus",  /* name */
1189                           "/org/freedesktop/DBus", /* object path */
1190                           "org.freedesktop.DBus",  /* interface */
1191                           "GetNameOwner",
1192                           g_variant_new ("(s)",
1193                                          data->proxy->priv->name),
1194                           G_VARIANT_TYPE ("(s)"),
1195                           G_DBUS_CALL_FLAGS_NONE,
1196                           -1,           /* timeout */
1197                           data->cancellable,
1198                           (GAsyncReadyCallback) async_init_get_name_owner_cb,
1199                           data);
1200 }
1201
1202 static void
1203 async_init_start_service_by_name_cb (GDBusConnection *connection,
1204                                      GAsyncResult    *res,
1205                                      gpointer         user_data)
1206 {
1207   AsyncInitData *data = user_data;
1208   GError *error;
1209   GVariant *result;
1210
1211   error = NULL;
1212   result = g_dbus_connection_call_finish (connection,
1213                                           res,
1214                                           &error);
1215   if (result == NULL)
1216     {
1217       /* Errors are not unexpected; the bus will reply e.g.
1218        *
1219        *   org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
1220        *   was not provided by any .service files
1221        *
1222        * This doesn't mean that the name doesn't have an owner, just
1223        * that it's not provided by a .service file. So just proceed to
1224        * invoke GetNameOwner() if dealing with that error.
1225        */
1226       if (error->domain == G_DBUS_ERROR &&
1227           error->code == G_DBUS_ERROR_SERVICE_UNKNOWN)
1228         {
1229           g_error_free (error);
1230         }
1231       else
1232         {
1233           g_prefix_error (&error,
1234                           _("Error calling StartServiceByName for %s: "),
1235                           data->proxy->priv->name);
1236           goto failed;
1237         }
1238     }
1239   else
1240     {
1241       guint32 start_service_result;
1242       g_variant_get (result,
1243                      "(u)",
1244                      &start_service_result);
1245       g_variant_unref (result);
1246       if (start_service_result == 1 ||  /* DBUS_START_REPLY_SUCCESS */
1247           start_service_result == 2)    /* DBUS_START_REPLY_ALREADY_RUNNING */
1248         {
1249           /* continue to invoke GetNameOwner() */
1250         }
1251       else
1252         {
1253           error = g_error_new (G_IO_ERROR,
1254                                G_IO_ERROR_FAILED,
1255                                _("Unexpected reply %d from StartServiceByName(\"%s\") method"),
1256                                start_service_result,
1257                                data->proxy->priv->name);
1258           goto failed;
1259         }
1260     }
1261
1262   async_init_call_get_name_owner (data);
1263   return;
1264
1265  failed:
1266   g_warn_if_fail (error != NULL);
1267   g_simple_async_result_take_error (data->simple, error);
1268   g_simple_async_result_complete_in_idle (data->simple);
1269   async_init_data_free (data);
1270 }
1271
1272 static void
1273 async_init_call_start_service_by_name (AsyncInitData *data)
1274 {
1275   g_dbus_connection_call (data->proxy->priv->connection,
1276                           "org.freedesktop.DBus",  /* name */
1277                           "/org/freedesktop/DBus", /* object path */
1278                           "org.freedesktop.DBus",  /* interface */
1279                           "StartServiceByName",
1280                           g_variant_new ("(su)",
1281                                          data->proxy->priv->name,
1282                                          0),
1283                           G_VARIANT_TYPE ("(u)"),
1284                           G_DBUS_CALL_FLAGS_NONE,
1285                           -1,           /* timeout */
1286                           data->cancellable,
1287                           (GAsyncReadyCallback) async_init_start_service_by_name_cb,
1288                           data);
1289 }
1290
1291 static void
1292 async_initable_init_second_async (GAsyncInitable      *initable,
1293                                   gint                 io_priority,
1294                                   GCancellable        *cancellable,
1295                                   GAsyncReadyCallback  callback,
1296                                   gpointer             user_data)
1297 {
1298   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1299   AsyncInitData *data;
1300
1301   data = g_new0 (AsyncInitData, 1);
1302   data->proxy = g_object_ref (proxy);
1303   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1304   data->simple = g_simple_async_result_new (G_OBJECT (proxy),
1305                                             callback,
1306                                             user_data,
1307                                             NULL);
1308
1309   /* Check name ownership asynchronously - possibly also start the service */
1310   if (proxy->priv->name == NULL)
1311     {
1312       /* Do nothing */
1313       async_init_get_name_owner_cb (proxy->priv->connection, NULL, data);
1314     }
1315   else if (g_dbus_is_unique_name (proxy->priv->name))
1316     {
1317       proxy->priv->name_owner = g_strdup (proxy->priv->name);
1318       async_init_get_name_owner_cb (proxy->priv->connection, NULL, data);
1319     }
1320   else
1321     {
1322       if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
1323         {
1324           async_init_call_get_name_owner (data);
1325         }
1326       else
1327         {
1328           async_init_call_start_service_by_name (data);
1329         }
1330     }
1331 }
1332
1333 static gboolean
1334 async_initable_init_second_finish (GAsyncInitable  *initable,
1335                                    GAsyncResult    *res,
1336                                    GError         **error)
1337 {
1338   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1339   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1340   GVariant *result;
1341   gboolean ret;
1342
1343   ret = FALSE;
1344
1345   if (g_simple_async_result_propagate_error (simple, error))
1346     goto out;
1347
1348   result = g_simple_async_result_get_op_res_gpointer (simple);
1349   if (result != NULL)
1350     {
1351       process_get_all_reply (proxy, result);
1352     }
1353
1354   ret = TRUE;
1355
1356  out:
1357   proxy->priv->initialized = TRUE;
1358   return ret;
1359 }
1360
1361 /* ---------------------------------------------------------------------------------------------------- */
1362
1363 static void
1364 async_initable_init_first (GAsyncInitable *initable)
1365 {
1366   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1367
1368   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES))
1369     {
1370       /* subscribe to PropertiesChanged() */
1371       proxy->priv->properties_changed_subscriber_id =
1372         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1373                                             proxy->priv->name,
1374                                             "org.freedesktop.DBus.Properties",
1375                                             "PropertiesChanged",
1376                                             proxy->priv->object_path,
1377                                             proxy->priv->interface_name,
1378                                             G_DBUS_SIGNAL_FLAGS_NONE,
1379                                             on_properties_changed,
1380                                             proxy,
1381                                             NULL);
1382     }
1383
1384   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS))
1385     {
1386       /* subscribe to all signals for the object */
1387       proxy->priv->signals_subscriber_id =
1388         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1389                                             proxy->priv->name,
1390                                             proxy->priv->interface_name,
1391                                             NULL,                        /* member */
1392                                             proxy->priv->object_path,
1393                                             NULL,                        /* arg0 */
1394                                             G_DBUS_SIGNAL_FLAGS_NONE,
1395                                             on_signal_received,
1396                                             proxy,
1397                                             NULL);
1398     }
1399
1400   if (proxy->priv->name != NULL && !g_dbus_is_unique_name (proxy->priv->name))
1401     {
1402       proxy->priv->name_owner_changed_subscription_id =
1403         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1404                                             "org.freedesktop.DBus",  /* name */
1405                                             "org.freedesktop.DBus",  /* interface */
1406                                             "NameOwnerChanged",      /* signal name */
1407                                             "/org/freedesktop/DBus", /* path */
1408                                             proxy->priv->name,       /* arg0 */
1409                                             G_DBUS_SIGNAL_FLAGS_NONE,
1410                                             on_name_owner_changed,
1411                                             proxy,
1412                                             NULL);
1413     }
1414 }
1415
1416 /* ---------------------------------------------------------------------------------------------------- */
1417
1418 /* initialization is split into two parts - the first is the
1419  * non-blocing part that requires the callers GMainContext - the
1420  * second is a blocking part async part that doesn't require the
1421  * callers GMainContext.. we do this split so the code can be reused
1422  * in the GInitable implementation below.
1423  *
1424  * Note that obtaining a GDBusConnection is not shared between the two
1425  * paths.
1426  */
1427
1428 typedef struct
1429 {
1430   GDBusProxy          *proxy;
1431   gint                 io_priority;
1432   GCancellable        *cancellable;
1433   GAsyncReadyCallback  callback;
1434   gpointer             user_data;
1435 } GetConnectionData;
1436
1437 static void
1438 get_connection_cb (GObject       *source_object,
1439                    GAsyncResult  *res,
1440                    gpointer       user_data)
1441 {
1442   GetConnectionData *data = user_data;
1443   GError *error;
1444
1445   error = NULL;
1446   data->proxy->priv->connection = g_bus_get_finish (res, &error);
1447   if (data->proxy->priv->connection == NULL)
1448     {
1449       GSimpleAsyncResult *simple;
1450       simple = g_simple_async_result_new (G_OBJECT (data->proxy),
1451                                           data->callback,
1452                                           data->user_data,
1453                                           NULL);
1454       g_simple_async_result_take_error (simple, error);
1455       g_simple_async_result_complete_in_idle (simple);
1456       g_object_unref (simple);
1457     }
1458   else
1459     {
1460       async_initable_init_first (G_ASYNC_INITABLE (data->proxy));
1461       async_initable_init_second_async (G_ASYNC_INITABLE (data->proxy),
1462                                         data->io_priority,
1463                                         data->cancellable,
1464                                         data->callback,
1465                                         data->user_data);
1466     }
1467
1468   if (data->cancellable != NULL)
1469     g_object_unref (data->cancellable);
1470   if (data->proxy != NULL)
1471     g_object_unref (data->proxy);
1472   g_free (data);
1473 }
1474
1475 static void
1476 async_initable_init_async (GAsyncInitable      *initable,
1477                            gint                 io_priority,
1478                            GCancellable        *cancellable,
1479                            GAsyncReadyCallback  callback,
1480                            gpointer             user_data)
1481 {
1482   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1483
1484   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1485     {
1486       GetConnectionData *data;
1487
1488       g_assert (proxy->priv->connection == NULL);
1489
1490       data = g_new0 (GetConnectionData, 1);
1491       data->proxy = g_object_ref (proxy);
1492       data->io_priority = io_priority;
1493       data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1494       data->callback = callback;
1495       data->user_data = user_data;
1496       g_bus_get (proxy->priv->bus_type,
1497                  cancellable,
1498                  get_connection_cb,
1499                  data);
1500     }
1501   else
1502     {
1503       async_initable_init_first (initable);
1504       async_initable_init_second_async (initable, io_priority, cancellable, callback, user_data);
1505     }
1506 }
1507
1508 static gboolean
1509 async_initable_init_finish (GAsyncInitable  *initable,
1510                             GAsyncResult    *res,
1511                             GError         **error)
1512 {
1513   return async_initable_init_second_finish (initable, res, error);
1514 }
1515
1516 static void
1517 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1518 {
1519   async_initable_iface->init_async = async_initable_init_async;
1520   async_initable_iface->init_finish = async_initable_init_finish;
1521 }
1522
1523 /* ---------------------------------------------------------------------------------------------------- */
1524
1525 typedef struct
1526 {
1527   GMainContext *context;
1528   GMainLoop *loop;
1529   GAsyncResult *res;
1530 } InitableAsyncInitableData;
1531
1532 static void
1533 async_initable_init_async_cb (GObject      *source_object,
1534                               GAsyncResult *res,
1535                               gpointer      user_data)
1536 {
1537   InitableAsyncInitableData *data = user_data;
1538   data->res = g_object_ref (res);
1539   g_main_loop_quit (data->loop);
1540 }
1541
1542 /* Simply reuse the GAsyncInitable implementation but run the first
1543  * part (that is non-blocking and requires the callers GMainContext)
1544  * with the callers GMainContext.. and the second with a private
1545  * GMainContext (bug 621310 is slightly related).
1546  *
1547  * Note that obtaining a GDBusConnection is not shared between the two
1548  * paths.
1549  */
1550 static gboolean
1551 initable_init (GInitable     *initable,
1552                GCancellable  *cancellable,
1553                GError       **error)
1554 {
1555   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1556   InitableAsyncInitableData *data;
1557   gboolean ret;
1558
1559   ret = FALSE;
1560
1561   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1562     {
1563       g_assert (proxy->priv->connection == NULL);
1564       proxy->priv->connection = g_bus_get_sync (proxy->priv->bus_type,
1565                                                 cancellable,
1566                                                 error);
1567       if (proxy->priv->connection == NULL)
1568         goto out;
1569     }
1570
1571   async_initable_init_first (G_ASYNC_INITABLE (initable));
1572
1573   data = g_new0 (InitableAsyncInitableData, 1);
1574   data->context = g_main_context_new ();
1575   data->loop = g_main_loop_new (data->context, FALSE);
1576
1577   g_main_context_push_thread_default (data->context);
1578
1579   async_initable_init_second_async (G_ASYNC_INITABLE (initable),
1580                                     G_PRIORITY_DEFAULT,
1581                                     cancellable,
1582                                     async_initable_init_async_cb,
1583                                     data);
1584
1585   g_main_loop_run (data->loop);
1586
1587   ret = async_initable_init_second_finish (G_ASYNC_INITABLE (initable),
1588                                            data->res,
1589                                            error);
1590
1591   g_main_context_pop_thread_default (data->context);
1592
1593   g_main_context_unref (data->context);
1594   g_main_loop_unref (data->loop);
1595   g_object_unref (data->res);
1596   g_free (data);
1597
1598  out:
1599
1600   return ret;
1601 }
1602
1603 static void
1604 initable_iface_init (GInitableIface *initable_iface)
1605 {
1606   initable_iface->init = initable_init;
1607 }
1608
1609 /* ---------------------------------------------------------------------------------------------------- */
1610
1611 /**
1612  * g_dbus_proxy_new:
1613  * @connection: A #GDBusConnection.
1614  * @flags: Flags used when constructing the proxy.
1615  * @info: A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1616  * @name: A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
1617  * @object_path: An object path.
1618  * @interface_name: A D-Bus interface name.
1619  * @cancellable: A #GCancellable or %NULL.
1620  * @callback: Callback function to invoke when the proxy is ready.
1621  * @user_data: User data to pass to @callback.
1622  *
1623  * Creates a proxy for accessing @interface_name on the remote object
1624  * at @object_path owned by @name at @connection and asynchronously
1625  * loads D-Bus properties unless the
1626  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used. Connect to
1627  * the #GDBusProxy::g-properties-changed signal to get notified about
1628  * property changes.
1629  *
1630  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
1631  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
1632  * to handle signals from the remote object.
1633  *
1634  * If @name is a well-known name and the
1635  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag isn't set and no name
1636  * owner currently exists, the message bus will be requested to launch
1637  * a name owner for the name.
1638  *
1639  * This is a failable asynchronous constructor - when the proxy is
1640  * ready, @callback will be invoked and you can use
1641  * g_dbus_proxy_new_finish() to get the result.
1642  *
1643  * See g_dbus_proxy_new_sync() and for a synchronous version of this constructor.
1644  *
1645  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1646  *
1647  * Since: 2.26
1648  */
1649 void
1650 g_dbus_proxy_new (GDBusConnection     *connection,
1651                   GDBusProxyFlags      flags,
1652                   GDBusInterfaceInfo  *info,
1653                   const gchar         *name,
1654                   const gchar         *object_path,
1655                   const gchar         *interface_name,
1656                   GCancellable        *cancellable,
1657                   GAsyncReadyCallback  callback,
1658                   gpointer             user_data)
1659 {
1660   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1661   g_return_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) || g_dbus_is_name (name));
1662   g_return_if_fail (g_variant_is_object_path (object_path));
1663   g_return_if_fail (g_dbus_is_interface_name (interface_name));
1664
1665   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
1666                               G_PRIORITY_DEFAULT,
1667                               cancellable,
1668                               callback,
1669                               user_data,
1670                               "g-flags", flags,
1671                               "g-interface-info", info,
1672                               "g-name", name,
1673                               "g-connection", connection,
1674                               "g-object-path", object_path,
1675                               "g-interface-name", interface_name,
1676                               NULL);
1677 }
1678
1679 /**
1680  * g_dbus_proxy_new_finish:
1681  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new().
1682  * @error: Return location for error or %NULL.
1683  *
1684  * Finishes creating a #GDBusProxy.
1685  *
1686  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
1687  *
1688  * Since: 2.26
1689  */
1690 GDBusProxy *
1691 g_dbus_proxy_new_finish (GAsyncResult  *res,
1692                          GError       **error)
1693 {
1694   GObject *object;
1695   GObject *source_object;
1696
1697   source_object = g_async_result_get_source_object (res);
1698   g_assert (source_object != NULL);
1699
1700   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1701                                         res,
1702                                         error);
1703   g_object_unref (source_object);
1704
1705   if (object != NULL)
1706     return G_DBUS_PROXY (object);
1707   else
1708     return NULL;
1709 }
1710
1711 /**
1712  * g_dbus_proxy_new_sync:
1713  * @connection: A #GDBusConnection.
1714  * @flags: Flags used when constructing the proxy.
1715  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1716  * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
1717  * @object_path: An object path.
1718  * @interface_name: A D-Bus interface name.
1719  * @cancellable: (allow-none): A #GCancellable or %NULL.
1720  * @error: (allow-none): Return location for error or %NULL.
1721  *
1722  * Creates a proxy for accessing @interface_name on the remote object
1723  * at @object_path owned by @name at @connection and synchronously
1724  * loads D-Bus properties unless the
1725  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used.
1726  *
1727  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
1728  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
1729  * to handle signals from the remote object.
1730  *
1731  * If @name is a well-known name and the
1732  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag isn't set and no name
1733  * owner currently exists, the message bus will be requested to launch
1734  * a name owner for the name.
1735  *
1736  * This is a synchronous failable constructor. See g_dbus_proxy_new()
1737  * and g_dbus_proxy_new_finish() for the asynchronous version.
1738  *
1739  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1740  *
1741  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
1742  *
1743  * Since: 2.26
1744  */
1745 GDBusProxy *
1746 g_dbus_proxy_new_sync (GDBusConnection     *connection,
1747                        GDBusProxyFlags      flags,
1748                        GDBusInterfaceInfo  *info,
1749                        const gchar         *name,
1750                        const gchar         *object_path,
1751                        const gchar         *interface_name,
1752                        GCancellable        *cancellable,
1753                        GError             **error)
1754 {
1755   GInitable *initable;
1756
1757   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1758   g_return_val_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) ||
1759                         g_dbus_is_name (name), NULL);
1760   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1761   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
1762
1763   initable = g_initable_new (G_TYPE_DBUS_PROXY,
1764                              cancellable,
1765                              error,
1766                              "g-flags", flags,
1767                              "g-interface-info", info,
1768                              "g-name", name,
1769                              "g-connection", connection,
1770                              "g-object-path", object_path,
1771                              "g-interface-name", interface_name,
1772                              NULL);
1773   if (initable != NULL)
1774     return G_DBUS_PROXY (initable);
1775   else
1776     return NULL;
1777 }
1778
1779 /* ---------------------------------------------------------------------------------------------------- */
1780
1781 /**
1782  * g_dbus_proxy_new_for_bus:
1783  * @bus_type: A #GBusType.
1784  * @flags: Flags used when constructing the proxy.
1785  * @info: A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1786  * @name: A bus name (well-known or unique).
1787  * @object_path: An object path.
1788  * @interface_name: A D-Bus interface name.
1789  * @cancellable: A #GCancellable or %NULL.
1790  * @callback: Callback function to invoke when the proxy is ready.
1791  * @user_data: User data to pass to @callback.
1792  *
1793  * Like g_dbus_proxy_new() but takes a #GBusType instead of a #GDBusConnection.
1794  *
1795  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1796  *
1797  * Since: 2.26
1798  */
1799 void
1800 g_dbus_proxy_new_for_bus (GBusType             bus_type,
1801                           GDBusProxyFlags      flags,
1802                           GDBusInterfaceInfo  *info,
1803                           const gchar         *name,
1804                           const gchar         *object_path,
1805                           const gchar         *interface_name,
1806                           GCancellable        *cancellable,
1807                           GAsyncReadyCallback  callback,
1808                           gpointer             user_data)
1809 {
1810   g_return_if_fail (g_dbus_is_name (name));
1811   g_return_if_fail (g_variant_is_object_path (object_path));
1812   g_return_if_fail (g_dbus_is_interface_name (interface_name));
1813
1814   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
1815                               G_PRIORITY_DEFAULT,
1816                               cancellable,
1817                               callback,
1818                               user_data,
1819                               "g-flags", flags,
1820                               "g-interface-info", info,
1821                               "g-name", name,
1822                               "g-bus-type", bus_type,
1823                               "g-object-path", object_path,
1824                               "g-interface-name", interface_name,
1825                               NULL);
1826 }
1827
1828 /**
1829  * g_dbus_proxy_new_for_bus_finish:
1830  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new_for_bus().
1831  * @error: Return location for error or %NULL.
1832  *
1833  * Finishes creating a #GDBusProxy.
1834  *
1835  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
1836  *
1837  * Since: 2.26
1838  */
1839 GDBusProxy *
1840 g_dbus_proxy_new_for_bus_finish (GAsyncResult  *res,
1841                                  GError       **error)
1842 {
1843   return g_dbus_proxy_new_finish (res, error);
1844 }
1845
1846 /**
1847  * g_dbus_proxy_new_for_bus_sync:
1848  * @bus_type: A #GBusType.
1849  * @flags: Flags used when constructing the proxy.
1850  * @info: A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
1851  * @name: A bus name (well-known or unique).
1852  * @object_path: An object path.
1853  * @interface_name: A D-Bus interface name.
1854  * @cancellable: A #GCancellable or %NULL.
1855  * @error: Return location for error or %NULL.
1856  *
1857  * Like g_dbus_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection.
1858  *
1859  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
1860  *
1861  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
1862  *
1863  * Since: 2.26
1864  */
1865 GDBusProxy *
1866 g_dbus_proxy_new_for_bus_sync (GBusType             bus_type,
1867                                GDBusProxyFlags      flags,
1868                                GDBusInterfaceInfo  *info,
1869                                const gchar         *name,
1870                                const gchar         *object_path,
1871                                const gchar         *interface_name,
1872                                GCancellable        *cancellable,
1873                                GError             **error)
1874 {
1875   GInitable *initable;
1876
1877   g_return_val_if_fail (g_dbus_is_name (name), NULL);
1878   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1879   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
1880
1881   initable = g_initable_new (G_TYPE_DBUS_PROXY,
1882                              cancellable,
1883                              error,
1884                              "g-flags", flags,
1885                              "g-interface-info", info,
1886                              "g-name", name,
1887                              "g-bus-type", bus_type,
1888                              "g-object-path", object_path,
1889                              "g-interface-name", interface_name,
1890                              NULL);
1891   if (initable != NULL)
1892     return G_DBUS_PROXY (initable);
1893   else
1894     return NULL;
1895 }
1896
1897 /* ---------------------------------------------------------------------------------------------------- */
1898
1899 /**
1900  * g_dbus_proxy_get_connection:
1901  * @proxy: A #GDBusProxy.
1902  *
1903  * Gets the connection @proxy is for.
1904  *
1905  * Returns: (transfer none): A #GDBusConnection owned by @proxy. Do not free.
1906  *
1907  * Since: 2.26
1908  */
1909 GDBusConnection *
1910 g_dbus_proxy_get_connection (GDBusProxy *proxy)
1911 {
1912   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
1913   return proxy->priv->connection;
1914 }
1915
1916 /**
1917  * g_dbus_proxy_get_flags:
1918  * @proxy: A #GDBusProxy.
1919  *
1920  * Gets the flags that @proxy was constructed with.
1921  *
1922  * Returns: Flags from the #GDBusProxyFlags enumeration.
1923  *
1924  * Since: 2.26
1925  */
1926 GDBusProxyFlags
1927 g_dbus_proxy_get_flags (GDBusProxy *proxy)
1928 {
1929   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), 0);
1930   return proxy->priv->flags;
1931 }
1932
1933 /**
1934  * g_dbus_proxy_get_name:
1935  * @proxy: A #GDBusProxy.
1936  *
1937  * Gets the name that @proxy was constructed for.
1938  *
1939  * Returns: A string owned by @proxy. Do not free.
1940  *
1941  * Since: 2.26
1942  */
1943 const gchar *
1944 g_dbus_proxy_get_name (GDBusProxy *proxy)
1945 {
1946   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
1947   return proxy->priv->name;
1948 }
1949
1950 /**
1951  * g_dbus_proxy_get_name_owner:
1952  * @proxy: A #GDBusProxy.
1953  *
1954  * The unique name that owns the name that @proxy is for or %NULL if
1955  * no-one currently owns that name. You may connect to the
1956  * #GObject::notify signal to track changes to the
1957  * #GDBusProxy:g-name-owner property.
1958  *
1959  * Returns: The name owner or %NULL if no name owner exists. Free with g_free().
1960  *
1961  * Since: 2.26
1962  */
1963 gchar *
1964 g_dbus_proxy_get_name_owner (GDBusProxy *proxy)
1965 {
1966   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
1967   return g_strdup (proxy->priv->name_owner);
1968 }
1969
1970 /**
1971  * g_dbus_proxy_get_object_path:
1972  * @proxy: A #GDBusProxy.
1973  *
1974  * Gets the object path @proxy is for.
1975  *
1976  * Returns: A string owned by @proxy. Do not free.
1977  *
1978  * Since: 2.26
1979  */
1980 const gchar *
1981 g_dbus_proxy_get_object_path (GDBusProxy *proxy)
1982 {
1983   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
1984   return proxy->priv->object_path;
1985 }
1986
1987 /**
1988  * g_dbus_proxy_get_interface_name:
1989  * @proxy: A #GDBusProxy.
1990  *
1991  * Gets the D-Bus interface name @proxy is for.
1992  *
1993  * Returns: A string owned by @proxy. Do not free.
1994  *
1995  * Since: 2.26
1996  */
1997 const gchar *
1998 g_dbus_proxy_get_interface_name (GDBusProxy *proxy)
1999 {
2000   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2001   return proxy->priv->interface_name;
2002 }
2003
2004 /**
2005  * g_dbus_proxy_get_default_timeout:
2006  * @proxy: A #GDBusProxy.
2007  *
2008  * Gets the timeout to use if -1 (specifying default timeout) is
2009  * passed as @timeout_msec in the g_dbus_proxy_call() and
2010  * g_dbus_proxy_call_sync() functions.
2011  *
2012  * See the #GDBusProxy:g-default-timeout property for more details.
2013  *
2014  * Returns: Timeout to use for @proxy.
2015  *
2016  * Since: 2.26
2017  */
2018 gint
2019 g_dbus_proxy_get_default_timeout (GDBusProxy *proxy)
2020 {
2021   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), -1);
2022   return proxy->priv->timeout_msec;
2023 }
2024
2025 /**
2026  * g_dbus_proxy_set_default_timeout:
2027  * @proxy: A #GDBusProxy.
2028  * @timeout_msec: Timeout in milliseconds.
2029  *
2030  * Sets the timeout to use if -1 (specifying default timeout) is
2031  * passed as @timeout_msec in the g_dbus_proxy_call() and
2032  * g_dbus_proxy_call_sync() functions.
2033  *
2034  * See the #GDBusProxy:g-default-timeout property for more details.
2035  *
2036  * Since: 2.26
2037  */
2038 void
2039 g_dbus_proxy_set_default_timeout (GDBusProxy *proxy,
2040                                   gint        timeout_msec)
2041 {
2042   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2043   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2044
2045   /* TODO: locking? */
2046   if (proxy->priv->timeout_msec != timeout_msec)
2047     {
2048       proxy->priv->timeout_msec = timeout_msec;
2049       g_object_notify (G_OBJECT (proxy), "g-default-timeout");
2050     }
2051 }
2052
2053 /**
2054  * g_dbus_proxy_get_interface_info:
2055  * @proxy: A #GDBusProxy
2056  *
2057  * Returns the #GDBusInterfaceInfo, if any, specifying the minimal
2058  * interface that @proxy conforms to.
2059  *
2060  * See the #GDBusProxy:g-interface-info property for more details.
2061  *
2062  * Returns: A #GDBusInterfaceInfo or %NULL. Do not unref the returned
2063  * object, it is owned by @proxy.
2064  *
2065  * Since: 2.26
2066  */
2067 GDBusInterfaceInfo *
2068 g_dbus_proxy_get_interface_info (GDBusProxy *proxy)
2069 {
2070   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2071   return proxy->priv->expected_interface;
2072 }
2073
2074 /**
2075  * g_dbus_proxy_set_interface_info:
2076  * @proxy: A #GDBusProxy
2077  * @info: Minimum interface this proxy conforms to or %NULL to unset.
2078  *
2079  * Ensure that interactions with @proxy conform to the given
2080  * interface.  For example, when completing a method call, if the type
2081  * signature of the message isn't what's expected, the given #GError
2082  * is set.  Signals that have a type signature mismatch are simply
2083  * dropped.
2084  *
2085  * See the #GDBusProxy:g-interface-info property for more details.
2086  *
2087  * Since: 2.26
2088  */
2089 void
2090 g_dbus_proxy_set_interface_info (GDBusProxy         *proxy,
2091                                  GDBusInterfaceInfo *info)
2092 {
2093   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2094   if (proxy->priv->expected_interface != NULL)
2095     g_dbus_interface_info_unref (proxy->priv->expected_interface);
2096   proxy->priv->expected_interface = info != NULL ? g_dbus_interface_info_ref (info) : NULL;
2097 }
2098
2099 /* ---------------------------------------------------------------------------------------------------- */
2100
2101 static gboolean
2102 maybe_split_method_name (const gchar  *method_name,
2103                          gchar       **out_interface_name,
2104                          const gchar **out_method_name)
2105 {
2106   gboolean was_split;
2107
2108   was_split = FALSE;
2109   g_assert (out_interface_name != NULL);
2110   g_assert (out_method_name != NULL);
2111   *out_interface_name = NULL;
2112   *out_method_name = NULL;
2113
2114   if (strchr (method_name, '.') != NULL)
2115     {
2116       gchar *p;
2117       gchar *last_dot;
2118
2119       p = g_strdup (method_name);
2120       last_dot = strrchr (p, '.');
2121       *last_dot = '\0';
2122
2123       *out_interface_name = p;
2124       *out_method_name = last_dot + 1;
2125
2126       was_split = TRUE;
2127     }
2128
2129   return was_split;
2130 }
2131
2132
2133 static void
2134 reply_cb (GDBusConnection *connection,
2135           GAsyncResult    *res,
2136           gpointer         user_data)
2137 {
2138   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
2139   GVariant *value;
2140   GError *error;
2141
2142   error = NULL;
2143   value = g_dbus_connection_call_finish (connection,
2144                                          res,
2145                                          &error);
2146   if (error != NULL)
2147     {
2148       g_simple_async_result_take_error (simple, error);
2149     }
2150   else
2151     {
2152       g_simple_async_result_set_op_res_gpointer (simple,
2153                                                  value,
2154                                                  (GDestroyNotify) g_variant_unref);
2155     }
2156
2157   /* no need to complete in idle since the method GDBusConnection already does */
2158   g_simple_async_result_complete (simple);
2159   g_object_unref (simple);
2160 }
2161
2162 static const GDBusMethodInfo *
2163 lookup_method_info_or_warn (GDBusProxy  *proxy,
2164                             const gchar *method_name)
2165 {
2166   const GDBusMethodInfo *info;
2167
2168   if (proxy->priv->expected_interface == NULL)
2169     return NULL;
2170
2171   info = g_dbus_interface_info_lookup_method (proxy->priv->expected_interface, method_name);
2172   if (info == NULL)
2173     {
2174       g_warning ("Trying to invoke method %s which isn't in expected interface %s",
2175                  method_name, proxy->priv->expected_interface->name);
2176     }
2177
2178   return info;
2179 }
2180
2181 static const gchar *
2182 get_destination_for_call (GDBusProxy *proxy)
2183 {
2184   const gchar *ret;
2185
2186   ret = NULL;
2187
2188   /* If proxy->priv->name is a unique name, then proxy->priv->name_owner
2189    * is never NULL and always the same as proxy->priv->name. We use this
2190    * knowledge to avoid checking if proxy->priv->name is a unique or
2191    * well-known name.
2192    */
2193   ret = proxy->priv->name_owner;
2194   if (ret != NULL)
2195     goto out;
2196
2197   if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
2198     goto out;
2199
2200   ret = proxy->priv->name;
2201
2202  out:
2203   return ret;
2204 }
2205
2206 /**
2207  * g_dbus_proxy_call:
2208  * @proxy: A #GDBusProxy.
2209  * @method_name: Name of method to invoke.
2210  * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
2211  * @flags: Flags from the #GDBusCallFlags enumeration.
2212  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
2213  *                "infinite") or -1 to use the proxy default timeout.
2214  * @cancellable: A #GCancellable or %NULL.
2215  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
2216  * care about the result of the method invocation.
2217  * @user_data: The data to pass to @callback.
2218  *
2219  * Asynchronously invokes the @method_name method on @proxy.
2220  *
2221  * If @method_name contains any dots, then @name is split into interface and
2222  * method name parts. This allows using @proxy for invoking methods on
2223  * other interfaces.
2224  *
2225  * If the #GDBusConnection associated with @proxy is closed then
2226  * the operation will fail with %G_IO_ERROR_CLOSED. If
2227  * @cancellable is canceled, the operation will fail with
2228  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
2229  * compatible with the D-Bus protocol, the operation fails with
2230  * %G_IO_ERROR_INVALID_ARGUMENT.
2231  *
2232  * If the @parameters #GVariant is floating, it is consumed. This allows
2233  * convenient 'inline' use of g_variant_new(), e.g.:
2234  * |[
2235  *  g_dbus_proxy_call (proxy,
2236  *                     "TwoStrings",
2237  *                     g_variant_new ("(ss)",
2238  *                                    "Thing One",
2239  *                                    "Thing Two"),
2240  *                     G_DBUS_CALL_FLAGS_NONE,
2241  *                     -1,
2242  *                     NULL,
2243  *                     (GAsyncReadyCallback) two_strings_done,
2244  *                     &amp;data);
2245  * ]|
2246  *
2247  * This is an asynchronous method. When the operation is finished,
2248  * @callback will be invoked in the
2249  * <link linkend="g-main-context-push-thread-default">thread-default
2250  * main loop</link> of the thread you are calling this method from.
2251  * You can then call g_dbus_proxy_call_finish() to get the result of
2252  * the operation. See g_dbus_proxy_call_sync() for the synchronous
2253  * version of this method.
2254  *
2255  * Since: 2.26
2256  */
2257 void
2258 g_dbus_proxy_call (GDBusProxy          *proxy,
2259                    const gchar         *method_name,
2260                    GVariant            *parameters,
2261                    GDBusCallFlags       flags,
2262                    gint                 timeout_msec,
2263                    GCancellable        *cancellable,
2264                    GAsyncReadyCallback  callback,
2265                    gpointer             user_data)
2266 {
2267   GSimpleAsyncResult *simple;
2268   gboolean was_split;
2269   gchar *split_interface_name;
2270   const gchar *split_method_name;
2271   const gchar *target_method_name;
2272   const gchar *target_interface_name;
2273   const gchar *destination;
2274   GVariantType *reply_type;
2275
2276   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2277   g_return_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name));
2278   g_return_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
2279   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2280
2281   reply_type = NULL;
2282   split_interface_name = NULL;
2283
2284   simple = g_simple_async_result_new (G_OBJECT (proxy),
2285                                       callback,
2286                                       user_data,
2287                                       g_dbus_proxy_call);
2288
2289   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2290   target_method_name = was_split ? split_method_name : method_name;
2291   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2292
2293   /* Warn if method is unexpected (cf. :g-interface-info) */
2294   if (!was_split)
2295     {
2296       const GDBusMethodInfo *expected_method_info;
2297       expected_method_info = lookup_method_info_or_warn (proxy, target_method_name);
2298       if (expected_method_info != NULL)
2299         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2300     }
2301
2302   destination = NULL;
2303   if (proxy->priv->name != NULL)
2304     {
2305       destination = get_destination_for_call (proxy);
2306       if (destination == NULL)
2307         {
2308           g_simple_async_result_set_error (simple,
2309                                            G_IO_ERROR,
2310                                            G_IO_ERROR_FAILED,
2311                                            _("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"));
2312           goto out;
2313         }
2314     }
2315
2316   g_dbus_connection_call (proxy->priv->connection,
2317                           destination,
2318                           proxy->priv->object_path,
2319                           target_interface_name,
2320                           target_method_name,
2321                           parameters,
2322                           reply_type,
2323                           flags,
2324                           timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2325                           cancellable,
2326                           (GAsyncReadyCallback) reply_cb,
2327                           simple);
2328
2329  out:
2330   if (reply_type != NULL)
2331     g_variant_type_free (reply_type);
2332
2333   g_free (split_interface_name);
2334 }
2335
2336 /**
2337  * g_dbus_proxy_call_finish:
2338  * @proxy: A #GDBusProxy.
2339  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_proxy_call().
2340  * @error: Return location for error or %NULL.
2341  *
2342  * Finishes an operation started with g_dbus_proxy_call().
2343  *
2344  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
2345  * return values. Free with g_variant_unref().
2346  *
2347  * Since: 2.26
2348  */
2349 GVariant *
2350 g_dbus_proxy_call_finish (GDBusProxy    *proxy,
2351                           GAsyncResult  *res,
2352                           GError       **error)
2353 {
2354   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2355   GVariant *value;
2356
2357   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2358   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2359   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2360
2361   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_proxy_call);
2362
2363   value = NULL;
2364
2365   if (g_simple_async_result_propagate_error (simple, error))
2366     goto out;
2367
2368   value = g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
2369
2370  out:
2371   return value;
2372 }
2373
2374 /**
2375  * g_dbus_proxy_call_sync:
2376  * @proxy: A #GDBusProxy.
2377  * @method_name: Name of method to invoke.
2378  * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
2379  * @flags: Flags from the #GDBusCallFlags enumeration.
2380  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
2381  *                "infinite") or -1 to use the proxy default timeout.
2382  * @cancellable: A #GCancellable or %NULL.
2383  * @error: Return location for error or %NULL.
2384  *
2385  * Synchronously invokes the @method_name method on @proxy.
2386  *
2387  * If @method_name contains any dots, then @name is split into interface and
2388  * method name parts. This allows using @proxy for invoking methods on
2389  * other interfaces.
2390  *
2391  * If the #GDBusConnection associated with @proxy is disconnected then
2392  * the operation will fail with %G_IO_ERROR_CLOSED. If
2393  * @cancellable is canceled, the operation will fail with
2394  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
2395  * compatible with the D-Bus protocol, the operation fails with
2396  * %G_IO_ERROR_INVALID_ARGUMENT.
2397  *
2398  * If the @parameters #GVariant is floating, it is consumed. This allows
2399  * convenient 'inline' use of g_variant_new(), e.g.:
2400  * |[
2401  *  g_dbus_proxy_call_sync (proxy,
2402  *                          "TwoStrings",
2403  *                          g_variant_new ("(ss)",
2404  *                                         "Thing One",
2405  *                                         "Thing Two"),
2406  *                          G_DBUS_CALL_FLAGS_NONE,
2407  *                          -1,
2408  *                          NULL,
2409  *                          &amp;error);
2410  * ]|
2411  *
2412  * The calling thread is blocked until a reply is received. See
2413  * g_dbus_proxy_call() for the asynchronous version of this
2414  * method.
2415  *
2416  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
2417  * return values. Free with g_variant_unref().
2418  *
2419  * Since: 2.26
2420  */
2421 GVariant *
2422 g_dbus_proxy_call_sync (GDBusProxy      *proxy,
2423                         const gchar     *method_name,
2424                         GVariant        *parameters,
2425                         GDBusCallFlags   flags,
2426                         gint             timeout_msec,
2427                         GCancellable    *cancellable,
2428                         GError         **error)
2429 {
2430   GVariant *ret;
2431   gboolean was_split;
2432   gchar *split_interface_name;
2433   const gchar *split_method_name;
2434   const gchar *target_method_name;
2435   const gchar *target_interface_name;
2436   const gchar *destination;
2437   GVariantType *reply_type;
2438
2439   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2440   g_return_val_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name), NULL);
2441   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
2442   g_return_val_if_fail (timeout_msec == -1 || timeout_msec >= 0, NULL);
2443   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2444
2445   reply_type = NULL;
2446
2447   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2448   target_method_name = was_split ? split_method_name : method_name;
2449   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2450
2451   /* Warn if method is unexpected (cf. :g-interface-info) */
2452   if (!was_split)
2453     {
2454       const GDBusMethodInfo *expected_method_info;
2455       expected_method_info = lookup_method_info_or_warn (proxy, target_method_name);
2456       if (expected_method_info != NULL)
2457         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2458     }
2459
2460   destination = NULL;
2461   if (proxy->priv->name != NULL)
2462     {
2463       destination = get_destination_for_call (proxy);
2464       if (destination == NULL)
2465         {
2466           g_set_error_literal (error,
2467                                G_IO_ERROR,
2468                                G_IO_ERROR_FAILED,
2469                                _("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"));
2470           ret = NULL;
2471           goto out;
2472         }
2473     }
2474
2475   ret = g_dbus_connection_call_sync (proxy->priv->connection,
2476                                      destination,
2477                                      proxy->priv->object_path,
2478                                      target_interface_name,
2479                                      target_method_name,
2480                                      parameters,
2481                                      reply_type,
2482                                      flags,
2483                                      timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2484                                      cancellable,
2485                                      error);
2486
2487  out:
2488   if (reply_type != NULL)
2489     g_variant_type_free (reply_type);
2490
2491   g_free (split_interface_name);
2492
2493   return ret;
2494 }
2495
2496 /* ---------------------------------------------------------------------------------------------------- */