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