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