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