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