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