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