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