GApplication: send platform data for actions again
[platform/upstream/glib.git] / gio / gapplication.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published
6  * by the Free Software Foundation; either version 2 of the licence or (at
7  * 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 /* Prologue {{{1 */
23 #include "config.h"
24
25 #include "gapplication.h"
26
27 #include "gapplicationcommandline.h"
28 #include "gsimpleactiongroup.h"
29 #include "gapplicationimpl.h"
30 #include "gactiongroup.h"
31 #include "gactionmap.h"
32 #include "gmenumodel.h"
33 #include "gsettings.h"
34
35 #include "gioenumtypes.h"
36 #include "gioenums.h"
37 #include "gfile.h"
38
39 #include "glibintl.h"
40
41 #include <string.h>
42
43 /**
44  * SECTION:gapplication
45  * @title: GApplication
46  * @short_description: Core application class
47  *
48  * A #GApplication is the foundation of an application, unique for a
49  * given application identifier.  The GApplication class wraps some
50  * low-level platform-specific services and is intended to act as the
51  * foundation for higher-level application classes such as
52  * #GtkApplication or #MxApplication.  In general, you should not use
53  * this class outside of a higher level framework.
54  *
55  * One of the core features that GApplication provides is process
56  * uniqueness, in the context of a "session".  The session concept is
57  * platform-dependent, but corresponds roughly to a graphical desktop
58  * login.  When your application is launched again, its arguments
59  * are passed through platform communication to the already running
60  * program. The already running instance of the program is called the
61  * <firstterm>primary instance</firstterm>. On Linux, the D-Bus session
62  * bus is used for communication.
63  *
64  * GApplication provides convenient life cycle management by maintaining
65  * a <firstterm>use count</firstterm> for the primary application instance.
66  * The use count can be changed using g_application_hold() and
67  * g_application_release(). If it drops to zero, the application exits.
68  * Higher-level classes such as #GtkApplication employ the use count to
69  * ensure that the application stays alive as long as it has any opened
70  * windows.
71  *
72  * Before using GApplication, you must choose an "application identifier".
73  * The expected form of an application identifier is very close to that of
74  * of a <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-interface">DBus bus name</ulink>.
75  * Examples include: "com.example.MyApp", "org.example.internal-apps.Calculator".
76  * For details on valid application identifiers, see g_application_id_is_valid().
77  *
78  * On Linux, the application identifier is claimed as a well-known bus name
79  * on the user's session bus.  This means that the uniqueness of your
80  * application is scoped to the current session.  It also means that your
81  * application may provide additional services (through registration of other
82  * object paths) at that bus name.  The registration of these object paths
83  * should be done with the shared GDBus session bus.  Note that due to the
84  * internal architecture of GDBus, method calls can be dispatched at any time
85  * (even if a main loop is not running).  For this reason, you must ensure that
86  * any object paths that you wish to register are registered before #GApplication
87  * attempts to acquire the bus name of your application (which happens in
88  * g_application_register()).  Unfortunately, this means that you cannot use
89  * g_application_get_is_remote() to decide if you want to register object paths.
90  *
91  * GApplication also implements the #GActionGroup and #GActionMap
92  * interfaces and lets you easily export actions by adding them with
93  * g_action_map_add_action(). When invoking an action by calling
94  * g_action_group_activate_action() on the application, it is always
95  * invoked in the primary instance. The actions are also exported on
96  * the session bus, and GIO provides the #GDBusActionGroup wrapper to
97  * conveniently access them remotely. Additionally, g_application_set_app_menu()
98  * and g_application_set_menubar() can be used to export representation
99  * data for the actions, in the form of #GMenuModels. GIO provides
100  * a #GDBusMenuModel wrapper for remote access to exported #GMenuModels.
101  *
102  * There is a number of different entry points into a GApplication:
103  * <itemizedlist>
104  * <listitem>via 'Activate' (i.e. just starting the application)</listitem>
105  * <listitem>via 'Open' (i.e. opening some files)</listitem>
106  * <listitem>by handling a command-line</listitem>
107  * <listitem>via activating an action</listitem>
108  * </itemizedlist>
109  * The #GApplication::startup signal lets you handle the application
110  * initialization for all of these in a single place.
111  *
112  * Regardless of which of these entry points is used to start the application,
113  * GApplication passes some <firstterm id="platform-data">platform
114  * data</firstterm> from the launching instance to the primary instance,
115  * in the form of a #GVariant dictionary mapping strings to variants.
116  * To use platform data, override the @before_emit or @after_emit virtual
117  * functions in your #GApplication subclass. When dealing with
118  * #GApplicationCommandline objects, the platform data is directly
119  * available via g_application_command_line_get_cwd(),
120  * g_application_command_line_get_environ() and
121  * g_application_command_line_get_platform_data().
122  *
123  * As the name indicates, the platform data may vary depending on the
124  * operating system, but it always includes the current directory (key
125  * "cwd"), and optionally the environment (ie the set of environment
126  * variables and their values) of the calling process (key "environ").
127  * The environment is only added to the platform data if the
128  * #G_APPLICATION_SEND_ENVIONMENT flag is set. GApplication subclasses
129  * can add their own platform data by overriding the @add_platform_data
130  * virtual function. For instance, #GtkApplication adds startup notification
131  * data in this way.
132  *
133  * To parse commandline arguments you may handle the
134  * #GApplication::command-line signal or override the local_command_line()
135  * vfunc, to parse them in either the primary instance or the local instance,
136  * respectively.
137  *
138  * <example id="gapplication-example-open"><title>Opening files with a GApplication</title>
139  * <programlisting>
140  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-open.c">
141  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
142  * </xi:include>
143  * </programlisting>
144  * </example>
145  *
146  * <example id="gapplication-example-actions"><title>A GApplication with actions</title>
147  * <programlisting>
148  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-actions.c">
149  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
150  * </xi:include>
151  * </programlisting>
152  * </example>
153  *
154  * <example id="gapplication-example-menu"><title>A GApplication with menus</title>
155  * <programlisting>
156  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-menu.c">
157  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
158  * </xi:include>
159  * </programlisting>
160  * </example>
161  */
162
163 /**
164  * GApplicationClass:
165  * @startup: invoked on the primary instance immediately after registration
166  * @shutdown: invoked only on the registered primary instance immediately
167  *      after the main loop terminates
168  * @activate: invoked on the primary instance when an activation occurs
169  * @open: invoked on the primary instance when there are files to open
170  * @command_line: invoked on the primary instance when a command-line is
171  *   not handled locally
172  * @local_command_line: invoked (locally) when the process has been invoked
173  *     via commandline execution (as opposed to, say, D-Bus activation - which
174  *     is not currently supported by GApplication). The virtual function has
175  *     the chance to inspect (and possibly replace) the list of command line
176  *     arguments. See g_application_run() for more information.
177  * @before_emit: invoked on the primary instance before 'activate', 'open',
178  *     'command-line' or any action invocation, gets the 'platform data' from
179  *     the calling instance
180  * @after_emit: invoked on the primary instance after 'activate', 'open',
181  *     'command-line' or any action invocation, gets the 'platform data' from
182  *     the calling instance
183  * @add_platform_data: invoked (locally) to add 'platform data' to be sent to
184  *     the primary instance when activating, opening or invoking actions
185  * @quit_mainloop: Used to be invoked on the primary instance when the use
186  *     count of the application drops to zero (and after any inactivity
187  *     timeout, if requested). Not used anymore since 2.32
188  * @run_mainloop: Used to be invoked on the primary instance from
189  *     g_application_run() if the use-count is non-zero. Since 2.32,
190  *     GApplication is iterating the main context directly and is not
191  *     using @run_mainloop anymore
192  *
193  * Virtual function table for #GApplication.
194  *
195  * Since: 2.28
196  */
197
198 struct _GApplicationPrivate
199 {
200   GApplicationFlags  flags;
201   gchar             *id;
202
203   GActionGroup      *actions;
204   GMenuModel        *app_menu;
205   GMenuModel        *menubar;
206
207   guint              inactivity_timeout_id;
208   guint              inactivity_timeout;
209   guint              use_count;
210
211   guint              is_registered : 1;
212   guint              is_remote : 1;
213   guint              did_startup : 1;
214   guint              did_shutdown : 1;
215
216   GActionGroup      *remote_actions;
217   GApplicationImpl  *impl;
218 };
219
220 enum
221 {
222   PROP_NONE,
223   PROP_APPLICATION_ID,
224   PROP_FLAGS,
225   PROP_IS_REGISTERED,
226   PROP_IS_REMOTE,
227   PROP_INACTIVITY_TIMEOUT,
228   PROP_ACTION_GROUP,
229   PROP_APP_MENU,
230   PROP_MENUBAR
231 };
232
233 enum
234 {
235   SIGNAL_STARTUP,
236   SIGNAL_SHUTDOWN,
237   SIGNAL_ACTIVATE,
238   SIGNAL_OPEN,
239   SIGNAL_ACTION,
240   SIGNAL_COMMAND_LINE,
241   NR_SIGNALS
242 };
243
244 static guint g_application_signals[NR_SIGNALS];
245
246 static void g_application_action_group_iface_init (GActionGroupInterface *);
247 static void g_application_action_map_iface_init (GActionMapInterface *);
248 G_DEFINE_TYPE_WITH_CODE (GApplication, g_application, G_TYPE_OBJECT,
249  G_IMPLEMENT_INTERFACE (G_TYPE_ACTION_GROUP, g_application_action_group_iface_init)
250  G_IMPLEMENT_INTERFACE (G_TYPE_ACTION_MAP, g_application_action_map_iface_init))
251
252 /* vfunc defaults {{{1 */
253 static void
254 g_application_real_before_emit (GApplication *application,
255                                 GVariant     *platform_data)
256 {
257 }
258
259 static void
260 g_application_real_after_emit (GApplication *application,
261                                GVariant     *platform_data)
262 {
263 }
264
265 static void
266 g_application_real_startup (GApplication *application)
267 {
268   application->priv->did_startup = TRUE;
269 }
270
271 static void
272 g_application_real_shutdown (GApplication *application)
273 {
274   application->priv->did_shutdown = TRUE;
275 }
276
277 static void
278 g_application_real_activate (GApplication *application)
279 {
280   if (!g_signal_has_handler_pending (application,
281                                      g_application_signals[SIGNAL_ACTIVATE],
282                                      0, TRUE) &&
283       G_APPLICATION_GET_CLASS (application)->activate == g_application_real_activate)
284     {
285       static gboolean warned;
286
287       if (warned)
288         return;
289
290       g_warning ("Your application does not implement "
291                  "g_application_activate() and has no handlers connected "
292                  "to the 'activate' signal.  It should do one of these.");
293       warned = TRUE;
294     }
295 }
296
297 static void
298 g_application_real_open (GApplication  *application,
299                          GFile        **files,
300                          gint           n_files,
301                          const gchar   *hint)
302 {
303   if (!g_signal_has_handler_pending (application,
304                                      g_application_signals[SIGNAL_OPEN],
305                                      0, TRUE) &&
306       G_APPLICATION_GET_CLASS (application)->open == g_application_real_open)
307     {
308       static gboolean warned;
309
310       if (warned)
311         return;
312
313       g_warning ("Your application claims to support opening files "
314                  "but does not implement g_application_open() and has no "
315                  "handlers connected to the 'open' signal.");
316       warned = TRUE;
317     }
318 }
319
320 static int
321 g_application_real_command_line (GApplication            *application,
322                                  GApplicationCommandLine *cmdline)
323 {
324   if (!g_signal_has_handler_pending (application,
325                                      g_application_signals[SIGNAL_COMMAND_LINE],
326                                      0, TRUE) &&
327       G_APPLICATION_GET_CLASS (application)->command_line == g_application_real_command_line)
328     {
329       static gboolean warned;
330
331       if (warned)
332         return 1;
333
334       g_warning ("Your application claims to support custom command line "
335                  "handling but does not implement g_application_command_line() "
336                  "and has no handlers connected to the 'command-line' signal.");
337
338       warned = TRUE;
339     }
340
341     return 1;
342 }
343
344 static gboolean
345 g_application_real_local_command_line (GApplication   *application,
346                                        gchar        ***arguments,
347                                        int            *exit_status)
348 {
349   if (application->priv->flags & G_APPLICATION_HANDLES_COMMAND_LINE)
350     return FALSE;
351
352   else
353     {
354       GError *error = NULL;
355       gint n_args;
356
357       if (!g_application_register (application, NULL, &error))
358         {
359           g_critical ("%s", error->message);
360           g_error_free (error);
361           *exit_status = 1;
362           return TRUE;
363         }
364
365       n_args = g_strv_length (*arguments);
366
367       if (application->priv->flags & G_APPLICATION_IS_SERVICE)
368         {
369           if ((*exit_status = n_args > 1))
370             {
371               g_printerr ("GApplication service mode takes no arguments.\n");
372               application->priv->flags &= ~G_APPLICATION_IS_SERVICE;
373             }
374
375           return TRUE;
376         }
377
378       if (n_args <= 1)
379         {
380           g_application_activate (application);
381           *exit_status = 0;
382         }
383
384       else
385         {
386           if (~application->priv->flags & G_APPLICATION_HANDLES_OPEN)
387             {
388               g_critical ("This application can not open files.");
389               *exit_status = 1;
390             }
391           else
392             {
393               GFile **files;
394               gint n_files;
395               gint i;
396
397               n_files = n_args - 1;
398               files = g_new (GFile *, n_files);
399
400               for (i = 0; i < n_files; i++)
401                 files[i] = g_file_new_for_commandline_arg ((*arguments)[i + 1]);
402
403               g_application_open (application, files, n_files, "");
404
405               for (i = 0; i < n_files; i++)
406                 g_object_unref (files[i]);
407               g_free (files);
408
409               *exit_status = 0;
410             }
411         }
412
413       return TRUE;
414     }
415 }
416
417 static void
418 g_application_real_add_platform_data (GApplication    *application,
419                                       GVariantBuilder *builder)
420 {
421 }
422
423 /* GObject implementation stuff {{{1 */
424 static void
425 g_application_set_property (GObject      *object,
426                             guint         prop_id,
427                             const GValue *value,
428                             GParamSpec   *pspec)
429 {
430   GApplication *application = G_APPLICATION (object);
431
432   switch (prop_id)
433     {
434     case PROP_APPLICATION_ID:
435       g_application_set_application_id (application,
436                                         g_value_get_string (value));
437       break;
438
439     case PROP_FLAGS:
440       g_application_set_flags (application, g_value_get_flags (value));
441       break;
442
443     case PROP_INACTIVITY_TIMEOUT:
444       g_application_set_inactivity_timeout (application,
445                                             g_value_get_uint (value));
446       break;
447
448     case PROP_ACTION_GROUP:
449       g_clear_object (&application->priv->actions);
450       application->priv->actions = g_value_dup_object (value);
451       break;
452
453     case PROP_APP_MENU:
454       g_application_set_app_menu (application, g_value_get_object (value));
455       break;
456
457     case PROP_MENUBAR:
458       g_application_set_menubar (application, g_value_get_object (value));
459       break;
460
461     default:
462       g_assert_not_reached ();
463     }
464 }
465
466 /**
467  * g_application_set_action_group:
468  * @application: a #GApplication
469  * @action_group: (allow-none): a #GActionGroup, or %NULL
470  *
471  * This used to be how actions were associated with a #GApplication.
472  * Now there is #GActionMap for that.
473  *
474  * Since: 2.28
475  *
476  * Deprecated:2.32:Use the #GActionMap interface instead.  Never ever
477  * mix use of this API with use of #GActionMap on the same @application
478  * or things will go very badly wrong.  This function is known to
479  * introduce buggy behaviour (ie: signals not emitted on changes to the
480  * action group), so you should really use #GActionMap instead.
481  **/
482 void
483 g_application_set_action_group (GApplication *application,
484                                 GActionGroup *action_group)
485 {
486   g_return_if_fail (G_IS_APPLICATION (application));
487   g_return_if_fail (!application->priv->is_registered);
488
489   if (application->priv->actions != NULL)
490     g_object_unref (application->priv->actions);
491
492   application->priv->actions = action_group;
493
494   if (application->priv->actions != NULL)
495     g_object_ref (application->priv->actions);
496 }
497
498 /**
499  * g_application_set_app_menu:
500  * @application: a #GApplication
501  * @app_menu: (allow-none): a #GMenuModel, or %NULL
502  *
503  * Sets or unsets the application menu for @application.
504  *
505  * The application menu is a single menu containing items that typically
506  * impact the application as a whole, rather than acting on a specific
507  * window or document.  For example, you would expect to see
508  * "Preferences" or "Quit" in an application menu, but not "Save" or
509  * "Print".
510  *
511  * If supported, the application menu will be rendered by the desktop
512  * environment.
513  *
514  * Since: 2.32
515  */
516 void
517 g_application_set_app_menu (GApplication *application,
518                             GMenuModel   *app_menu)
519 {
520   g_return_if_fail (G_IS_APPLICATION (application));
521
522   if (app_menu != application->priv->app_menu)
523     {
524       if (application->priv->app_menu != NULL)
525         g_object_unref (application->priv->app_menu);
526
527       application->priv->app_menu = app_menu;
528
529       if (application->priv->app_menu != NULL)
530         g_object_ref (application->priv->app_menu);
531
532       g_object_notify (G_OBJECT (application), "app-menu");
533     }
534 }
535
536 /**
537  * g_application_get_app_menu:
538  * @application: a #GApplication
539  *
540  * Returns the menu model that has been set with
541  * g_application_set_app_menu().
542  *
543  * Returns: the application menu of @application
544  *
545  * Since: 2.32
546  */
547 GMenuModel *
548 g_application_get_app_menu (GApplication *application)
549 {
550   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
551
552   return application->priv->app_menu;
553 }
554
555 /**
556  * g_application_set_menubar:
557  * @application: a #GApplication
558  * @menubar: (allow-none): a #GMenuModel, or %NULL
559  *
560  * Sets or unsets the menubar for windows of @application.
561  *
562  * This is a menubar in the traditional sense.
563  *
564  * Depending on the desktop environment, this may appear at the top of
565  * each window, or at the top of the screen.  In some environments, if
566  * both the application menu and the menubar are set, the application
567  * menu will be presented as if it were the first item of the menubar.
568  * Other environments treat the two as completely separate -- for
569  * example, the application menu may be rendered by the desktop shell
570  * while the menubar (if set) remains in each individual window.
571  *
572  * Since: 2.32
573  */
574 void
575 g_application_set_menubar (GApplication *application,
576                             GMenuModel   *menubar)
577 {
578   g_return_if_fail (G_IS_APPLICATION (application));
579
580   if (menubar != application->priv->menubar)
581     {
582       if (application->priv->menubar != NULL)
583         g_object_unref (application->priv->menubar);
584
585       application->priv->menubar = menubar;
586
587       if (application->priv->menubar != NULL)
588         g_object_ref (application->priv->menubar);
589
590       g_object_notify (G_OBJECT (application), "menubar");
591     }
592 }
593
594 /**
595  * g_application_get_menubar:
596  * @application: a #GApplication
597  *
598  * Returns the menu model that has been set with
599  * g_application_set_menubar().
600  *
601  * Returns: the menubar for windows of @application
602  *
603  * Since: 2.32
604  */
605 GMenuModel *
606 g_application_get_menubar (GApplication *application)
607 {
608   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
609
610   return application->priv->menubar;
611 }
612
613 static void
614 g_application_get_property (GObject    *object,
615                             guint       prop_id,
616                             GValue     *value,
617                             GParamSpec *pspec)
618 {
619   GApplication *application = G_APPLICATION (object);
620
621   switch (prop_id)
622     {
623     case PROP_APPLICATION_ID:
624       g_value_set_string (value,
625                           g_application_get_application_id (application));
626       break;
627
628     case PROP_FLAGS:
629       g_value_set_flags (value,
630                          g_application_get_flags (application));
631       break;
632
633     case PROP_IS_REGISTERED:
634       g_value_set_boolean (value,
635                            g_application_get_is_registered (application));
636       break;
637
638     case PROP_IS_REMOTE:
639       g_value_set_boolean (value,
640                            g_application_get_is_remote (application));
641       break;
642
643     case PROP_INACTIVITY_TIMEOUT:
644       g_value_set_uint (value,
645                         g_application_get_inactivity_timeout (application));
646       break;
647
648     case PROP_APP_MENU:
649       g_value_set_object (value,
650                           g_application_get_app_menu (application));
651       break;
652
653     case PROP_MENUBAR:
654       g_value_set_object (value,
655                           g_application_get_menubar (application));
656       break;
657
658     default:
659       g_assert_not_reached ();
660     }
661 }
662
663 static void
664 g_application_constructed (GObject *object)
665 {
666   GApplication *application = G_APPLICATION (object);
667
668   g_assert (application->priv->id != NULL);
669
670   if (g_application_get_default () == NULL)
671     g_application_set_default (application);
672 }
673
674 static void
675 g_application_finalize (GObject *object)
676 {
677   GApplication *application = G_APPLICATION (object);
678
679   if (application->priv->impl)
680     g_application_impl_destroy (application->priv->impl);
681   g_free (application->priv->id);
682
683   if (g_application_get_default () == application)
684     g_application_set_default (NULL);
685
686   if (application->priv->app_menu)
687     g_object_unref (application->priv->app_menu);
688
689   if (application->priv->menubar)
690     g_object_unref (application->priv->menubar);
691
692   if (application->priv->actions)
693     g_object_unref (application->priv->actions);
694
695   G_OBJECT_CLASS (g_application_parent_class)
696     ->finalize (object);
697 }
698
699 static void
700 g_application_init (GApplication *application)
701 {
702   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application,
703                                                    G_TYPE_APPLICATION,
704                                                    GApplicationPrivate);
705
706   application->priv->actions = G_ACTION_GROUP (g_simple_action_group_new ());
707
708   /* application->priv->actions is the one and only ref on the group, so when
709    * we dispose, the action group will die, disconnecting all signals.
710    */
711   g_signal_connect_swapped (application->priv->actions, "action-added",
712                             G_CALLBACK (g_action_group_action_added), application);
713   g_signal_connect_swapped (application->priv->actions, "action-enabled-changed",
714                             G_CALLBACK (g_action_group_action_enabled_changed), application);
715   g_signal_connect_swapped (application->priv->actions, "action-state-changed",
716                             G_CALLBACK (g_action_group_action_state_changed), application);
717   g_signal_connect_swapped (application->priv->actions, "action-removed",
718                             G_CALLBACK (g_action_group_action_removed), application);
719 }
720
721 static void
722 g_application_class_init (GApplicationClass *class)
723 {
724   GObjectClass *object_class = G_OBJECT_CLASS (class);
725
726   object_class->constructed = g_application_constructed;
727   object_class->finalize = g_application_finalize;
728   object_class->get_property = g_application_get_property;
729   object_class->set_property = g_application_set_property;
730
731   class->before_emit = g_application_real_before_emit;
732   class->after_emit = g_application_real_after_emit;
733   class->startup = g_application_real_startup;
734   class->shutdown = g_application_real_shutdown;
735   class->activate = g_application_real_activate;
736   class->open = g_application_real_open;
737   class->command_line = g_application_real_command_line;
738   class->local_command_line = g_application_real_local_command_line;
739   class->add_platform_data = g_application_real_add_platform_data;
740
741   g_object_class_install_property (object_class, PROP_APPLICATION_ID,
742     g_param_spec_string ("application-id",
743                          P_("Application identifier"),
744                          P_("The unique identifier for the application"),
745                          NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
746                          G_PARAM_STATIC_STRINGS));
747
748   g_object_class_install_property (object_class, PROP_FLAGS,
749     g_param_spec_flags ("flags",
750                         P_("Application flags"),
751                         P_("Flags specifying the behaviour of the application"),
752                         G_TYPE_APPLICATION_FLAGS, G_APPLICATION_FLAGS_NONE,
753                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
754
755   g_object_class_install_property (object_class, PROP_IS_REGISTERED,
756     g_param_spec_boolean ("is-registered",
757                           P_("Is registered"),
758                           P_("If g_application_register() has been called"),
759                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
760
761   g_object_class_install_property (object_class, PROP_IS_REMOTE,
762     g_param_spec_boolean ("is-remote",
763                           P_("Is remote"),
764                           P_("If this application instance is remote"),
765                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
766
767   g_object_class_install_property (object_class, PROP_INACTIVITY_TIMEOUT,
768     g_param_spec_uint ("inactivity-timeout",
769                        P_("Inactivity timeout"),
770                        P_("Time (ms) to stay alive after becoming idle"),
771                        0, G_MAXUINT, 0,
772                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
773
774   g_object_class_install_property (object_class, PROP_ACTION_GROUP,
775     g_param_spec_object ("action-group",
776                          P_("Action group"),
777                          P_("The group of actions that the application exports"),
778                          G_TYPE_ACTION_GROUP,
779                          G_PARAM_DEPRECATED | G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
780
781   g_object_class_install_property (object_class, PROP_APP_MENU,
782     g_param_spec_object ("app-menu",
783                          P_("Application menu"),
784                          P_("The GMenuModel for the application menu"),
785                          G_TYPE_MENU_MODEL,
786                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
787
788   g_object_class_install_property (object_class, PROP_MENUBAR,
789     g_param_spec_object ("menubar",
790                          P_("Menubar"),
791                          P_("The GMenuModel for the menubar"),
792                          G_TYPE_MENU_MODEL,
793                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
794
795   /**
796    * GApplication::startup:
797    * @application: the application
798    *
799    * The ::startup signal is emitted on the primary instance immediately
800    * after registration. See g_application_register().
801    */
802   g_application_signals[SIGNAL_STARTUP] =
803     g_signal_new ("startup", G_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
804                   G_STRUCT_OFFSET (GApplicationClass, startup),
805                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
806
807   /**
808    * GApplication::shutdown:
809    * @application: the application
810    *
811    * The ::shutdown signal is emitted only on the registered primary instance
812    * immediately after the main loop terminates.
813    */
814   g_application_signals[SIGNAL_SHUTDOWN] =
815     g_signal_new ("shutdown", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
816                   G_STRUCT_OFFSET (GApplicationClass, shutdown),
817                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
818
819   /**
820    * GApplication::activate:
821    * @application: the application
822    *
823    * The ::activate signal is emitted on the primary instance when an
824    * activation occurs. See g_application_activate().
825    */
826   g_application_signals[SIGNAL_ACTIVATE] =
827     g_signal_new ("activate", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
828                   G_STRUCT_OFFSET (GApplicationClass, activate),
829                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
830
831
832   /**
833    * GApplication::open:
834    * @application: the application
835    * @files: (array length=n_files) (element-type GFile): an array of #GFiles
836    * @n_files: the length of @files
837    * @hint: a hint provided by the calling instance
838    *
839    * The ::open signal is emitted on the primary instance when there are
840    * files to open. See g_application_open() for more information.
841    */
842   g_application_signals[SIGNAL_OPEN] =
843     g_signal_new ("open", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
844                   G_STRUCT_OFFSET (GApplicationClass, open),
845                   NULL, NULL, NULL,
846                   G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_STRING);
847
848   /**
849    * GApplication::command-line:
850    * @application: the application
851    * @command_line: a #GApplicationCommandLine representing the
852    *     passed commandline
853    *
854    * The ::command-line signal is emitted on the primary instance when
855    * a commandline is not handled locally. See g_application_run() and
856    * the #GApplicationCommandline documentation for more information.
857    *
858    * Returns: An integer that is set as the exit status for the calling
859    *   process. See g_application_command_line_set_exit_status().
860    */
861   g_application_signals[SIGNAL_COMMAND_LINE] =
862     g_signal_new ("command-line", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
863                   G_STRUCT_OFFSET (GApplicationClass, command_line),
864                   g_signal_accumulator_first_wins, NULL,
865                   NULL,
866                   G_TYPE_INT, 1, G_TYPE_APPLICATION_COMMAND_LINE);
867
868   g_type_class_add_private (class, sizeof (GApplicationPrivate));
869 }
870
871 static GVariant *
872 get_platform_data (GApplication *application)
873 {
874   GVariantBuilder *builder;
875   GVariant *result;
876
877   builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
878
879   {
880     gchar *cwd = g_get_current_dir ();
881     g_variant_builder_add (builder, "{sv}", "cwd",
882                            g_variant_new_bytestring (cwd));
883     g_free (cwd);
884   }
885
886   if (application->priv->flags & G_APPLICATION_SEND_ENVIRONMENT)
887     {
888       GVariant *array;
889       gchar **envp;
890
891       envp = g_get_environ ();
892       array = g_variant_new_bytestring_array ((const gchar **) envp, -1);
893       g_strfreev (envp);
894
895       g_variant_builder_add (builder, "{sv}", "environ", array);
896     }
897
898   G_APPLICATION_GET_CLASS (application)->
899     add_platform_data (application, builder);
900
901   result = g_variant_builder_end (builder);
902   g_variant_builder_unref (builder);
903
904   return result;
905 }
906
907 /* Application ID validity {{{1 */
908
909 /**
910  * g_application_id_is_valid:
911  * @application_id: a potential application identifier
912  *
913  * Checks if @application_id is a valid application identifier.
914  *
915  * A valid ID is required for calls to g_application_new() and
916  * g_application_set_application_id().
917  *
918  * For convenience, the restrictions on application identifiers are
919  * reproduced here:
920  * <itemizedlist>
921  *   <listitem>Application identifiers must contain only the ASCII characters "[A-Z][a-z][0-9]_-." and must not begin with a digit.</listitem>
922  *   <listitem>Application identifiers must contain at least one '.' (period) character (and thus at least three elements).</listitem>
923  *   <listitem>Application identifiers must not begin or end with a '.' (period) character.</listitem>
924  *   <listitem>Application identifiers must not contain consecutive '.' (period) characters.</listitem>
925  *   <listitem>Application identifiers must not exceed 255 characters.</listitem>
926  * </itemizedlist>
927  *
928  * Returns: %TRUE if @application_id is valid
929  **/
930 gboolean
931 g_application_id_is_valid (const gchar *application_id)
932 {
933   gsize len;
934   gboolean allow_dot;
935   gboolean has_dot;
936
937   len = strlen (application_id);
938
939   if (len > 255)
940     return FALSE;
941
942   if (!g_ascii_isalpha (application_id[0]))
943     return FALSE;
944
945   if (application_id[len-1] == '.')
946     return FALSE;
947
948   application_id++;
949   allow_dot = TRUE;
950   has_dot = FALSE;
951   for (; *application_id; application_id++)
952     {
953       if (g_ascii_isalnum (*application_id) ||
954           (*application_id == '-') ||
955           (*application_id == '_'))
956         {
957           allow_dot = TRUE;
958         }
959       else if (allow_dot && *application_id == '.')
960         {
961           has_dot = TRUE;
962           allow_dot = FALSE;
963         }
964       else
965         return FALSE;
966     }
967
968   if (!has_dot)
969     return FALSE;
970
971   return TRUE;
972 }
973
974 /* Public Constructor {{{1 */
975 /**
976  * g_application_new:
977  * @application_id: the application id
978  * @flags: the application flags
979  *
980  * Creates a new #GApplication instance.
981  *
982  * This function calls g_type_init() for you.
983  *
984  * The application id must be valid.  See g_application_id_is_valid().
985  *
986  * Returns: a new #GApplication instance
987  **/
988 GApplication *
989 g_application_new (const gchar       *application_id,
990                    GApplicationFlags  flags)
991 {
992   g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);
993
994   g_type_init ();
995
996   return g_object_new (G_TYPE_APPLICATION,
997                        "application-id", application_id,
998                        "flags", flags,
999                        NULL);
1000 }
1001
1002 /* Simple get/set: application id, flags, inactivity timeout {{{1 */
1003 /**
1004  * g_application_get_application_id:
1005  * @application: a #GApplication
1006  *
1007  * Gets the unique identifier for @application.
1008  *
1009  * Returns: the identifier for @application, owned by @application
1010  *
1011  * Since: 2.28
1012  **/
1013 const gchar *
1014 g_application_get_application_id (GApplication *application)
1015 {
1016   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
1017
1018   return application->priv->id;
1019 }
1020
1021 /**
1022  * g_application_set_application_id:
1023  * @application: a #GApplication
1024  * @application_id: the identifier for @application
1025  *
1026  * Sets the unique identifier for @application.
1027  *
1028  * The application id can only be modified if @application has not yet
1029  * been registered.
1030  *
1031  * The application id must be valid.  See g_application_id_is_valid().
1032  *
1033  * Since: 2.28
1034  **/
1035 void
1036 g_application_set_application_id (GApplication *application,
1037                                   const gchar  *application_id)
1038 {
1039   g_return_if_fail (G_IS_APPLICATION (application));
1040
1041   if (g_strcmp0 (application->priv->id, application_id) != 0)
1042     {
1043       g_return_if_fail (g_application_id_is_valid (application_id));
1044       g_return_if_fail (!application->priv->is_registered);
1045
1046       g_free (application->priv->id);
1047       application->priv->id = g_strdup (application_id);
1048
1049       g_object_notify (G_OBJECT (application), "application-id");
1050     }
1051 }
1052
1053 /**
1054  * g_application_get_flags:
1055  * @application: a #GApplication
1056  *
1057  * Gets the flags for @application.
1058  *
1059  * See #GApplicationFlags.
1060  *
1061  * Returns: the flags for @application
1062  *
1063  * Since: 2.28
1064  **/
1065 GApplicationFlags
1066 g_application_get_flags (GApplication *application)
1067 {
1068   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1069
1070   return application->priv->flags;
1071 }
1072
1073 /**
1074  * g_application_set_flags:
1075  * @application: a #GApplication
1076  * @flags: the flags for @application
1077  *
1078  * Sets the flags for @application.
1079  *
1080  * The flags can only be modified if @application has not yet been
1081  * registered.
1082  *
1083  * See #GApplicationFlags.
1084  *
1085  * Since: 2.28
1086  **/
1087 void
1088 g_application_set_flags (GApplication      *application,
1089                          GApplicationFlags  flags)
1090 {
1091   g_return_if_fail (G_IS_APPLICATION (application));
1092
1093   if (application->priv->flags != flags)
1094     {
1095       g_return_if_fail (!application->priv->is_registered);
1096
1097       application->priv->flags = flags;
1098
1099       g_object_notify (G_OBJECT (application), "flags");
1100     }
1101 }
1102
1103 /**
1104  * g_application_get_inactivity_timeout:
1105  * @application: a #GApplication
1106  *
1107  * Gets the current inactivity timeout for the application.
1108  *
1109  * This is the amount of time (in milliseconds) after the last call to
1110  * g_application_release() before the application stops running.
1111  *
1112  * Returns: the timeout, in milliseconds
1113  *
1114  * Since: 2.28
1115  **/
1116 guint
1117 g_application_get_inactivity_timeout (GApplication *application)
1118 {
1119   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1120
1121   return application->priv->inactivity_timeout;
1122 }
1123
1124 /**
1125  * g_application_set_inactivity_timeout:
1126  * @application: a #GApplication
1127  * @inactivity_timeout: the timeout, in milliseconds
1128  *
1129  * Sets the current inactivity timeout for the application.
1130  *
1131  * This is the amount of time (in milliseconds) after the last call to
1132  * g_application_release() before the application stops running.
1133  *
1134  * This call has no side effects of its own.  The value set here is only
1135  * used for next time g_application_release() drops the use count to
1136  * zero.  Any timeouts currently in progress are not impacted.
1137  *
1138  * Since: 2.28
1139  **/
1140 void
1141 g_application_set_inactivity_timeout (GApplication *application,
1142                                       guint         inactivity_timeout)
1143 {
1144   g_return_if_fail (G_IS_APPLICATION (application));
1145
1146   if (application->priv->inactivity_timeout != inactivity_timeout)
1147     {
1148       application->priv->inactivity_timeout = inactivity_timeout;
1149
1150       g_object_notify (G_OBJECT (application), "inactivity-timeout");
1151     }
1152 }
1153 /* Read-only property getters (is registered, is remote) {{{1 */
1154 /**
1155  * g_application_get_is_registered:
1156  * @application: a #GApplication
1157  *
1158  * Checks if @application is registered.
1159  *
1160  * An application is registered if g_application_register() has been
1161  * successfully called.
1162  *
1163  * Returns: %TRUE if @application is registered
1164  *
1165  * Since: 2.28
1166  **/
1167 gboolean
1168 g_application_get_is_registered (GApplication *application)
1169 {
1170   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1171
1172   return application->priv->is_registered;
1173 }
1174
1175 /**
1176  * g_application_get_is_remote:
1177  * @application: a #GApplication
1178  *
1179  * Checks if @application is remote.
1180  *
1181  * If @application is remote then it means that another instance of
1182  * application already exists (the 'primary' instance).  Calls to
1183  * perform actions on @application will result in the actions being
1184  * performed by the primary instance.
1185  *
1186  * The value of this property cannot be accessed before
1187  * g_application_register() has been called.  See
1188  * g_application_get_is_registered().
1189  *
1190  * Returns: %TRUE if @application is remote
1191  *
1192  * Since: 2.28
1193  **/
1194 gboolean
1195 g_application_get_is_remote (GApplication *application)
1196 {
1197   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1198   g_return_val_if_fail (application->priv->is_registered, FALSE);
1199
1200   return application->priv->is_remote;
1201 }
1202
1203 /* Register {{{1 */
1204 /**
1205  * g_application_register:
1206  * @application: a #GApplication
1207  * @cancellable: a #GCancellable, or %NULL
1208  * @error: a pointer to a NULL #GError, or %NULL
1209  *
1210  * Attempts registration of the application.
1211  *
1212  * This is the point at which the application discovers if it is the
1213  * primary instance or merely acting as a remote for an already-existing
1214  * primary instance.  This is implemented by attempting to acquire the
1215  * application identifier as a unique bus name on the session bus using
1216  * GDBus.
1217  *
1218  * Due to the internal architecture of GDBus, method calls can be
1219  * dispatched at any time (even if a main loop is not running).  For
1220  * this reason, you must ensure that any object paths that you wish to
1221  * register are registered before calling this function.
1222  *
1223  * If the application has already been registered then %TRUE is
1224  * returned with no work performed.
1225  *
1226  * The #GApplication::startup signal is emitted if registration succeeds
1227  * and @application is the primary instance.
1228  *
1229  * In the event of an error (such as @cancellable being cancelled, or a
1230  * failure to connect to the session bus), %FALSE is returned and @error
1231  * is set appropriately.
1232  *
1233  * Note: the return value of this function is not an indicator that this
1234  * instance is or is not the primary instance of the application.  See
1235  * g_application_get_is_remote() for that.
1236  *
1237  * Returns: %TRUE if registration succeeded
1238  *
1239  * Since: 2.28
1240  **/
1241 gboolean
1242 g_application_register (GApplication  *application,
1243                         GCancellable  *cancellable,
1244                         GError       **error)
1245 {
1246   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1247
1248   if (!application->priv->is_registered)
1249     {
1250       if (~application->priv->flags & G_APPLICATION_NON_UNIQUE)
1251         {
1252           application->priv->impl =
1253             g_application_impl_register (application, application->priv->id,
1254                                          application->priv->flags,
1255                                          &application->priv->remote_actions,
1256                                          cancellable, error);
1257
1258           if (application->priv->impl == NULL)
1259             return FALSE;
1260         }
1261
1262       application->priv->is_remote = application->priv->remote_actions != NULL;
1263       application->priv->is_registered = TRUE;
1264
1265       g_object_notify (G_OBJECT (application), "is-registered");
1266
1267       if (!application->priv->is_remote)
1268         {
1269           g_signal_emit (application, g_application_signals[SIGNAL_STARTUP], 0);
1270
1271           if (!application->priv->did_startup)
1272             g_critical ("GApplication subclass '%s' failed to chain up on"
1273                         " ::startup (from start of override function)",
1274                         G_OBJECT_TYPE_NAME (application));
1275         }
1276     }
1277
1278   return TRUE;
1279 }
1280
1281 /* Hold/release {{{1 */
1282 /**
1283  * g_application_hold:
1284  * @application: a #GApplication
1285  *
1286  * Increases the use count of @application.
1287  *
1288  * Use this function to indicate that the application has a reason to
1289  * continue to run.  For example, g_application_hold() is called by GTK+
1290  * when a toplevel window is on the screen.
1291  *
1292  * To cancel the hold, call g_application_release().
1293  **/
1294 void
1295 g_application_hold (GApplication *application)
1296 {
1297   if (application->priv->inactivity_timeout_id)
1298     {
1299       g_source_remove (application->priv->inactivity_timeout_id);
1300       application->priv->inactivity_timeout_id = 0;
1301     }
1302
1303   application->priv->use_count++;
1304 }
1305
1306 static gboolean
1307 inactivity_timeout_expired (gpointer data)
1308 {
1309   GApplication *application = G_APPLICATION (data);
1310
1311   application->priv->inactivity_timeout_id = 0;
1312
1313   return FALSE;
1314 }
1315
1316
1317 /**
1318  * g_application_release:
1319  * @application: a #GApplication
1320  *
1321  * Decrease the use count of @application.
1322  *
1323  * When the use count reaches zero, the application will stop running.
1324  *
1325  * Never call this function except to cancel the effect of a previous
1326  * call to g_application_hold().
1327  **/
1328 void
1329 g_application_release (GApplication *application)
1330 {
1331   application->priv->use_count--;
1332
1333   if (application->priv->use_count == 0 && application->priv->inactivity_timeout)
1334     application->priv->inactivity_timeout_id = g_timeout_add (application->priv->inactivity_timeout,
1335                                                               inactivity_timeout_expired, application);
1336 }
1337
1338 /* Activate, Open {{{1 */
1339 /**
1340  * g_application_activate:
1341  * @application: a #GApplication
1342  *
1343  * Activates the application.
1344  *
1345  * In essence, this results in the #GApplication::activate() signal being
1346  * emitted in the primary instance.
1347  *
1348  * The application must be registered before calling this function.
1349  *
1350  * Since: 2.28
1351  **/
1352 void
1353 g_application_activate (GApplication *application)
1354 {
1355   g_return_if_fail (G_IS_APPLICATION (application));
1356   g_return_if_fail (application->priv->is_registered);
1357
1358   if (application->priv->is_remote)
1359     g_application_impl_activate (application->priv->impl,
1360                                  get_platform_data (application));
1361
1362   else
1363     g_signal_emit (application, g_application_signals[SIGNAL_ACTIVATE], 0);
1364 }
1365
1366 /**
1367  * g_application_open:
1368  * @application: a #GApplication
1369  * @files: (array length=n_files): an array of #GFiles to open
1370  * @n_files: the length of the @files array
1371  * @hint: a hint (or ""), but never %NULL
1372  *
1373  * Opens the given files.
1374  *
1375  * In essence, this results in the #GApplication::open signal being emitted
1376  * in the primary instance.
1377  *
1378  * @n_files must be greater than zero.
1379  *
1380  * @hint is simply passed through to the ::open signal.  It is
1381  * intended to be used by applications that have multiple modes for
1382  * opening files (eg: "view" vs "edit", etc).  Unless you have a need
1383  * for this functionality, you should use "".
1384  *
1385  * The application must be registered before calling this function
1386  * and it must have the %G_APPLICATION_HANDLES_OPEN flag set.
1387  *
1388  * Since: 2.28
1389  **/
1390 void
1391 g_application_open (GApplication  *application,
1392                     GFile        **files,
1393                     gint           n_files,
1394                     const gchar   *hint)
1395 {
1396   g_return_if_fail (G_IS_APPLICATION (application));
1397   g_return_if_fail (application->priv->flags &
1398                     G_APPLICATION_HANDLES_OPEN);
1399   g_return_if_fail (application->priv->is_registered);
1400
1401   if (application->priv->is_remote)
1402     g_application_impl_open (application->priv->impl,
1403                              files, n_files, hint,
1404                              get_platform_data (application));
1405
1406   else
1407     g_signal_emit (application, g_application_signals[SIGNAL_OPEN],
1408                    0, files, n_files, hint);
1409 }
1410
1411 /* Run {{{1 */
1412 /**
1413  * g_application_run:
1414  * @application: a #GApplication
1415  * @argc: the argc from main() (or 0 if @argv is %NULL)
1416  * @argv: (array length=argc) (allow-none): the argv from main(), or %NULL
1417  *
1418  * Runs the application.
1419  *
1420  * This function is intended to be run from main() and its return value
1421  * is intended to be returned by main(). Although you are expected to pass
1422  * the @argc, @argv parameters from main() to this function, it is possible
1423  * to pass %NULL if @argv is not available or commandline handling is not
1424  * required.
1425  *
1426  * First, the local_command_line() virtual function is invoked.
1427  * This function always runs on the local instance. It gets passed a pointer
1428  * to a %NULL-terminated copy of @argv and is expected to remove the arguments
1429  * that it handled (shifting up remaining arguments). See
1430  * <xref linkend="gapplication-example-cmdline2"/> for an example of
1431  * parsing @argv manually. Alternatively, you may use the #GOptionContext API,
1432  * after setting <literal>argc = g_strv_length (argv);</literal>.
1433  *
1434  * The last argument to local_command_line() is a pointer to the @status
1435  * variable which can used to set the exit status that is returned from
1436  * g_application_run().
1437  *
1438  * If local_command_line() returns %TRUE, the command line is expected
1439  * to be completely handled, including possibly registering as the primary
1440  * instance, calling g_application_activate() or g_application_open(), etc.
1441  *
1442  * If local_command_line() returns %FALSE then the application is registered
1443  * and the #GApplication::command-line signal is emitted in the primary
1444  * instance (which may or may not be this instance). The signal handler
1445  * gets passed a #GApplicationCommandline object that (among other things)
1446  * contains the remaining commandline arguments that have not been handled
1447  * by local_command_line().
1448  *
1449  * If the application has the %G_APPLICATION_HANDLES_COMMAND_LINE
1450  * flag set then the default implementation of local_command_line()
1451  * always returns %FALSE immediately, resulting in the commandline
1452  * always being handled in the primary instance.
1453  *
1454  * Otherwise, the default implementation of local_command_line() tries
1455  * to do a couple of things that are probably reasonable for most
1456  * applications.  First, g_application_register() is called to attempt
1457  * to register the application.  If that works, then the command line
1458  * arguments are inspected.  If no commandline arguments are given, then
1459  * g_application_activate() is called.  If commandline arguments are
1460  * given and the %G_APPLICATION_HANDLES_OPEN flag is set then they
1461  * are assumed to be filenames and g_application_open() is called.
1462  *
1463  * If you need to handle commandline arguments that are not filenames,
1464  * and you don't mind commandline handling to happen in the primary
1465  * instance, you should set %G_APPLICATION_HANDLED_COMMAND_LINE and
1466  * process the commandline arguments in your #GApplication::command-line
1467  * signal handler, either manually or using the #GOptionContext API.
1468  *
1469  * If you are interested in doing more complicated local handling of the
1470  * commandline then you should implement your own #GApplication subclass
1471  * and override local_command_line(). In this case, you most likely want
1472  * to return %TRUE from your local_command_line() implementation to
1473  * suppress the default handling. See
1474  * <xref linkend="gapplication-example-cmdline2"/> for an example.
1475  *
1476  * If, after the above is done, the use count of the application is zero
1477  * then the exit status is returned immediately.  If the use count is
1478  * non-zero then the default main context is iterated until the use count
1479  * falls to zero, at which point 0 is returned.
1480  *
1481  * If the %G_APPLICATION_IS_SERVICE flag is set, then the exiting at
1482  * use count of zero is delayed for a while (ie: the instance stays
1483  * around to provide its <emphasis>service</emphasis> to others).
1484  *
1485  * Returns: the exit status
1486  *
1487  * Since: 2.28
1488  **/
1489 int
1490 g_application_run (GApplication  *application,
1491                    int            argc,
1492                    char         **argv)
1493 {
1494   gchar **arguments;
1495   int status;
1496   gint i;
1497
1498   g_return_val_if_fail (G_IS_APPLICATION (application), 1);
1499   g_return_val_if_fail (argc == 0 || argv != NULL, 1);
1500
1501   arguments = g_new (gchar *, argc + 1);
1502   for (i = 0; i < argc; i++)
1503     arguments[i] = g_strdup (argv[i]);
1504   arguments[i] = NULL;
1505
1506   if (g_get_prgname () == NULL && argc > 0)
1507     {
1508       gchar *prgname;
1509
1510       prgname = g_path_get_basename (argv[0]);
1511       g_set_prgname (prgname);
1512       g_free (prgname);
1513     }
1514
1515   if (!G_APPLICATION_GET_CLASS (application)
1516         ->local_command_line (application, &arguments, &status))
1517     {
1518       GError *error = NULL;
1519
1520       if (!g_application_register (application, NULL, &error))
1521         {
1522           g_printerr ("%s", error->message);
1523           g_error_free (error);
1524           return 1;
1525         }
1526
1527       if (application->priv->is_remote)
1528         {
1529           GVariant *platform_data;
1530
1531           platform_data = get_platform_data (application);
1532           status = g_application_impl_command_line (application->priv->impl,
1533                                                     arguments, platform_data);
1534         }
1535       else
1536         {
1537           GApplicationCommandLine *cmdline;
1538           GVariant *v;
1539
1540           v = g_variant_new_bytestring_array ((const gchar **) arguments, -1);
1541           cmdline = g_object_new (G_TYPE_APPLICATION_COMMAND_LINE,
1542                                   "arguments", v, NULL);
1543           g_signal_emit (application,
1544                          g_application_signals[SIGNAL_COMMAND_LINE],
1545                          0, cmdline, &status);
1546           g_object_unref (cmdline);
1547         }
1548     }
1549
1550   g_strfreev (arguments);
1551
1552   if (application->priv->flags & G_APPLICATION_IS_SERVICE &&
1553       application->priv->is_registered &&
1554       !application->priv->use_count &&
1555       !application->priv->inactivity_timeout_id)
1556     {
1557       application->priv->inactivity_timeout_id =
1558         g_timeout_add (10000, inactivity_timeout_expired, application);
1559     }
1560
1561   while (application->priv->use_count || application->priv->inactivity_timeout_id)
1562     {
1563       g_main_context_iteration (NULL, TRUE);
1564       status = 0;
1565     }
1566
1567   if (!application->priv->is_remote)
1568     {
1569       g_signal_emit (application, g_application_signals[SIGNAL_SHUTDOWN], 0);
1570
1571       if (!application->priv->did_shutdown)
1572         g_critical ("GApplication subclass '%s' failed to chain up on"
1573                     " ::shutdown (from end of override function)",
1574                     G_OBJECT_TYPE_NAME (application));
1575     }
1576
1577   if (application->priv->impl)
1578     g_application_impl_flush (application->priv->impl);
1579
1580   g_settings_sync ();
1581
1582   return status;
1583 }
1584
1585 static gchar **
1586 g_application_list_actions (GActionGroup *action_group)
1587 {
1588   GApplication *application = G_APPLICATION (action_group);
1589
1590   g_return_val_if_fail (application->priv->is_registered, NULL);
1591
1592   if (application->priv->remote_actions != NULL)
1593     return g_action_group_list_actions (application->priv->remote_actions);
1594
1595   else if (application->priv->actions != NULL)
1596     return g_action_group_list_actions (application->priv->actions);
1597
1598   else
1599     /* empty string array */
1600     return g_new0 (gchar *, 1);
1601 }
1602
1603 static gboolean
1604 g_application_query_action (GActionGroup        *group,
1605                             const gchar         *action_name,
1606                             gboolean            *enabled,
1607                             const GVariantType **parameter_type,
1608                             const GVariantType **state_type,
1609                             GVariant           **state_hint,
1610                             GVariant           **state)
1611 {
1612   GApplication *application = G_APPLICATION (group);
1613
1614   g_return_val_if_fail (application->priv->is_registered, FALSE);
1615
1616   if (application->priv->remote_actions != NULL)
1617     return g_action_group_query_action (application->priv->remote_actions,
1618                                         action_name,
1619                                         enabled,
1620                                         parameter_type,
1621                                         state_type,
1622                                         state_hint,
1623                                         state);
1624
1625   if (application->priv->actions != NULL)
1626     return g_action_group_query_action (application->priv->actions,
1627                                         action_name,
1628                                         enabled,
1629                                         parameter_type,
1630                                         state_type,
1631                                         state_hint,
1632                                         state);
1633
1634   return FALSE;
1635 }
1636
1637 static void
1638 g_application_change_action_state (GActionGroup *action_group,
1639                                    const gchar  *action_name,
1640                                    GVariant     *value)
1641 {
1642   GApplication *application = G_APPLICATION (action_group);
1643
1644   g_return_if_fail (application->priv->is_remote ||
1645                     application->priv->actions != NULL);
1646   g_return_if_fail (application->priv->is_registered);
1647
1648   if (application->priv->remote_actions)
1649     g_application_impl_change_action_state (application->priv->impl, action_name, value,
1650                                             get_platform_data (application));
1651
1652   else
1653     g_action_group_change_action_state (application->priv->actions, action_name, value);
1654 }
1655
1656 static void
1657 g_application_activate_action (GActionGroup *action_group,
1658                                const gchar  *action_name,
1659                                GVariant     *parameter)
1660 {
1661   GApplication *application = G_APPLICATION (action_group);
1662
1663   g_return_if_fail (application->priv->is_remote ||
1664                     application->priv->actions != NULL);
1665   g_return_if_fail (application->priv->is_registered);
1666
1667   if (application->priv->is_remote)
1668     g_application_impl_activate_action (application->priv->impl, action_name, parameter,
1669                                         get_platform_data (application));
1670
1671   else
1672     g_action_group_activate_action (application->priv->actions, action_name, parameter);
1673 }
1674
1675 static GAction *
1676 g_application_lookup_action (GActionMap  *action_map,
1677                              const gchar *action_name)
1678 {
1679   GApplication *application = G_APPLICATION (action_map);
1680
1681   g_return_val_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions), NULL);
1682
1683   return g_simple_action_group_lookup (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1684 }
1685
1686 static void
1687 g_application_add_action (GActionMap *action_map,
1688                           GAction    *action)
1689 {
1690   GApplication *application = G_APPLICATION (action_map);
1691
1692   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1693
1694   g_simple_action_group_insert (G_SIMPLE_ACTION_GROUP (application->priv->actions), action);
1695 }
1696
1697 static void
1698 g_application_remove_action (GActionMap  *action_map,
1699                              const gchar *action_name)
1700 {
1701   GApplication *application = G_APPLICATION (action_map);
1702
1703   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1704
1705   g_simple_action_group_remove (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1706 }
1707
1708 static void
1709 g_application_action_group_iface_init (GActionGroupInterface *iface)
1710 {
1711   iface->list_actions = g_application_list_actions;
1712   iface->query_action = g_application_query_action;
1713   iface->change_action_state = g_application_change_action_state;
1714   iface->activate_action = g_application_activate_action;
1715 }
1716
1717 static void
1718 g_application_action_map_iface_init (GActionMapInterface *iface)
1719 {
1720   iface->lookup_action = g_application_lookup_action;
1721   iface->add_action = g_application_add_action;
1722   iface->remove_action = g_application_remove_action;
1723 }
1724
1725 /* Default Application {{{1 */
1726
1727 static GApplication *default_app;
1728
1729 /**
1730  * g_application_get_default:
1731  * @returns: (transfer none): the default application for this process, or %NULL
1732  *
1733  * Returns the default #GApplication instance for this process.
1734  *
1735  * Normally there is only one #GApplication per process and it becomes
1736  * the default when it is created.  You can exercise more control over
1737  * this by using g_application_set_default().
1738  *
1739  * If there is no default application then %NULL is returned.
1740  *
1741  * Since: 2.32
1742  **/
1743 GApplication *
1744 g_application_get_default (void)
1745 {
1746   return default_app;
1747 }
1748
1749 /**
1750  * g_application_set_default:
1751  * @application: the application to set as default, or %NULL
1752  *
1753  * Sets or unsets the default application for the process, as returned
1754  * by g_application_get_default().
1755  *
1756  * This function does not take its own reference on @application.  If
1757  * @application is destroyed then the default application will revert
1758  * back to %NULL.
1759  *
1760  * Since: 2.32
1761  **/
1762 void
1763 g_application_set_default (GApplication *application)
1764 {
1765   default_app = application;
1766 }
1767
1768 /* Epilogue {{{1 */
1769 /* vim:set foldmethod=marker: */