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