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