GApplication: fix a copy-paste error
[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.
479  **/
480 void
481 g_application_set_action_group (GApplication *application,
482                                 GActionGroup *action_group)
483 {
484   g_return_if_fail (G_IS_APPLICATION (application));
485   g_return_if_fail (!application->priv->is_registered);
486
487   if (application->priv->actions != NULL)
488     g_object_unref (application->priv->actions);
489
490   application->priv->actions = action_group;
491
492   if (application->priv->actions != NULL)
493     g_object_ref (application->priv->actions);
494 }
495
496 /**
497  * g_application_set_app_menu:
498  * @application: a #GApplication
499  * @app_menu: (allow-none): a #GMenuModel, or %NULL
500  *
501  * Sets or unsets the application menu for @application.
502  *
503  * The application menu is a single menu containing items that typically
504  * impact the application as a whole, rather than acting on a specific
505  * window or document.  For example, you would expect to see
506  * "Preferences" or "Quit" in an application menu, but not "Save" or
507  * "Print".
508  *
509  * If supported, the application menu will be rendered by the desktop
510  * environment.
511  *
512  * Since: 2.32
513  */
514 void
515 g_application_set_app_menu (GApplication *application,
516                             GMenuModel   *app_menu)
517 {
518   g_return_if_fail (G_IS_APPLICATION (application));
519
520   if (app_menu != application->priv->app_menu)
521     {
522       if (application->priv->app_menu != NULL)
523         g_object_unref (application->priv->app_menu);
524
525       application->priv->app_menu = app_menu;
526
527       if (application->priv->app_menu != NULL)
528         g_object_ref (application->priv->app_menu);
529
530       g_object_notify (G_OBJECT (application), "app-menu");
531     }
532 }
533
534 /**
535  * g_application_get_app_menu:
536  * @application: a #GApplication
537  *
538  * Returns the menu model that has been set with
539  * g_application_set_app_menu().
540  *
541  * Returns: the application menu of @application
542  *
543  * Since: 2.32
544  */
545 GMenuModel *
546 g_application_get_app_menu (GApplication *application)
547 {
548   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
549
550   return application->priv->app_menu;
551 }
552
553 /**
554  * g_application_set_menubar:
555  * @application: a #GApplication
556  * @menubar: (allow-none): a #GMenuModel, or %NULL
557  *
558  * Sets or unsets the menubar for windows of @application.
559  *
560  * This is a menubar in the traditional sense.
561  *
562  * Depending on the desktop environment, this may appear at the top of
563  * each window, or at the top of the screen.  In some environments, if
564  * both the application menu and the menubar are set, the application
565  * menu will be presented as if it were the first item of the menubar.
566  * Other environments treat the two as completely separate -- for
567  * example, the application menu may be rendered by the desktop shell
568  * while the menubar (if set) remains in each individual window.
569  *
570  * Since: 2.32
571  */
572 void
573 g_application_set_menubar (GApplication *application,
574                             GMenuModel   *menubar)
575 {
576   g_return_if_fail (G_IS_APPLICATION (application));
577
578   if (menubar != application->priv->menubar)
579     {
580       if (application->priv->menubar != NULL)
581         g_object_unref (application->priv->menubar);
582
583       application->priv->menubar = menubar;
584
585       if (application->priv->menubar != NULL)
586         g_object_ref (application->priv->menubar);
587
588       g_object_notify (G_OBJECT (application), "menubar");
589     }
590 }
591
592 /**
593  * g_application_get_menubar:
594  * @application: a #GApplication
595  *
596  * Returns the menu model that has been set with
597  * g_application_set_menubar().
598  *
599  * Returns: the menubar for windows of @application
600  *
601  * Since: 2.32
602  */
603 GMenuModel *
604 g_application_get_menubar (GApplication *application)
605 {
606   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
607
608   return application->priv->menubar;
609 }
610
611 static void
612 g_application_get_property (GObject    *object,
613                             guint       prop_id,
614                             GValue     *value,
615                             GParamSpec *pspec)
616 {
617   GApplication *application = G_APPLICATION (object);
618
619   switch (prop_id)
620     {
621     case PROP_APPLICATION_ID:
622       g_value_set_string (value,
623                           g_application_get_application_id (application));
624       break;
625
626     case PROP_FLAGS:
627       g_value_set_flags (value,
628                          g_application_get_flags (application));
629       break;
630
631     case PROP_IS_REGISTERED:
632       g_value_set_boolean (value,
633                            g_application_get_is_registered (application));
634       break;
635
636     case PROP_IS_REMOTE:
637       g_value_set_boolean (value,
638                            g_application_get_is_remote (application));
639       break;
640
641     case PROP_INACTIVITY_TIMEOUT:
642       g_value_set_uint (value,
643                         g_application_get_inactivity_timeout (application));
644       break;
645
646     case PROP_APP_MENU:
647       g_value_set_object (value,
648                           g_application_get_app_menu (application));
649       break;
650
651     case PROP_MENUBAR:
652       g_value_set_object (value,
653                           g_application_get_menubar (application));
654       break;
655
656     default:
657       g_assert_not_reached ();
658     }
659 }
660
661 static void
662 g_application_constructed (GObject *object)
663 {
664   GApplication *application = G_APPLICATION (object);
665
666   g_assert (application->priv->id != NULL);
667
668   if (g_application_get_default () == NULL)
669     g_application_set_default (application);
670 }
671
672 static void
673 g_application_finalize (GObject *object)
674 {
675   GApplication *application = G_APPLICATION (object);
676
677   if (application->priv->impl)
678     g_application_impl_destroy (application->priv->impl);
679   g_free (application->priv->id);
680
681   if (g_application_get_default () == application)
682     g_application_set_default (NULL);
683
684   if (application->priv->app_menu)
685     g_object_unref (application->priv->app_menu);
686
687   if (application->priv->menubar)
688     g_object_unref (application->priv->menubar);
689
690   if (application->priv->actions)
691     g_object_unref (application->priv->actions);
692
693   G_OBJECT_CLASS (g_application_parent_class)
694     ->finalize (object);
695 }
696
697 static void
698 g_application_init (GApplication *application)
699 {
700   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application,
701                                                    G_TYPE_APPLICATION,
702                                                    GApplicationPrivate);
703   application->priv->actions = G_ACTION_GROUP (g_simple_action_group_new ());
704 }
705
706 static void
707 g_application_class_init (GApplicationClass *class)
708 {
709   GObjectClass *object_class = G_OBJECT_CLASS (class);
710
711   object_class->constructed = g_application_constructed;
712   object_class->finalize = g_application_finalize;
713   object_class->get_property = g_application_get_property;
714   object_class->set_property = g_application_set_property;
715
716   class->before_emit = g_application_real_before_emit;
717   class->after_emit = g_application_real_after_emit;
718   class->startup = g_application_real_startup;
719   class->shutdown = g_application_real_shutdown;
720   class->activate = g_application_real_activate;
721   class->open = g_application_real_open;
722   class->command_line = g_application_real_command_line;
723   class->local_command_line = g_application_real_local_command_line;
724   class->add_platform_data = g_application_real_add_platform_data;
725
726   g_object_class_install_property (object_class, PROP_APPLICATION_ID,
727     g_param_spec_string ("application-id",
728                          P_("Application identifier"),
729                          P_("The unique identifier for the application"),
730                          NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
731                          G_PARAM_STATIC_STRINGS));
732
733   g_object_class_install_property (object_class, PROP_FLAGS,
734     g_param_spec_flags ("flags",
735                         P_("Application flags"),
736                         P_("Flags specifying the behaviour of the application"),
737                         G_TYPE_APPLICATION_FLAGS, G_APPLICATION_FLAGS_NONE,
738                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
739
740   g_object_class_install_property (object_class, PROP_IS_REGISTERED,
741     g_param_spec_boolean ("is-registered",
742                           P_("Is registered"),
743                           P_("If g_application_register() has been called"),
744                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
745
746   g_object_class_install_property (object_class, PROP_IS_REMOTE,
747     g_param_spec_boolean ("is-remote",
748                           P_("Is remote"),
749                           P_("If this application instance is remote"),
750                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
751
752   g_object_class_install_property (object_class, PROP_INACTIVITY_TIMEOUT,
753     g_param_spec_uint ("inactivity-timeout",
754                        P_("Inactivity timeout"),
755                        P_("Time (ms) to stay alive after becoming idle"),
756                        0, G_MAXUINT, 0,
757                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
758
759   g_object_class_install_property (object_class, PROP_ACTION_GROUP,
760     g_param_spec_object ("action-group",
761                          P_("Action group"),
762                          P_("The group of actions that the application exports"),
763                          G_TYPE_ACTION_GROUP,
764                          G_PARAM_DEPRECATED | G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
765
766   g_object_class_install_property (object_class, PROP_APP_MENU,
767     g_param_spec_object ("app-menu",
768                          P_("Application menu"),
769                          P_("The GMenuModel for the application menu"),
770                          G_TYPE_MENU_MODEL,
771                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
772
773   g_object_class_install_property (object_class, PROP_MENUBAR,
774     g_param_spec_object ("menubar",
775                          P_("Menubar"),
776                          P_("The GMenuModel for the menubar"),
777                          G_TYPE_MENU_MODEL,
778                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
779
780   /**
781    * GApplication::startup:
782    * @application: the application
783    *
784    * The ::startup signal is emitted on the primary instance immediately
785    * after registration. See g_application_register().
786    */
787   g_application_signals[SIGNAL_STARTUP] =
788     g_signal_new ("startup", G_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
789                   G_STRUCT_OFFSET (GApplicationClass, startup),
790                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
791
792   /**
793    * GApplication::shutdown:
794    * @application: the application
795    *
796    * The ::shutdown signal is emitted only on the registered primary instance
797    * immediately after the main loop terminates.
798    */
799   g_application_signals[SIGNAL_SHUTDOWN] =
800     g_signal_new ("shutdown", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
801                   G_STRUCT_OFFSET (GApplicationClass, shutdown),
802                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
803
804   /**
805    * GApplication::activate:
806    * @application: the application
807    *
808    * The ::activate signal is emitted on the primary instance when an
809    * activation occurs. See g_application_activate().
810    */
811   g_application_signals[SIGNAL_ACTIVATE] =
812     g_signal_new ("activate", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
813                   G_STRUCT_OFFSET (GApplicationClass, activate),
814                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
815
816
817   /**
818    * GApplication::open:
819    * @application: the application
820    * @files: (array length=n_files) (element-type GFile): an array of #GFiles
821    * @n_files: the length of @files
822    * @hint: a hint provided by the calling instance
823    *
824    * The ::open signal is emitted on the primary instance when there are
825    * files to open. See g_application_open() for more information.
826    */
827   g_application_signals[SIGNAL_OPEN] =
828     g_signal_new ("open", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
829                   G_STRUCT_OFFSET (GApplicationClass, open),
830                   NULL, NULL, NULL,
831                   G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_STRING);
832
833   /**
834    * GApplication::command-line:
835    * @application: the application
836    * @command_line: a #GApplicationCommandLine representing the
837    *     passed commandline
838    *
839    * The ::command-line signal is emitted on the primary instance when
840    * a commandline is not handled locally. See g_application_run() and
841    * the #GApplicationCommandline documentation for more information.
842    *
843    * Returns: An integer that is set as the exit status for the calling
844    *   process. See g_application_command_line_set_exit_status().
845    */
846   g_application_signals[SIGNAL_COMMAND_LINE] =
847     g_signal_new ("command-line", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
848                   G_STRUCT_OFFSET (GApplicationClass, command_line),
849                   g_signal_accumulator_first_wins, NULL,
850                   NULL,
851                   G_TYPE_INT, 1, G_TYPE_APPLICATION_COMMAND_LINE);
852
853   g_type_class_add_private (class, sizeof (GApplicationPrivate));
854 }
855
856 static GVariant *
857 get_platform_data (GApplication *application)
858 {
859   GVariantBuilder *builder;
860   GVariant *result;
861
862   builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
863
864   {
865     gchar *cwd = g_get_current_dir ();
866     g_variant_builder_add (builder, "{sv}", "cwd",
867                            g_variant_new_bytestring (cwd));
868     g_free (cwd);
869   }
870
871   if (application->priv->flags & G_APPLICATION_SEND_ENVIRONMENT)
872     {
873       GVariant *array;
874       gchar **envp;
875
876       envp = g_get_environ ();
877       array = g_variant_new_bytestring_array ((const gchar **) envp, -1);
878       g_strfreev (envp);
879
880       g_variant_builder_add (builder, "{sv}", "environ", array);
881     }
882
883   G_APPLICATION_GET_CLASS (application)->
884     add_platform_data (application, builder);
885
886   result = g_variant_builder_end (builder);
887   g_variant_builder_unref (builder);
888
889   return result;
890 }
891
892 /* Application ID validity {{{1 */
893
894 /**
895  * g_application_id_is_valid:
896  * @application_id: a potential application identifier
897  *
898  * Checks if @application_id is a valid application identifier.
899  *
900  * A valid ID is required for calls to g_application_new() and
901  * g_application_set_application_id().
902  *
903  * For convenience, the restrictions on application identifiers are
904  * reproduced here:
905  * <itemizedlist>
906  *   <listitem>Application identifiers must contain only the ASCII characters "[A-Z][a-z][0-9]_-." and must not begin with a digit.</listitem>
907  *   <listitem>Application identifiers must contain at least one '.' (period) character (and thus at least three elements).</listitem>
908  *   <listitem>Application identifiers must not begin or end with a '.' (period) character.</listitem>
909  *   <listitem>Application identifiers must not contain consecutive '.' (period) characters.</listitem>
910  *   <listitem>Application identifiers must not exceed 255 characters.</listitem>
911  * </itemizedlist>
912  *
913  * Returns: %TRUE if @application_id is valid
914  **/
915 gboolean
916 g_application_id_is_valid (const gchar *application_id)
917 {
918   gsize len;
919   gboolean allow_dot;
920   gboolean has_dot;
921
922   len = strlen (application_id);
923
924   if (len > 255)
925     return FALSE;
926
927   if (!g_ascii_isalpha (application_id[0]))
928     return FALSE;
929
930   if (application_id[len-1] == '.')
931     return FALSE;
932
933   application_id++;
934   allow_dot = TRUE;
935   has_dot = FALSE;
936   for (; *application_id; application_id++)
937     {
938       if (g_ascii_isalnum (*application_id) ||
939           (*application_id == '-') ||
940           (*application_id == '_'))
941         {
942           allow_dot = TRUE;
943         }
944       else if (allow_dot && *application_id == '.')
945         {
946           has_dot = TRUE;
947           allow_dot = FALSE;
948         }
949       else
950         return FALSE;
951     }
952
953   if (!has_dot)
954     return FALSE;
955
956   return TRUE;
957 }
958
959 /* Public Constructor {{{1 */
960 /**
961  * g_application_new:
962  * @application_id: the application id
963  * @flags: the application flags
964  *
965  * Creates a new #GApplication instance.
966  *
967  * This function calls g_type_init() for you.
968  *
969  * The application id must be valid.  See g_application_id_is_valid().
970  *
971  * Returns: a new #GApplication instance
972  **/
973 GApplication *
974 g_application_new (const gchar       *application_id,
975                    GApplicationFlags  flags)
976 {
977   g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);
978
979   g_type_init ();
980
981   return g_object_new (G_TYPE_APPLICATION,
982                        "application-id", application_id,
983                        "flags", flags,
984                        NULL);
985 }
986
987 /* Simple get/set: application id, flags, inactivity timeout {{{1 */
988 /**
989  * g_application_get_application_id:
990  * @application: a #GApplication
991  *
992  * Gets the unique identifier for @application.
993  *
994  * Returns: the identifier for @application, owned by @application
995  *
996  * Since: 2.28
997  **/
998 const gchar *
999 g_application_get_application_id (GApplication *application)
1000 {
1001   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
1002
1003   return application->priv->id;
1004 }
1005
1006 /**
1007  * g_application_set_application_id:
1008  * @application: a #GApplication
1009  * @application_id: the identifier for @application
1010  *
1011  * Sets the unique identifier for @application.
1012  *
1013  * The application id can only be modified if @application has not yet
1014  * been registered.
1015  *
1016  * The application id must be valid.  See g_application_id_is_valid().
1017  *
1018  * Since: 2.28
1019  **/
1020 void
1021 g_application_set_application_id (GApplication *application,
1022                                   const gchar  *application_id)
1023 {
1024   g_return_if_fail (G_IS_APPLICATION (application));
1025
1026   if (g_strcmp0 (application->priv->id, application_id) != 0)
1027     {
1028       g_return_if_fail (g_application_id_is_valid (application_id));
1029       g_return_if_fail (!application->priv->is_registered);
1030
1031       g_free (application->priv->id);
1032       application->priv->id = g_strdup (application_id);
1033
1034       g_object_notify (G_OBJECT (application), "application-id");
1035     }
1036 }
1037
1038 /**
1039  * g_application_get_flags:
1040  * @application: a #GApplication
1041  *
1042  * Gets the flags for @application.
1043  *
1044  * See #GApplicationFlags.
1045  *
1046  * Returns: the flags for @application
1047  *
1048  * Since: 2.28
1049  **/
1050 GApplicationFlags
1051 g_application_get_flags (GApplication *application)
1052 {
1053   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1054
1055   return application->priv->flags;
1056 }
1057
1058 /**
1059  * g_application_set_flags:
1060  * @application: a #GApplication
1061  * @flags: the flags for @application
1062  *
1063  * Sets the flags for @application.
1064  *
1065  * The flags can only be modified if @application has not yet been
1066  * registered.
1067  *
1068  * See #GApplicationFlags.
1069  *
1070  * Since: 2.28
1071  **/
1072 void
1073 g_application_set_flags (GApplication      *application,
1074                          GApplicationFlags  flags)
1075 {
1076   g_return_if_fail (G_IS_APPLICATION (application));
1077
1078   if (application->priv->flags != flags)
1079     {
1080       g_return_if_fail (!application->priv->is_registered);
1081
1082       application->priv->flags = flags;
1083
1084       g_object_notify (G_OBJECT (application), "flags");
1085     }
1086 }
1087
1088 /**
1089  * g_application_get_inactivity_timeout:
1090  * @application: a #GApplication
1091  *
1092  * Gets the current inactivity timeout for the application.
1093  *
1094  * This is the amount of time (in milliseconds) after the last call to
1095  * g_application_release() before the application stops running.
1096  *
1097  * Returns: the timeout, in milliseconds
1098  *
1099  * Since: 2.28
1100  **/
1101 guint
1102 g_application_get_inactivity_timeout (GApplication *application)
1103 {
1104   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1105
1106   return application->priv->inactivity_timeout;
1107 }
1108
1109 /**
1110  * g_application_set_inactivity_timeout:
1111  * @application: a #GApplication
1112  * @inactivity_timeout: the timeout, in milliseconds
1113  *
1114  * Sets the current inactivity timeout for the application.
1115  *
1116  * This is the amount of time (in milliseconds) after the last call to
1117  * g_application_release() before the application stops running.
1118  *
1119  * This call has no side effects of its own.  The value set here is only
1120  * used for next time g_application_release() drops the use count to
1121  * zero.  Any timeouts currently in progress are not impacted.
1122  *
1123  * Since: 2.28
1124  **/
1125 void
1126 g_application_set_inactivity_timeout (GApplication *application,
1127                                       guint         inactivity_timeout)
1128 {
1129   g_return_if_fail (G_IS_APPLICATION (application));
1130
1131   if (application->priv->inactivity_timeout != inactivity_timeout)
1132     {
1133       application->priv->inactivity_timeout = inactivity_timeout;
1134
1135       g_object_notify (G_OBJECT (application), "inactivity-timeout");
1136     }
1137 }
1138 /* Read-only property getters (is registered, is remote) {{{1 */
1139 /**
1140  * g_application_get_is_registered:
1141  * @application: a #GApplication
1142  *
1143  * Checks if @application is registered.
1144  *
1145  * An application is registered if g_application_register() has been
1146  * successfully called.
1147  *
1148  * Returns: %TRUE if @application is registered
1149  *
1150  * Since: 2.28
1151  **/
1152 gboolean
1153 g_application_get_is_registered (GApplication *application)
1154 {
1155   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1156
1157   return application->priv->is_registered;
1158 }
1159
1160 /**
1161  * g_application_get_is_remote:
1162  * @application: a #GApplication
1163  *
1164  * Checks if @application is remote.
1165  *
1166  * If @application is remote then it means that another instance of
1167  * application already exists (the 'primary' instance).  Calls to
1168  * perform actions on @application will result in the actions being
1169  * performed by the primary instance.
1170  *
1171  * The value of this property cannot be accessed before
1172  * g_application_register() has been called.  See
1173  * g_application_get_is_registered().
1174  *
1175  * Returns: %TRUE if @application is remote
1176  *
1177  * Since: 2.28
1178  **/
1179 gboolean
1180 g_application_get_is_remote (GApplication *application)
1181 {
1182   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1183   g_return_val_if_fail (application->priv->is_registered, FALSE);
1184
1185   return application->priv->is_remote;
1186 }
1187
1188 /* Register {{{1 */
1189 /**
1190  * g_application_register:
1191  * @application: a #GApplication
1192  * @cancellable: a #GCancellable, or %NULL
1193  * @error: a pointer to a NULL #GError, or %NULL
1194  *
1195  * Attempts registration of the application.
1196  *
1197  * This is the point at which the application discovers if it is the
1198  * primary instance or merely acting as a remote for an already-existing
1199  * primary instance.  This is implemented by attempting to acquire the
1200  * application identifier as a unique bus name on the session bus using
1201  * GDBus.
1202  *
1203  * Due to the internal architecture of GDBus, method calls can be
1204  * dispatched at any time (even if a main loop is not running).  For
1205  * this reason, you must ensure that any object paths that you wish to
1206  * register are registered before calling this function.
1207  *
1208  * If the application has already been registered then %TRUE is
1209  * returned with no work performed.
1210  *
1211  * The #GApplication::startup signal is emitted if registration succeeds
1212  * and @application is the primary instance.
1213  *
1214  * In the event of an error (such as @cancellable being cancelled, or a
1215  * failure to connect to the session bus), %FALSE is returned and @error
1216  * is set appropriately.
1217  *
1218  * Note: the return value of this function is not an indicator that this
1219  * instance is or is not the primary instance of the application.  See
1220  * g_application_get_is_remote() for that.
1221  *
1222  * Returns: %TRUE if registration succeeded
1223  *
1224  * Since: 2.28
1225  **/
1226 gboolean
1227 g_application_register (GApplication  *application,
1228                         GCancellable  *cancellable,
1229                         GError       **error)
1230 {
1231   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1232
1233   if (!application->priv->is_registered)
1234     {
1235       if (~application->priv->flags & G_APPLICATION_NON_UNIQUE)
1236         {
1237           application->priv->impl =
1238             g_application_impl_register (application, application->priv->id,
1239                                          application->priv->flags,
1240                                          &application->priv->remote_actions,
1241                                          cancellable, error);
1242
1243           if (application->priv->impl == NULL)
1244             return FALSE;
1245         }
1246
1247       application->priv->is_remote = application->priv->remote_actions != NULL;
1248       application->priv->is_registered = TRUE;
1249
1250       g_object_notify (G_OBJECT (application), "is-registered");
1251
1252       if (!application->priv->is_remote)
1253         {
1254           g_signal_emit (application, g_application_signals[SIGNAL_STARTUP], 0);
1255
1256           if (!application->priv->did_startup)
1257             g_critical ("GApplication subclass '%s' failed to chain up on"
1258                         " ::startup (from start of override function)",
1259                         G_OBJECT_TYPE_NAME (application));
1260         }
1261     }
1262
1263   return TRUE;
1264 }
1265
1266 /* Hold/release {{{1 */
1267 /**
1268  * g_application_hold:
1269  * @application: a #GApplication
1270  *
1271  * Increases the use count of @application.
1272  *
1273  * Use this function to indicate that the application has a reason to
1274  * continue to run.  For example, g_application_hold() is called by GTK+
1275  * when a toplevel window is on the screen.
1276  *
1277  * To cancel the hold, call g_application_release().
1278  **/
1279 void
1280 g_application_hold (GApplication *application)
1281 {
1282   if (application->priv->inactivity_timeout_id)
1283     {
1284       g_source_remove (application->priv->inactivity_timeout_id);
1285       application->priv->inactivity_timeout_id = 0;
1286     }
1287
1288   application->priv->use_count++;
1289 }
1290
1291 static gboolean
1292 inactivity_timeout_expired (gpointer data)
1293 {
1294   GApplication *application = G_APPLICATION (data);
1295
1296   application->priv->inactivity_timeout_id = 0;
1297
1298   return FALSE;
1299 }
1300
1301
1302 /**
1303  * g_application_release:
1304  * @application: a #GApplication
1305  *
1306  * Decrease the use count of @application.
1307  *
1308  * When the use count reaches zero, the application will stop running.
1309  *
1310  * Never call this function except to cancel the effect of a previous
1311  * call to g_application_hold().
1312  **/
1313 void
1314 g_application_release (GApplication *application)
1315 {
1316   application->priv->use_count--;
1317
1318   if (application->priv->use_count == 0 && application->priv->inactivity_timeout)
1319     application->priv->inactivity_timeout_id = g_timeout_add (application->priv->inactivity_timeout,
1320                                                               inactivity_timeout_expired, application);
1321 }
1322
1323 /* Activate, Open {{{1 */
1324 /**
1325  * g_application_activate:
1326  * @application: a #GApplication
1327  *
1328  * Activates the application.
1329  *
1330  * In essence, this results in the #GApplication::activate() signal being
1331  * emitted in the primary instance.
1332  *
1333  * The application must be registered before calling this function.
1334  *
1335  * Since: 2.28
1336  **/
1337 void
1338 g_application_activate (GApplication *application)
1339 {
1340   g_return_if_fail (G_IS_APPLICATION (application));
1341   g_return_if_fail (application->priv->is_registered);
1342
1343   if (application->priv->is_remote)
1344     g_application_impl_activate (application->priv->impl,
1345                                  get_platform_data (application));
1346
1347   else
1348     g_signal_emit (application, g_application_signals[SIGNAL_ACTIVATE], 0);
1349 }
1350
1351 /**
1352  * g_application_open:
1353  * @application: a #GApplication
1354  * @files: (array length=n_files): an array of #GFiles to open
1355  * @n_files: the length of the @files array
1356  * @hint: a hint (or ""), but never %NULL
1357  *
1358  * Opens the given files.
1359  *
1360  * In essence, this results in the #GApplication::open signal being emitted
1361  * in the primary instance.
1362  *
1363  * @n_files must be greater than zero.
1364  *
1365  * @hint is simply passed through to the ::open signal.  It is
1366  * intended to be used by applications that have multiple modes for
1367  * opening files (eg: "view" vs "edit", etc).  Unless you have a need
1368  * for this functionality, you should use "".
1369  *
1370  * The application must be registered before calling this function
1371  * and it must have the %G_APPLICATION_HANDLES_OPEN flag set.
1372  *
1373  * Since: 2.28
1374  **/
1375 void
1376 g_application_open (GApplication  *application,
1377                     GFile        **files,
1378                     gint           n_files,
1379                     const gchar   *hint)
1380 {
1381   g_return_if_fail (G_IS_APPLICATION (application));
1382   g_return_if_fail (application->priv->flags &
1383                     G_APPLICATION_HANDLES_OPEN);
1384   g_return_if_fail (application->priv->is_registered);
1385
1386   if (application->priv->is_remote)
1387     g_application_impl_open (application->priv->impl,
1388                              files, n_files, hint,
1389                              get_platform_data (application));
1390
1391   else
1392     g_signal_emit (application, g_application_signals[SIGNAL_OPEN],
1393                    0, files, n_files, hint);
1394 }
1395
1396 /* Run {{{1 */
1397 /**
1398  * g_application_run:
1399  * @application: a #GApplication
1400  * @argc: the argc from main() (or 0 if @argv is %NULL)
1401  * @argv: (array length=argc) (allow-none): the argv from main(), or %NULL
1402  *
1403  * Runs the application.
1404  *
1405  * This function is intended to be run from main() and its return value
1406  * is intended to be returned by main(). Although you are expected to pass
1407  * the @argc, @argv parameters from main() to this function, it is possible
1408  * to pass %NULL if @argv is not available or commandline handling is not
1409  * required.
1410  *
1411  * First, the local_command_line() virtual function is invoked.
1412  * This function always runs on the local instance. It gets passed a pointer
1413  * to a %NULL-terminated copy of @argv and is expected to remove the arguments
1414  * that it handled (shifting up remaining arguments). See
1415  * <xref linkend="gapplication-example-cmdline2"/> for an example of
1416  * parsing @argv manually. Alternatively, you may use the #GOptionContext API,
1417  * after setting <literal>argc = g_strv_length (argv);</literal>.
1418  *
1419  * The last argument to local_command_line() is a pointer to the @status
1420  * variable which can used to set the exit status that is returned from
1421  * g_application_run().
1422  *
1423  * If local_command_line() returns %TRUE, the command line is expected
1424  * to be completely handled, including possibly registering as the primary
1425  * instance, calling g_application_activate() or g_application_open(), etc.
1426  *
1427  * If local_command_line() returns %FALSE then the application is registered
1428  * and the #GApplication::command-line signal is emitted in the primary
1429  * instance (which may or may not be this instance). The signal handler
1430  * gets passed a #GApplicationCommandline object that (among other things)
1431  * contains the remaining commandline arguments that have not been handled
1432  * by local_command_line().
1433  *
1434  * If the application has the %G_APPLICATION_HANDLES_COMMAND_LINE
1435  * flag set then the default implementation of local_command_line()
1436  * always returns %FALSE immediately, resulting in the commandline
1437  * always being handled in the primary instance.
1438  *
1439  * Otherwise, the default implementation of local_command_line() tries
1440  * to do a couple of things that are probably reasonable for most
1441  * applications.  First, g_application_register() is called to attempt
1442  * to register the application.  If that works, then the command line
1443  * arguments are inspected.  If no commandline arguments are given, then
1444  * g_application_activate() is called.  If commandline arguments are
1445  * given and the %G_APPLICATION_HANDLES_OPEN flag is set then they
1446  * are assumed to be filenames and g_application_open() is called.
1447  *
1448  * If you need to handle commandline arguments that are not filenames,
1449  * and you don't mind commandline handling to happen in the primary
1450  * instance, you should set %G_APPLICATION_HANDLED_COMMAND_LINE and
1451  * process the commandline arguments in your #GApplication::command-line
1452  * signal handler, either manually or using the #GOptionContext API.
1453  *
1454  * If you are interested in doing more complicated local handling of the
1455  * commandline then you should implement your own #GApplication subclass
1456  * and override local_command_line(). In this case, you most likely want
1457  * to return %TRUE from your local_command_line() implementation to
1458  * suppress the default handling. See
1459  * <xref linkend="gapplication-example-cmdline2"/> for an example.
1460  *
1461  * If, after the above is done, the use count of the application is zero
1462  * then the exit status is returned immediately.  If the use count is
1463  * non-zero then the default main context is iterated until the use count
1464  * falls to zero, at which point 0 is returned.
1465  *
1466  * If the %G_APPLICATION_IS_SERVICE flag is set, then the exiting at
1467  * use count of zero is delayed for a while (ie: the instance stays
1468  * around to provide its <emphasis>service</emphasis> to others).
1469  *
1470  * Returns: the exit status
1471  *
1472  * Since: 2.28
1473  **/
1474 int
1475 g_application_run (GApplication  *application,
1476                    int            argc,
1477                    char         **argv)
1478 {
1479   gchar **arguments;
1480   int status;
1481   gint i;
1482
1483   g_return_val_if_fail (G_IS_APPLICATION (application), 1);
1484   g_return_val_if_fail (argc == 0 || argv != NULL, 1);
1485
1486   arguments = g_new (gchar *, argc + 1);
1487   for (i = 0; i < argc; i++)
1488     arguments[i] = g_strdup (argv[i]);
1489   arguments[i] = NULL;
1490
1491   if (g_get_prgname () == NULL && argc > 0)
1492     {
1493       gchar *prgname;
1494
1495       prgname = g_path_get_basename (argv[0]);
1496       g_set_prgname (prgname);
1497       g_free (prgname);
1498     }
1499
1500   if (!G_APPLICATION_GET_CLASS (application)
1501         ->local_command_line (application, &arguments, &status))
1502     {
1503       GError *error = NULL;
1504
1505       if (!g_application_register (application, NULL, &error))
1506         {
1507           g_printerr ("%s", error->message);
1508           g_error_free (error);
1509           return 1;
1510         }
1511
1512       if (application->priv->is_remote)
1513         {
1514           GVariant *platform_data;
1515
1516           platform_data = get_platform_data (application);
1517           status = g_application_impl_command_line (application->priv->impl,
1518                                                     arguments, platform_data);
1519         }
1520       else
1521         {
1522           GApplicationCommandLine *cmdline;
1523           GVariant *v;
1524
1525           v = g_variant_new_bytestring_array ((const gchar **) arguments, -1);
1526           cmdline = g_object_new (G_TYPE_APPLICATION_COMMAND_LINE,
1527                                   "arguments", v, NULL);
1528           g_signal_emit (application,
1529                          g_application_signals[SIGNAL_COMMAND_LINE],
1530                          0, cmdline, &status);
1531           g_object_unref (cmdline);
1532         }
1533     }
1534
1535   g_strfreev (arguments);
1536
1537   if (application->priv->flags & G_APPLICATION_IS_SERVICE &&
1538       application->priv->is_registered &&
1539       !application->priv->use_count &&
1540       !application->priv->inactivity_timeout_id)
1541     {
1542       application->priv->inactivity_timeout_id =
1543         g_timeout_add (10000, inactivity_timeout_expired, application);
1544     }
1545
1546   while (application->priv->use_count || application->priv->inactivity_timeout_id)
1547     {
1548       g_main_context_iteration (NULL, TRUE);
1549       status = 0;
1550     }
1551
1552   if (!application->priv->is_remote)
1553     {
1554       g_signal_emit (application, g_application_signals[SIGNAL_SHUTDOWN], 0);
1555
1556       if (!application->priv->did_shutdown)
1557         g_critical ("GApplication subclass '%s' failed to chain up on"
1558                     " ::shutdown (from end of override function)",
1559                     G_OBJECT_TYPE_NAME (application));
1560     }
1561
1562   if (application->priv->impl)
1563     g_application_impl_flush (application->priv->impl);
1564
1565   g_settings_sync ();
1566
1567   return status;
1568 }
1569
1570 static gchar **
1571 g_application_list_actions (GActionGroup *action_group)
1572 {
1573   GApplication *application = G_APPLICATION (action_group);
1574
1575   g_return_val_if_fail (application->priv->is_registered, NULL);
1576
1577   if (application->priv->remote_actions != NULL)
1578     return g_action_group_list_actions (application->priv->remote_actions);
1579
1580   else if (application->priv->actions != NULL)
1581     return g_action_group_list_actions (application->priv->actions);
1582
1583   else
1584     /* empty string array */
1585     return g_new0 (gchar *, 1);
1586 }
1587
1588 static gboolean
1589 g_application_query_action (GActionGroup        *group,
1590                             const gchar         *action_name,
1591                             gboolean            *enabled,
1592                             const GVariantType **parameter_type,
1593                             const GVariantType **state_type,
1594                             GVariant           **state_hint,
1595                             GVariant           **state)
1596 {
1597   GApplication *application = G_APPLICATION (group);
1598
1599   g_return_val_if_fail (application->priv->is_registered, FALSE);
1600
1601   if (application->priv->remote_actions != NULL)
1602     return g_action_group_query_action (application->priv->remote_actions,
1603                                         action_name,
1604                                         enabled,
1605                                         parameter_type,
1606                                         state_type,
1607                                         state_hint,
1608                                         state);
1609
1610   if (application->priv->actions != NULL)
1611     return g_action_group_query_action (application->priv->actions,
1612                                         action_name,
1613                                         enabled,
1614                                         parameter_type,
1615                                         state_type,
1616                                         state_hint,
1617                                         state);
1618
1619   return FALSE;
1620 }
1621
1622 static void
1623 g_application_change_action_state (GActionGroup *action_group,
1624                                    const gchar  *action_name,
1625                                    GVariant     *value)
1626 {
1627   GApplication *application = G_APPLICATION (action_group);
1628
1629   g_return_if_fail (application->priv->is_remote ||
1630                     application->priv->actions != NULL);
1631   g_return_if_fail (application->priv->is_registered);
1632
1633   if (application->priv->remote_actions)
1634     return g_action_group_change_action_state (application->priv->remote_actions,
1635                                                action_name, value);
1636
1637   else
1638     g_action_group_change_action_state (application->priv->actions,
1639                                         action_name, value);
1640 }
1641
1642 static void
1643 g_application_activate_action (GActionGroup *action_group,
1644                                const gchar  *action_name,
1645                                GVariant     *parameter)
1646 {
1647   GApplication *application = G_APPLICATION (action_group);
1648
1649   g_return_if_fail (application->priv->is_remote ||
1650                     application->priv->actions != NULL);
1651   g_return_if_fail (application->priv->is_registered);
1652
1653   if (application->priv->remote_actions)
1654     return g_action_group_activate_action (application->priv->remote_actions,
1655                                            action_name, parameter);
1656
1657   else
1658     g_action_group_activate_action (application->priv->actions,
1659                                     action_name, parameter);
1660 }
1661
1662 static GAction *
1663 g_application_lookup_action (GActionMap  *action_map,
1664                              const gchar *action_name)
1665 {
1666   GApplication *application = G_APPLICATION (action_map);
1667
1668   g_return_val_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions), NULL);
1669
1670   return g_simple_action_group_lookup (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1671 }
1672
1673 static void
1674 g_application_add_action (GActionMap *action_map,
1675                           GAction    *action)
1676 {
1677   GApplication *application = G_APPLICATION (action_map);
1678
1679   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1680
1681   g_simple_action_group_insert (G_SIMPLE_ACTION_GROUP (application->priv->actions), action);
1682 }
1683
1684 static void
1685 g_application_remove_action (GActionMap  *action_map,
1686                              const gchar *action_name)
1687 {
1688   GApplication *application = G_APPLICATION (action_map);
1689
1690   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1691
1692   g_simple_action_group_remove (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1693 }
1694
1695 static void
1696 g_application_action_group_iface_init (GActionGroupInterface *iface)
1697 {
1698   iface->list_actions = g_application_list_actions;
1699   iface->query_action = g_application_query_action;
1700   iface->change_action_state = g_application_change_action_state;
1701   iface->activate_action = g_application_activate_action;
1702 }
1703
1704 static void
1705 g_application_action_map_iface_init (GActionMapInterface *iface)
1706 {
1707   iface->lookup_action = g_application_lookup_action;
1708   iface->add_action = g_application_add_action;
1709   iface->remove_action = g_application_remove_action;
1710 }
1711
1712 /* Default Application {{{1 */
1713
1714 static GApplication *default_app;
1715
1716 /**
1717  * g_application_get_default:
1718  * @returns: (transfer none): the default application for this process, or %NULL
1719  *
1720  * Returns the default #GApplication instance for this process.
1721  *
1722  * Normally there is only one #GApplication per process and it becomes
1723  * the default when it is created.  You can exercise more control over
1724  * this by using g_application_set_default().
1725  *
1726  * If there is no default application then %NULL is returned.
1727  *
1728  * Since: 2.32
1729  **/
1730 GApplication *
1731 g_application_get_default (void)
1732 {
1733   return default_app;
1734 }
1735
1736 /**
1737  * g_application_set_default:
1738  * @application: the application to set as default, or %NULL
1739  *
1740  * Sets or unsets the default application for the process, as returned
1741  * by g_application_get_default().
1742  *
1743  * This function does not take its own reference on @application.  If
1744  * @application is destroyed then the default application will revert
1745  * back to %NULL.
1746  *
1747  * Since: 2.32
1748  **/
1749 void
1750 g_application_set_default (GApplication *application)
1751 {
1752   default_app = application;
1753 }
1754
1755 /* Epilogue {{{1 */
1756 /* vim:set foldmethod=marker: */