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