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