Action group exporter: clean up the API
[platform/upstream/glib.git] / gio / gapplicationimpl-dbus.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General
15  * Public License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Authors: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "gapplicationimpl.h"
23
24 #include "gactiongroup.h"
25 #include "gactiongroupexporter.h"
26 #include "gdbusactiongroup.h"
27 #include "gapplication.h"
28 #include "gfile.h"
29 #include "gdbusconnection.h"
30 #include "gdbusintrospection.h"
31 #include "gdbuserror.h"
32 #include "gmenuexporter.h"
33
34 #include <string.h>
35 #include <stdio.h>
36
37 #include "gapplicationcommandline.h"
38 #include "gdbusmethodinvocation.h"
39
40 /* DBus Interface definition {{{1 */
41 static const gchar org_gtk_Application_xml[] =
42   "<node>"
43   "  <interface name='org.gtk.Application'>"
44   "    <method name='Activate'>"
45   "      <arg type='a{sv}' name='platform-data' direction='in'/>"
46   "    </method>"
47   "    <method name='Open'>"
48   "      <arg type='as' name='uris' direction='in'/>"
49   "      <arg type='s' name='hint' direction='in'/>"
50   "      <arg type='a{sv}' name='platform-data' direction='in'/>"
51   "    </method>"
52   "    <method name='CommandLine'>"
53   "      <arg type='o' name='path' direction='in'/>"
54   "      <arg type='aay' name='arguments' direction='in'/>"
55   "      <arg type='a{sv}' name='platform-data' direction='in'/>"
56   "      <arg type='i' name='exit-status' direction='out'/>"
57   "    </method>"
58   "  </interface>"
59   "</node>";
60
61 static GDBusInterfaceInfo *org_gtk_Application;
62
63 static const gchar org_gtk_private_CommandLine_xml[] =
64   "<node>"
65   "  <interface name='org.gtk.private.CommandLine'>"
66   "    <method name='Print'>"
67   "      <arg type='s' name='message' direction='in'/>"
68   "    </method>"
69   "    <method name='PrintError'>"
70   "      <arg type='s' name='message' direction='in'/>"
71   "    </method>"
72   "  </interface>"
73   "</node>";
74
75 static GDBusInterfaceInfo *org_gtk_private_CommandLine;
76
77 /* GApplication implementation {{{1 */
78 struct _GApplicationImpl
79 {
80   GDBusConnection *session_bus;
81   const gchar     *bus_name;
82   gchar           *object_path;
83   guint            object_id;
84   guint            actions_id;
85   gboolean         primary;
86   gpointer         app;
87 };
88
89
90 static GApplicationCommandLine *
91 g_dbus_command_line_new (GDBusMethodInvocation *invocation);
92
93
94 static void
95 g_application_impl_method_call (GDBusConnection       *connection,
96                                 const gchar           *sender,
97                                 const gchar           *object_path,
98                                 const gchar           *interface_name,
99                                 const gchar           *method_name,
100                                 GVariant              *parameters,
101                                 GDBusMethodInvocation *invocation,
102                                 gpointer               user_data)
103 {
104   GApplicationImpl *impl = user_data;
105   GApplicationClass *class;
106
107   class = G_APPLICATION_GET_CLASS (impl->app);
108
109   if (strcmp (method_name, "Activate") == 0)
110     {
111       GVariant *platform_data;
112
113       g_variant_get (parameters, "(@a{sv})", &platform_data);
114       class->before_emit (impl->app, platform_data);
115       g_signal_emit_by_name (impl->app, "activate");
116       class->after_emit (impl->app, platform_data);
117       g_variant_unref (platform_data);
118
119       g_dbus_method_invocation_return_value (invocation, NULL);
120     }
121
122   else if (strcmp (method_name, "Open") == 0)
123     {
124       GVariant *platform_data;
125       const gchar *hint;
126       GVariant *array;
127       GFile **files;
128       gint n, i;
129
130       g_variant_get (parameters, "(@ass@a{sv})",
131                      &array, &hint, &platform_data);
132
133       n = g_variant_n_children (array);
134       files = g_new (GFile *, n + 1);
135
136       for (i = 0; i < n; i++)
137         {
138           const gchar *uri;
139
140           g_variant_get_child (array, i, "&s", &uri);
141           files[i] = g_file_new_for_uri (uri);
142         }
143       g_variant_unref (array);
144       files[n] = NULL;
145
146       class->before_emit (impl->app, platform_data);
147       g_signal_emit_by_name (impl->app, "open", files, n, hint);
148       class->after_emit (impl->app, platform_data);
149
150       g_variant_unref (platform_data);
151
152       for (i = 0; i < n; i++)
153         g_object_unref (files[i]);
154       g_free (files);
155
156       g_dbus_method_invocation_return_value (invocation, NULL);
157     }
158
159   else if (strcmp (method_name, "CommandLine") == 0)
160     {
161       GApplicationCommandLine *cmdline;
162       GVariant *platform_data;
163       int status;
164
165       cmdline = g_dbus_command_line_new (invocation);
166       platform_data = g_variant_get_child_value (parameters, 2);
167       class->before_emit (impl->app, platform_data);
168       g_signal_emit_by_name (impl->app, "command-line", cmdline, &status);
169       g_application_command_line_set_exit_status (cmdline, status);
170       class->after_emit (impl->app, platform_data);
171       g_variant_unref (platform_data);
172       g_object_unref (cmdline);
173     }
174   else
175     g_assert_not_reached ();
176 }
177
178 static gchar *
179 application_path_from_appid (const gchar *appid)
180 {
181   gchar *appid_path, *iter;
182
183   appid_path = g_strconcat ("/", appid, NULL);
184   for (iter = appid_path; *iter; iter++)
185     {
186       if (*iter == '.')
187         *iter = '/';
188
189       if (*iter == '-')
190         *iter = '_';
191     }
192
193   return appid_path;
194 }
195
196 /* Attempt to become the primary instance.
197  *
198  * Returns %TRUE if everything went OK, regardless of if we became the
199  * primary instance or not.  %FALSE is reserved for when something went
200  * seriously wrong (and @error will be set too, in that case).
201  *
202  * After a %TRUE return, impl->primary will be TRUE if we were
203  * successful.
204  */
205 static gboolean
206 g_application_impl_attempt_primary (GApplicationImpl  *impl,
207                                     GCancellable      *cancellable,
208                                     GError           **error)
209 {
210   const static GDBusInterfaceVTable vtable = {
211     g_application_impl_method_call,
212   };
213   GVariant *reply;
214   guint32 rval;
215
216   if (org_gtk_Application == NULL)
217     {
218       GError *error = NULL;
219       GDBusNodeInfo *info;
220
221       info = g_dbus_node_info_new_for_xml (org_gtk_Application_xml, &error);
222       if G_UNLIKELY (info == NULL)
223         g_error ("%s", error->message);
224       org_gtk_Application = g_dbus_node_info_lookup_interface (info, "org.gtk.Application");
225       g_assert (org_gtk_Application != NULL);
226       g_dbus_interface_info_ref (org_gtk_Application);
227       g_dbus_node_info_unref (info);
228     }
229
230   /* We could possibly have been D-Bus activated as a result of incoming
231    * requests on either the application or actiongroup interfaces.
232    * Because of how GDBus dispatches messages, we need to ensure that
233    * both of those things are registered before we attempt to request
234    * our name.
235    *
236    * The action group need not be populated yet, as long as it happens
237    * before we return to the mainloop.  The reason for that is because
238    * GDBus does the check to make sure the object exists from the worker
239    * thread but doesn't actually dispatch the action invocation until we
240    * hit the mainloop in this thread.  There is also no danger of
241    * receiving 'activate' or 'open' signals until after 'startup' runs,
242    * for the same reason.
243    */
244   impl->object_id = g_dbus_connection_register_object (impl->session_bus, impl->object_path,
245                                                        org_gtk_Application, &vtable, impl, NULL, error);
246
247   if (impl->object_id == 0)
248     return FALSE;
249
250   impl->actions_id = g_dbus_connection_export_action_group (impl->session_bus, impl->object_path, impl->app, error);
251
252   if (impl->actions_id == 0)
253     return FALSE;
254
255   /* DBUS_NAME_FLAG_DO_NOT_QUEUE: 0x4 */
256   reply = g_dbus_connection_call_sync (impl->session_bus, "org.freedesktop.DBus", "/org/freedesktop/DBus",
257                                        "org.freedesktop.DBus", "RequestName",
258                                        g_variant_new ("(su)", impl->bus_name, 0x4), G_VARIANT_TYPE ("(u)"),
259                                        0, -1, cancellable, error);
260
261   if (reply == NULL)
262     return FALSE;
263
264   g_variant_get (reply, "(u)", &rval);
265   g_variant_unref (reply);
266
267   /* DBUS_REQUEST_NAME_REPLY_EXISTS: 3 */
268   impl->primary = (rval != 3);
269
270   return TRUE;
271 }
272
273 /* Stop doing the things that the primary instance does.
274  *
275  * This should be called if attempting to become the primary instance
276  * failed (in order to clean up any partial success) and should also
277  * be called when freeing the GApplication.
278  *
279  * It is safe to call this multiple times.
280  */
281 static void
282 g_application_impl_stop_primary (GApplicationImpl *impl)
283 {
284   if (impl->object_id)
285     {
286       g_dbus_connection_unregister_object (impl->session_bus, impl->object_id);
287       impl->object_id = 0;
288     }
289
290   if (impl->actions_id)
291     {
292       g_dbus_connection_unexport_action_group (impl->session_bus, impl->actions_id);
293       impl->actions_id = 0;
294     }
295
296   if (impl->primary)
297     {
298       g_dbus_connection_call (impl->session_bus, "org.freedesktop.DBus",
299                               "/org/freedesktop/DBus", "org.freedesktop.DBus",
300                               "ReleaseName", g_variant_new ("(s)", impl->bus_name),
301                               NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
302       impl->primary = FALSE;
303     }
304 }
305
306 void
307 g_application_impl_destroy (GApplicationImpl *impl)
308 {
309   g_application_impl_stop_primary (impl);
310
311   if (impl->session_bus)
312     g_object_unref (impl->session_bus);
313
314   g_free (impl->object_path);
315
316   g_slice_free (GApplicationImpl, impl);
317 }
318
319 GApplicationImpl *
320 g_application_impl_register (GApplication       *application,
321                              const gchar        *appid,
322                              GApplicationFlags   flags,
323                              GActionGroup      **remote_actions,
324                              GCancellable       *cancellable,
325                              GError            **error)
326 {
327   GDBusActionGroup *actions;
328   GApplicationImpl *impl;
329
330   impl = g_slice_new0 (GApplicationImpl);
331
332   impl->app = application;
333   impl->bus_name = appid;
334
335   impl->session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, cancellable, NULL);
336
337   if (impl->session_bus == NULL)
338     {
339       /* If we can't connect to the session bus, proceed as a normal
340        * non-unique application.
341        */
342       *remote_actions = NULL;
343       return impl;
344     }
345
346   impl->object_path = application_path_from_appid (appid);
347
348   /* Only try to be the primary instance if
349    * G_APPLICATION_IS_LAUNCHER was not specified.
350    */
351   if (~flags & G_APPLICATION_IS_LAUNCHER)
352     {
353       if (!g_application_impl_attempt_primary (impl, cancellable, error))
354         {
355           g_application_impl_destroy (impl);
356           return NULL;
357         }
358
359       if (impl->primary)
360         return impl;
361
362       /* We didn't make it.  Drop our service-side stuff. */
363       g_application_impl_stop_primary (impl);
364
365       if (flags & G_APPLICATION_IS_SERVICE)
366         {
367           g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
368                        "Unable to acquire bus name `%s'", appid);
369           g_application_impl_destroy (impl);
370
371           return NULL;
372         }
373     }
374
375   /* We are non-primary.  Try to get the primary's list of actions.
376    * This also serves as a mechanism to ensure that the primary exists
377    * (ie: DBus service files installed correctly, etc).
378    */
379   actions = g_dbus_action_group_new_sync (impl->session_bus, impl->bus_name, impl->object_path,
380                                           G_DBUS_ACTION_GROUP_FLAGS_NONE, cancellable, error);
381
382   if (actions == NULL)
383     {
384       /* The primary appears not to exist.  Fail the registration. */
385       g_application_impl_destroy (impl);
386
387       return NULL;
388     }
389
390   *remote_actions = G_ACTION_GROUP (actions);
391
392   return impl;
393 }
394
395 void
396 g_application_impl_activate (GApplicationImpl *impl,
397                              GVariant         *platform_data)
398 {
399   g_dbus_connection_call (impl->session_bus,
400                           impl->bus_name,
401                           impl->object_path,
402                           "org.gtk.Application",
403                           "Activate",
404                           g_variant_new ("(@a{sv})", platform_data),
405                           NULL, 0, -1, NULL, NULL, NULL);
406 }
407
408 void
409 g_application_impl_open (GApplicationImpl  *impl,
410                          GFile            **files,
411                          gint               n_files,
412                          const gchar       *hint,
413                          GVariant          *platform_data)
414 {
415   GVariantBuilder builder;
416   gint i;
417
418   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(assa{sv})"));
419   g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
420   for (i = 0; i < n_files; i++)
421     {
422       gchar *uri = g_file_get_uri (files[i]);
423       g_variant_builder_add (&builder, "s", uri);
424       g_free (uri);
425     }
426   g_variant_builder_close (&builder);
427   g_variant_builder_add (&builder, "s", hint);
428   g_variant_builder_add_value (&builder, platform_data);
429
430   g_dbus_connection_call (impl->session_bus,
431                           impl->bus_name,
432                           impl->object_path,
433                           "org.gtk.Application",
434                           "Open",
435                           g_variant_builder_end (&builder),
436                           NULL, 0, -1, NULL, NULL, NULL);
437 }
438
439 static void
440 g_application_impl_cmdline_method_call (GDBusConnection       *connection,
441                                         const gchar           *sender,
442                                         const gchar           *object_path,
443                                         const gchar           *interface_name,
444                                         const gchar           *method_name,
445                                         GVariant              *parameters,
446                                         GDBusMethodInvocation *invocation,
447                                         gpointer               user_data)
448 {
449   const gchar *message;
450
451   g_variant_get_child (parameters, 0, "&s", &message);
452
453   if (strcmp (method_name, "Print") == 0)
454     g_print ("%s", message);
455   else if (strcmp (method_name, "PrintError") == 0)
456     g_printerr ("%s", message);
457   else
458     g_assert_not_reached ();
459
460   g_dbus_method_invocation_return_value (invocation, NULL);
461 }
462
463 typedef struct
464 {
465   GMainLoop *loop;
466   int status;
467 } CommandLineData;
468
469 static void
470 g_application_impl_cmdline_done (GObject      *source,
471                                  GAsyncResult *result,
472                                  gpointer      user_data)
473 {
474   CommandLineData *data = user_data;
475   GError *error = NULL;
476   GVariant *reply;
477
478   reply = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source),
479                                          result, &error);
480
481   if (reply != NULL)
482     {
483       g_variant_get (reply, "(i)", &data->status);
484       g_variant_unref (reply);
485     }
486
487   else
488     {
489       g_printerr ("%s\n", error->message);
490       g_error_free (error);
491       data->status = 1;
492     }
493
494   g_main_loop_quit (data->loop);
495 }
496
497 int
498 g_application_impl_command_line (GApplicationImpl  *impl,
499                                  gchar            **arguments,
500                                  GVariant          *platform_data)
501 {
502   const static GDBusInterfaceVTable vtable = {
503     g_application_impl_cmdline_method_call
504   };
505   const gchar *object_path = "/org/gtk/Application/CommandLine";
506   GMainContext *context;
507   CommandLineData data;
508   guint object_id;
509
510   context = g_main_context_new ();
511   data.loop = g_main_loop_new (context, FALSE);
512   g_main_context_push_thread_default (context);
513
514   if (org_gtk_private_CommandLine == NULL)
515     {
516       GError *error = NULL;
517       GDBusNodeInfo *info;
518
519       info = g_dbus_node_info_new_for_xml (org_gtk_private_CommandLine_xml, &error);
520       if G_UNLIKELY (info == NULL)
521         g_error ("%s", error->message);
522       org_gtk_private_CommandLine = g_dbus_node_info_lookup_interface (info, "org.gtk.private.CommandLine");
523       g_assert (org_gtk_private_CommandLine != NULL);
524       g_dbus_interface_info_ref (org_gtk_private_CommandLine);
525       g_dbus_node_info_unref (info);
526     }
527
528   object_id = g_dbus_connection_register_object (impl->session_bus, object_path,
529                                                  org_gtk_private_CommandLine,
530                                                  &vtable, &data, NULL, NULL);
531   /* In theory we should try other paths... */
532   g_assert (object_id != 0);
533
534   g_dbus_connection_call (impl->session_bus,
535                           impl->bus_name,
536                           impl->object_path,
537                           "org.gtk.Application",
538                           "CommandLine",
539                           g_variant_new ("(o^aay@a{sv})", object_path,
540                                          arguments, platform_data),
541                           G_VARIANT_TYPE ("(i)"), 0, G_MAXINT, NULL,
542                           g_application_impl_cmdline_done, &data);
543
544   g_main_loop_run (data.loop);
545
546   g_main_context_pop_thread_default (context);
547   g_main_context_unref (context);
548   g_main_loop_unref (data.loop);
549
550   return data.status;
551 }
552
553 void
554 g_application_impl_flush (GApplicationImpl *impl)
555 {
556   if (impl->session_bus)
557     g_dbus_connection_flush_sync (impl->session_bus, NULL, NULL);
558 }
559
560
561 /* GDBusCommandLine implementation {{{1 */
562
563 typedef GApplicationCommandLineClass GDBusCommandLineClass;
564 static GType g_dbus_command_line_get_type (void);
565 typedef struct
566 {
567   GApplicationCommandLine  parent_instance;
568   GDBusMethodInvocation   *invocation;
569
570   GDBusConnection *connection;
571   const gchar     *bus_name;
572   const gchar     *object_path;
573 } GDBusCommandLine;
574
575
576 G_DEFINE_TYPE (GDBusCommandLine,
577                g_dbus_command_line,
578                G_TYPE_APPLICATION_COMMAND_LINE)
579
580 static void
581 g_dbus_command_line_print_literal (GApplicationCommandLine *cmdline,
582                                    const gchar             *message)
583 {
584   GDBusCommandLine *gdbcl = (GDBusCommandLine *) cmdline;
585
586   g_dbus_connection_call (gdbcl->connection,
587                           gdbcl->bus_name,
588                           gdbcl->object_path,
589                           "org.gtk.private.CommandLine", "Print",
590                           g_variant_new ("(s)", message),
591                           NULL, 0, -1, NULL, NULL, NULL);
592 }
593
594 static void
595 g_dbus_command_line_printerr_literal (GApplicationCommandLine *cmdline,
596                                       const gchar             *message)
597 {
598   GDBusCommandLine *gdbcl = (GDBusCommandLine *) cmdline;
599
600   g_dbus_connection_call (gdbcl->connection,
601                           gdbcl->bus_name,
602                           gdbcl->object_path,
603                           "org.gtk.private.CommandLine", "PrintError",
604                           g_variant_new ("(s)", message),
605                           NULL, 0, -1, NULL, NULL, NULL);
606 }
607
608 static void
609 g_dbus_command_line_finalize (GObject *object)
610 {
611   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
612   GDBusCommandLine *gdbcl = (GDBusCommandLine *) object;
613   gint status;
614
615   status = g_application_command_line_get_exit_status (cmdline);
616
617   g_dbus_method_invocation_return_value (gdbcl->invocation,
618                                          g_variant_new ("(i)", status));
619   g_object_unref (gdbcl->invocation);
620
621   G_OBJECT_CLASS (g_dbus_command_line_parent_class)
622     ->finalize (object);
623 }
624
625 static void
626 g_dbus_command_line_init (GDBusCommandLine *gdbcl)
627 {
628 }
629
630 static void
631 g_dbus_command_line_class_init (GApplicationCommandLineClass *class)
632 {
633   GObjectClass *object_class = G_OBJECT_CLASS (class);
634
635   object_class->finalize = g_dbus_command_line_finalize;
636   class->printerr_literal = g_dbus_command_line_printerr_literal;
637   class->print_literal = g_dbus_command_line_print_literal;
638 }
639
640 static GApplicationCommandLine *
641 g_dbus_command_line_new (GDBusMethodInvocation *invocation)
642 {
643   GDBusCommandLine *gdbcl;
644   GVariant *args;
645
646   args = g_dbus_method_invocation_get_parameters (invocation);
647
648   gdbcl = g_object_new (g_dbus_command_line_get_type (),
649                         "arguments", g_variant_get_child_value (args, 1),
650                         "platform-data", g_variant_get_child_value (args, 2),
651                         NULL);
652   gdbcl->connection = g_dbus_method_invocation_get_connection (invocation);
653   gdbcl->bus_name = g_dbus_method_invocation_get_sender (invocation);
654   g_variant_get_child (args, 0, "&o", &gdbcl->object_path);
655   gdbcl->invocation = g_object_ref (invocation);
656
657   return G_APPLICATION_COMMAND_LINE (gdbcl);
658 }
659
660 /* Epilogue {{{1 */
661
662 /* vim:set foldmethod=marker: */