Imported Upstream version 2.60.7
[platform/upstream/glib.git] / gio / gapplication.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at 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, see <http://www.gnu.org/licenses/>.
16  *
17  * Authors: Ryan Lortie <desrt@desrt.ca>
18  */
19
20 /* Prologue {{{1 */
21 #include "config.h"
22
23 #include "gapplication.h"
24
25 #include "gapplicationcommandline.h"
26 #include "gsimpleactiongroup.h"
27 #include "gremoteactiongroup.h"
28 #include "gapplicationimpl.h"
29 #include "gactiongroup.h"
30 #include "gactionmap.h"
31 #include "gsettings.h"
32 #include "gnotification-private.h"
33 #include "gnotificationbackend.h"
34 #include "gdbusutils.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  * @include: gio/gio.h
49  *
50  * A #GApplication is the foundation of an application.  It wraps some
51  * low-level platform-specific services and is intended to act as the
52  * foundation for higher-level application classes such as
53  * #GtkApplication or #MxApplication.  In general, you should not use
54  * this class outside of a higher level framework.
55  *
56  * GApplication provides convenient life cycle management by maintaining
57  * a "use count" for the primary application instance. The use count can
58  * be changed using g_application_hold() and g_application_release(). If
59  * it drops to zero, the application exits. Higher-level classes such as
60  * #GtkApplication employ the use count to ensure that the application
61  * stays alive as long as it has any opened 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 "primary instance"; for non-unique applications this is
72  * the always the current instance. On Linux, the D-Bus session bus
73  * 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
78  * if it is the primary instance. Instead, the main() function of a
79  * #GApplication should do very little more than instantiating the
80  * application instance, possibly connecting signal handlers, then
81  * calling g_application_run(). All checks for uniqueness are done
82  * internally. If the application is the primary instance then the
83  * startup signal is emitted and the mainloop runs. If the application
84  * is not the primary instance then a signal is sent to the primary
85  * instance and g_application_run() promptly returns. See the code
86  * examples below.
87  *
88  * If used, the expected form of an application identifier is the same as
89  * that of of a
90  * [D-Bus well-known bus name](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus).
91  * Examples include: `com.example.MyApp`, `org.example.internal_apps.Calculator`,
92  * `org._7_zip.Archiver`.
93  * For details on valid application identifiers, see g_application_id_is_valid().
94  *
95  * On Linux, the application identifier is claimed as a well-known bus name
96  * on the user's session bus.  This means that the uniqueness of your
97  * application is scoped to the current session.  It also means that your
98  * application may provide additional services (through registration of other
99  * object paths) at that bus name.  The registration of these object paths
100  * should be done with the shared GDBus session bus.  Note that due to the
101  * internal architecture of GDBus, method calls can be dispatched at any time
102  * (even if a main loop is not running).  For this reason, you must ensure that
103  * any object paths that you wish to register are registered before #GApplication
104  * attempts to acquire the bus name of your application (which happens in
105  * g_application_register()).  Unfortunately, this means that you cannot use
106  * g_application_get_is_remote() to decide if you want to register object paths.
107  *
108  * GApplication also implements the #GActionGroup and #GActionMap
109  * interfaces and lets you easily export actions by adding them with
110  * g_action_map_add_action(). When invoking an action by calling
111  * g_action_group_activate_action() on the application, it is always
112  * invoked in the primary instance. The actions are also exported on
113  * the session bus, and GIO provides the #GDBusActionGroup wrapper to
114  * conveniently access them remotely. GIO provides a #GDBusMenuModel wrapper
115  * for remote access to exported #GMenuModels.
116  *
117  * There is a number of different entry points into a GApplication:
118  *
119  * - via 'Activate' (i.e. just starting the application)
120  *
121  * - via 'Open' (i.e. opening some files)
122  *
123  * - by handling a command-line
124  *
125  * - via activating an action
126  *
127  * The #GApplication::startup signal lets you handle the application
128  * initialization for all of these in a single place.
129  *
130  * Regardless of which of these entry points is used to start the
131  * application, GApplication passes some "platform data from the
132  * launching instance to the primary instance, in the form of a
133  * #GVariant dictionary mapping strings to variants. To use platform
134  * data, override the @before_emit or @after_emit virtual functions
135  * in your #GApplication subclass. When dealing with
136  * #GApplicationCommandLine objects, the platform data is
137  * directly available via g_application_command_line_get_cwd(),
138  * g_application_command_line_get_environ() and
139  * g_application_command_line_get_platform_data().
140  *
141  * As the name indicates, the platform data may vary depending on the
142  * operating system, but it always includes the current directory (key
143  * "cwd"), and optionally the environment (ie the set of environment
144  * variables and their values) of the calling process (key "environ").
145  * The environment is only added to the platform data if the
146  * %G_APPLICATION_SEND_ENVIRONMENT flag is set. #GApplication subclasses
147  * can add their own platform data by overriding the @add_platform_data
148  * virtual function. For instance, #GtkApplication adds startup notification
149  * data in this way.
150  *
151  * To parse commandline arguments you may handle the
152  * #GApplication::command-line signal or override the local_command_line()
153  * vfunc, to parse them in either the primary instance or the local instance,
154  * respectively.
155  *
156  * For an example of opening files with a GApplication, see
157  * [gapplication-example-open.c](https://git.gnome.org/browse/glib/tree/gio/tests/gapplication-example-open.c).
158  *
159  * For an example of using actions with GApplication, see
160  * [gapplication-example-actions.c](https://git.gnome.org/browse/glib/tree/gio/tests/gapplication-example-actions.c).
161  *
162  * For an example of using extra D-Bus hooks with GApplication, see
163  * [gapplication-example-dbushooks.c](https://git.gnome.org/browse/glib/tree/gio/tests/gapplication-example-dbushooks.c).
164  */
165
166 /**
167  * GApplication:
168  *
169  * #GApplication is an opaque data structure and can only be accessed
170  * using the following functions.
171  * Since: 2.28
172  */
173
174 /**
175  * GApplicationClass:
176  * @startup: invoked on the primary instance immediately after registration
177  * @shutdown: invoked only on the registered primary instance immediately
178  *      after the main loop terminates
179  * @activate: invoked on the primary instance when an activation occurs
180  * @open: invoked on the primary instance when there are files to open
181  * @command_line: invoked on the primary instance when a command-line is
182  *   not handled locally
183  * @local_command_line: invoked (locally). The virtual function has the chance
184  *     to inspect (and possibly replace) command line arguments. See
185  *     g_application_run() for more information. Also see the
186  *     #GApplication::handle-local-options signal, which is a simpler
187  *     alternative to handling some commandline options locally
188  * @before_emit: invoked on the primary instance before 'activate', 'open',
189  *     'command-line' or any action invocation, gets the 'platform data' from
190  *     the calling instance
191  * @after_emit: invoked on the primary instance after 'activate', 'open',
192  *     'command-line' or any action invocation, gets the 'platform data' from
193  *     the calling instance
194  * @add_platform_data: invoked (locally) to add 'platform data' to be sent to
195  *     the primary instance when activating, opening or invoking actions
196  * @quit_mainloop: Used to be invoked on the primary instance when the use
197  *     count of the application drops to zero (and after any inactivity
198  *     timeout, if requested). Not used anymore since 2.32
199  * @run_mainloop: Used to be invoked on the primary instance from
200  *     g_application_run() if the use-count is non-zero. Since 2.32,
201  *     GApplication is iterating the main context directly and is not
202  *     using @run_mainloop anymore
203  * @dbus_register: invoked locally during registration, if the application is
204  *     using its D-Bus backend. You can use this to export extra objects on the
205  *     bus, that need to exist before the application tries to own the bus name.
206  *     The function is passed the #GDBusConnection to to session bus, and the
207  *     object path that #GApplication will use to export is D-Bus API.
208  *     If this function returns %TRUE, registration will proceed; otherwise
209  *     registration will abort. Since: 2.34
210  * @dbus_unregister: invoked locally during unregistration, if the application
211  *     is using its D-Bus backend. Use this to undo anything done by
212  *     the @dbus_register vfunc. Since: 2.34
213  * @handle_local_options: invoked locally after the parsing of the commandline
214  *  options has occurred. Since: 2.40
215  * @name_lost: invoked when another instance is taking over the name. Since: 2.60
216  *
217  * Virtual function table for #GApplication.
218  *
219  * Since: 2.28
220  */
221
222 struct _GApplicationPrivate
223 {
224   GApplicationFlags  flags;
225   gchar             *id;
226   gchar             *resource_path;
227
228   GActionGroup      *actions;
229
230   guint              inactivity_timeout_id;
231   guint              inactivity_timeout;
232   guint              use_count;
233   guint              busy_count;
234
235   guint              is_registered : 1;
236   guint              is_remote : 1;
237   guint              did_startup : 1;
238   guint              did_shutdown : 1;
239   guint              must_quit_now : 1;
240
241   GRemoteActionGroup *remote_actions;
242   GApplicationImpl   *impl;
243
244   GNotificationBackend *notifications;
245
246   /* GOptionContext support */
247   GOptionGroup       *main_options;
248   GSList             *option_groups;
249   GHashTable         *packed_options;
250   gboolean            options_parsed;
251   gchar              *parameter_string;
252   gchar              *summary;
253   gchar              *description;
254
255   /* Allocated option strings, from g_application_add_main_option() */
256   GSList             *option_strings;
257 };
258
259 enum
260 {
261   PROP_NONE,
262   PROP_APPLICATION_ID,
263   PROP_FLAGS,
264   PROP_RESOURCE_BASE_PATH,
265   PROP_IS_REGISTERED,
266   PROP_IS_REMOTE,
267   PROP_INACTIVITY_TIMEOUT,
268   PROP_ACTION_GROUP,
269   PROP_IS_BUSY
270 };
271
272 enum
273 {
274   SIGNAL_STARTUP,
275   SIGNAL_SHUTDOWN,
276   SIGNAL_ACTIVATE,
277   SIGNAL_OPEN,
278   SIGNAL_ACTION,
279   SIGNAL_COMMAND_LINE,
280   SIGNAL_HANDLE_LOCAL_OPTIONS,
281   SIGNAL_NAME_LOST,
282   NR_SIGNALS
283 };
284
285 static guint g_application_signals[NR_SIGNALS];
286
287 static void g_application_action_group_iface_init (GActionGroupInterface *);
288 static void g_application_action_map_iface_init (GActionMapInterface *);
289 G_DEFINE_TYPE_WITH_CODE (GApplication, g_application, G_TYPE_OBJECT,
290  G_ADD_PRIVATE (GApplication)
291  G_IMPLEMENT_INTERFACE (G_TYPE_ACTION_GROUP, g_application_action_group_iface_init)
292  G_IMPLEMENT_INTERFACE (G_TYPE_ACTION_MAP, g_application_action_map_iface_init))
293
294 /* GApplicationExportedActions {{{1 */
295
296 /* We create a subclass of GSimpleActionGroup that implements
297  * GRemoteActionGroup and deals with the platform data using
298  * GApplication's before/after_emit vfuncs.  This is the action group we
299  * will be exporting.
300  *
301  * We could implement GRemoteActionGroup on GApplication directly, but
302  * this would be potentially extremely confusing to have exposed as part
303  * of the public API of GApplication.  We certainly don't want anyone in
304  * the same process to be calling these APIs...
305  */
306 typedef GSimpleActionGroupClass GApplicationExportedActionsClass;
307 typedef struct
308 {
309   GSimpleActionGroup parent_instance;
310   GApplication *application;
311 } GApplicationExportedActions;
312
313 static GType g_application_exported_actions_get_type   (void);
314 static void  g_application_exported_actions_iface_init (GRemoteActionGroupInterface *iface);
315 G_DEFINE_TYPE_WITH_CODE (GApplicationExportedActions, g_application_exported_actions, G_TYPE_SIMPLE_ACTION_GROUP,
316                          G_IMPLEMENT_INTERFACE (G_TYPE_REMOTE_ACTION_GROUP, g_application_exported_actions_iface_init))
317
318 static void
319 g_application_exported_actions_activate_action_full (GRemoteActionGroup *remote,
320                                                      const gchar        *action_name,
321                                                      GVariant           *parameter,
322                                                      GVariant           *platform_data)
323 {
324   GApplicationExportedActions *exported = (GApplicationExportedActions *) remote;
325
326   G_APPLICATION_GET_CLASS (exported->application)
327     ->before_emit (exported->application, platform_data);
328
329   g_action_group_activate_action (G_ACTION_GROUP (exported), action_name, parameter);
330
331   G_APPLICATION_GET_CLASS (exported->application)
332     ->after_emit (exported->application, platform_data);
333 }
334
335 static void
336 g_application_exported_actions_change_action_state_full (GRemoteActionGroup *remote,
337                                                          const gchar        *action_name,
338                                                          GVariant           *value,
339                                                          GVariant           *platform_data)
340 {
341   GApplicationExportedActions *exported = (GApplicationExportedActions *) remote;
342
343   G_APPLICATION_GET_CLASS (exported->application)
344     ->before_emit (exported->application, platform_data);
345
346   g_action_group_change_action_state (G_ACTION_GROUP (exported), action_name, value);
347
348   G_APPLICATION_GET_CLASS (exported->application)
349     ->after_emit (exported->application, platform_data);
350 }
351
352 static void
353 g_application_exported_actions_init (GApplicationExportedActions *actions)
354 {
355 }
356
357 static void
358 g_application_exported_actions_iface_init (GRemoteActionGroupInterface *iface)
359 {
360   iface->activate_action_full = g_application_exported_actions_activate_action_full;
361   iface->change_action_state_full = g_application_exported_actions_change_action_state_full;
362 }
363
364 static void
365 g_application_exported_actions_class_init (GApplicationExportedActionsClass *class)
366 {
367 }
368
369 static GActionGroup *
370 g_application_exported_actions_new (GApplication *application)
371 {
372   GApplicationExportedActions *actions;
373
374   actions = g_object_new (g_application_exported_actions_get_type (), NULL);
375   actions->application = application;
376
377   return G_ACTION_GROUP (actions);
378 }
379
380 /* Command line option handling {{{1 */
381
382 static void
383 free_option_entry (gpointer data)
384 {
385   GOptionEntry *entry = data;
386
387   switch (entry->arg)
388     {
389     case G_OPTION_ARG_STRING:
390     case G_OPTION_ARG_FILENAME:
391       g_free (*(gchar **) entry->arg_data);
392       break;
393
394     case G_OPTION_ARG_STRING_ARRAY:
395     case G_OPTION_ARG_FILENAME_ARRAY:
396       g_strfreev (*(gchar ***) entry->arg_data);
397       break;
398
399     default:
400       /* most things require no free... */
401       break;
402     }
403
404   /* ...except for the space that we allocated for it ourselves */
405   g_free (entry->arg_data);
406
407   g_slice_free (GOptionEntry, entry);
408 }
409
410 static void
411 g_application_pack_option_entries (GApplication *application,
412                                    GVariantDict *dict)
413 {
414   GHashTableIter iter;
415   gpointer item;
416
417   g_hash_table_iter_init (&iter, application->priv->packed_options);
418   while (g_hash_table_iter_next (&iter, NULL, &item))
419     {
420       GOptionEntry *entry = item;
421       GVariant *value = NULL;
422
423       switch (entry->arg)
424         {
425         case G_OPTION_ARG_NONE:
426           if (*(gboolean *) entry->arg_data != 2)
427             value = g_variant_new_boolean (*(gboolean *) entry->arg_data);
428           break;
429
430         case G_OPTION_ARG_STRING:
431           if (*(gchar **) entry->arg_data)
432             value = g_variant_new_string (*(gchar **) entry->arg_data);
433           break;
434
435         case G_OPTION_ARG_INT:
436           if (*(gint32 *) entry->arg_data)
437             value = g_variant_new_int32 (*(gint32 *) entry->arg_data);
438           break;
439
440         case G_OPTION_ARG_FILENAME:
441           if (*(gchar **) entry->arg_data)
442             value = g_variant_new_bytestring (*(gchar **) entry->arg_data);
443           break;
444
445         case G_OPTION_ARG_STRING_ARRAY:
446           if (*(gchar ***) entry->arg_data)
447             value = g_variant_new_strv (*(const gchar ***) entry->arg_data, -1);
448           break;
449
450         case G_OPTION_ARG_FILENAME_ARRAY:
451           if (*(gchar ***) entry->arg_data)
452             value = g_variant_new_bytestring_array (*(const gchar ***) entry->arg_data, -1);
453           break;
454
455         case G_OPTION_ARG_DOUBLE:
456           if (*(gdouble *) entry->arg_data)
457             value = g_variant_new_double (*(gdouble *) entry->arg_data);
458           break;
459
460         case G_OPTION_ARG_INT64:
461           if (*(gint64 *) entry->arg_data)
462             value = g_variant_new_int64 (*(gint64 *) entry->arg_data);
463           break;
464
465         default:
466           g_assert_not_reached ();
467         }
468
469       if (value)
470         g_variant_dict_insert_value (dict, entry->long_name, value);
471     }
472 }
473
474 static GVariantDict *
475 g_application_parse_command_line (GApplication   *application,
476                                   gchar        ***arguments,
477                                   GError        **error)
478 {
479   gboolean become_service = FALSE;
480   gchar *app_id = NULL;
481   gboolean replace = FALSE;
482   GVariantDict *dict = NULL;
483   GOptionContext *context;
484   GOptionGroup *gapplication_group;
485
486   /* Due to the memory management of GOptionGroup we can only parse
487    * options once.  That's because once you add a group to the
488    * GOptionContext there is no way to get it back again.  This is fine:
489    * local_command_line() should never get invoked more than once
490    * anyway.  Add a sanity check just to be sure.
491    */
492   g_return_val_if_fail (!application->priv->options_parsed, NULL);
493
494   context = g_option_context_new (application->priv->parameter_string);
495   g_option_context_set_summary (context, application->priv->summary);
496   g_option_context_set_description (context, application->priv->description);
497
498   gapplication_group = g_option_group_new ("gapplication",
499                                            _("GApplication options"), _("Show GApplication options"),
500                                            NULL, NULL);
501   g_option_group_set_translation_domain (gapplication_group, GETTEXT_PACKAGE);
502   g_option_context_add_group (context, gapplication_group);
503
504   /* If the application has not registered local options and it has
505    * G_APPLICATION_HANDLES_COMMAND_LINE then we have to assume that
506    * their primary instance commandline handler may want to deal with
507    * the arguments.  We must therefore ignore them.
508    *
509    * We must also ignore --help in this case since some applications
510    * will try to handle this from the remote side.  See #737869.
511    */
512   if (application->priv->main_options == NULL && (application->priv->flags & G_APPLICATION_HANDLES_COMMAND_LINE))
513     {
514       g_option_context_set_ignore_unknown_options (context, TRUE);
515       g_option_context_set_help_enabled (context, FALSE);
516     }
517
518   /* Add the main option group, if it exists */
519   if (application->priv->main_options)
520     {
521       /* This consumes the main_options */
522       g_option_context_set_main_group (context, application->priv->main_options);
523       application->priv->main_options = NULL;
524     }
525
526   /* Add any other option groups if they exist.  Adding them to the
527    * context will consume them, so we free the list as we go...
528    */
529   while (application->priv->option_groups)
530     {
531       g_option_context_add_group (context, application->priv->option_groups->data);
532       application->priv->option_groups = g_slist_delete_link (application->priv->option_groups,
533                                                               application->priv->option_groups);
534     }
535
536   /* In the case that we are not explicitly marked as a service or a
537    * launcher then we want to add the "--gapplication-service" option to
538    * allow the process to be made into a service.
539    */
540   if ((application->priv->flags & (G_APPLICATION_IS_SERVICE | G_APPLICATION_IS_LAUNCHER)) == 0)
541     {
542       GOptionEntry entries[] = {
543         { "gapplication-service", '\0', 0, G_OPTION_ARG_NONE, &become_service,
544           N_("Enter GApplication service mode (use from D-Bus service files)") },
545         { NULL }
546       };
547
548       g_option_group_add_entries (gapplication_group, entries);
549     }
550
551   /* Allow overriding the ID if the application allows it */
552   if (application->priv->flags & G_APPLICATION_CAN_OVERRIDE_APP_ID)
553     {
554       GOptionEntry entries[] = {
555         { "gapplication-app-id", '\0', 0, G_OPTION_ARG_STRING, &app_id,
556           N_("Override the application’s ID") },
557         { NULL }
558       };
559
560       g_option_group_add_entries (gapplication_group, entries);
561     }
562
563   /* Allow replacing if the application allows it */
564   if (application->priv->flags & G_APPLICATION_ALLOW_REPLACEMENT)
565     {
566       GOptionEntry entries[] = {
567         { "gapplication-replace", '\0', 0, G_OPTION_ARG_NONE, &replace,
568           N_("Replace the running instance") },
569         { NULL }
570       };
571
572       g_option_group_add_entries (gapplication_group, entries);
573     }
574
575   /* Now we parse... */
576   if (!g_option_context_parse_strv (context, arguments, error))
577     goto out;
578
579   /* Check for --gapplication-service */
580   if (become_service)
581     application->priv->flags |= G_APPLICATION_IS_SERVICE;
582
583   /* Check for --gapplication-app-id */
584   if (app_id)
585     g_application_set_application_id (application, app_id);
586
587   /* Check for --gapplication-replace */
588   if (replace)
589     application->priv->flags |= G_APPLICATION_REPLACE;
590
591   dict = g_variant_dict_new (NULL);
592   if (application->priv->packed_options)
593     {
594       g_application_pack_option_entries (application, dict);
595       g_hash_table_unref (application->priv->packed_options);
596       application->priv->packed_options = NULL;
597     }
598
599 out:
600   /* Make sure we don't run again */
601   application->priv->options_parsed = TRUE;
602
603   g_option_context_free (context);
604   g_free (app_id);
605
606   return dict;
607 }
608
609 static void
610 add_packed_option (GApplication *application,
611                    GOptionEntry *entry)
612 {
613   switch (entry->arg)
614     {
615     case G_OPTION_ARG_NONE:
616       entry->arg_data = g_new (gboolean, 1);
617       *(gboolean *) entry->arg_data = 2;
618       break;
619
620     case G_OPTION_ARG_INT:
621       entry->arg_data = g_new0 (gint, 1);
622       break;
623
624     case G_OPTION_ARG_STRING:
625     case G_OPTION_ARG_FILENAME:
626     case G_OPTION_ARG_STRING_ARRAY:
627     case G_OPTION_ARG_FILENAME_ARRAY:
628       entry->arg_data = g_new0 (gpointer, 1);
629       break;
630
631     case G_OPTION_ARG_INT64:
632       entry->arg_data = g_new0 (gint64, 1);
633       break;
634
635     case G_OPTION_ARG_DOUBLE:
636       entry->arg_data = g_new0 (gdouble, 1);
637       break;
638
639     default:
640       g_return_if_reached ();
641     }
642
643   if (!application->priv->packed_options)
644     application->priv->packed_options = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, free_option_entry);
645
646   g_hash_table_insert (application->priv->packed_options,
647                        g_strdup (entry->long_name),
648                        g_slice_dup (GOptionEntry, entry));
649 }
650
651 /**
652  * g_application_add_main_option_entries:
653  * @application: a #GApplication
654  * @entries: (array zero-terminated=1) (element-type GOptionEntry) a
655  *           %NULL-terminated list of #GOptionEntrys
656  *
657  * Adds main option entries to be handled by @application.
658  *
659  * This function is comparable to g_option_context_add_main_entries().
660  *
661  * After the commandline arguments are parsed, the
662  * #GApplication::handle-local-options signal will be emitted.  At this
663  * point, the application can inspect the values pointed to by @arg_data
664  * in the given #GOptionEntrys.
665  *
666  * Unlike #GOptionContext, #GApplication supports giving a %NULL
667  * @arg_data for a non-callback #GOptionEntry.  This results in the
668  * argument in question being packed into a #GVariantDict which is also
669  * passed to #GApplication::handle-local-options, where it can be
670  * inspected and modified.  If %G_APPLICATION_HANDLES_COMMAND_LINE is
671  * set, then the resulting dictionary is sent to the primary instance,
672  * where g_application_command_line_get_options_dict() will return it.
673  * This "packing" is done according to the type of the argument --
674  * booleans for normal flags, strings for strings, bytestrings for
675  * filenames, etc.  The packing only occurs if the flag is given (ie: we
676  * do not pack a "false" #GVariant in the case that a flag is missing).
677  *
678  * In general, it is recommended that all commandline arguments are
679  * parsed locally.  The options dictionary should then be used to
680  * transmit the result of the parsing to the primary instance, where
681  * g_variant_dict_lookup() can be used.  For local options, it is
682  * possible to either use @arg_data in the usual way, or to consult (and
683  * potentially remove) the option from the options dictionary.
684  *
685  * This function is new in GLib 2.40.  Before then, the only real choice
686  * was to send all of the commandline arguments (options and all) to the
687  * primary instance for handling.  #GApplication ignored them completely
688  * on the local side.  Calling this function "opts in" to the new
689  * behaviour, and in particular, means that unrecognised options will be
690  * treated as errors.  Unrecognised options have never been ignored when
691  * %G_APPLICATION_HANDLES_COMMAND_LINE is unset.
692  *
693  * If #GApplication::handle-local-options needs to see the list of
694  * filenames, then the use of %G_OPTION_REMAINING is recommended.  If
695  * @arg_data is %NULL then %G_OPTION_REMAINING can be used as a key into
696  * the options dictionary.  If you do use %G_OPTION_REMAINING then you
697  * need to handle these arguments for yourself because once they are
698  * consumed, they will no longer be visible to the default handling
699  * (which treats them as filenames to be opened).
700  *
701  * It is important to use the proper GVariant format when retrieving
702  * the options with g_variant_dict_lookup():
703  * - for %G_OPTION_ARG_NONE, use b
704  * - for %G_OPTION_ARG_STRING, use &s
705  * - for %G_OPTION_ARG_INT, use i
706  * - for %G_OPTION_ARG_INT64, use x
707  * - for %G_OPTION_ARG_DOUBLE, use d
708  * - for %G_OPTION_ARG_FILENAME, use ^ay
709  * - for %G_OPTION_ARG_STRING_ARRAY, use &as
710  * - for %G_OPTION_ARG_FILENAME_ARRAY, use ^aay
711  *
712  * Since: 2.40
713  */
714 void
715 g_application_add_main_option_entries (GApplication       *application,
716                                        const GOptionEntry *entries)
717 {
718   gint i;
719
720   g_return_if_fail (G_IS_APPLICATION (application));
721   g_return_if_fail (entries != NULL);
722
723   if (!application->priv->main_options)
724     {
725       application->priv->main_options = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
726       g_option_group_set_translation_domain (application->priv->main_options, NULL);
727     }
728
729   for (i = 0; entries[i].long_name; i++)
730     {
731       GOptionEntry my_entries[2] = { { NULL }, { NULL } };
732       my_entries[0] = entries[i];
733
734       if (!my_entries[0].arg_data)
735         add_packed_option (application, &my_entries[0]);
736
737       g_option_group_add_entries (application->priv->main_options, my_entries);
738     }
739 }
740
741 /**
742  * g_application_add_main_option:
743  * @application: the #GApplication
744  * @long_name: the long name of an option used to specify it in a commandline
745  * @short_name: the short name of an option
746  * @flags: flags from #GOptionFlags
747  * @arg: the type of the option, as a #GOptionArg
748  * @description: the description for the option in `--help` output
749  * @arg_description: (nullable): the placeholder to use for the extra argument
750  *    parsed by the option in `--help` output
751  *
752  * Add an option to be handled by @application.
753  *
754  * Calling this function is the equivalent of calling
755  * g_application_add_main_option_entries() with a single #GOptionEntry
756  * that has its arg_data member set to %NULL.
757  *
758  * The parsed arguments will be packed into a #GVariantDict which
759  * is passed to #GApplication::handle-local-options. If
760  * %G_APPLICATION_HANDLES_COMMAND_LINE is set, then it will also
761  * be sent to the primary instance. See
762  * g_application_add_main_option_entries() for more details.
763  *
764  * See #GOptionEntry for more documentation of the arguments.
765  *
766  * Since: 2.42
767  **/
768 void
769 g_application_add_main_option (GApplication *application,
770                                const char   *long_name,
771                                char          short_name,
772                                GOptionFlags  flags,
773                                GOptionArg    arg,
774                                const char   *description,
775                                const char   *arg_description)
776 {
777   gchar *dup_string;
778   GOptionEntry my_entry[2] = {
779     { NULL, short_name, flags, arg, NULL, NULL, NULL },
780     { NULL }
781   };
782
783   g_return_if_fail (G_IS_APPLICATION (application));
784   g_return_if_fail (long_name != NULL);
785   g_return_if_fail (description != NULL);
786
787   my_entry[0].long_name = dup_string = g_strdup (long_name);
788   application->priv->option_strings = g_slist_prepend (application->priv->option_strings, dup_string);
789
790   my_entry[0].description = dup_string = g_strdup (description);
791   application->priv->option_strings = g_slist_prepend (application->priv->option_strings, dup_string);
792
793   my_entry[0].arg_description = dup_string = g_strdup (arg_description);
794   application->priv->option_strings = g_slist_prepend (application->priv->option_strings, dup_string);
795
796   g_application_add_main_option_entries (application, my_entry);
797 }
798
799 /**
800  * g_application_add_option_group:
801  * @application: the #GApplication
802  * @group: (transfer full): a #GOptionGroup
803  *
804  * Adds a #GOptionGroup to the commandline handling of @application.
805  *
806  * This function is comparable to g_option_context_add_group().
807  *
808  * Unlike g_application_add_main_option_entries(), this function does
809  * not deal with %NULL @arg_data and never transmits options to the
810  * primary instance.
811  *
812  * The reason for that is because, by the time the options arrive at the
813  * primary instance, it is typically too late to do anything with them.
814  * Taking the GTK option group as an example: GTK will already have been
815  * initialised by the time the #GApplication::command-line handler runs.
816  * In the case that this is not the first-running instance of the
817  * application, the existing instance may already have been running for
818  * a very long time.
819  *
820  * This means that the options from #GOptionGroup are only really usable
821  * in the case that the instance of the application being run is the
822  * first instance.  Passing options like `--display=` or `--gdk-debug=`
823  * on future runs will have no effect on the existing primary instance.
824  *
825  * Calling this function will cause the options in the supplied option
826  * group to be parsed, but it does not cause you to be "opted in" to the
827  * new functionality whereby unrecognised options are rejected even if
828  * %G_APPLICATION_HANDLES_COMMAND_LINE was given.
829  *
830  * Since: 2.40
831  **/
832 void
833 g_application_add_option_group (GApplication *application,
834                                 GOptionGroup *group)
835 {
836   g_return_if_fail (G_IS_APPLICATION (application));
837   g_return_if_fail (group != NULL);
838
839   application->priv->option_groups = g_slist_prepend (application->priv->option_groups, group);
840 }
841
842 /**
843  * g_application_set_option_context_parameter_string:
844  * @application: the #GApplication
845  * @parameter_string: (nullable): a string which is displayed
846  *   in the first line of `--help` output, after the usage summary `programname [OPTION...]`.
847  *
848  * Sets the parameter string to be used by the commandline handling of @application.
849  *
850  * This function registers the argument to be passed to g_option_context_new()
851  * when the internal #GOptionContext of @application is created.
852  *
853  * See g_option_context_new() for more information about @parameter_string.
854  *
855  * Since: 2.56
856  */
857 void
858 g_application_set_option_context_parameter_string (GApplication *application,
859                                                    const gchar  *parameter_string)
860 {
861   g_return_if_fail (G_IS_APPLICATION (application));
862
863   g_free (application->priv->parameter_string);
864   application->priv->parameter_string = g_strdup (parameter_string);
865 }
866
867 /**
868  * g_application_set_option_context_summary:
869  * @application: the #GApplication
870  * @summary: (nullable): a string to be shown in `--help` output
871  *  before the list of options, or %NULL
872  *
873  * Adds a summary to the @application option context.
874  *
875  * See g_option_context_set_summary() for more information.
876  *
877  * Since: 2.56
878  */
879 void
880 g_application_set_option_context_summary (GApplication *application,
881                                           const gchar  *summary)
882 {
883   g_return_if_fail (G_IS_APPLICATION (application));
884
885   g_free (application->priv->summary);
886   application->priv->summary = g_strdup (summary);
887 }
888
889 /**
890  * g_application_set_option_context_description:
891  * @application: the #GApplication
892  * @description: (nullable): a string to be shown in `--help` output
893  *  after the list of options, or %NULL
894  *
895  * Adds a description to the @application option context.
896  *
897  * See g_option_context_set_description() for more information.
898  *
899  * Since: 2.56
900  */
901 void
902 g_application_set_option_context_description (GApplication *application,
903                                               const gchar  *description)
904 {
905   g_return_if_fail (G_IS_APPLICATION (application));
906
907   g_free (application->priv->description);
908   application->priv->description = g_strdup (description);
909
910 }
911
912
913 /* vfunc defaults {{{1 */
914 static void
915 g_application_real_before_emit (GApplication *application,
916                                 GVariant     *platform_data)
917 {
918 }
919
920 static void
921 g_application_real_after_emit (GApplication *application,
922                                GVariant     *platform_data)
923 {
924 }
925
926 static void
927 g_application_real_startup (GApplication *application)
928 {
929   application->priv->did_startup = TRUE;
930 }
931
932 static void
933 g_application_real_shutdown (GApplication *application)
934 {
935   application->priv->did_shutdown = TRUE;
936 }
937
938 static void
939 g_application_real_activate (GApplication *application)
940 {
941   if (!g_signal_has_handler_pending (application,
942                                      g_application_signals[SIGNAL_ACTIVATE],
943                                      0, TRUE) &&
944       G_APPLICATION_GET_CLASS (application)->activate == g_application_real_activate)
945     {
946       static gboolean warned;
947
948       if (warned)
949         return;
950
951       g_warning ("Your application does not implement "
952                  "g_application_activate() and has no handlers connected "
953                  "to the 'activate' signal.  It should do one of these.");
954       warned = TRUE;
955     }
956 }
957
958 static void
959 g_application_real_open (GApplication  *application,
960                          GFile        **files,
961                          gint           n_files,
962                          const gchar   *hint)
963 {
964   if (!g_signal_has_handler_pending (application,
965                                      g_application_signals[SIGNAL_OPEN],
966                                      0, TRUE) &&
967       G_APPLICATION_GET_CLASS (application)->open == g_application_real_open)
968     {
969       static gboolean warned;
970
971       if (warned)
972         return;
973
974       g_warning ("Your application claims to support opening files "
975                  "but does not implement g_application_open() and has no "
976                  "handlers connected to the 'open' signal.");
977       warned = TRUE;
978     }
979 }
980
981 static int
982 g_application_real_command_line (GApplication            *application,
983                                  GApplicationCommandLine *cmdline)
984 {
985   if (!g_signal_has_handler_pending (application,
986                                      g_application_signals[SIGNAL_COMMAND_LINE],
987                                      0, TRUE) &&
988       G_APPLICATION_GET_CLASS (application)->command_line == g_application_real_command_line)
989     {
990       static gboolean warned;
991
992       if (warned)
993         return 1;
994
995       g_warning ("Your application claims to support custom command line "
996                  "handling but does not implement g_application_command_line() "
997                  "and has no handlers connected to the 'command-line' signal.");
998
999       warned = TRUE;
1000     }
1001
1002     return 1;
1003 }
1004
1005 static gint
1006 g_application_real_handle_local_options (GApplication *application,
1007                                          GVariantDict *options)
1008 {
1009   return -1;
1010 }
1011
1012 static GVariant *
1013 get_platform_data (GApplication *application,
1014                    GVariant     *options)
1015 {
1016   GVariantBuilder *builder;
1017   GVariant *result;
1018
1019   builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
1020
1021   {
1022     gchar *cwd = g_get_current_dir ();
1023     g_variant_builder_add (builder, "{sv}", "cwd",
1024                            g_variant_new_bytestring (cwd));
1025     g_free (cwd);
1026   }
1027
1028   if (application->priv->flags & G_APPLICATION_SEND_ENVIRONMENT)
1029     {
1030       GVariant *array;
1031       gchar **envp;
1032
1033       envp = g_get_environ ();
1034       array = g_variant_new_bytestring_array ((const gchar **) envp, -1);
1035       g_strfreev (envp);
1036
1037       g_variant_builder_add (builder, "{sv}", "environ", array);
1038     }
1039
1040   if (options)
1041     g_variant_builder_add (builder, "{sv}", "options", options);
1042
1043   G_APPLICATION_GET_CLASS (application)->
1044     add_platform_data (application, builder);
1045
1046   result = g_variant_builder_end (builder);
1047   g_variant_builder_unref (builder);
1048
1049   return result;
1050 }
1051
1052 static void
1053 g_application_call_command_line (GApplication        *application,
1054                                  const gchar * const *arguments,
1055                                  GVariant            *options,
1056                                  gint                *exit_status)
1057 {
1058   if (application->priv->is_remote)
1059     {
1060       GVariant *platform_data;
1061
1062       platform_data = get_platform_data (application, options);
1063       *exit_status = g_application_impl_command_line (application->priv->impl, arguments, platform_data);
1064     }
1065   else
1066     {
1067       GApplicationCommandLine *cmdline;
1068       GVariant *v;
1069
1070       v = g_variant_new_bytestring_array ((const gchar **) arguments, -1);
1071       cmdline = g_object_new (G_TYPE_APPLICATION_COMMAND_LINE,
1072                               "arguments", v,
1073                               "options", options,
1074                               NULL);
1075       g_signal_emit (application, g_application_signals[SIGNAL_COMMAND_LINE], 0, cmdline, exit_status);
1076       g_object_unref (cmdline);
1077     }
1078 }
1079
1080 static gboolean
1081 g_application_real_local_command_line (GApplication   *application,
1082                                        gchar        ***arguments,
1083                                        int            *exit_status)
1084 {
1085   GError *error = NULL;
1086   GVariantDict *options;
1087   gint n_args;
1088
1089   options = g_application_parse_command_line (application, arguments, &error);
1090   if (!options)
1091     {
1092       g_printerr ("%s\n", error->message);
1093       *exit_status = 1;
1094       return TRUE;
1095     }
1096
1097   g_signal_emit (application, g_application_signals[SIGNAL_HANDLE_LOCAL_OPTIONS], 0, options, exit_status);
1098
1099   if (*exit_status >= 0)
1100     {
1101       g_variant_dict_unref (options);
1102       return TRUE;
1103     }
1104
1105   if (!g_application_register (application, NULL, &error))
1106     {
1107       g_printerr ("Failed to register: %s\n", error->message);
1108       g_variant_dict_unref (options);
1109       g_error_free (error);
1110       *exit_status = 1;
1111       return TRUE;
1112     }
1113
1114   n_args = g_strv_length (*arguments);
1115
1116   if (application->priv->flags & G_APPLICATION_IS_SERVICE)
1117     {
1118       if ((*exit_status = n_args > 1))
1119         {
1120           g_printerr ("GApplication service mode takes no arguments.\n");
1121           application->priv->flags &= ~G_APPLICATION_IS_SERVICE;
1122           *exit_status = 1;
1123         }
1124       else
1125         *exit_status = 0;
1126     }
1127   else if (application->priv->flags & G_APPLICATION_HANDLES_COMMAND_LINE)
1128     {
1129       g_application_call_command_line (application,
1130                                        (const gchar **) *arguments,
1131                                        g_variant_dict_end (options),
1132                                        exit_status);
1133     }
1134   else
1135     {
1136       if (n_args <= 1)
1137         {
1138           g_application_activate (application);
1139           *exit_status = 0;
1140         }
1141
1142       else
1143         {
1144           if (~application->priv->flags & G_APPLICATION_HANDLES_OPEN)
1145             {
1146               g_critical ("This application can not open files.");
1147               *exit_status = 1;
1148             }
1149           else
1150             {
1151               GFile **files;
1152               gint n_files;
1153               gint i;
1154
1155               n_files = n_args - 1;
1156               files = g_new (GFile *, n_files);
1157
1158               for (i = 0; i < n_files; i++)
1159                 files[i] = g_file_new_for_commandline_arg ((*arguments)[i + 1]);
1160
1161               g_application_open (application, files, n_files, "");
1162
1163               for (i = 0; i < n_files; i++)
1164                 g_object_unref (files[i]);
1165               g_free (files);
1166
1167               *exit_status = 0;
1168             }
1169         }
1170     }
1171
1172   g_variant_dict_unref (options);
1173
1174   return TRUE;
1175 }
1176
1177 static void
1178 g_application_real_add_platform_data (GApplication    *application,
1179                                       GVariantBuilder *builder)
1180 {
1181 }
1182
1183 static gboolean
1184 g_application_real_dbus_register (GApplication    *application,
1185                                   GDBusConnection *connection,
1186                                   const gchar     *object_path,
1187                                   GError         **error)
1188 {
1189   return TRUE;
1190 }
1191
1192 static void
1193 g_application_real_dbus_unregister (GApplication    *application,
1194                                     GDBusConnection *connection,
1195                                     const gchar     *object_path)
1196 {
1197 }
1198
1199 static gboolean
1200 g_application_real_name_lost (GApplication *application)
1201 {
1202   g_application_quit (application);
1203   return TRUE;
1204 }
1205
1206 /* GObject implementation stuff {{{1 */
1207 static void
1208 g_application_set_property (GObject      *object,
1209                             guint         prop_id,
1210                             const GValue *value,
1211                             GParamSpec   *pspec)
1212 {
1213   GApplication *application = G_APPLICATION (object);
1214
1215   switch (prop_id)
1216     {
1217     case PROP_APPLICATION_ID:
1218       g_application_set_application_id (application,
1219                                         g_value_get_string (value));
1220       break;
1221
1222     case PROP_FLAGS:
1223       g_application_set_flags (application, g_value_get_flags (value));
1224       break;
1225
1226     case PROP_RESOURCE_BASE_PATH:
1227       g_application_set_resource_base_path (application, g_value_get_string (value));
1228       break;
1229
1230     case PROP_INACTIVITY_TIMEOUT:
1231       g_application_set_inactivity_timeout (application,
1232                                             g_value_get_uint (value));
1233       break;
1234
1235     case PROP_ACTION_GROUP:
1236       g_clear_object (&application->priv->actions);
1237       application->priv->actions = g_value_dup_object (value);
1238       break;
1239
1240     default:
1241       g_assert_not_reached ();
1242     }
1243 }
1244
1245 /**
1246  * g_application_set_action_group:
1247  * @application: a #GApplication
1248  * @action_group: (nullable): a #GActionGroup, or %NULL
1249  *
1250  * This used to be how actions were associated with a #GApplication.
1251  * Now there is #GActionMap for that.
1252  *
1253  * Since: 2.28
1254  *
1255  * Deprecated:2.32:Use the #GActionMap interface instead.  Never ever
1256  * mix use of this API with use of #GActionMap on the same @application
1257  * or things will go very badly wrong.  This function is known to
1258  * introduce buggy behaviour (ie: signals not emitted on changes to the
1259  * action group), so you should really use #GActionMap instead.
1260  **/
1261 void
1262 g_application_set_action_group (GApplication *application,
1263                                 GActionGroup *action_group)
1264 {
1265   g_return_if_fail (G_IS_APPLICATION (application));
1266   g_return_if_fail (!application->priv->is_registered);
1267
1268   if (application->priv->actions != NULL)
1269     g_object_unref (application->priv->actions);
1270
1271   application->priv->actions = action_group;
1272
1273   if (application->priv->actions != NULL)
1274     g_object_ref (application->priv->actions);
1275 }
1276
1277 static void
1278 g_application_get_property (GObject    *object,
1279                             guint       prop_id,
1280                             GValue     *value,
1281                             GParamSpec *pspec)
1282 {
1283   GApplication *application = G_APPLICATION (object);
1284
1285   switch (prop_id)
1286     {
1287     case PROP_APPLICATION_ID:
1288       g_value_set_string (value,
1289                           g_application_get_application_id (application));
1290       break;
1291
1292     case PROP_FLAGS:
1293       g_value_set_flags (value,
1294                          g_application_get_flags (application));
1295       break;
1296
1297     case PROP_RESOURCE_BASE_PATH:
1298       g_value_set_string (value, g_application_get_resource_base_path (application));
1299       break;
1300
1301     case PROP_IS_REGISTERED:
1302       g_value_set_boolean (value,
1303                            g_application_get_is_registered (application));
1304       break;
1305
1306     case PROP_IS_REMOTE:
1307       g_value_set_boolean (value,
1308                            g_application_get_is_remote (application));
1309       break;
1310
1311     case PROP_INACTIVITY_TIMEOUT:
1312       g_value_set_uint (value,
1313                         g_application_get_inactivity_timeout (application));
1314       break;
1315
1316     case PROP_IS_BUSY:
1317       g_value_set_boolean (value, g_application_get_is_busy (application));
1318       break;
1319
1320     default:
1321       g_assert_not_reached ();
1322     }
1323 }
1324
1325 static void
1326 g_application_constructed (GObject *object)
1327 {
1328   GApplication *application = G_APPLICATION (object);
1329
1330   if (g_application_get_default () == NULL)
1331     g_application_set_default (application);
1332
1333   /* People should not set properties from _init... */
1334   g_assert (application->priv->resource_path == NULL);
1335
1336   if (application->priv->id != NULL)
1337     {
1338       gint i;
1339
1340       application->priv->resource_path = g_strconcat ("/", application->priv->id, NULL);
1341
1342       for (i = 1; application->priv->resource_path[i]; i++)
1343         if (application->priv->resource_path[i] == '.')
1344           application->priv->resource_path[i] = '/';
1345     }
1346 }
1347
1348 static void
1349 g_application_dispose (GObject *object)
1350 {
1351   GApplication *application = G_APPLICATION (object);
1352
1353   if (application->priv->impl != NULL &&
1354       G_APPLICATION_GET_CLASS (application)->dbus_unregister != g_application_real_dbus_unregister)
1355     {
1356       static gboolean warned;
1357
1358       if (!warned)
1359         {
1360           g_warning ("Your application did not unregister from D-Bus before destruction. "
1361                      "Consider using g_application_run().");
1362         }
1363
1364       warned = TRUE;
1365     }
1366
1367   G_OBJECT_CLASS (g_application_parent_class)->dispose (object);
1368 }
1369
1370 static void
1371 g_application_finalize (GObject *object)
1372 {
1373   GApplication *application = G_APPLICATION (object);
1374
1375   if (application->priv->inactivity_timeout_id)
1376     g_source_remove (application->priv->inactivity_timeout_id);
1377
1378   g_slist_free_full (application->priv->option_groups, (GDestroyNotify) g_option_group_unref);
1379   if (application->priv->main_options)
1380     g_option_group_unref (application->priv->main_options);
1381   if (application->priv->packed_options)
1382     g_hash_table_unref (application->priv->packed_options);
1383
1384   g_free (application->priv->parameter_string);
1385   g_free (application->priv->summary);
1386   g_free (application->priv->description);
1387
1388   g_slist_free_full (application->priv->option_strings, g_free);
1389
1390   if (application->priv->impl)
1391     g_application_impl_destroy (application->priv->impl);
1392   g_free (application->priv->id);
1393
1394   if (g_application_get_default () == application)
1395     g_application_set_default (NULL);
1396
1397   if (application->priv->actions)
1398     g_object_unref (application->priv->actions);
1399
1400   if (application->priv->notifications)
1401     g_object_unref (application->priv->notifications);
1402
1403   g_free (application->priv->resource_path);
1404
1405   G_OBJECT_CLASS (g_application_parent_class)
1406     ->finalize (object);
1407 }
1408
1409 static void
1410 g_application_init (GApplication *application)
1411 {
1412   application->priv = g_application_get_instance_private (application);
1413
1414   application->priv->actions = g_application_exported_actions_new (application);
1415
1416   /* application->priv->actions is the one and only ref on the group, so when
1417    * we dispose, the action group will die, disconnecting all signals.
1418    */
1419   g_signal_connect_swapped (application->priv->actions, "action-added",
1420                             G_CALLBACK (g_action_group_action_added), application);
1421   g_signal_connect_swapped (application->priv->actions, "action-enabled-changed",
1422                             G_CALLBACK (g_action_group_action_enabled_changed), application);
1423   g_signal_connect_swapped (application->priv->actions, "action-state-changed",
1424                             G_CALLBACK (g_action_group_action_state_changed), application);
1425   g_signal_connect_swapped (application->priv->actions, "action-removed",
1426                             G_CALLBACK (g_action_group_action_removed), application);
1427 }
1428
1429 static gboolean
1430 g_application_handle_local_options_accumulator (GSignalInvocationHint *ihint,
1431                                                 GValue                *return_accu,
1432                                                 const GValue          *handler_return,
1433                                                 gpointer               dummy)
1434 {
1435   gint value;
1436
1437   value = g_value_get_int (handler_return);
1438   g_value_set_int (return_accu, value);
1439
1440   return value < 0;
1441 }
1442
1443 static void
1444 g_application_class_init (GApplicationClass *class)
1445 {
1446   GObjectClass *object_class = G_OBJECT_CLASS (class);
1447
1448   object_class->constructed = g_application_constructed;
1449   object_class->dispose = g_application_dispose;
1450   object_class->finalize = g_application_finalize;
1451   object_class->get_property = g_application_get_property;
1452   object_class->set_property = g_application_set_property;
1453
1454   class->before_emit = g_application_real_before_emit;
1455   class->after_emit = g_application_real_after_emit;
1456   class->startup = g_application_real_startup;
1457   class->shutdown = g_application_real_shutdown;
1458   class->activate = g_application_real_activate;
1459   class->open = g_application_real_open;
1460   class->command_line = g_application_real_command_line;
1461   class->local_command_line = g_application_real_local_command_line;
1462   class->handle_local_options = g_application_real_handle_local_options;
1463   class->add_platform_data = g_application_real_add_platform_data;
1464   class->dbus_register = g_application_real_dbus_register;
1465   class->dbus_unregister = g_application_real_dbus_unregister;
1466   class->name_lost = g_application_real_name_lost;
1467
1468   g_object_class_install_property (object_class, PROP_APPLICATION_ID,
1469     g_param_spec_string ("application-id",
1470                          P_("Application identifier"),
1471                          P_("The unique identifier for the application"),
1472                          NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
1473                          G_PARAM_STATIC_STRINGS));
1474
1475   g_object_class_install_property (object_class, PROP_FLAGS,
1476     g_param_spec_flags ("flags",
1477                         P_("Application flags"),
1478                         P_("Flags specifying the behaviour of the application"),
1479                         G_TYPE_APPLICATION_FLAGS, G_APPLICATION_FLAGS_NONE,
1480                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1481
1482   g_object_class_install_property (object_class, PROP_RESOURCE_BASE_PATH,
1483     g_param_spec_string ("resource-base-path",
1484                          P_("Resource base path"),
1485                          P_("The base resource path for the application"),
1486                          NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1487
1488   g_object_class_install_property (object_class, PROP_IS_REGISTERED,
1489     g_param_spec_boolean ("is-registered",
1490                           P_("Is registered"),
1491                           P_("If g_application_register() has been called"),
1492                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1493
1494   g_object_class_install_property (object_class, PROP_IS_REMOTE,
1495     g_param_spec_boolean ("is-remote",
1496                           P_("Is remote"),
1497                           P_("If this application instance is remote"),
1498                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1499
1500   g_object_class_install_property (object_class, PROP_INACTIVITY_TIMEOUT,
1501     g_param_spec_uint ("inactivity-timeout",
1502                        P_("Inactivity timeout"),
1503                        P_("Time (ms) to stay alive after becoming idle"),
1504                        0, G_MAXUINT, 0,
1505                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1506
1507   g_object_class_install_property (object_class, PROP_ACTION_GROUP,
1508     g_param_spec_object ("action-group",
1509                          P_("Action group"),
1510                          P_("The group of actions that the application exports"),
1511                          G_TYPE_ACTION_GROUP,
1512                          G_PARAM_DEPRECATED | G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
1513
1514   /**
1515    * GApplication:is-busy:
1516    *
1517    * Whether the application is currently marked as busy through
1518    * g_application_mark_busy() or g_application_bind_busy_property().
1519    *
1520    * Since: 2.44
1521    */
1522   g_object_class_install_property (object_class, PROP_IS_BUSY,
1523     g_param_spec_boolean ("is-busy",
1524                           P_("Is busy"),
1525                           P_("If this application is currently marked busy"),
1526                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1527
1528   /**
1529    * GApplication::startup:
1530    * @application: the application
1531    *
1532    * The ::startup signal is emitted on the primary instance immediately
1533    * after registration. See g_application_register().
1534    */
1535   g_application_signals[SIGNAL_STARTUP] =
1536     g_signal_new (I_("startup"), G_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
1537                   G_STRUCT_OFFSET (GApplicationClass, startup),
1538                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
1539
1540   /**
1541    * GApplication::shutdown:
1542    * @application: the application
1543    *
1544    * The ::shutdown signal is emitted only on the registered primary instance
1545    * immediately after the main loop terminates.
1546    */
1547   g_application_signals[SIGNAL_SHUTDOWN] =
1548     g_signal_new (I_("shutdown"), G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
1549                   G_STRUCT_OFFSET (GApplicationClass, shutdown),
1550                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
1551
1552   /**
1553    * GApplication::activate:
1554    * @application: the application
1555    *
1556    * The ::activate signal is emitted on the primary instance when an
1557    * activation occurs. See g_application_activate().
1558    */
1559   g_application_signals[SIGNAL_ACTIVATE] =
1560     g_signal_new (I_("activate"), G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
1561                   G_STRUCT_OFFSET (GApplicationClass, activate),
1562                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
1563
1564
1565   /**
1566    * GApplication::open:
1567    * @application: the application
1568    * @files: (array length=n_files) (element-type GFile): an array of #GFiles
1569    * @n_files: the length of @files
1570    * @hint: a hint provided by the calling instance
1571    *
1572    * The ::open signal is emitted on the primary instance when there are
1573    * files to open. See g_application_open() for more information.
1574    */
1575   g_application_signals[SIGNAL_OPEN] =
1576     g_signal_new (I_("open"), G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
1577                   G_STRUCT_OFFSET (GApplicationClass, open),
1578                   NULL, NULL, NULL,
1579                   G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_STRING);
1580
1581   /**
1582    * GApplication::command-line:
1583    * @application: the application
1584    * @command_line: a #GApplicationCommandLine representing the
1585    *     passed commandline
1586    *
1587    * The ::command-line signal is emitted on the primary instance when
1588    * a commandline is not handled locally. See g_application_run() and
1589    * the #GApplicationCommandLine documentation for more information.
1590    *
1591    * Returns: An integer that is set as the exit status for the calling
1592    *   process. See g_application_command_line_set_exit_status().
1593    */
1594   g_application_signals[SIGNAL_COMMAND_LINE] =
1595     g_signal_new (I_("command-line"), G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
1596                   G_STRUCT_OFFSET (GApplicationClass, command_line),
1597                   g_signal_accumulator_first_wins, NULL,
1598                   NULL,
1599                   G_TYPE_INT, 1, G_TYPE_APPLICATION_COMMAND_LINE);
1600
1601   /**
1602    * GApplication::handle-local-options:
1603    * @application: the application
1604    * @options: the options dictionary
1605    *
1606    * The ::handle-local-options signal is emitted on the local instance
1607    * after the parsing of the commandline options has occurred.
1608    *
1609    * You can add options to be recognised during commandline option
1610    * parsing using g_application_add_main_option_entries() and
1611    * g_application_add_option_group().
1612    *
1613    * Signal handlers can inspect @options (along with values pointed to
1614    * from the @arg_data of an installed #GOptionEntrys) in order to
1615    * decide to perform certain actions, including direct local handling
1616    * (which may be useful for options like --version).
1617    *
1618    * In the event that the application is marked
1619    * %G_APPLICATION_HANDLES_COMMAND_LINE the "normal processing" will
1620    * send the @options dictionary to the primary instance where it can be
1621    * read with g_application_command_line_get_options_dict().  The signal
1622    * handler can modify the dictionary before returning, and the
1623    * modified dictionary will be sent.
1624    *
1625    * In the event that %G_APPLICATION_HANDLES_COMMAND_LINE is not set,
1626    * "normal processing" will treat the remaining uncollected command
1627    * line arguments as filenames or URIs.  If there are no arguments,
1628    * the application is activated by g_application_activate().  One or
1629    * more arguments results in a call to g_application_open().
1630    *
1631    * If you want to handle the local commandline arguments for yourself
1632    * by converting them to calls to g_application_open() or
1633    * g_action_group_activate_action() then you must be sure to register
1634    * the application first.  You should probably not call
1635    * g_application_activate() for yourself, however: just return -1 and
1636    * allow the default handler to do it for you.  This will ensure that
1637    * the `--gapplication-service` switch works properly (i.e. no activation
1638    * in that case).
1639    *
1640    * Note that this signal is emitted from the default implementation of
1641    * local_command_line().  If you override that function and don't
1642    * chain up then this signal will never be emitted.
1643    *
1644    * You can override local_command_line() if you need more powerful
1645    * capabilities than what is provided here, but this should not
1646    * normally be required.
1647    *
1648    * Returns: an exit code. If you have handled your options and want
1649    * to exit the process, return a non-negative option, 0 for success,
1650    * and a positive value for failure. To continue, return -1 to let
1651    * the default option processing continue.
1652    *
1653    * Since: 2.40
1654    **/
1655   g_application_signals[SIGNAL_HANDLE_LOCAL_OPTIONS] =
1656     g_signal_new (I_("handle-local-options"), G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
1657                   G_STRUCT_OFFSET (GApplicationClass, handle_local_options),
1658                   g_application_handle_local_options_accumulator, NULL, NULL,
1659                   G_TYPE_INT, 1, G_TYPE_VARIANT_DICT);
1660
1661   /**
1662    * GApplication::name-lost:
1663    * @application: the application
1664    *
1665    * The ::name-lost signal is emitted only on the registered primary instance
1666    * when a new instance has taken over. This can only happen if the application
1667    * is using the %G_APPLICATION_ALLOW_REPLACEMENT flag.
1668    *
1669    * The default handler for this signal calls g_application_quit().
1670    *
1671    * Returns: %TRUE if the signal has been handled
1672    *
1673    * Since: 2.60
1674    */
1675   g_application_signals[SIGNAL_NAME_LOST] =
1676     g_signal_new (I_("name-lost"), G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
1677                   G_STRUCT_OFFSET (GApplicationClass, name_lost),
1678                   g_signal_accumulator_true_handled, NULL, NULL,
1679                   G_TYPE_BOOLEAN, 0);
1680 }
1681
1682 /* Application ID validity {{{1 */
1683
1684 /**
1685  * g_application_id_is_valid:
1686  * @application_id: a potential application identifier
1687  *
1688  * Checks if @application_id is a valid application identifier.
1689  *
1690  * A valid ID is required for calls to g_application_new() and
1691  * g_application_set_application_id().
1692  *
1693  * Application identifiers follow the same format as
1694  * [D-Bus well-known bus names](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus).
1695  * For convenience, the restrictions on application identifiers are
1696  * reproduced here:
1697  *
1698  * - Application identifiers are composed of 1 or more elements separated by a
1699  *   period (`.`) character. All elements must contain at least one character.
1700  *
1701  * - Each element must only contain the ASCII characters `[A-Z][a-z][0-9]_-`,
1702  *   with `-` discouraged in new application identifiers. Each element must not
1703  *   begin with a digit.
1704  *
1705  * - Application identifiers must contain at least one `.` (period) character
1706  *   (and thus at least two elements).
1707  *
1708  * - Application identifiers must not begin with a `.` (period) character.
1709  *
1710  * - Application identifiers must not exceed 255 characters.
1711  *
1712  * Note that the hyphen (`-`) character is allowed in application identifiers,
1713  * but is problematic or not allowed in various specifications and APIs that
1714  * refer to D-Bus, such as
1715  * [Flatpak application IDs](http://docs.flatpak.org/en/latest/introduction.html#identifiers),
1716  * the
1717  * [`DBusActivatable` interface in the Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#dbus),
1718  * and the convention that an application's "main" interface and object path
1719  * resemble its application identifier and bus name. To avoid situations that
1720  * require special-case handling, it is recommended that new application
1721  * identifiers consistently replace hyphens with underscores.
1722  *
1723  * Like D-Bus interface names, application identifiers should start with the
1724  * reversed DNS domain name of the author of the interface (in lower-case), and
1725  * it is conventional for the rest of the application identifier to consist of
1726  * words run together, with initial capital letters.
1727  *
1728  * As with D-Bus interface names, if the author's DNS domain name contains
1729  * hyphen/minus characters they should be replaced by underscores, and if it
1730  * contains leading digits they should be escaped by prepending an underscore.
1731  * For example, if the owner of 7-zip.org used an application identifier for an
1732  * archiving application, it might be named `org._7_zip.Archiver`.
1733  *
1734  * Returns: %TRUE if @application_id is valid
1735  */
1736 gboolean
1737 g_application_id_is_valid (const gchar *application_id)
1738 {
1739   return g_dbus_is_name (application_id) &&
1740          !g_dbus_is_unique_name (application_id);
1741 }
1742
1743 /* Public Constructor {{{1 */
1744 /**
1745  * g_application_new:
1746  * @application_id: (nullable): the application id
1747  * @flags: the application flags
1748  *
1749  * Creates a new #GApplication instance.
1750  *
1751  * If non-%NULL, the application id must be valid.  See
1752  * g_application_id_is_valid().
1753  *
1754  * If no application ID is given then some features of #GApplication
1755  * (most notably application uniqueness) will be disabled.
1756  *
1757  * Returns: a new #GApplication instance
1758  **/
1759 GApplication *
1760 g_application_new (const gchar       *application_id,
1761                    GApplicationFlags  flags)
1762 {
1763   g_return_val_if_fail (application_id == NULL || g_application_id_is_valid (application_id), NULL);
1764
1765   return g_object_new (G_TYPE_APPLICATION,
1766                        "application-id", application_id,
1767                        "flags", flags,
1768                        NULL);
1769 }
1770
1771 /* Simple get/set: application id, flags, inactivity timeout {{{1 */
1772 /**
1773  * g_application_get_application_id:
1774  * @application: a #GApplication
1775  *
1776  * Gets the unique identifier for @application.
1777  *
1778  * Returns: the identifier for @application, owned by @application
1779  *
1780  * Since: 2.28
1781  **/
1782 const gchar *
1783 g_application_get_application_id (GApplication *application)
1784 {
1785   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
1786
1787   return application->priv->id;
1788 }
1789
1790 /**
1791  * g_application_set_application_id:
1792  * @application: a #GApplication
1793  * @application_id: (nullable): the identifier for @application
1794  *
1795  * Sets the unique identifier for @application.
1796  *
1797  * The application id can only be modified if @application has not yet
1798  * been registered.
1799  *
1800  * If non-%NULL, the application id must be valid.  See
1801  * g_application_id_is_valid().
1802  *
1803  * Since: 2.28
1804  **/
1805 void
1806 g_application_set_application_id (GApplication *application,
1807                                   const gchar  *application_id)
1808 {
1809   g_return_if_fail (G_IS_APPLICATION (application));
1810
1811   if (g_strcmp0 (application->priv->id, application_id) != 0)
1812     {
1813       g_return_if_fail (application_id == NULL || g_application_id_is_valid (application_id));
1814       g_return_if_fail (!application->priv->is_registered);
1815
1816       g_free (application->priv->id);
1817       application->priv->id = g_strdup (application_id);
1818
1819       g_object_notify (G_OBJECT (application), "application-id");
1820     }
1821 }
1822
1823 /**
1824  * g_application_get_flags:
1825  * @application: a #GApplication
1826  *
1827  * Gets the flags for @application.
1828  *
1829  * See #GApplicationFlags.
1830  *
1831  * Returns: the flags for @application
1832  *
1833  * Since: 2.28
1834  **/
1835 GApplicationFlags
1836 g_application_get_flags (GApplication *application)
1837 {
1838   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1839
1840   return application->priv->flags;
1841 }
1842
1843 /**
1844  * g_application_set_flags:
1845  * @application: a #GApplication
1846  * @flags: the flags for @application
1847  *
1848  * Sets the flags for @application.
1849  *
1850  * The flags can only be modified if @application has not yet been
1851  * registered.
1852  *
1853  * See #GApplicationFlags.
1854  *
1855  * Since: 2.28
1856  **/
1857 void
1858 g_application_set_flags (GApplication      *application,
1859                          GApplicationFlags  flags)
1860 {
1861   g_return_if_fail (G_IS_APPLICATION (application));
1862
1863   if (application->priv->flags != flags)
1864     {
1865       g_return_if_fail (!application->priv->is_registered);
1866
1867       application->priv->flags = flags;
1868
1869       g_object_notify (G_OBJECT (application), "flags");
1870     }
1871 }
1872
1873 /**
1874  * g_application_get_resource_base_path:
1875  * @application: a #GApplication
1876  *
1877  * Gets the resource base path of @application.
1878  *
1879  * See g_application_set_resource_base_path() for more information.
1880  *
1881  * Returns: (nullable): the base resource path, if one is set
1882  *
1883  * Since: 2.42
1884  */
1885 const gchar *
1886 g_application_get_resource_base_path (GApplication *application)
1887 {
1888   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
1889
1890   return application->priv->resource_path;
1891 }
1892
1893 /**
1894  * g_application_set_resource_base_path:
1895  * @application: a #GApplication
1896  * @resource_path: (nullable): the resource path to use
1897  *
1898  * Sets (or unsets) the base resource path of @application.
1899  *
1900  * The path is used to automatically load various [application
1901  * resources][gresource] such as menu layouts and action descriptions.
1902  * The various types of resources will be found at fixed names relative
1903  * to the given base path.
1904  *
1905  * By default, the resource base path is determined from the application
1906  * ID by prefixing '/' and replacing each '.' with '/'.  This is done at
1907  * the time that the #GApplication object is constructed.  Changes to
1908  * the application ID after that point will not have an impact on the
1909  * resource base path.
1910  *
1911  * As an example, if the application has an ID of "org.example.app" then
1912  * the default resource base path will be "/org/example/app".  If this
1913  * is a #GtkApplication (and you have not manually changed the path)
1914  * then Gtk will then search for the menus of the application at
1915  * "/org/example/app/gtk/menus.ui".
1916  *
1917  * See #GResource for more information about adding resources to your
1918  * application.
1919  *
1920  * You can disable automatic resource loading functionality by setting
1921  * the path to %NULL.
1922  *
1923  * Changing the resource base path once the application is running is
1924  * not recommended.  The point at which the resource path is consulted
1925  * for forming paths for various purposes is unspecified.  When writing
1926  * a sub-class of #GApplication you should either set the
1927  * #GApplication:resource-base-path property at construction time, or call
1928  * this function during the instance initialization. Alternatively, you
1929  * can call this function in the #GApplicationClass.startup virtual function,
1930  * before chaining up to the parent implementation.
1931  *
1932  * Since: 2.42
1933  */
1934 void
1935 g_application_set_resource_base_path (GApplication *application,
1936                                       const gchar  *resource_path)
1937 {
1938   g_return_if_fail (G_IS_APPLICATION (application));
1939   g_return_if_fail (resource_path == NULL || g_str_has_prefix (resource_path, "/"));
1940
1941   if (g_strcmp0 (application->priv->resource_path, resource_path) != 0)
1942     {
1943       g_free (application->priv->resource_path);
1944
1945       application->priv->resource_path = g_strdup (resource_path);
1946
1947       g_object_notify (G_OBJECT (application), "resource-base-path");
1948     }
1949 }
1950
1951 /**
1952  * g_application_get_inactivity_timeout:
1953  * @application: a #GApplication
1954  *
1955  * Gets the current inactivity timeout for the application.
1956  *
1957  * This is the amount of time (in milliseconds) after the last call to
1958  * g_application_release() before the application stops running.
1959  *
1960  * Returns: the timeout, in milliseconds
1961  *
1962  * Since: 2.28
1963  **/
1964 guint
1965 g_application_get_inactivity_timeout (GApplication *application)
1966 {
1967   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1968
1969   return application->priv->inactivity_timeout;
1970 }
1971
1972 /**
1973  * g_application_set_inactivity_timeout:
1974  * @application: a #GApplication
1975  * @inactivity_timeout: the timeout, in milliseconds
1976  *
1977  * Sets the current inactivity timeout for the application.
1978  *
1979  * This is the amount of time (in milliseconds) after the last call to
1980  * g_application_release() before the application stops running.
1981  *
1982  * This call has no side effects of its own.  The value set here is only
1983  * used for next time g_application_release() drops the use count to
1984  * zero.  Any timeouts currently in progress are not impacted.
1985  *
1986  * Since: 2.28
1987  **/
1988 void
1989 g_application_set_inactivity_timeout (GApplication *application,
1990                                       guint         inactivity_timeout)
1991 {
1992   g_return_if_fail (G_IS_APPLICATION (application));
1993
1994   if (application->priv->inactivity_timeout != inactivity_timeout)
1995     {
1996       application->priv->inactivity_timeout = inactivity_timeout;
1997
1998       g_object_notify (G_OBJECT (application), "inactivity-timeout");
1999     }
2000 }
2001 /* Read-only property getters (is registered, is remote, dbus stuff) {{{1 */
2002 /**
2003  * g_application_get_is_registered:
2004  * @application: a #GApplication
2005  *
2006  * Checks if @application is registered.
2007  *
2008  * An application is registered if g_application_register() has been
2009  * successfully called.
2010  *
2011  * Returns: %TRUE if @application is registered
2012  *
2013  * Since: 2.28
2014  **/
2015 gboolean
2016 g_application_get_is_registered (GApplication *application)
2017 {
2018   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
2019
2020   return application->priv->is_registered;
2021 }
2022
2023 /**
2024  * g_application_get_is_remote:
2025  * @application: a #GApplication
2026  *
2027  * Checks if @application is remote.
2028  *
2029  * If @application is remote then it means that another instance of
2030  * application already exists (the 'primary' instance).  Calls to
2031  * perform actions on @application will result in the actions being
2032  * performed by the primary instance.
2033  *
2034  * The value of this property cannot be accessed before
2035  * g_application_register() has been called.  See
2036  * g_application_get_is_registered().
2037  *
2038  * Returns: %TRUE if @application is remote
2039  *
2040  * Since: 2.28
2041  **/
2042 gboolean
2043 g_application_get_is_remote (GApplication *application)
2044 {
2045   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
2046   g_return_val_if_fail (application->priv->is_registered, FALSE);
2047
2048   return application->priv->is_remote;
2049 }
2050
2051 /**
2052  * g_application_get_dbus_connection:
2053  * @application: a #GApplication
2054  *
2055  * Gets the #GDBusConnection being used by the application, or %NULL.
2056  *
2057  * If #GApplication is using its D-Bus backend then this function will
2058  * return the #GDBusConnection being used for uniqueness and
2059  * communication with the desktop environment and other instances of the
2060  * application.
2061  *
2062  * If #GApplication is not using D-Bus then this function will return
2063  * %NULL.  This includes the situation where the D-Bus backend would
2064  * normally be in use but we were unable to connect to the bus.
2065  *
2066  * This function must not be called before the application has been
2067  * registered.  See g_application_get_is_registered().
2068  *
2069  * Returns: (transfer none): a #GDBusConnection, or %NULL
2070  *
2071  * Since: 2.34
2072  **/
2073 GDBusConnection *
2074 g_application_get_dbus_connection (GApplication *application)
2075 {
2076   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
2077   g_return_val_if_fail (application->priv->is_registered, FALSE);
2078
2079   return g_application_impl_get_dbus_connection (application->priv->impl);
2080 }
2081
2082 /**
2083  * g_application_get_dbus_object_path:
2084  * @application: a #GApplication
2085  *
2086  * Gets the D-Bus object path being used by the application, or %NULL.
2087  *
2088  * If #GApplication is using its D-Bus backend then this function will
2089  * return the D-Bus object path that #GApplication is using.  If the
2090  * application is the primary instance then there is an object published
2091  * at this path.  If the application is not the primary instance then
2092  * the result of this function is undefined.
2093  *
2094  * If #GApplication is not using D-Bus then this function will return
2095  * %NULL.  This includes the situation where the D-Bus backend would
2096  * normally be in use but we were unable to connect to the bus.
2097  *
2098  * This function must not be called before the application has been
2099  * registered.  See g_application_get_is_registered().
2100  *
2101  * Returns: the object path, or %NULL
2102  *
2103  * Since: 2.34
2104  **/
2105 const gchar *
2106 g_application_get_dbus_object_path (GApplication *application)
2107 {
2108   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
2109   g_return_val_if_fail (application->priv->is_registered, FALSE);
2110
2111   return g_application_impl_get_dbus_object_path (application->priv->impl);
2112 }
2113
2114
2115 /* Register {{{1 */
2116 /**
2117  * g_application_register:
2118  * @application: a #GApplication
2119  * @cancellable: (nullable): a #GCancellable, or %NULL
2120  * @error: a pointer to a NULL #GError, or %NULL
2121  *
2122  * Attempts registration of the application.
2123  *
2124  * This is the point at which the application discovers if it is the
2125  * primary instance or merely acting as a remote for an already-existing
2126  * primary instance.  This is implemented by attempting to acquire the
2127  * application identifier as a unique bus name on the session bus using
2128  * GDBus.
2129  *
2130  * If there is no application ID or if %G_APPLICATION_NON_UNIQUE was
2131  * given, then this process will always become the primary instance.
2132  *
2133  * Due to the internal architecture of GDBus, method calls can be
2134  * dispatched at any time (even if a main loop is not running).  For
2135  * this reason, you must ensure that any object paths that you wish to
2136  * register are registered before calling this function.
2137  *
2138  * If the application has already been registered then %TRUE is
2139  * returned with no work performed.
2140  *
2141  * The #GApplication::startup signal is emitted if registration succeeds
2142  * and @application is the primary instance (including the non-unique
2143  * case).
2144  *
2145  * In the event of an error (such as @cancellable being cancelled, or a
2146  * failure to connect to the session bus), %FALSE is returned and @error
2147  * is set appropriately.
2148  *
2149  * Note: the return value of this function is not an indicator that this
2150  * instance is or is not the primary instance of the application.  See
2151  * g_application_get_is_remote() for that.
2152  *
2153  * Returns: %TRUE if registration succeeded
2154  *
2155  * Since: 2.28
2156  **/
2157 gboolean
2158 g_application_register (GApplication  *application,
2159                         GCancellable  *cancellable,
2160                         GError       **error)
2161 {
2162   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
2163
2164   if (!application->priv->is_registered)
2165     {
2166       if (application->priv->id == NULL)
2167         application->priv->flags |= G_APPLICATION_NON_UNIQUE;
2168
2169       application->priv->impl =
2170         g_application_impl_register (application, application->priv->id,
2171                                      application->priv->flags,
2172                                      application->priv->actions,
2173                                      &application->priv->remote_actions,
2174                                      cancellable, error);
2175
2176       if (application->priv->impl == NULL)
2177         return FALSE;
2178
2179       application->priv->is_remote = application->priv->remote_actions != NULL;
2180       application->priv->is_registered = TRUE;
2181
2182       g_object_notify (G_OBJECT (application), "is-registered");
2183
2184       if (!application->priv->is_remote)
2185         {
2186           g_signal_emit (application, g_application_signals[SIGNAL_STARTUP], 0);
2187
2188           if (!application->priv->did_startup)
2189             g_critical ("GApplication subclass '%s' failed to chain up on"
2190                         " ::startup (from start of override function)",
2191                         G_OBJECT_TYPE_NAME (application));
2192         }
2193     }
2194
2195   return TRUE;
2196 }
2197
2198 /* Hold/release {{{1 */
2199 /**
2200  * g_application_hold:
2201  * @application: a #GApplication
2202  *
2203  * Increases the use count of @application.
2204  *
2205  * Use this function to indicate that the application has a reason to
2206  * continue to run.  For example, g_application_hold() is called by GTK+
2207  * when a toplevel window is on the screen.
2208  *
2209  * To cancel the hold, call g_application_release().
2210  **/
2211 void
2212 g_application_hold (GApplication *application)
2213 {
2214   g_return_if_fail (G_IS_APPLICATION (application));
2215
2216   if (application->priv->inactivity_timeout_id)
2217     {
2218       g_source_remove (application->priv->inactivity_timeout_id);
2219       application->priv->inactivity_timeout_id = 0;
2220     }
2221
2222   application->priv->use_count++;
2223 }
2224
2225 static gboolean
2226 inactivity_timeout_expired (gpointer data)
2227 {
2228   GApplication *application = G_APPLICATION (data);
2229
2230   application->priv->inactivity_timeout_id = 0;
2231
2232   return G_SOURCE_REMOVE;
2233 }
2234
2235
2236 /**
2237  * g_application_release:
2238  * @application: a #GApplication
2239  *
2240  * Decrease the use count of @application.
2241  *
2242  * When the use count reaches zero, the application will stop running.
2243  *
2244  * Never call this function except to cancel the effect of a previous
2245  * call to g_application_hold().
2246  **/
2247 void
2248 g_application_release (GApplication *application)
2249 {
2250   g_return_if_fail (G_IS_APPLICATION (application));
2251   g_return_if_fail (application->priv->use_count > 0);
2252
2253   application->priv->use_count--;
2254
2255   if (application->priv->use_count == 0 && application->priv->inactivity_timeout)
2256     application->priv->inactivity_timeout_id = g_timeout_add (application->priv->inactivity_timeout,
2257                                                               inactivity_timeout_expired, application);
2258 }
2259
2260 /* Activate, Open {{{1 */
2261 /**
2262  * g_application_activate:
2263  * @application: a #GApplication
2264  *
2265  * Activates the application.
2266  *
2267  * In essence, this results in the #GApplication::activate signal being
2268  * emitted in the primary instance.
2269  *
2270  * The application must be registered before calling this function.
2271  *
2272  * Since: 2.28
2273  **/
2274 void
2275 g_application_activate (GApplication *application)
2276 {
2277   g_return_if_fail (G_IS_APPLICATION (application));
2278   g_return_if_fail (application->priv->is_registered);
2279
2280   if (application->priv->is_remote)
2281     g_application_impl_activate (application->priv->impl,
2282                                  get_platform_data (application, NULL));
2283
2284   else
2285     g_signal_emit (application, g_application_signals[SIGNAL_ACTIVATE], 0);
2286 }
2287
2288 /**
2289  * g_application_open:
2290  * @application: a #GApplication
2291  * @files: (array length=n_files): an array of #GFiles to open
2292  * @n_files: the length of the @files array
2293  * @hint: a hint (or ""), but never %NULL
2294  *
2295  * Opens the given files.
2296  *
2297  * In essence, this results in the #GApplication::open signal being emitted
2298  * in the primary instance.
2299  *
2300  * @n_files must be greater than zero.
2301  *
2302  * @hint is simply passed through to the ::open signal.  It is
2303  * intended to be used by applications that have multiple modes for
2304  * opening files (eg: "view" vs "edit", etc).  Unless you have a need
2305  * for this functionality, you should use "".
2306  *
2307  * The application must be registered before calling this function
2308  * and it must have the %G_APPLICATION_HANDLES_OPEN flag set.
2309  *
2310  * Since: 2.28
2311  **/
2312 void
2313 g_application_open (GApplication  *application,
2314                     GFile        **files,
2315                     gint           n_files,
2316                     const gchar   *hint)
2317 {
2318   g_return_if_fail (G_IS_APPLICATION (application));
2319   g_return_if_fail (application->priv->flags &
2320                     G_APPLICATION_HANDLES_OPEN);
2321   g_return_if_fail (application->priv->is_registered);
2322
2323   if (application->priv->is_remote)
2324     g_application_impl_open (application->priv->impl,
2325                              files, n_files, hint,
2326                              get_platform_data (application, NULL));
2327
2328   else
2329     g_signal_emit (application, g_application_signals[SIGNAL_OPEN],
2330                    0, files, n_files, hint);
2331 }
2332
2333 /* Run {{{1 */
2334 /**
2335  * g_application_run:
2336  * @application: a #GApplication
2337  * @argc: the argc from main() (or 0 if @argv is %NULL)
2338  * @argv: (array length=argc) (element-type filename) (nullable):
2339  *     the argv from main(), or %NULL
2340  *
2341  * Runs the application.
2342  *
2343  * This function is intended to be run from main() and its return value
2344  * is intended to be returned by main(). Although you are expected to pass
2345  * the @argc, @argv parameters from main() to this function, it is possible
2346  * to pass %NULL if @argv is not available or commandline handling is not
2347  * required.  Note that on Windows, @argc and @argv are ignored, and
2348  * g_win32_get_command_line() is called internally (for proper support
2349  * of Unicode commandline arguments).
2350  *
2351  * #GApplication will attempt to parse the commandline arguments.  You
2352  * can add commandline flags to the list of recognised options by way of
2353  * g_application_add_main_option_entries().  After this, the
2354  * #GApplication::handle-local-options signal is emitted, from which the
2355  * application can inspect the values of its #GOptionEntrys.
2356  *
2357  * #GApplication::handle-local-options is a good place to handle options
2358  * such as `--version`, where an immediate reply from the local process is
2359  * desired (instead of communicating with an already-running instance).
2360  * A #GApplication::handle-local-options handler can stop further processing
2361  * by returning a non-negative value, which then becomes the exit status of
2362  * the process.
2363  *
2364  * What happens next depends on the flags: if
2365  * %G_APPLICATION_HANDLES_COMMAND_LINE was specified then the remaining
2366  * commandline arguments are sent to the primary instance, where a
2367  * #GApplication::command-line signal is emitted.  Otherwise, the
2368  * remaining commandline arguments are assumed to be a list of files.
2369  * If there are no files listed, the application is activated via the
2370  * #GApplication::activate signal.  If there are one or more files, and
2371  * %G_APPLICATION_HANDLES_OPEN was specified then the files are opened
2372  * via the #GApplication::open signal.
2373  *
2374  * If you are interested in doing more complicated local handling of the
2375  * commandline then you should implement your own #GApplication subclass
2376  * and override local_command_line(). In this case, you most likely want
2377  * to return %TRUE from your local_command_line() implementation to
2378  * suppress the default handling. See
2379  * [gapplication-example-cmdline2.c][gapplication-example-cmdline2]
2380  * for an example.
2381  *
2382  * If, after the above is done, the use count of the application is zero
2383  * then the exit status is returned immediately.  If the use count is
2384  * non-zero then the default main context is iterated until the use count
2385  * falls to zero, at which point 0 is returned.
2386  *
2387  * If the %G_APPLICATION_IS_SERVICE flag is set, then the service will
2388  * run for as much as 10 seconds with a use count of zero while waiting
2389  * for the message that caused the activation to arrive.  After that,
2390  * if the use count falls to zero the application will exit immediately,
2391  * except in the case that g_application_set_inactivity_timeout() is in
2392  * use.
2393  *
2394  * This function sets the prgname (g_set_prgname()), if not already set,
2395  * to the basename of argv[0].
2396  *
2397  * Much like g_main_loop_run(), this function will acquire the main context
2398  * for the duration that the application is running.
2399  *
2400  * Since 2.40, applications that are not explicitly flagged as services
2401  * or launchers (ie: neither %G_APPLICATION_IS_SERVICE or
2402  * %G_APPLICATION_IS_LAUNCHER are given as flags) will check (from the
2403  * default handler for local_command_line) if "--gapplication-service"
2404  * was given in the command line.  If this flag is present then normal
2405  * commandline processing is interrupted and the
2406  * %G_APPLICATION_IS_SERVICE flag is set.  This provides a "compromise"
2407  * solution whereby running an application directly from the commandline
2408  * will invoke it in the normal way (which can be useful for debugging)
2409  * while still allowing applications to be D-Bus activated in service
2410  * mode.  The D-Bus service file should invoke the executable with
2411  * "--gapplication-service" as the sole commandline argument.  This
2412  * approach is suitable for use by most graphical applications but
2413  * should not be used from applications like editors that need precise
2414  * control over when processes invoked via the commandline will exit and
2415  * what their exit status will be.
2416  *
2417  * Returns: the exit status
2418  *
2419  * Since: 2.28
2420  **/
2421 int
2422 g_application_run (GApplication  *application,
2423                    int            argc,
2424                    char         **argv)
2425 {
2426   gchar **arguments;
2427   int status;
2428   GMainContext *context;
2429   gboolean acquired_context;
2430
2431   g_return_val_if_fail (G_IS_APPLICATION (application), 1);
2432   g_return_val_if_fail (argc == 0 || argv != NULL, 1);
2433   g_return_val_if_fail (!application->priv->must_quit_now, 1);
2434
2435 #ifdef G_OS_WIN32
2436   {
2437     gint new_argc = 0;
2438
2439     arguments = g_win32_get_command_line ();
2440
2441     /*
2442      * CommandLineToArgvW(), which is called by g_win32_get_command_line(),
2443      * pulls in the whole command line that is used to call the program.  This is
2444      * fine in cases where the program is a .exe program, but in the cases where the
2445      * program is a called via a script, such as PyGObject's gtk-demo.py, which is normally
2446      * called using 'python gtk-demo.py' on Windows, the program name (argv[0])
2447      * returned by g_win32_get_command_line() will not be the argv[0] that ->local_command_line()
2448      * would expect, causing the program to fail with "This application can not open files."
2449      */
2450     new_argc = g_strv_length (arguments);
2451
2452     if (new_argc > argc)
2453       {
2454         gint i;
2455
2456         for (i = 0; i < new_argc - argc; i++)
2457           g_free (arguments[i]);
2458
2459         memmove (&arguments[0],
2460                  &arguments[new_argc - argc],
2461                  sizeof (arguments[0]) * (argc + 1));
2462       }
2463   }
2464 #else
2465   {
2466     gint i;
2467
2468     arguments = g_new (gchar *, argc + 1);
2469     for (i = 0; i < argc; i++)
2470       arguments[i] = g_strdup (argv[i]);
2471     arguments[i] = NULL;
2472   }
2473 #endif
2474
2475   if (g_get_prgname () == NULL && argc > 0)
2476     {
2477       gchar *prgname;
2478
2479       prgname = g_path_get_basename (argv[0]);
2480       g_set_prgname (prgname);
2481       g_free (prgname);
2482     }
2483
2484   context = g_main_context_default ();
2485   acquired_context = g_main_context_acquire (context);
2486   g_return_val_if_fail (acquired_context, 0);
2487
2488   if (!G_APPLICATION_GET_CLASS (application)
2489         ->local_command_line (application, &arguments, &status))
2490     {
2491       GError *error = NULL;
2492
2493       if (!g_application_register (application, NULL, &error))
2494         {
2495           g_printerr ("Failed to register: %s\n", error->message);
2496           g_error_free (error);
2497           return 1;
2498         }
2499
2500       g_application_call_command_line (application, (const gchar **) arguments, NULL, &status);
2501     }
2502
2503   g_strfreev (arguments);
2504
2505   if (application->priv->flags & G_APPLICATION_IS_SERVICE &&
2506       application->priv->is_registered &&
2507       !application->priv->use_count &&
2508       !application->priv->inactivity_timeout_id)
2509     {
2510       application->priv->inactivity_timeout_id =
2511         g_timeout_add (10000, inactivity_timeout_expired, application);
2512     }
2513
2514   while (application->priv->use_count || application->priv->inactivity_timeout_id)
2515     {
2516       if (application->priv->must_quit_now)
2517         break;
2518
2519       g_main_context_iteration (context, TRUE);
2520       status = 0;
2521     }
2522
2523   if (application->priv->is_registered && !application->priv->is_remote)
2524     {
2525       g_signal_emit (application, g_application_signals[SIGNAL_SHUTDOWN], 0);
2526
2527       if (!application->priv->did_shutdown)
2528         g_critical ("GApplication subclass '%s' failed to chain up on"
2529                     " ::shutdown (from end of override function)",
2530                     G_OBJECT_TYPE_NAME (application));
2531     }
2532
2533   if (application->priv->impl)
2534     {
2535       g_application_impl_flush (application->priv->impl);
2536       g_application_impl_destroy (application->priv->impl);
2537       application->priv->impl = NULL;
2538     }
2539
2540   g_settings_sync ();
2541
2542   if (!application->priv->must_quit_now)
2543     while (g_main_context_iteration (context, FALSE))
2544       ;
2545
2546   g_main_context_release (context);
2547
2548   return status;
2549 }
2550
2551 static gchar **
2552 g_application_list_actions (GActionGroup *action_group)
2553 {
2554   GApplication *application = G_APPLICATION (action_group);
2555
2556   g_return_val_if_fail (application->priv->is_registered, NULL);
2557
2558   if (application->priv->remote_actions != NULL)
2559     return g_action_group_list_actions (G_ACTION_GROUP (application->priv->remote_actions));
2560
2561   else if (application->priv->actions != NULL)
2562     return g_action_group_list_actions (application->priv->actions);
2563
2564   else
2565     /* empty string array */
2566     return g_new0 (gchar *, 1);
2567 }
2568
2569 static gboolean
2570 g_application_query_action (GActionGroup        *group,
2571                             const gchar         *action_name,
2572                             gboolean            *enabled,
2573                             const GVariantType **parameter_type,
2574                             const GVariantType **state_type,
2575                             GVariant           **state_hint,
2576                             GVariant           **state)
2577 {
2578   GApplication *application = G_APPLICATION (group);
2579
2580   g_return_val_if_fail (application->priv->is_registered, FALSE);
2581
2582   if (application->priv->remote_actions != NULL)
2583     return g_action_group_query_action (G_ACTION_GROUP (application->priv->remote_actions),
2584                                         action_name,
2585                                         enabled,
2586                                         parameter_type,
2587                                         state_type,
2588                                         state_hint,
2589                                         state);
2590
2591   if (application->priv->actions != NULL)
2592     return g_action_group_query_action (application->priv->actions,
2593                                         action_name,
2594                                         enabled,
2595                                         parameter_type,
2596                                         state_type,
2597                                         state_hint,
2598                                         state);
2599
2600   return FALSE;
2601 }
2602
2603 static void
2604 g_application_change_action_state (GActionGroup *action_group,
2605                                    const gchar  *action_name,
2606                                    GVariant     *value)
2607 {
2608   GApplication *application = G_APPLICATION (action_group);
2609
2610   g_return_if_fail (application->priv->is_remote ||
2611                     application->priv->actions != NULL);
2612   g_return_if_fail (application->priv->is_registered);
2613
2614   if (application->priv->remote_actions)
2615     g_remote_action_group_change_action_state_full (application->priv->remote_actions,
2616                                                     action_name, value, get_platform_data (application, NULL));
2617
2618   else
2619     g_action_group_change_action_state (application->priv->actions, action_name, value);
2620 }
2621
2622 static void
2623 g_application_activate_action (GActionGroup *action_group,
2624                                const gchar  *action_name,
2625                                GVariant     *parameter)
2626 {
2627   GApplication *application = G_APPLICATION (action_group);
2628
2629   g_return_if_fail (application->priv->is_remote ||
2630                     application->priv->actions != NULL);
2631   g_return_if_fail (application->priv->is_registered);
2632
2633   if (application->priv->remote_actions)
2634     g_remote_action_group_activate_action_full (application->priv->remote_actions,
2635                                                 action_name, parameter, get_platform_data (application, NULL));
2636
2637   else
2638     g_action_group_activate_action (application->priv->actions, action_name, parameter);
2639 }
2640
2641 static GAction *
2642 g_application_lookup_action (GActionMap  *action_map,
2643                              const gchar *action_name)
2644 {
2645   GApplication *application = G_APPLICATION (action_map);
2646
2647   g_return_val_if_fail (G_IS_ACTION_MAP (application->priv->actions), NULL);
2648
2649   return g_action_map_lookup_action (G_ACTION_MAP (application->priv->actions), action_name);
2650 }
2651
2652 static void
2653 g_application_add_action (GActionMap *action_map,
2654                           GAction    *action)
2655 {
2656   GApplication *application = G_APPLICATION (action_map);
2657
2658   g_return_if_fail (G_IS_ACTION_MAP (application->priv->actions));
2659
2660   g_action_map_add_action (G_ACTION_MAP (application->priv->actions), action);
2661 }
2662
2663 static void
2664 g_application_remove_action (GActionMap  *action_map,
2665                              const gchar *action_name)
2666 {
2667   GApplication *application = G_APPLICATION (action_map);
2668
2669   g_return_if_fail (G_IS_ACTION_MAP (application->priv->actions));
2670
2671   g_action_map_remove_action (G_ACTION_MAP (application->priv->actions), action_name);
2672 }
2673
2674 static void
2675 g_application_action_group_iface_init (GActionGroupInterface *iface)
2676 {
2677   iface->list_actions = g_application_list_actions;
2678   iface->query_action = g_application_query_action;
2679   iface->change_action_state = g_application_change_action_state;
2680   iface->activate_action = g_application_activate_action;
2681 }
2682
2683 static void
2684 g_application_action_map_iface_init (GActionMapInterface *iface)
2685 {
2686   iface->lookup_action = g_application_lookup_action;
2687   iface->add_action = g_application_add_action;
2688   iface->remove_action = g_application_remove_action;
2689 }
2690
2691 /* Default Application {{{1 */
2692
2693 static GApplication *default_app;
2694
2695 /**
2696  * g_application_get_default:
2697  *
2698  * Returns the default #GApplication instance for this process.
2699  *
2700  * Normally there is only one #GApplication per process and it becomes
2701  * the default when it is created.  You can exercise more control over
2702  * this by using g_application_set_default().
2703  *
2704  * If there is no default application then %NULL is returned.
2705  *
2706  * Returns: (transfer none): the default application for this process, or %NULL
2707  *
2708  * Since: 2.32
2709  **/
2710 GApplication *
2711 g_application_get_default (void)
2712 {
2713   return default_app;
2714 }
2715
2716 /**
2717  * g_application_set_default:
2718  * @application: (nullable): the application to set as default, or %NULL
2719  *
2720  * Sets or unsets the default application for the process, as returned
2721  * by g_application_get_default().
2722  *
2723  * This function does not take its own reference on @application.  If
2724  * @application is destroyed then the default application will revert
2725  * back to %NULL.
2726  *
2727  * Since: 2.32
2728  **/
2729 void
2730 g_application_set_default (GApplication *application)
2731 {
2732   default_app = application;
2733 }
2734
2735 /**
2736  * g_application_quit:
2737  * @application: a #GApplication
2738  *
2739  * Immediately quits the application.
2740  *
2741  * Upon return to the mainloop, g_application_run() will return,
2742  * calling only the 'shutdown' function before doing so.
2743  *
2744  * The hold count is ignored.
2745  * Take care if your code has called g_application_hold() on the application and
2746  * is therefore still expecting it to exist.
2747  * (Note that you may have called g_application_hold() indirectly, for example
2748  * through gtk_application_add_window().)
2749  *
2750  * The result of calling g_application_run() again after it returns is
2751  * unspecified.
2752  *
2753  * Since: 2.32
2754  **/
2755 void
2756 g_application_quit (GApplication *application)
2757 {
2758   g_return_if_fail (G_IS_APPLICATION (application));
2759
2760   application->priv->must_quit_now = TRUE;
2761 }
2762
2763 /**
2764  * g_application_mark_busy:
2765  * @application: a #GApplication
2766  *
2767  * Increases the busy count of @application.
2768  *
2769  * Use this function to indicate that the application is busy, for instance
2770  * while a long running operation is pending.
2771  *
2772  * The busy state will be exposed to other processes, so a session shell will
2773  * use that information to indicate the state to the user (e.g. with a
2774  * spinner).
2775  *
2776  * To cancel the busy indication, use g_application_unmark_busy().
2777  *
2778  * Since: 2.38
2779  **/
2780 void
2781 g_application_mark_busy (GApplication *application)
2782 {
2783   gboolean was_busy;
2784
2785   g_return_if_fail (G_IS_APPLICATION (application));
2786
2787   was_busy = (application->priv->busy_count > 0);
2788   application->priv->busy_count++;
2789
2790   if (!was_busy)
2791     {
2792       g_application_impl_set_busy_state (application->priv->impl, TRUE);
2793       g_object_notify (G_OBJECT (application), "is-busy");
2794     }
2795 }
2796
2797 /**
2798  * g_application_unmark_busy:
2799  * @application: a #GApplication
2800  *
2801  * Decreases the busy count of @application.
2802  *
2803  * When the busy count reaches zero, the new state will be propagated
2804  * to other processes.
2805  *
2806  * This function must only be called to cancel the effect of a previous
2807  * call to g_application_mark_busy().
2808  *
2809  * Since: 2.38
2810  **/
2811 void
2812 g_application_unmark_busy (GApplication *application)
2813 {
2814   g_return_if_fail (G_IS_APPLICATION (application));
2815   g_return_if_fail (application->priv->busy_count > 0);
2816
2817   application->priv->busy_count--;
2818
2819   if (application->priv->busy_count == 0)
2820     {
2821       g_application_impl_set_busy_state (application->priv->impl, FALSE);
2822       g_object_notify (G_OBJECT (application), "is-busy");
2823     }
2824 }
2825
2826 /**
2827  * g_application_get_is_busy:
2828  * @application: a #GApplication
2829  *
2830  * Gets the application's current busy state, as set through
2831  * g_application_mark_busy() or g_application_bind_busy_property().
2832  *
2833  * Returns: %TRUE if @application is currenty marked as busy
2834  *
2835  * Since: 2.44
2836  */
2837 gboolean
2838 g_application_get_is_busy (GApplication *application)
2839 {
2840   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
2841
2842   return application->priv->busy_count > 0;
2843 }
2844
2845 /* Notifications {{{1 */
2846
2847 /**
2848  * g_application_send_notification:
2849  * @application: a #GApplication
2850  * @id: (nullable): id of the notification, or %NULL
2851  * @notification: the #GNotification to send
2852  *
2853  * Sends a notification on behalf of @application to the desktop shell.
2854  * There is no guarantee that the notification is displayed immediately,
2855  * or even at all.
2856  *
2857  * Notifications may persist after the application exits. It will be
2858  * D-Bus-activated when the notification or one of its actions is
2859  * activated.
2860  *
2861  * Modifying @notification after this call has no effect. However, the
2862  * object can be reused for a later call to this function.
2863  *
2864  * @id may be any string that uniquely identifies the event for the
2865  * application. It does not need to be in any special format. For
2866  * example, "new-message" might be appropriate for a notification about
2867  * new messages.
2868  *
2869  * If a previous notification was sent with the same @id, it will be
2870  * replaced with @notification and shown again as if it was a new
2871  * notification. This works even for notifications sent from a previous
2872  * execution of the application, as long as @id is the same string.
2873  *
2874  * @id may be %NULL, but it is impossible to replace or withdraw
2875  * notifications without an id.
2876  *
2877  * If @notification is no longer relevant, it can be withdrawn with
2878  * g_application_withdraw_notification().
2879  *
2880  * Since: 2.40
2881  */
2882 void
2883 g_application_send_notification (GApplication  *application,
2884                                  const gchar   *id,
2885                                  GNotification *notification)
2886 {
2887   gchar *generated_id = NULL;
2888
2889   g_return_if_fail (G_IS_APPLICATION (application));
2890   g_return_if_fail (G_IS_NOTIFICATION (notification));
2891   g_return_if_fail (g_application_get_is_registered (application));
2892   g_return_if_fail (!g_application_get_is_remote (application));
2893
2894   if (application->priv->notifications == NULL)
2895     application->priv->notifications = g_notification_backend_new_default (application);
2896
2897   if (id == NULL)
2898     {
2899       generated_id = g_dbus_generate_guid ();
2900       id = generated_id;
2901     }
2902
2903   g_notification_backend_send_notification (application->priv->notifications, id, notification);
2904
2905   g_free (generated_id);
2906 }
2907
2908 /**
2909  * g_application_withdraw_notification:
2910  * @application: a #GApplication
2911  * @id: id of a previously sent notification
2912  *
2913  * Withdraws a notification that was sent with
2914  * g_application_send_notification().
2915  *
2916  * This call does nothing if a notification with @id doesn't exist or
2917  * the notification was never sent.
2918  *
2919  * This function works even for notifications sent in previous
2920  * executions of this application, as long @id is the same as it was for
2921  * the sent notification.
2922  *
2923  * Note that notifications are dismissed when the user clicks on one
2924  * of the buttons in a notification or triggers its default action, so
2925  * there is no need to explicitly withdraw the notification in that case.
2926  *
2927  * Since: 2.40
2928  */
2929 void
2930 g_application_withdraw_notification (GApplication *application,
2931                                      const gchar  *id)
2932 {
2933   g_return_if_fail (G_IS_APPLICATION (application));
2934   g_return_if_fail (id != NULL);
2935
2936   if (application->priv->notifications == NULL)
2937     application->priv->notifications = g_notification_backend_new_default (application);
2938
2939   g_notification_backend_withdraw_notification (application->priv->notifications, id);
2940 }
2941
2942 /* Busy binding {{{1 */
2943
2944 typedef struct
2945 {
2946   GApplication *app;
2947   gboolean is_busy;
2948 } GApplicationBusyBinding;
2949
2950 static void
2951 g_application_busy_binding_destroy (gpointer  data,
2952                                     GClosure *closure)
2953 {
2954   GApplicationBusyBinding *binding = data;
2955
2956   if (binding->is_busy)
2957     g_application_unmark_busy (binding->app);
2958
2959   g_object_unref (binding->app);
2960   g_slice_free (GApplicationBusyBinding, binding);
2961 }
2962
2963 static void
2964 g_application_notify_busy_binding (GObject    *object,
2965                                    GParamSpec *pspec,
2966                                    gpointer    user_data)
2967 {
2968   GApplicationBusyBinding *binding = user_data;
2969   gboolean is_busy;
2970
2971   g_object_get (object, pspec->name, &is_busy, NULL);
2972
2973   if (is_busy && !binding->is_busy)
2974     g_application_mark_busy (binding->app);
2975   else if (!is_busy && binding->is_busy)
2976     g_application_unmark_busy (binding->app);
2977
2978   binding->is_busy = is_busy;
2979 }
2980
2981 /**
2982  * g_application_bind_busy_property:
2983  * @application: a #GApplication
2984  * @object: (type GObject.Object): a #GObject
2985  * @property: the name of a boolean property of @object
2986  *
2987  * Marks @application as busy (see g_application_mark_busy()) while
2988  * @property on @object is %TRUE.
2989  *
2990  * The binding holds a reference to @application while it is active, but
2991  * not to @object. Instead, the binding is destroyed when @object is
2992  * finalized.
2993  *
2994  * Since: 2.44
2995  */
2996 void
2997 g_application_bind_busy_property (GApplication *application,
2998                                   gpointer      object,
2999                                   const gchar  *property)
3000 {
3001   guint notify_id;
3002   GQuark property_quark;
3003   GParamSpec *pspec;
3004   GApplicationBusyBinding *binding;
3005   GClosure *closure;
3006
3007   g_return_if_fail (G_IS_APPLICATION (application));
3008   g_return_if_fail (G_IS_OBJECT (object));
3009   g_return_if_fail (property != NULL);
3010
3011   notify_id = g_signal_lookup ("notify", G_TYPE_OBJECT);
3012   property_quark = g_quark_from_string (property);
3013   pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (object), property);
3014
3015   g_return_if_fail (pspec != NULL && pspec->value_type == G_TYPE_BOOLEAN);
3016
3017   if (g_signal_handler_find (object, G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_DETAIL | G_SIGNAL_MATCH_FUNC,
3018                              notify_id, property_quark, NULL, g_application_notify_busy_binding, NULL) > 0)
3019     {
3020       g_critical ("%s: '%s' is already bound to the busy state of the application", G_STRFUNC, property);
3021       return;
3022     }
3023
3024   binding = g_slice_new (GApplicationBusyBinding);
3025   binding->app = g_object_ref (application);
3026   binding->is_busy = FALSE;
3027
3028   closure = g_cclosure_new (G_CALLBACK (g_application_notify_busy_binding), binding,
3029                             g_application_busy_binding_destroy);
3030   g_signal_connect_closure_by_id (object, notify_id, property_quark, closure, FALSE);
3031
3032   /* fetch the initial value */
3033   g_application_notify_busy_binding (object, pspec, binding);
3034 }
3035
3036 /**
3037  * g_application_unbind_busy_property:
3038  * @application: a #GApplication
3039  * @object: (type GObject.Object): a #GObject
3040  * @property: the name of a boolean property of @object
3041  *
3042  * Destroys a binding between @property and the busy state of
3043  * @application that was previously created with
3044  * g_application_bind_busy_property().
3045  *
3046  * Since: 2.44
3047  */
3048 void
3049 g_application_unbind_busy_property (GApplication *application,
3050                                     gpointer      object,
3051                                     const gchar  *property)
3052 {
3053   guint notify_id;
3054   GQuark property_quark;
3055   gulong handler_id;
3056
3057   g_return_if_fail (G_IS_APPLICATION (application));
3058   g_return_if_fail (G_IS_OBJECT (object));
3059   g_return_if_fail (property != NULL);
3060
3061   notify_id = g_signal_lookup ("notify", G_TYPE_OBJECT);
3062   property_quark = g_quark_from_string (property);
3063
3064   handler_id = g_signal_handler_find (object, G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_DETAIL | G_SIGNAL_MATCH_FUNC,
3065                                       notify_id, property_quark, NULL, g_application_notify_busy_binding, NULL);
3066   if (handler_id == 0)
3067     {
3068       g_critical ("%s: '%s' is not bound to the busy state of the application", G_STRFUNC, property);
3069       return;
3070     }
3071
3072   g_signal_handler_disconnect (object, handler_id);
3073 }
3074
3075 /* Epilogue {{{1 */
3076 /* vim:set foldmethod=marker: */