GApplication: allow handles_commandline and service
[platform/upstream/glib.git] / gio / gactiongroupexporter.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  * Copyright © 2011 Canonical Limited
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published
7  * by the Free Software Foundation; either version 2 of the licence or (at
8  * 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  * Authors: Ryan Lortie <desrt@desrt.ca>
21  */
22
23 #include "config.h"
24
25 #include "gactiongroupexporter.h"
26
27 #include "gdbusmethodinvocation.h"
28 #include "gremoteactiongroup.h"
29 #include "gdbusintrospection.h"
30 #include "gdbusconnection.h"
31 #include "gactiongroup.h"
32 #include "gdbuserror.h"
33
34 /**
35  * SECTION:gactiongroupexporter
36  * @title: GActionGroup exporter
37  * @include: gio/gio.h
38  * @short_description: Export GActionGroups on D-Bus
39  * @see_also: #GActionGroup, #GDBusActionGroup
40  *
41  * These functions support exporting a #GActionGroup on D-Bus.
42  * The D-Bus interface that is used is a private implementation
43  * detail.
44  *
45  * To access an exported #GActionGroup remotely, use
46  * g_dbus_action_group_get() to obtain a #GDBusActionGroup.
47  */
48
49 static GVariant *
50 g_action_group_describe_action (GActionGroup *action_group,
51                                 const gchar  *name)
52 {
53   const GVariantType *type;
54   GVariantBuilder builder;
55   gboolean enabled;
56   GVariant *state;
57
58   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(bgav)"));
59
60   enabled = g_action_group_get_action_enabled (action_group, name);
61   g_variant_builder_add (&builder, "b", enabled);
62
63   if ((type = g_action_group_get_action_parameter_type (action_group, name)))
64     {
65       gchar *str = g_variant_type_dup_string (type);
66       g_variant_builder_add (&builder, "g", str);
67       g_free (str);
68     }
69   else
70     g_variant_builder_add (&builder, "g", "");
71
72   g_variant_builder_open (&builder, G_VARIANT_TYPE ("av"));
73   if ((state = g_action_group_get_action_state (action_group, name)))
74     {
75       g_variant_builder_add (&builder, "v", state);
76       g_variant_unref (state);
77     }
78   g_variant_builder_close (&builder);
79
80   return g_variant_builder_end (&builder);
81 }
82
83 /* Using XML saves us dozens of relocations vs. using the introspection
84  * structure types.  We only need to burn cycles and memory if we
85  * actually use the exporter -- not in every single app using GIO.
86  *
87  * It's also a lot easier to read. :)
88  *
89  * For documentation of this interface, see
90  * http://live.gnome.org/GTK+/GApplication-dbus-apis
91  */
92 const char org_gtk_Actions_xml[] =
93   "<node>"
94   "  <interface name='org.gtk.Actions'>"
95   "    <method name='List'>"
96   "      <arg type='as' name='list' direction='out'/>"
97   "    </method>"
98   "    <method name='Describe'>"
99   "      <arg type='s' name='action_name' direction='in'/>"
100   "      <arg type='(bgav)' name='description' direction='out'/>"
101   "    </method>"
102   "    <method name='DescribeAll'>"
103   "      <arg type='a{s(bgav)}' name='descriptions' direction='out'/>"
104   "    </method>"
105   "    <method name='Activate'>"
106   "      <arg type='s' name='action_name' direction='in'/>"
107   "      <arg type='av' name='parameter' direction='in'/>"
108   "      <arg type='a{sv}' name='platform_data' direction='in'/>"
109   "    </method>"
110   "    <method name='SetState'>"
111   "      <arg type='s' name='action_name' direction='in'/>"
112   "      <arg type='v' name='value' direction='in'/>"
113   "      <arg type='a{sv}' name='platform_data' direction='in'/>"
114   "    </method>"
115   "    <signal name='Changed'>"
116   "      <arg type='as' name='removals'/>"
117   "      <arg type='a{sb}' name='enable_changes'/>"
118   "      <arg type='a{sv}' name='state_changes'/>"
119   "      <arg type='a{s(bgav)}' name='additions'/>"
120   "    </signal>"
121   "  </interface>"
122   "</node>";
123
124 static GDBusInterfaceInfo *org_gtk_Actions;
125
126 typedef struct
127 {
128   GActionGroup    *action_group;
129   GDBusConnection *connection;
130   GMainContext    *context;
131   gchar           *object_path;
132   GHashTable      *pending_changes;
133   GSource         *pending_source;
134 } GActionGroupExporter;
135
136 #define ACTION_ADDED_EVENT             (1u<<0)
137 #define ACTION_REMOVED_EVENT           (1u<<1)
138 #define ACTION_STATE_CHANGED_EVENT     (1u<<2)
139 #define ACTION_ENABLED_CHANGED_EVENT   (1u<<3)
140
141 static gboolean
142 g_action_group_exporter_dispatch_events (gpointer user_data)
143 {
144   GActionGroupExporter *exporter = user_data;
145   GVariantBuilder removes;
146   GVariantBuilder enabled_changes;
147   GVariantBuilder state_changes;
148   GVariantBuilder adds;
149   GHashTableIter iter;
150   gpointer value;
151   gpointer key;
152
153   g_variant_builder_init (&removes, G_VARIANT_TYPE_STRING_ARRAY);
154   g_variant_builder_init (&enabled_changes, G_VARIANT_TYPE ("a{sb}"));
155   g_variant_builder_init (&state_changes, G_VARIANT_TYPE ("a{sv}"));
156   g_variant_builder_init (&adds, G_VARIANT_TYPE ("a{s(bgav)}"));
157
158   g_hash_table_iter_init (&iter, exporter->pending_changes);
159   while (g_hash_table_iter_next (&iter, &key, &value))
160     {
161       guint events = GPOINTER_TO_INT (value);
162       const gchar *name = key;
163
164       /* Adds and removes are incompatible with enabled or state
165        * changes, but we must report at least one event.
166        */
167       g_assert (((events & (ACTION_ENABLED_CHANGED_EVENT | ACTION_STATE_CHANGED_EVENT)) == 0) !=
168                 ((events & (ACTION_REMOVED_EVENT | ACTION_ADDED_EVENT)) == 0));
169
170       if (events & ACTION_REMOVED_EVENT)
171         g_variant_builder_add (&removes, "s", name);
172
173       if (events & ACTION_ENABLED_CHANGED_EVENT)
174         {
175           gboolean enabled;
176
177           enabled = g_action_group_get_action_enabled (exporter->action_group, name);
178           g_variant_builder_add (&enabled_changes, "{sb}", name, enabled);
179         }
180
181       if (events & ACTION_STATE_CHANGED_EVENT)
182         {
183           GVariant *state;
184
185           state = g_action_group_get_action_state (exporter->action_group, name);
186           g_variant_builder_add (&state_changes, "{sv}", name, state);
187           g_variant_unref (state);
188         }
189
190       if (events & ACTION_ADDED_EVENT)
191         {
192           GVariant *description;
193
194           description = g_action_group_describe_action (exporter->action_group, name);
195           g_variant_builder_add (&adds, "{s@(bgav)}", name, description);
196         }
197     }
198
199   g_hash_table_remove_all (exporter->pending_changes);
200
201   g_dbus_connection_emit_signal (exporter->connection, NULL, exporter->object_path,
202                                  "org.gtk.Actions", "Changed",
203                                  g_variant_new ("(asa{sb}a{sv}a{s(bgav)})",
204                                                 &removes, &enabled_changes,
205                                                 &state_changes, &adds),
206                                  NULL);
207
208   exporter->pending_source = NULL;
209
210   return FALSE;
211 }
212
213 static guint
214 g_action_group_exporter_get_events (GActionGroupExporter *exporter,
215                                     const gchar          *name)
216 {
217   return (gsize) g_hash_table_lookup (exporter->pending_changes, name);
218 }
219
220 static void
221 g_action_group_exporter_set_events (GActionGroupExporter *exporter,
222                                     const gchar          *name,
223                                     guint                 events)
224 {
225   gboolean have_events;
226   gboolean is_queued;
227
228   if (events != 0)
229     g_hash_table_insert (exporter->pending_changes, g_strdup (name), GINT_TO_POINTER (events));
230   else
231     g_hash_table_remove (exporter->pending_changes, name);
232
233   have_events = g_hash_table_size (exporter->pending_changes) > 0;
234   is_queued = exporter->pending_source != NULL;
235
236   if (have_events && !is_queued)
237     {
238       GSource *source;
239
240       source = g_idle_source_new ();
241       exporter->pending_source = source;
242       g_source_set_callback (source, g_action_group_exporter_dispatch_events, exporter, NULL);
243       g_source_attach (source, exporter->context);
244       g_source_unref (source);
245     }
246
247   if (!have_events && is_queued)
248     {
249       g_source_destroy (exporter->pending_source);
250       exporter->pending_source = NULL;
251     }
252 }
253
254 static void
255 g_action_group_exporter_action_added (GActionGroup *action_group,
256                                       const gchar  *action_name,
257                                       gpointer      user_data)
258 {
259   GActionGroupExporter *exporter = user_data;
260   guint event_mask;
261
262   event_mask = g_action_group_exporter_get_events (exporter, action_name);
263
264   /* The action is new, so we should not have any pending
265    * enabled-changed or state-changed signals for it.
266    */
267   g_assert (~event_mask & (ACTION_STATE_CHANGED_EVENT |
268                            ACTION_ENABLED_CHANGED_EVENT));
269
270   event_mask |= ACTION_ADDED_EVENT;
271
272   g_action_group_exporter_set_events (exporter, action_name, event_mask);
273 }
274
275 static void
276 g_action_group_exporter_action_removed (GActionGroup *action_group,
277                                         const gchar  *action_name,
278                                         gpointer      user_data)
279 {
280   GActionGroupExporter *exporter = user_data;
281   guint event_mask;
282
283   event_mask = g_action_group_exporter_get_events (exporter, action_name);
284
285   /* If the add event for this is still queued then just cancel it since
286    * it's gone now.
287    *
288    * If the event was freshly added, there should not have been any
289    * enabled or state changed events.
290    */
291   if (event_mask & ACTION_ADDED_EVENT)
292     {
293       g_assert (~event_mask & ~(ACTION_STATE_CHANGED_EVENT | ACTION_ENABLED_CHANGED_EVENT));
294       event_mask &= ~ACTION_ADDED_EVENT;
295     }
296
297   /* Otherwise, queue a remove event.  Drop any state or enabled changes
298    * that were queued before the remove. */
299   else
300     {
301       event_mask |= ACTION_REMOVED_EVENT;
302       event_mask &= ~(ACTION_STATE_CHANGED_EVENT | ACTION_ENABLED_CHANGED_EVENT);
303     }
304
305   g_action_group_exporter_set_events (exporter, action_name, event_mask);
306 }
307
308 static void
309 g_action_group_exporter_action_state_changed (GActionGroup *action_group,
310                                               const gchar  *action_name,
311                                               GVariant     *value,
312                                               gpointer      user_data)
313 {
314   GActionGroupExporter *exporter = user_data;
315   guint event_mask;
316
317   event_mask = g_action_group_exporter_get_events (exporter, action_name);
318
319   /* If it was removed, it must have been added back.  Otherwise, why
320    * are we hearing about changes?
321    */
322   g_assert (~event_mask & ACTION_REMOVED_EVENT ||
323             event_mask & ACTION_ADDED_EVENT);
324
325   /* If it is freshly added, don't also bother with the state change
326    * signal since the updated state will be sent as part of the pending
327    * add message.
328    */
329   if (~event_mask & ACTION_ADDED_EVENT)
330     event_mask |= ACTION_STATE_CHANGED_EVENT;
331
332   g_action_group_exporter_set_events (exporter, action_name, event_mask);
333 }
334
335 static void
336 g_action_group_exporter_action_enabled_changed (GActionGroup *action_group,
337                                                 const gchar  *action_name,
338                                                 gboolean      enabled,
339                                                 gpointer      user_data)
340 {
341   GActionGroupExporter *exporter = user_data;
342   guint event_mask;
343
344   event_mask = g_action_group_exporter_get_events (exporter, action_name);
345
346   /* Reasoning as above. */
347   g_assert (~event_mask & ACTION_REMOVED_EVENT ||
348             event_mask & ACTION_ADDED_EVENT);
349
350   if (~event_mask & ACTION_ADDED_EVENT)
351     event_mask |= ACTION_ENABLED_CHANGED_EVENT;
352
353   g_action_group_exporter_set_events (exporter, action_name, event_mask);
354 }
355
356 static void
357 org_gtk_Actions_method_call (GDBusConnection       *connection,
358                              const gchar           *sender,
359                              const gchar           *object_path,
360                              const gchar           *interface_name,
361                              const gchar           *method_name,
362                              GVariant              *parameters,
363                              GDBusMethodInvocation *invocation,
364                              gpointer               user_data)
365 {
366   GActionGroupExporter *exporter = user_data;
367   GVariant *result = NULL;
368
369   if (g_str_equal (method_name, "List"))
370     {
371       gchar **list;
372
373       list = g_action_group_list_actions (exporter->action_group);
374       result = g_variant_new ("(^as)", list);
375       g_strfreev (list);
376     }
377
378   else if (g_str_equal (method_name, "Describe"))
379     {
380       const gchar *name;
381       GVariant *desc;
382
383       g_variant_get (parameters, "(&s)", &name);
384
385       if (!g_action_group_has_action (exporter->action_group, name))
386         {
387           g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
388                                                  "The named action ('%s') does not exist.", name);
389           return;
390         }
391
392       desc = g_action_group_describe_action (exporter->action_group, name);
393       result = g_variant_new ("(@(bgav))", desc);
394     }
395
396   else if (g_str_equal (method_name, "DescribeAll"))
397     {
398       GVariantBuilder builder;
399       gchar **list;
400       gint i;
401
402       list = g_action_group_list_actions (exporter->action_group);
403       g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{s(bgav)}"));
404       for (i = 0; list[i]; i++)
405         {
406           const gchar *name = list[i];
407           GVariant *description;
408
409           description = g_action_group_describe_action (exporter->action_group, name);
410           g_variant_builder_add (&builder, "{s@(bgav)}", name, description);
411         }
412       result = g_variant_new ("(a{s(bgav)})", &builder);
413       g_strfreev (list);
414     }
415
416   else if (g_str_equal (method_name, "Activate"))
417     {
418       GVariant *parameter = NULL;
419       GVariant *platform_data;
420       GVariantIter *iter;
421       const gchar *name;
422
423       g_variant_get (parameters, "(&sav@a{sv})", &name, &iter, &platform_data);
424       g_variant_iter_next (iter, "v", &parameter);
425       g_variant_iter_free (iter);
426
427       if (G_IS_REMOTE_ACTION_GROUP (exporter->action_group))
428         g_remote_action_group_activate_action_full (G_REMOTE_ACTION_GROUP (exporter->action_group),
429                                                     name, parameter, platform_data);
430       else
431         g_action_group_activate_action (exporter->action_group, name, parameter);
432
433       if (parameter)
434         g_variant_unref (parameter);
435
436       g_variant_unref (platform_data);
437     }
438
439   else if (g_str_equal (method_name, "SetState"))
440     {
441       GVariant *platform_data;
442       const gchar *name;
443       GVariant *state;
444
445       g_variant_get (parameters, "(&sv@a{sv})", &name, &state, &platform_data);
446
447       if (G_IS_REMOTE_ACTION_GROUP (exporter->action_group))
448         g_remote_action_group_change_action_state_full (G_REMOTE_ACTION_GROUP (exporter->action_group),
449                                                         name, state, platform_data);
450       else
451         g_action_group_change_action_state (exporter->action_group, name, state);
452
453       g_variant_unref (platform_data);
454       g_variant_unref (state);
455     }
456
457   else
458     g_assert_not_reached ();
459
460   g_dbus_method_invocation_return_value (invocation, result);
461 }
462
463 static void
464 g_action_group_exporter_free (gpointer user_data)
465 {
466   GActionGroupExporter *exporter = user_data;
467
468   g_signal_handlers_disconnect_by_func (exporter->action_group,
469                                         g_action_group_exporter_action_added, exporter);
470   g_signal_handlers_disconnect_by_func (exporter->action_group,
471                                         g_action_group_exporter_action_enabled_changed, exporter);
472   g_signal_handlers_disconnect_by_func (exporter->action_group,
473                                         g_action_group_exporter_action_state_changed, exporter);
474   g_signal_handlers_disconnect_by_func (exporter->action_group,
475                                         g_action_group_exporter_action_removed, exporter);
476
477   g_hash_table_unref (exporter->pending_changes);
478   if (exporter->pending_source)
479     g_source_destroy (exporter->pending_source);
480
481   g_main_context_unref (exporter->context);
482   g_object_unref (exporter->connection);
483   g_object_unref (exporter->action_group);
484   g_free (exporter->object_path);
485
486   g_slice_free (GActionGroupExporter, exporter);
487 }
488
489 /**
490  * g_dbus_connection_export_action_group:
491  * @connection: a #GDBusConnection
492  * @object_path: a D-Bus object path
493  * @action_group: a #GActionGroup
494  * @error: a pointer to a %NULL #GError, or %NULL
495  *
496  * Exports @action_group on @connection at @object_path.
497  *
498  * The implemented D-Bus API should be considered private.  It is
499  * subject to change in the future.
500  *
501  * A given object path can only have one action group exported on it.
502  * If this constraint is violated, the export will fail and 0 will be
503  * returned (with @error set accordingly).
504  *
505  * You can unexport the action group using
506  * g_dbus_connection_unexport_action_group() with the return value of
507  * this function.
508  *
509  * The thread default main context is taken at the time of this call.
510  * All incoming action activations and state change requests are
511  * reported from this context.  Any changes on the action group that
512  * cause it to emit signals must also come from this same context.
513  * Since incoming action activations and state change requests are
514  * rather likely to cause changes on the action group, this effectively
515  * limits a given action group to being exported from only one main
516  * context.
517  *
518  * Returns: the ID of the export (never zero), or 0 in case of failure
519  *
520  * Since: 2.32
521  **/
522 guint
523 g_dbus_connection_export_action_group (GDBusConnection  *connection,
524                                        const gchar      *object_path,
525                                        GActionGroup     *action_group,
526                                        GError          **error)
527 {
528   const GDBusInterfaceVTable vtable = {
529     org_gtk_Actions_method_call
530   };
531   GActionGroupExporter *exporter;
532   guint id;
533
534   if G_UNLIKELY (org_gtk_Actions == NULL)
535     {
536       GError *error = NULL;
537       GDBusNodeInfo *info;
538
539       info = g_dbus_node_info_new_for_xml (org_gtk_Actions_xml, &error);
540       if G_UNLIKELY (info == NULL)
541         g_error ("%s", error->message);
542       org_gtk_Actions = g_dbus_node_info_lookup_interface (info, "org.gtk.Actions");
543       g_assert (org_gtk_Actions != NULL);
544       g_dbus_interface_info_ref (org_gtk_Actions);
545       g_dbus_node_info_unref (info);
546     }
547
548   exporter = g_slice_new (GActionGroupExporter);
549   id = g_dbus_connection_register_object (connection, object_path, org_gtk_Actions, &vtable,
550                                           exporter, g_action_group_exporter_free, error);
551
552   if (id == 0)
553     {
554       g_slice_free (GActionGroupExporter, exporter);
555       return 0;
556     }
557
558   exporter->context = g_main_context_ref_thread_default ();
559   exporter->pending_changes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
560   exporter->pending_source = NULL;
561   exporter->action_group = g_object_ref (action_group);
562   exporter->connection = g_object_ref (connection);
563   exporter->object_path = g_strdup (object_path);
564
565   g_signal_connect (action_group, "action-added",
566                     G_CALLBACK (g_action_group_exporter_action_added), exporter);
567   g_signal_connect (action_group, "action-removed",
568                     G_CALLBACK (g_action_group_exporter_action_removed), exporter);
569   g_signal_connect (action_group, "action-state-changed",
570                     G_CALLBACK (g_action_group_exporter_action_state_changed), exporter);
571   g_signal_connect (action_group, "action-enabled-changed",
572                     G_CALLBACK (g_action_group_exporter_action_enabled_changed), exporter);
573
574   return id;
575 }
576
577 /**
578  * g_dbus_connection_unexport_action_group:
579  * @connection: a #GDBusConnection
580  * @export_id: the ID from g_dbus_connection_export_action_group()
581  *
582  * Reverses the effect of a previous call to
583  * g_dbus_connection_export_action_group().
584  *
585  * It is an error to call this function with an ID that wasn't returned
586  * from g_dbus_connection_export_action_group() or to call it with the
587  * same ID more than once.
588  *
589  * Since: 2.32
590  **/
591 void
592 g_dbus_connection_unexport_action_group (GDBusConnection *connection,
593                                          guint            export_id)
594 {
595   g_dbus_connection_unregister_object (connection, export_id);
596 }