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