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