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