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