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.1 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, see <http://www.gnu.org/licenses/>.
16  *
17  * Authors: Ryan Lortie <desrt@desrt.ca>
18  */
19 
20 #include "config.h"
21 
22 #include "gapplicationimpl.h"
23 
24 #include "gactiongroup.h"
25 #include "gactiongroupexporter.h"
26 #include "gremoteactiongroup.h"
27 #include "gdbusactiongroup-private.h"
28 #include "gapplication.h"
29 #include "gfile.h"
30 #include "gdbusconnection.h"
31 #include "gdbusintrospection.h"
32 #include "gdbuserror.h"
33 #include "glib/gstdio.h"
34 
35 #include <string.h>
36 #include <stdio.h>
37 
38 #include "gapplicationcommandline.h"
39 #include "gdbusmethodinvocation.h"
40 
41 #ifdef G_OS_UNIX
42 #include "gunixinputstream.h"
43 #include "gunixfdlist.h"
44 #endif
45 
46 /* D-Bus Interface definition {{{1 */
47 
48 /* For documentation of these interfaces, see
49  * https://wiki.gnome.org/Projects/GLib/GApplication/DBusAPI
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     "<property name='Busy' type='b' access='read'/>"
69     "</interface>"
70   "</node>";
71 
72 static GDBusInterfaceInfo *org_gtk_Application;
73 
74 static const gchar org_freedesktop_Application_xml[] =
75   "<node>"
76     "<interface name='org.freedesktop.Application'>"
77       "<method name='Activate'>"
78         "<arg type='a{sv}' name='platform-data' direction='in'/>"
79       "</method>"
80       "<method name='Open'>"
81         "<arg type='as' name='uris' direction='in'/>"
82         "<arg type='a{sv}' name='platform-data' direction='in'/>"
83       "</method>"
84       "<method name='ActivateAction'>"
85         "<arg type='s' name='action-name' direction='in'/>"
86         "<arg type='av' name='parameter' direction='in'/>"
87         "<arg type='a{sv}' name='platform-data' direction='in'/>"
88       "</method>"
89     "</interface>"
90   "</node>";
91 
92 static GDBusInterfaceInfo *org_freedesktop_Application;
93 
94 static const gchar org_gtk_private_CommandLine_xml[] =
95   "<node>"
96     "<interface name='org.gtk.private.CommandLine'>"
97       "<method name='Print'>"
98         "<arg type='s' name='message' direction='in'/>"
99       "</method>"
100       "<method name='PrintError'>"
101         "<arg type='s' name='message' direction='in'/>"
102       "</method>"
103     "</interface>"
104   "</node>";
105 
106 static GDBusInterfaceInfo *org_gtk_private_CommandLine;
107 
108 /* GApplication implementation {{{1 */
109 struct _GApplicationImpl
110 {
111   GDBusConnection *session_bus;
112   GActionGroup    *exported_actions;
113   const gchar     *bus_name;
114   guint            name_lost_signal;
115 
116   gchar           *object_path;
117   guint            object_id;
118   guint            fdo_object_id;
119   guint            actions_id;
120 
121   gboolean         properties_live;
122   gboolean         primary;
123   gboolean         busy;
124   gboolean         registered;
125   GApplication    *app;
126 };
127 
128 
129 static GApplicationCommandLine *
130 g_dbus_command_line_new (GDBusMethodInvocation *invocation);
131 
132 static GVariant *
g_application_impl_get_property(GDBusConnection * connection,const gchar * sender,const gchar * object_path,const gchar * interface_name,const gchar * property_name,GError ** error,gpointer user_data)133 g_application_impl_get_property (GDBusConnection *connection,
134                                  const gchar  *sender,
135                                  const gchar  *object_path,
136                                  const gchar  *interface_name,
137                                  const gchar  *property_name,
138                                  GError      **error,
139                                  gpointer      user_data)
140 {
141   GApplicationImpl *impl = user_data;
142 
143   if (strcmp (property_name, "Busy") == 0)
144     return g_variant_new_boolean (impl->busy);
145 
146   g_assert_not_reached ();
147 
148   return NULL;
149 }
150 
151 static void
send_property_change(GApplicationImpl * impl)152 send_property_change (GApplicationImpl *impl)
153 {
154   GVariantBuilder builder;
155 
156   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
157   g_variant_builder_add (&builder,
158                          "{sv}",
159                          "Busy", g_variant_new_boolean (impl->busy));
160 
161   g_dbus_connection_emit_signal (impl->session_bus,
162                                  NULL,
163                                  impl->object_path,
164                                  "org.freedesktop.DBus.Properties",
165                                  "PropertiesChanged",
166                                  g_variant_new ("(sa{sv}as)",
167                                                 "org.gtk.Application",
168                                                 &builder,
169                                                 NULL),
170                                  NULL);
171 }
172 
173 static void
g_application_impl_method_call(GDBusConnection * connection,const gchar * sender,const gchar * object_path,const gchar * interface_name,const gchar * method_name,GVariant * parameters,GDBusMethodInvocation * invocation,gpointer user_data)174 g_application_impl_method_call (GDBusConnection       *connection,
175                                 const gchar           *sender,
176                                 const gchar           *object_path,
177                                 const gchar           *interface_name,
178                                 const gchar           *method_name,
179                                 GVariant              *parameters,
180                                 GDBusMethodInvocation *invocation,
181                                 gpointer               user_data)
182 {
183   GApplicationImpl *impl = user_data;
184   GApplicationClass *class;
185 
186   class = G_APPLICATION_GET_CLASS (impl->app);
187 
188   if (strcmp (method_name, "Activate") == 0)
189     {
190       GVariant *platform_data;
191 
192       /* Completely the same for both freedesktop and gtk interfaces */
193 
194       g_variant_get (parameters, "(@a{sv})", &platform_data);
195 
196       class->before_emit (impl->app, platform_data);
197       g_signal_emit_by_name (impl->app, "activate");
198       class->after_emit (impl->app, platform_data);
199       g_variant_unref (platform_data);
200 
201       g_dbus_method_invocation_return_value (invocation, NULL);
202     }
203 
204   else if (strcmp (method_name, "Open") == 0)
205     {
206       GApplicationFlags flags;
207       GVariant *platform_data;
208       const gchar *hint;
209       GVariant *array;
210       GFile **files;
211       gint n, i;
212 
213       flags = g_application_get_flags (impl->app);
214       if ((flags & G_APPLICATION_HANDLES_OPEN) == 0)
215         {
216           g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED, "Application does not open files");
217           return;
218         }
219 
220       /* freedesktop interface has no hint parameter */
221       if (g_str_equal (interface_name, "org.freedesktop.Application"))
222         {
223           g_variant_get (parameters, "(@as@a{sv})", &array, &platform_data);
224           hint = "";
225         }
226       else
227         g_variant_get (parameters, "(@as&s@a{sv})", &array, &hint, &platform_data);
228 
229       n = g_variant_n_children (array);
230       files = g_new (GFile *, n + 1);
231 
232       for (i = 0; i < n; i++)
233         {
234           const gchar *uri;
235 
236           g_variant_get_child (array, i, "&s", &uri);
237           files[i] = g_file_new_for_uri (uri);
238         }
239       g_variant_unref (array);
240       files[n] = NULL;
241 
242       class->before_emit (impl->app, platform_data);
243       g_signal_emit_by_name (impl->app, "open", files, n, hint);
244       class->after_emit (impl->app, platform_data);
245 
246       g_variant_unref (platform_data);
247 
248       for (i = 0; i < n; i++)
249         g_object_unref (files[i]);
250       g_free (files);
251 
252       g_dbus_method_invocation_return_value (invocation, NULL);
253     }
254 
255   else if (strcmp (method_name, "CommandLine") == 0)
256     {
257       GApplicationFlags flags;
258       GApplicationCommandLine *cmdline;
259       GVariant *platform_data;
260       int status;
261 
262       flags = g_application_get_flags (impl->app);
263       if ((flags & G_APPLICATION_HANDLES_COMMAND_LINE) == 0)
264         {
265           g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
266                                                  "Application does not handle command line arguments");
267           return;
268         }
269 
270       /* Only on the GtkApplication interface */
271 
272       cmdline = g_dbus_command_line_new (invocation);
273       platform_data = g_variant_get_child_value (parameters, 2);
274       class->before_emit (impl->app, platform_data);
275       g_signal_emit_by_name (impl->app, "command-line", cmdline, &status);
276       g_application_command_line_set_exit_status (cmdline, status);
277       class->after_emit (impl->app, platform_data);
278       g_variant_unref (platform_data);
279       g_object_unref (cmdline);
280     }
281   else if (g_str_equal (method_name, "ActivateAction"))
282     {
283       GVariant *parameter = NULL;
284       GVariant *platform_data;
285       GVariantIter *iter;
286       const gchar *name;
287 
288       /* Only on the freedesktop interface */
289 
290       g_variant_get (parameters, "(&sav@a{sv})", &name, &iter, &platform_data);
291       g_variant_iter_next (iter, "v", &parameter);
292       g_variant_iter_free (iter);
293 
294       class->before_emit (impl->app, platform_data);
295       g_action_group_activate_action (impl->exported_actions, name, parameter);
296       class->after_emit (impl->app, platform_data);
297 
298       if (parameter)
299         g_variant_unref (parameter);
300 
301       g_variant_unref (platform_data);
302 
303       g_dbus_method_invocation_return_value (invocation, NULL);
304     }
305   else
306     g_assert_not_reached ();
307 }
308 
309 static gchar *
application_path_from_appid(const gchar * appid)310 application_path_from_appid (const gchar *appid)
311 {
312   gchar *appid_path, *iter;
313 
314   if (appid == NULL)
315     /* this is a private implementation detail */
316     return g_strdup ("/org/gtk/Application/anonymous");
317 
318   appid_path = g_strconcat ("/", appid, NULL);
319   for (iter = appid_path; *iter; iter++)
320     {
321       if (*iter == '.')
322         *iter = '/';
323 
324       if (*iter == '-')
325         *iter = '_';
326     }
327 
328   return appid_path;
329 }
330 
331 static void g_application_impl_stop_primary (GApplicationImpl *impl);
332 
333 static void
name_lost(GDBusConnection * bus,const char * sender_name,const char * object_path,const char * interface_name,const char * signal_name,GVariant * parameters,gpointer user_data)334 name_lost (GDBusConnection *bus,
335            const char      *sender_name,
336            const char      *object_path,
337            const char      *interface_name,
338            const char      *signal_name,
339            GVariant        *parameters,
340            gpointer         user_data)
341 {
342   GApplicationImpl *impl = user_data;
343   gboolean handled;
344 
345   impl->primary = FALSE;
346   g_application_impl_stop_primary (impl);
347   g_signal_emit_by_name (impl->app, "name-lost", &handled);
348 }
349 
350 /* Attempt to become the primary instance.
351  *
352  * Returns %TRUE if everything went OK, regardless of if we became the
353  * primary instance or not.  %FALSE is reserved for when something went
354  * seriously wrong (and @error will be set too, in that case).
355  *
356  * After a %TRUE return, impl->primary will be TRUE if we were
357  * successful.
358  */
359 static gboolean
g_application_impl_attempt_primary(GApplicationImpl * impl,GCancellable * cancellable,GError ** error)360 g_application_impl_attempt_primary (GApplicationImpl  *impl,
361                                     GCancellable      *cancellable,
362                                     GError           **error)
363 {
364   static const GDBusInterfaceVTable vtable = {
365     g_application_impl_method_call,
366     g_application_impl_get_property,
367     NULL, /* set_property */
368     { 0 }
369   };
370   GApplicationClass *app_class = G_APPLICATION_GET_CLASS (impl->app);
371   GBusNameOwnerFlags name_owner_flags;
372   GApplicationFlags app_flags;
373   GVariant *reply;
374   guint32 rval;
375   GError *local_error = NULL;
376 
377   if (org_gtk_Application == NULL)
378     {
379       GError *error = NULL;
380       GDBusNodeInfo *info;
381 
382       info = g_dbus_node_info_new_for_xml (org_gtk_Application_xml, &error);
383       if G_UNLIKELY (info == NULL)
384         g_error ("%s", error->message);
385       org_gtk_Application = g_dbus_node_info_lookup_interface (info, "org.gtk.Application");
386       g_assert (org_gtk_Application != NULL);
387       g_dbus_interface_info_ref (org_gtk_Application);
388       g_dbus_node_info_unref (info);
389 
390       info = g_dbus_node_info_new_for_xml (org_freedesktop_Application_xml, &error);
391       if G_UNLIKELY (info == NULL)
392         g_error ("%s", error->message);
393       org_freedesktop_Application = g_dbus_node_info_lookup_interface (info, "org.freedesktop.Application");
394       g_assert (org_freedesktop_Application != NULL);
395       g_dbus_interface_info_ref (org_freedesktop_Application);
396       g_dbus_node_info_unref (info);
397     }
398 
399   /* We could possibly have been D-Bus activated as a result of incoming
400    * requests on either the application or actiongroup interfaces.
401    * Because of how GDBus dispatches messages, we need to ensure that
402    * both of those things are registered before we attempt to request
403    * our name.
404    *
405    * The action group need not be populated yet, as long as it happens
406    * before we return to the mainloop.  The reason for that is because
407    * GDBus does the check to make sure the object exists from the worker
408    * thread but doesn't actually dispatch the action invocation until we
409    * hit the mainloop in this thread.  There is also no danger of
410    * receiving 'activate' or 'open' signals until after 'startup' runs,
411    * for the same reason.
412    */
413   impl->object_id = g_dbus_connection_register_object (impl->session_bus, impl->object_path,
414                                                        org_gtk_Application, &vtable, impl, NULL, error);
415 
416   if (impl->object_id == 0)
417     return FALSE;
418 
419   impl->fdo_object_id = g_dbus_connection_register_object (impl->session_bus, impl->object_path,
420                                                            org_freedesktop_Application, &vtable, impl, NULL, error);
421 
422   if (impl->fdo_object_id == 0)
423     return FALSE;
424 
425   impl->actions_id = g_dbus_connection_export_action_group (impl->session_bus, impl->object_path,
426                                                             impl->exported_actions, error);
427 
428   if (impl->actions_id == 0)
429     return FALSE;
430 
431   impl->registered = TRUE;
432   if (!app_class->dbus_register (impl->app,
433                                  impl->session_bus,
434                                  impl->object_path,
435                                  &local_error))
436     {
437       g_return_val_if_fail (local_error != NULL, FALSE);
438       g_propagate_error (error, g_steal_pointer (&local_error));
439       return FALSE;
440     }
441 
442   g_return_val_if_fail (local_error == NULL, FALSE);
443 
444   if (impl->bus_name == NULL)
445     {
446       /* If this is a non-unique application then it is sufficient to
447        * have our object paths registered. We can return now.
448        *
449        * Note: non-unique applications always act as primary-instance.
450        */
451       impl->primary = TRUE;
452       return TRUE;
453     }
454 
455   /* If this is a unique application then we need to attempt to own
456    * the well-known name and fall back to remote mode (!is_primary)
457    * in the case that we can't do that.
458    */
459   name_owner_flags = G_BUS_NAME_OWNER_FLAGS_DO_NOT_QUEUE;
460   app_flags = g_application_get_flags (impl->app);
461 
462   if (app_flags & G_APPLICATION_ALLOW_REPLACEMENT)
463     {
464       impl->name_lost_signal = g_dbus_connection_signal_subscribe (impl->session_bus,
465                                                                    "org.freedesktop.DBus",
466                                                                    "org.freedesktop.DBus",
467                                                                    "NameLost",
468                                                                    "/org/freedesktop/DBus",
469                                                                    impl->bus_name,
470                                                                    G_DBUS_SIGNAL_FLAGS_NONE,
471                                                                    name_lost,
472                                                                    impl,
473                                                                    NULL);
474 
475       name_owner_flags |= G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
476     }
477   if (app_flags & G_APPLICATION_REPLACE)
478     name_owner_flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
479 
480   reply = g_dbus_connection_call_sync (impl->session_bus,
481                                        "org.freedesktop.DBus",
482                                        "/org/freedesktop/DBus",
483                                        "org.freedesktop.DBus",
484                                        "RequestName",
485                                        g_variant_new ("(su)", impl->bus_name, name_owner_flags),
486                                        G_VARIANT_TYPE ("(u)"),
487                                        0, -1, cancellable, error);
488 
489   if (reply == NULL)
490     return FALSE;
491 
492   g_variant_get (reply, "(u)", &rval);
493   g_variant_unref (reply);
494 
495   /* DBUS_REQUEST_NAME_REPLY_EXISTS: 3 */
496   impl->primary = (rval != 3);
497 
498   if (!impl->primary && impl->name_lost_signal)
499     {
500       g_dbus_connection_signal_unsubscribe (impl->session_bus, impl->name_lost_signal);
501       impl->name_lost_signal = 0;
502     }
503 
504   return TRUE;
505 }
506 
507 /* Stop doing the things that the primary instance does.
508  *
509  * This should be called if attempting to become the primary instance
510  * failed (in order to clean up any partial success) and should also
511  * be called when freeing the GApplication.
512  *
513  * It is safe to call this multiple times.
514  */
515 static void
g_application_impl_stop_primary(GApplicationImpl * impl)516 g_application_impl_stop_primary (GApplicationImpl *impl)
517 {
518   GApplicationClass *app_class = G_APPLICATION_GET_CLASS (impl->app);
519 
520   if (impl->registered)
521     {
522       app_class->dbus_unregister (impl->app,
523                                   impl->session_bus,
524                                   impl->object_path);
525       impl->registered = FALSE;
526     }
527 
528   if (impl->object_id)
529     {
530       g_dbus_connection_unregister_object (impl->session_bus, impl->object_id);
531       impl->object_id = 0;
532     }
533 
534   if (impl->fdo_object_id)
535     {
536       g_dbus_connection_unregister_object (impl->session_bus, impl->fdo_object_id);
537       impl->fdo_object_id = 0;
538     }
539 
540   if (impl->actions_id)
541     {
542       g_dbus_connection_unexport_action_group (impl->session_bus, impl->actions_id);
543       impl->actions_id = 0;
544     }
545 
546   if (impl->name_lost_signal)
547     {
548       g_dbus_connection_signal_unsubscribe (impl->session_bus, impl->name_lost_signal);
549       impl->name_lost_signal = 0;
550     }
551 
552   if (impl->primary && impl->bus_name)
553     {
554       g_dbus_connection_call (impl->session_bus, "org.freedesktop.DBus",
555                               "/org/freedesktop/DBus", "org.freedesktop.DBus",
556                               "ReleaseName", g_variant_new ("(s)", impl->bus_name),
557                               NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
558       impl->primary = FALSE;
559     }
560 }
561 
562 void
g_application_impl_set_busy_state(GApplicationImpl * impl,gboolean busy)563 g_application_impl_set_busy_state (GApplicationImpl *impl,
564                                    gboolean          busy)
565 {
566   if (impl->busy != busy)
567     {
568       impl->busy = busy;
569       send_property_change (impl);
570     }
571 }
572 
573 void
g_application_impl_destroy(GApplicationImpl * impl)574 g_application_impl_destroy (GApplicationImpl *impl)
575 {
576   g_application_impl_stop_primary (impl);
577 
578   if (impl->session_bus)
579     g_object_unref (impl->session_bus);
580 
581   g_free (impl->object_path);
582 
583   g_slice_free (GApplicationImpl, impl);
584 }
585 
586 GApplicationImpl *
g_application_impl_register(GApplication * application,const gchar * appid,GApplicationFlags flags,GActionGroup * exported_actions,GRemoteActionGroup ** remote_actions,GCancellable * cancellable,GError ** error)587 g_application_impl_register (GApplication        *application,
588                              const gchar         *appid,
589                              GApplicationFlags    flags,
590                              GActionGroup        *exported_actions,
591                              GRemoteActionGroup **remote_actions,
592                              GCancellable        *cancellable,
593                              GError             **error)
594 {
595   GDBusActionGroup *actions;
596   GApplicationImpl *impl;
597 
598   g_assert ((flags & G_APPLICATION_NON_UNIQUE) || appid != NULL);
599 
600   impl = g_slice_new0 (GApplicationImpl);
601 
602   impl->app = application;
603   impl->exported_actions = exported_actions;
604 
605   /* non-unique applications do not attempt to acquire a bus name */
606   if (~flags & G_APPLICATION_NON_UNIQUE)
607     impl->bus_name = appid;
608 
609   impl->session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, cancellable, NULL);
610 
611   if (impl->session_bus == NULL)
612     {
613       /* If we can't connect to the session bus, proceed as a normal
614        * non-unique application.
615        */
616       *remote_actions = NULL;
617       return impl;
618     }
619 
620   impl->object_path = application_path_from_appid (appid);
621 
622   /* Only try to be the primary instance if
623    * G_APPLICATION_IS_LAUNCHER was not specified.
624    */
625   if (~flags & G_APPLICATION_IS_LAUNCHER)
626     {
627       if (!g_application_impl_attempt_primary (impl, cancellable, error))
628         {
629           g_application_impl_destroy (impl);
630           return NULL;
631         }
632 
633       if (impl->primary)
634         return impl;
635 
636       /* We didn't make it.  Drop our service-side stuff. */
637       g_application_impl_stop_primary (impl);
638 
639       if (flags & G_APPLICATION_IS_SERVICE)
640         {
641           g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
642                        "Unable to acquire bus name '%s'", appid);
643           g_application_impl_destroy (impl);
644 
645           return NULL;
646         }
647     }
648 
649   /* We are non-primary.  Try to get the primary's list of actions.
650    * This also serves as a mechanism to ensure that the primary exists
651    * (ie: D-Bus service files installed correctly, etc).
652    */
653   actions = g_dbus_action_group_get (impl->session_bus, impl->bus_name, impl->object_path);
654   if (!g_dbus_action_group_sync (actions, cancellable, error))
655     {
656       /* The primary appears not to exist.  Fail the registration. */
657       g_application_impl_destroy (impl);
658       g_object_unref (actions);
659 
660       return NULL;
661     }
662 
663   *remote_actions = G_REMOTE_ACTION_GROUP (actions);
664 
665   return impl;
666 }
667 
668 void
g_application_impl_activate(GApplicationImpl * impl,GVariant * platform_data)669 g_application_impl_activate (GApplicationImpl *impl,
670                              GVariant         *platform_data)
671 {
672   g_dbus_connection_call (impl->session_bus,
673                           impl->bus_name,
674                           impl->object_path,
675                           "org.gtk.Application",
676                           "Activate",
677                           g_variant_new ("(@a{sv})", platform_data),
678                           NULL, 0, -1, NULL, NULL, NULL);
679 }
680 
681 void
g_application_impl_open(GApplicationImpl * impl,GFile ** files,gint n_files,const gchar * hint,GVariant * platform_data)682 g_application_impl_open (GApplicationImpl  *impl,
683                          GFile            **files,
684                          gint               n_files,
685                          const gchar       *hint,
686                          GVariant          *platform_data)
687 {
688   GVariantBuilder builder;
689   gint i;
690 
691   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(assa{sv})"));
692   g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
693   for (i = 0; i < n_files; i++)
694     {
695       gchar *uri = g_file_get_uri (files[i]);
696       g_variant_builder_add (&builder, "s", uri);
697       g_free (uri);
698     }
699   g_variant_builder_close (&builder);
700   g_variant_builder_add (&builder, "s", hint);
701   g_variant_builder_add_value (&builder, platform_data);
702 
703   g_dbus_connection_call (impl->session_bus,
704                           impl->bus_name,
705                           impl->object_path,
706                           "org.gtk.Application",
707                           "Open",
708                           g_variant_builder_end (&builder),
709                           NULL, 0, -1, NULL, NULL, NULL);
710 }
711 
712 static void
g_application_impl_cmdline_method_call(GDBusConnection * connection,const gchar * sender,const gchar * object_path,const gchar * interface_name,const gchar * method_name,GVariant * parameters,GDBusMethodInvocation * invocation,gpointer user_data)713 g_application_impl_cmdline_method_call (GDBusConnection       *connection,
714                                         const gchar           *sender,
715                                         const gchar           *object_path,
716                                         const gchar           *interface_name,
717                                         const gchar           *method_name,
718                                         GVariant              *parameters,
719                                         GDBusMethodInvocation *invocation,
720                                         gpointer               user_data)
721 {
722   const gchar *message;
723 
724   g_variant_get_child (parameters, 0, "&s", &message);
725 
726   if (strcmp (method_name, "Print") == 0)
727     g_print ("%s", message);
728   else if (strcmp (method_name, "PrintError") == 0)
729     g_printerr ("%s", message);
730   else
731     g_assert_not_reached ();
732 
733   g_dbus_method_invocation_return_value (invocation, NULL);
734 }
735 
736 typedef struct
737 {
738   GMainLoop *loop;
739   int status;
740 } CommandLineData;
741 
742 static void
g_application_impl_cmdline_done(GObject * source,GAsyncResult * result,gpointer user_data)743 g_application_impl_cmdline_done (GObject      *source,
744                                  GAsyncResult *result,
745                                  gpointer      user_data)
746 {
747   CommandLineData *data = user_data;
748   GError *error = NULL;
749   GVariant *reply;
750 
751 #ifdef G_OS_UNIX
752   reply = g_dbus_connection_call_with_unix_fd_list_finish (G_DBUS_CONNECTION (source), NULL, result, &error);
753 #else
754   reply = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source), result, &error);
755 #endif
756 
757 
758   if (reply != NULL)
759     {
760       g_variant_get (reply, "(i)", &data->status);
761       g_variant_unref (reply);
762     }
763 
764   else
765     {
766       g_printerr ("%s\n", error->message);
767       g_error_free (error);
768       data->status = 1;
769     }
770 
771   g_main_loop_quit (data->loop);
772 }
773 
774 int
g_application_impl_command_line(GApplicationImpl * impl,const gchar * const * arguments,GVariant * platform_data)775 g_application_impl_command_line (GApplicationImpl    *impl,
776                                  const gchar * const *arguments,
777                                  GVariant            *platform_data)
778 {
779   static const GDBusInterfaceVTable vtable = {
780     g_application_impl_cmdline_method_call, NULL, NULL, { 0 }
781   };
782   const gchar *object_path = "/org/gtk/Application/CommandLine";
783   GMainContext *context;
784   CommandLineData data;
785   guint object_id G_GNUC_UNUSED  /* when compiling with G_DISABLE_ASSERT */;
786 
787   context = g_main_context_new ();
788   data.loop = g_main_loop_new (context, FALSE);
789   g_main_context_push_thread_default (context);
790 
791   if (org_gtk_private_CommandLine == NULL)
792     {
793       GError *error = NULL;
794       GDBusNodeInfo *info;
795 
796       info = g_dbus_node_info_new_for_xml (org_gtk_private_CommandLine_xml, &error);
797       if G_UNLIKELY (info == NULL)
798         g_error ("%s", error->message);
799       org_gtk_private_CommandLine = g_dbus_node_info_lookup_interface (info, "org.gtk.private.CommandLine");
800       g_assert (org_gtk_private_CommandLine != NULL);
801       g_dbus_interface_info_ref (org_gtk_private_CommandLine);
802       g_dbus_node_info_unref (info);
803     }
804 
805   object_id = g_dbus_connection_register_object (impl->session_bus, object_path,
806                                                  org_gtk_private_CommandLine,
807                                                  &vtable, &data, NULL, NULL);
808   /* In theory we should try other paths... */
809   g_assert (object_id != 0);
810 
811 #ifdef G_OS_UNIX
812   {
813     GError *error = NULL;
814     GUnixFDList *fd_list;
815 
816     /* send along the stdin in case
817      * g_application_command_line_get_stdin_data() is called
818      */
819     fd_list = g_unix_fd_list_new ();
820     g_unix_fd_list_append (fd_list, 0, &error);
821     g_assert_no_error (error);
822 
823     g_dbus_connection_call_with_unix_fd_list (impl->session_bus, impl->bus_name, impl->object_path,
824                                               "org.gtk.Application", "CommandLine",
825                                               g_variant_new ("(o^aay@a{sv})", object_path, arguments, platform_data),
826                                               G_VARIANT_TYPE ("(i)"), 0, G_MAXINT, fd_list, NULL,
827                                               g_application_impl_cmdline_done, &data);
828     g_object_unref (fd_list);
829   }
830 #else
831   g_dbus_connection_call (impl->session_bus, impl->bus_name, impl->object_path,
832                           "org.gtk.Application", "CommandLine",
833                           g_variant_new ("(o^aay@a{sv})", object_path, arguments, platform_data),
834                           G_VARIANT_TYPE ("(i)"), 0, G_MAXINT, NULL,
835                           g_application_impl_cmdline_done, &data);
836 #endif
837 
838   g_main_loop_run (data.loop);
839 
840   g_main_context_pop_thread_default (context);
841   g_main_context_unref (context);
842   g_main_loop_unref (data.loop);
843 
844   return data.status;
845 }
846 
847 void
g_application_impl_flush(GApplicationImpl * impl)848 g_application_impl_flush (GApplicationImpl *impl)
849 {
850   if (impl->session_bus)
851     g_dbus_connection_flush_sync (impl->session_bus, NULL, NULL);
852 }
853 
854 GDBusConnection *
g_application_impl_get_dbus_connection(GApplicationImpl * impl)855 g_application_impl_get_dbus_connection (GApplicationImpl *impl)
856 {
857   return impl->session_bus;
858 }
859 
860 const gchar *
g_application_impl_get_dbus_object_path(GApplicationImpl * impl)861 g_application_impl_get_dbus_object_path (GApplicationImpl *impl)
862 {
863   return impl->object_path;
864 }
865 
866 /* GDBusCommandLine implementation {{{1 */
867 
868 typedef GApplicationCommandLineClass GDBusCommandLineClass;
869 static GType g_dbus_command_line_get_type (void);
870 typedef struct
871 {
872   GApplicationCommandLine  parent_instance;
873   GDBusMethodInvocation   *invocation;
874 
875   GDBusConnection *connection;
876   const gchar     *bus_name;
877   const gchar     *object_path;
878 } GDBusCommandLine;
879 
880 
G_DEFINE_TYPE(GDBusCommandLine,g_dbus_command_line,G_TYPE_APPLICATION_COMMAND_LINE)881 G_DEFINE_TYPE (GDBusCommandLine,
882                g_dbus_command_line,
883                G_TYPE_APPLICATION_COMMAND_LINE)
884 
885 static void
886 g_dbus_command_line_print_literal (GApplicationCommandLine *cmdline,
887                                    const gchar             *message)
888 {
889   GDBusCommandLine *gdbcl = (GDBusCommandLine *) cmdline;
890 
891   g_dbus_connection_call (gdbcl->connection,
892                           gdbcl->bus_name,
893                           gdbcl->object_path,
894                           "org.gtk.private.CommandLine", "Print",
895                           g_variant_new ("(s)", message),
896                           NULL, 0, -1, NULL, NULL, NULL);
897 }
898 
899 static void
g_dbus_command_line_printerr_literal(GApplicationCommandLine * cmdline,const gchar * message)900 g_dbus_command_line_printerr_literal (GApplicationCommandLine *cmdline,
901                                       const gchar             *message)
902 {
903   GDBusCommandLine *gdbcl = (GDBusCommandLine *) cmdline;
904 
905   g_dbus_connection_call (gdbcl->connection,
906                           gdbcl->bus_name,
907                           gdbcl->object_path,
908                           "org.gtk.private.CommandLine", "PrintError",
909                           g_variant_new ("(s)", message),
910                           NULL, 0, -1, NULL, NULL, NULL);
911 }
912 
913 static GInputStream *
g_dbus_command_line_get_stdin(GApplicationCommandLine * cmdline)914 g_dbus_command_line_get_stdin (GApplicationCommandLine *cmdline)
915 {
916 #ifdef G_OS_UNIX
917   GDBusCommandLine *gdbcl = (GDBusCommandLine *) cmdline;
918   GInputStream *result = NULL;
919   GDBusMessage *message;
920   GUnixFDList *fd_list;
921 
922   message = g_dbus_method_invocation_get_message (gdbcl->invocation);
923   fd_list = g_dbus_message_get_unix_fd_list (message);
924 
925   if (fd_list && g_unix_fd_list_get_length (fd_list))
926     {
927       gint *fds, n_fds, i;
928 
929       fds = g_unix_fd_list_steal_fds (fd_list, &n_fds);
930       result = g_unix_input_stream_new (fds[0], TRUE);
931       for (i = 1; i < n_fds; i++)
932         (void) g_close (fds[i], NULL);
933       g_free (fds);
934     }
935 
936   return result;
937 #else
938   return NULL;
939 #endif
940 }
941 
942 static void
g_dbus_command_line_finalize(GObject * object)943 g_dbus_command_line_finalize (GObject *object)
944 {
945   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
946   GDBusCommandLine *gdbcl = (GDBusCommandLine *) object;
947   gint status;
948 
949   status = g_application_command_line_get_exit_status (cmdline);
950 
951   g_dbus_method_invocation_return_value (gdbcl->invocation,
952                                          g_variant_new ("(i)", status));
953   g_object_unref (gdbcl->invocation);
954 
955   G_OBJECT_CLASS (g_dbus_command_line_parent_class)
956     ->finalize (object);
957 }
958 
959 static void
g_dbus_command_line_init(GDBusCommandLine * gdbcl)960 g_dbus_command_line_init (GDBusCommandLine *gdbcl)
961 {
962 }
963 
964 static void
g_dbus_command_line_class_init(GApplicationCommandLineClass * class)965 g_dbus_command_line_class_init (GApplicationCommandLineClass *class)
966 {
967   GObjectClass *object_class = G_OBJECT_CLASS (class);
968 
969   object_class->finalize = g_dbus_command_line_finalize;
970   class->printerr_literal = g_dbus_command_line_printerr_literal;
971   class->print_literal = g_dbus_command_line_print_literal;
972   class->get_stdin = g_dbus_command_line_get_stdin;
973 }
974 
975 static GApplicationCommandLine *
g_dbus_command_line_new(GDBusMethodInvocation * invocation)976 g_dbus_command_line_new (GDBusMethodInvocation *invocation)
977 {
978   GDBusCommandLine *gdbcl;
979   GVariant *args;
980   GVariant *arguments, *platform_data;
981 
982   args = g_dbus_method_invocation_get_parameters (invocation);
983 
984   arguments = g_variant_get_child_value (args, 1);
985   platform_data = g_variant_get_child_value (args, 2);
986   gdbcl = g_object_new (g_dbus_command_line_get_type (),
987                         "arguments", arguments,
988                         "platform-data", platform_data,
989                         NULL);
990   g_variant_unref (arguments);
991   g_variant_unref (platform_data);
992 
993   gdbcl->connection = g_dbus_method_invocation_get_connection (invocation);
994   gdbcl->bus_name = g_dbus_method_invocation_get_sender (invocation);
995   g_variant_get_child (args, 0, "&o", &gdbcl->object_path);
996   gdbcl->invocation = g_object_ref (invocation);
997 
998   return G_APPLICATION_COMMAND_LINE (gdbcl);
999 }
1000 
1001 /* Epilogue {{{1 */
1002 
1003 /* vim:set foldmethod=marker: */
1004