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