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