Add return-if-fail checks to g_application_hold/release
[platform/upstream/glib.git] / gio / gapplication.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published
6  * by the Free Software Foundation; either version 2 of the licence or (at
7  * your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General
15  * Public License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Authors: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 /* Prologue {{{1 */
23 #include "config.h"
24
25 #include "gapplication.h"
26
27 #include "gapplicationcommandline.h"
28 #include "gsimpleactiongroup.h"
29 #include "gremoteactiongroup.h"
30 #include "gapplicationimpl.h"
31 #include "gactiongroup.h"
32 #include "gactionmap.h"
33 #include "gmenumodel.h"
34 #include "gsettings.h"
35
36 #include "gioenumtypes.h"
37 #include "gioenums.h"
38 #include "gfile.h"
39
40 #include "glibintl.h"
41
42 #include <string.h>
43
44 /**
45  * SECTION:gapplication
46  * @title: GApplication
47  * @short_description: Core application class
48  *
49  * A #GApplication is the foundation of an application.  It wraps some
50  * low-level platform-specific services and is intended to act as the
51  * foundation for higher-level application classes such as
52  * #GtkApplication or #MxApplication.  In general, you should not use
53  * this class outside of a higher level framework.
54  *
55  * GApplication provides convenient life cycle management by maintaining
56  * a <firstterm>use count</firstterm> for the primary application instance.
57  * The use count can be changed using g_application_hold() and
58  * g_application_release(). If it drops to zero, the application exits.
59  * Higher-level classes such as #GtkApplication employ the use count to
60  * ensure that the application stays alive as long as it has any opened
61  * windows.
62  *
63  * Another feature that GApplication (optionally) provides is process
64  * uniqueness.  Applications can make use of this functionality by
65  * providing a unique application ID.  If given, only one application
66  * with this ID can be running at a time per session.  The session
67  * concept is platform-dependent, but corresponds roughly to a graphical
68  * desktop login.  When your application is launched again, its
69  * arguments are passed through platform communication to the already
70  * running program.  The already running instance of the program is
71  * called the <firstterm>primary instance</firstterm>; for non-unique
72  * applications this is the always the current instance.
73  * On Linux, the D-Bus session bus is used for communication.
74  *
75  * The use of #GApplication differs from some other commonly-used
76  * uniqueness libraries (such as libunique) in important ways.  The
77  * application is not expected to manually register itself and check if
78  * it is the primary instance.  Instead, the <code>main()</code>
79  * function of a #GApplication should do very little more than
80  * instantiating the application instance, possibly connecting signal
81  * handlers, then calling g_application_run().  All checks for
82  * uniqueness are done internally.  If the application is the primary
83  * instance then the startup signal is emitted and the mainloop runs.
84  * If the application is not the primary instance then a signal is sent
85  * to the primary instance and g_application_run() promptly returns.
86  * See the code examples below.
87  *
88  * If used, the expected form of an application identifier is very close
89  * to that of of a
90  * <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-interface">DBus bus name</ulink>.
91  * Examples include: "com.example.MyApp", "org.example.internal-apps.Calculator".
92  * For details on valid application identifiers, see g_application_id_is_valid().
93  *
94  * On Linux, the application identifier is claimed as a well-known bus name
95  * on the user's session bus.  This means that the uniqueness of your
96  * application is scoped to the current session.  It also means that your
97  * application may provide additional services (through registration of other
98  * object paths) at that bus name.  The registration of these object paths
99  * should be done with the shared GDBus session bus.  Note that due to the
100  * internal architecture of GDBus, method calls can be dispatched at any time
101  * (even if a main loop is not running).  For this reason, you must ensure that
102  * any object paths that you wish to register are registered before #GApplication
103  * attempts to acquire the bus name of your application (which happens in
104  * g_application_register()).  Unfortunately, this means that you cannot use
105  * g_application_get_is_remote() to decide if you want to register object paths.
106  *
107  * GApplication also implements the #GActionGroup and #GActionMap
108  * interfaces and lets you easily export actions by adding them with
109  * g_action_map_add_action(). When invoking an action by calling
110  * g_action_group_activate_action() on the application, it is always
111  * invoked in the primary instance. The actions are also exported on
112  * the session bus, and GIO provides the #GDBusActionGroup wrapper to
113  * conveniently access them remotely. GIO provides a #GDBusMenuModel wrapper
114  * for remote access to exported #GMenuModels.
115  *
116  * There is a number of different entry points into a GApplication:
117  * <itemizedlist>
118  * <listitem>via 'Activate' (i.e. just starting the application)</listitem>
119  * <listitem>via 'Open' (i.e. opening some files)</listitem>
120  * <listitem>by handling a command-line</listitem>
121  * <listitem>via activating an action</listitem>
122  * </itemizedlist>
123  * The #GApplication::startup signal lets you handle the application
124  * initialization for all of these in a single place.
125  *
126  * Regardless of which of these entry points is used to start the application,
127  * GApplication passes some <firstterm id="platform-data">platform
128  * data</firstterm> from the launching instance to the primary instance,
129  * in the form of a #GVariant dictionary mapping strings to variants.
130  * To use platform data, override the @before_emit or @after_emit virtual
131  * functions in your #GApplication subclass. When dealing with
132  * #GApplicationCommandLine objects, the platform data is directly
133  * available via g_application_command_line_get_cwd(),
134  * g_application_command_line_get_environ() and
135  * g_application_command_line_get_platform_data().
136  *
137  * As the name indicates, the platform data may vary depending on the
138  * operating system, but it always includes the current directory (key
139  * "cwd"), and optionally the environment (ie the set of environment
140  * variables and their values) of the calling process (key "environ").
141  * The environment is only added to the platform data if the
142  * %G_APPLICATION_SEND_ENVIRONMENT flag is set. #GApplication subclasses
143  * can add their own platform data by overriding the @add_platform_data
144  * virtual function. For instance, #GtkApplication adds startup notification
145  * data in this way.
146  *
147  * To parse commandline arguments you may handle the
148  * #GApplication::command-line signal or override the local_command_line()
149  * vfunc, to parse them in either the primary instance or the local instance,
150  * respectively.
151  *
152  * <example id="gapplication-example-open"><title>Opening files with a GApplication</title>
153  * <programlisting>
154  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-open.c">
155  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
156  * </xi:include>
157  * </programlisting>
158  * </example>
159  *
160  * <example id="gapplication-example-actions"><title>A GApplication with actions</title>
161  * <programlisting>
162  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-actions.c">
163  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
164  * </xi:include>
165  * </programlisting>
166  * </example>
167  *
168  * <example id="gapplication-example-menu"><title>A GApplication with menus</title>
169  * <programlisting>
170  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-menu.c">
171  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
172  * </xi:include>
173  * </programlisting>
174  * </example>
175  *
176  * <example id="gapplication-example-dbushooks"><title>Using extra D-Bus hooks with a GApplication</title>
177  * <programlisting>
178  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-dbushooks.c">
179  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
180  * </xi:include>
181  * </programlisting>
182  * </example>
183  */
184
185 /**
186  * GApplicationClass:
187  * @startup: invoked on the primary instance immediately after registration
188  * @shutdown: invoked only on the registered primary instance immediately
189  *      after the main loop terminates
190  * @activate: invoked on the primary instance when an activation occurs
191  * @open: invoked on the primary instance when there are files to open
192  * @command_line: invoked on the primary instance when a command-line is
193  *   not handled locally
194  * @local_command_line: invoked (locally) when the process has been invoked
195  *     via commandline execution (as opposed to, say, D-Bus activation - which
196  *     is not currently supported by GApplication). The virtual function has
197  *     the chance to inspect (and possibly replace) the list of command line
198  *     arguments. See g_application_run() for more information.
199  * @before_emit: invoked on the primary instance before 'activate', 'open',
200  *     'command-line' or any action invocation, gets the 'platform data' from
201  *     the calling instance
202  * @after_emit: invoked on the primary instance after 'activate', 'open',
203  *     'command-line' or any action invocation, gets the 'platform data' from
204  *     the calling instance
205  * @add_platform_data: invoked (locally) to add 'platform data' to be sent to
206  *     the primary instance when activating, opening or invoking actions
207  * @quit_mainloop: Used to be invoked on the primary instance when the use
208  *     count of the application drops to zero (and after any inactivity
209  *     timeout, if requested). Not used anymore since 2.32
210  * @run_mainloop: Used to be invoked on the primary instance from
211  *     g_application_run() if the use-count is non-zero. Since 2.32,
212  *     GApplication is iterating the main context directly and is not
213  *     using @run_mainloop anymore
214  * @dbus_register: invoked locally during registration, if the application is
215  *     using its D-Bus backend. You can use this to export extra objects on the
216  *     bus, that need to exist before the application tries to own the bus name.
217  *     The function is passed the #GDBusConnection to to session bus, and the
218  *     object path that #GApplication will use to export is D-Bus API.
219  *     If this function returns %TRUE, registration will proceed; otherwise
220  *     registration will abort. Since: 2.34
221  * @dbus_unregister: invoked locally during unregistration, if the application
222  *     is using its D-Bus backend. Use this to undo anything done by the
223  *     @dbus_register vfunc. Since: 2.34
224  *
225  * Virtual function table for #GApplication.
226  *
227  * Since: 2.28
228  */
229
230 struct _GApplicationPrivate
231 {
232   GApplicationFlags  flags;
233   gchar             *id;
234
235   GActionGroup      *actions;
236   GMenuModel        *app_menu;
237   GMenuModel        *menubar;
238
239   guint              inactivity_timeout_id;
240   guint              inactivity_timeout;
241   guint              use_count;
242
243   guint              is_registered : 1;
244   guint              is_remote : 1;
245   guint              did_startup : 1;
246   guint              did_shutdown : 1;
247   guint              must_quit_now : 1;
248
249   GRemoteActionGroup *remote_actions;
250   GApplicationImpl   *impl;
251 };
252
253 enum
254 {
255   PROP_NONE,
256   PROP_APPLICATION_ID,
257   PROP_FLAGS,
258   PROP_IS_REGISTERED,
259   PROP_IS_REMOTE,
260   PROP_INACTIVITY_TIMEOUT,
261   PROP_ACTION_GROUP
262 };
263
264 enum
265 {
266   SIGNAL_STARTUP,
267   SIGNAL_SHUTDOWN,
268   SIGNAL_ACTIVATE,
269   SIGNAL_OPEN,
270   SIGNAL_ACTION,
271   SIGNAL_COMMAND_LINE,
272   NR_SIGNALS
273 };
274
275 static guint g_application_signals[NR_SIGNALS];
276
277 static void g_application_action_group_iface_init (GActionGroupInterface *);
278 static void g_application_action_map_iface_init (GActionMapInterface *);
279 G_DEFINE_TYPE_WITH_CODE (GApplication, g_application, G_TYPE_OBJECT,
280  G_IMPLEMENT_INTERFACE (G_TYPE_ACTION_GROUP, g_application_action_group_iface_init)
281  G_IMPLEMENT_INTERFACE (G_TYPE_ACTION_MAP, g_application_action_map_iface_init))
282
283 /* GApplicationExportedActions {{{1 */
284
285 /* We create a subclass of GSimpleActionGroup that implements
286  * GRemoteActionGroup and deals with the platform data using
287  * GApplication's before/after_emit vfuncs.  This is the action group we
288  * will be exporting.
289  *
290  * We could implement GRemoteActionGroup on GApplication directly, but
291  * this would be potentially extremely confusing to have exposed as part
292  * of the public API of GApplication.  We certainly don't want anyone in
293  * the same process to be calling these APIs...
294  */
295 typedef GSimpleActionGroupClass GApplicationExportedActionsClass;
296 typedef struct
297 {
298   GSimpleActionGroup parent_instance;
299   GApplication *application;
300 } GApplicationExportedActions;
301
302 static GType g_application_exported_actions_get_type   (void);
303 static void  g_application_exported_actions_iface_init (GRemoteActionGroupInterface *iface);
304 G_DEFINE_TYPE_WITH_CODE (GApplicationExportedActions, g_application_exported_actions, G_TYPE_SIMPLE_ACTION_GROUP,
305                          G_IMPLEMENT_INTERFACE (G_TYPE_REMOTE_ACTION_GROUP, g_application_exported_actions_iface_init))
306
307 static void
308 g_application_exported_actions_activate_action_full (GRemoteActionGroup *remote,
309                                                      const gchar        *action_name,
310                                                      GVariant           *parameter,
311                                                      GVariant           *platform_data)
312 {
313   GApplicationExportedActions *exported = (GApplicationExportedActions *) remote;
314
315   G_APPLICATION_GET_CLASS (exported->application)
316     ->before_emit (exported->application, platform_data);
317
318   g_action_group_activate_action (G_ACTION_GROUP (exported), action_name, parameter);
319
320   G_APPLICATION_GET_CLASS (exported->application)
321     ->after_emit (exported->application, platform_data);
322 }
323
324 static void
325 g_application_exported_actions_change_action_state_full (GRemoteActionGroup *remote,
326                                                          const gchar        *action_name,
327                                                          GVariant           *value,
328                                                          GVariant           *platform_data)
329 {
330   GApplicationExportedActions *exported = (GApplicationExportedActions *) remote;
331
332   G_APPLICATION_GET_CLASS (exported->application)
333     ->before_emit (exported->application, platform_data);
334
335   g_action_group_change_action_state (G_ACTION_GROUP (exported), action_name, value);
336
337   G_APPLICATION_GET_CLASS (exported->application)
338     ->after_emit (exported->application, platform_data);
339 }
340
341 static void
342 g_application_exported_actions_init (GApplicationExportedActions *actions)
343 {
344 }
345
346 static void
347 g_application_exported_actions_iface_init (GRemoteActionGroupInterface *iface)
348 {
349   iface->activate_action_full = g_application_exported_actions_activate_action_full;
350   iface->change_action_state_full = g_application_exported_actions_change_action_state_full;
351 }
352
353 static void
354 g_application_exported_actions_class_init (GApplicationExportedActionsClass *class)
355 {
356 }
357
358 static GActionGroup *
359 g_application_exported_actions_new (GApplication *application)
360 {
361   GApplicationExportedActions *actions;
362
363   actions = g_object_new (g_application_exported_actions_get_type (), NULL);
364   actions->application = application;
365
366   return G_ACTION_GROUP (actions);
367 }
368
369 /* vfunc defaults {{{1 */
370 static void
371 g_application_real_before_emit (GApplication *application,
372                                 GVariant     *platform_data)
373 {
374 }
375
376 static void
377 g_application_real_after_emit (GApplication *application,
378                                GVariant     *platform_data)
379 {
380 }
381
382 static void
383 g_application_real_startup (GApplication *application)
384 {
385   application->priv->did_startup = TRUE;
386 }
387
388 static void
389 g_application_real_shutdown (GApplication *application)
390 {
391   application->priv->did_shutdown = TRUE;
392 }
393
394 static void
395 g_application_real_activate (GApplication *application)
396 {
397   if (!g_signal_has_handler_pending (application,
398                                      g_application_signals[SIGNAL_ACTIVATE],
399                                      0, TRUE) &&
400       G_APPLICATION_GET_CLASS (application)->activate == g_application_real_activate)
401     {
402       static gboolean warned;
403
404       if (warned)
405         return;
406
407       g_warning ("Your application does not implement "
408                  "g_application_activate() and has no handlers connected "
409                  "to the 'activate' signal.  It should do one of these.");
410       warned = TRUE;
411     }
412 }
413
414 static void
415 g_application_real_open (GApplication  *application,
416                          GFile        **files,
417                          gint           n_files,
418                          const gchar   *hint)
419 {
420   if (!g_signal_has_handler_pending (application,
421                                      g_application_signals[SIGNAL_OPEN],
422                                      0, TRUE) &&
423       G_APPLICATION_GET_CLASS (application)->open == g_application_real_open)
424     {
425       static gboolean warned;
426
427       if (warned)
428         return;
429
430       g_warning ("Your application claims to support opening files "
431                  "but does not implement g_application_open() and has no "
432                  "handlers connected to the 'open' signal.");
433       warned = TRUE;
434     }
435 }
436
437 static int
438 g_application_real_command_line (GApplication            *application,
439                                  GApplicationCommandLine *cmdline)
440 {
441   if (!g_signal_has_handler_pending (application,
442                                      g_application_signals[SIGNAL_COMMAND_LINE],
443                                      0, TRUE) &&
444       G_APPLICATION_GET_CLASS (application)->command_line == g_application_real_command_line)
445     {
446       static gboolean warned;
447
448       if (warned)
449         return 1;
450
451       g_warning ("Your application claims to support custom command line "
452                  "handling but does not implement g_application_command_line() "
453                  "and has no handlers connected to the 'command-line' signal.");
454
455       warned = TRUE;
456     }
457
458     return 1;
459 }
460
461 static gboolean
462 g_application_real_local_command_line (GApplication   *application,
463                                        gchar        ***arguments,
464                                        int            *exit_status)
465 {
466   if (application->priv->flags & G_APPLICATION_HANDLES_COMMAND_LINE)
467     return FALSE;
468
469   else
470     {
471       GError *error = NULL;
472       gint n_args;
473
474       if (!g_application_register (application, NULL, &error))
475         {
476           g_critical ("%s", error->message);
477           g_error_free (error);
478           *exit_status = 1;
479           return TRUE;
480         }
481
482       n_args = g_strv_length (*arguments);
483
484       if (application->priv->flags & G_APPLICATION_IS_SERVICE)
485         {
486           if ((*exit_status = n_args > 1))
487             {
488               g_printerr ("GApplication service mode takes no arguments.\n");
489               application->priv->flags &= ~G_APPLICATION_IS_SERVICE;
490             }
491
492           return TRUE;
493         }
494
495       if (n_args <= 1)
496         {
497           g_application_activate (application);
498           *exit_status = 0;
499         }
500
501       else
502         {
503           if (~application->priv->flags & G_APPLICATION_HANDLES_OPEN)
504             {
505               g_critical ("This application can not open files.");
506               *exit_status = 1;
507             }
508           else
509             {
510               GFile **files;
511               gint n_files;
512               gint i;
513
514               n_files = n_args - 1;
515               files = g_new (GFile *, n_files);
516
517               for (i = 0; i < n_files; i++)
518                 files[i] = g_file_new_for_commandline_arg ((*arguments)[i + 1]);
519
520               g_application_open (application, files, n_files, "");
521
522               for (i = 0; i < n_files; i++)
523                 g_object_unref (files[i]);
524               g_free (files);
525
526               *exit_status = 0;
527             }
528         }
529
530       return TRUE;
531     }
532 }
533
534 static void
535 g_application_real_add_platform_data (GApplication    *application,
536                                       GVariantBuilder *builder)
537 {
538 }
539
540 static gboolean
541 g_application_real_dbus_register (GApplication    *application,
542                                   GDBusConnection *connection,
543                                   const gchar     *object_path,
544                                   GError         **error)
545 {
546   return TRUE;
547 }
548
549 static void
550 g_application_real_dbus_unregister (GApplication    *application,
551                                     GDBusConnection *connection,
552                                     const gchar     *object_path)
553 {
554 }
555
556 /* GObject implementation stuff {{{1 */
557 static void
558 g_application_set_property (GObject      *object,
559                             guint         prop_id,
560                             const GValue *value,
561                             GParamSpec   *pspec)
562 {
563   GApplication *application = G_APPLICATION (object);
564
565   switch (prop_id)
566     {
567     case PROP_APPLICATION_ID:
568       g_application_set_application_id (application,
569                                         g_value_get_string (value));
570       break;
571
572     case PROP_FLAGS:
573       g_application_set_flags (application, g_value_get_flags (value));
574       break;
575
576     case PROP_INACTIVITY_TIMEOUT:
577       g_application_set_inactivity_timeout (application,
578                                             g_value_get_uint (value));
579       break;
580
581     case PROP_ACTION_GROUP:
582       g_clear_object (&application->priv->actions);
583       application->priv->actions = g_value_dup_object (value);
584       break;
585
586     default:
587       g_assert_not_reached ();
588     }
589 }
590
591 /**
592  * g_application_set_action_group:
593  * @application: a #GApplication
594  * @action_group: (allow-none): a #GActionGroup, or %NULL
595  *
596  * This used to be how actions were associated with a #GApplication.
597  * Now there is #GActionMap for that.
598  *
599  * Since: 2.28
600  *
601  * Deprecated:2.32:Use the #GActionMap interface instead.  Never ever
602  * mix use of this API with use of #GActionMap on the same @application
603  * or things will go very badly wrong.  This function is known to
604  * introduce buggy behaviour (ie: signals not emitted on changes to the
605  * action group), so you should really use #GActionMap instead.
606  **/
607 void
608 g_application_set_action_group (GApplication *application,
609                                 GActionGroup *action_group)
610 {
611   g_return_if_fail (G_IS_APPLICATION (application));
612   g_return_if_fail (!application->priv->is_registered);
613
614   if (application->priv->actions != NULL)
615     g_object_unref (application->priv->actions);
616
617   application->priv->actions = action_group;
618
619   if (application->priv->actions != NULL)
620     g_object_ref (application->priv->actions);
621 }
622
623 static void
624 g_application_get_property (GObject    *object,
625                             guint       prop_id,
626                             GValue     *value,
627                             GParamSpec *pspec)
628 {
629   GApplication *application = G_APPLICATION (object);
630
631   switch (prop_id)
632     {
633     case PROP_APPLICATION_ID:
634       g_value_set_string (value,
635                           g_application_get_application_id (application));
636       break;
637
638     case PROP_FLAGS:
639       g_value_set_flags (value,
640                          g_application_get_flags (application));
641       break;
642
643     case PROP_IS_REGISTERED:
644       g_value_set_boolean (value,
645                            g_application_get_is_registered (application));
646       break;
647
648     case PROP_IS_REMOTE:
649       g_value_set_boolean (value,
650                            g_application_get_is_remote (application));
651       break;
652
653     case PROP_INACTIVITY_TIMEOUT:
654       g_value_set_uint (value,
655                         g_application_get_inactivity_timeout (application));
656       break;
657
658     default:
659       g_assert_not_reached ();
660     }
661 }
662
663 static void
664 g_application_constructed (GObject *object)
665 {
666   GApplication *application = G_APPLICATION (object);
667
668   if (g_application_get_default () == NULL)
669     g_application_set_default (application);
670 }
671
672 static void
673 g_application_finalize (GObject *object)
674 {
675   GApplication *application = G_APPLICATION (object);
676
677   if (application->priv->impl)
678     g_application_impl_destroy (application->priv->impl);
679   g_free (application->priv->id);
680
681   if (g_application_get_default () == application)
682     g_application_set_default (NULL);
683
684   if (application->priv->actions)
685     g_object_unref (application->priv->actions);
686
687   G_OBJECT_CLASS (g_application_parent_class)
688     ->finalize (object);
689 }
690
691 static void
692 g_application_init (GApplication *application)
693 {
694   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application,
695                                                    G_TYPE_APPLICATION,
696                                                    GApplicationPrivate);
697
698   application->priv->actions = g_application_exported_actions_new (application);
699
700   /* application->priv->actions is the one and only ref on the group, so when
701    * we dispose, the action group will die, disconnecting all signals.
702    */
703   g_signal_connect_swapped (application->priv->actions, "action-added",
704                             G_CALLBACK (g_action_group_action_added), application);
705   g_signal_connect_swapped (application->priv->actions, "action-enabled-changed",
706                             G_CALLBACK (g_action_group_action_enabled_changed), application);
707   g_signal_connect_swapped (application->priv->actions, "action-state-changed",
708                             G_CALLBACK (g_action_group_action_state_changed), application);
709   g_signal_connect_swapped (application->priv->actions, "action-removed",
710                             G_CALLBACK (g_action_group_action_removed), application);
711 }
712
713 static void
714 g_application_class_init (GApplicationClass *class)
715 {
716   GObjectClass *object_class = G_OBJECT_CLASS (class);
717
718   object_class->constructed = g_application_constructed;
719   object_class->finalize = g_application_finalize;
720   object_class->get_property = g_application_get_property;
721   object_class->set_property = g_application_set_property;
722
723   class->before_emit = g_application_real_before_emit;
724   class->after_emit = g_application_real_after_emit;
725   class->startup = g_application_real_startup;
726   class->shutdown = g_application_real_shutdown;
727   class->activate = g_application_real_activate;
728   class->open = g_application_real_open;
729   class->command_line = g_application_real_command_line;
730   class->local_command_line = g_application_real_local_command_line;
731   class->add_platform_data = g_application_real_add_platform_data;
732   class->dbus_register = g_application_real_dbus_register;
733   class->dbus_unregister = g_application_real_dbus_unregister;
734
735   g_object_class_install_property (object_class, PROP_APPLICATION_ID,
736     g_param_spec_string ("application-id",
737                          P_("Application identifier"),
738                          P_("The unique identifier for the application"),
739                          NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
740                          G_PARAM_STATIC_STRINGS));
741
742   g_object_class_install_property (object_class, PROP_FLAGS,
743     g_param_spec_flags ("flags",
744                         P_("Application flags"),
745                         P_("Flags specifying the behaviour of the application"),
746                         G_TYPE_APPLICATION_FLAGS, G_APPLICATION_FLAGS_NONE,
747                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
748
749   g_object_class_install_property (object_class, PROP_IS_REGISTERED,
750     g_param_spec_boolean ("is-registered",
751                           P_("Is registered"),
752                           P_("If g_application_register() has been called"),
753                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
754
755   g_object_class_install_property (object_class, PROP_IS_REMOTE,
756     g_param_spec_boolean ("is-remote",
757                           P_("Is remote"),
758                           P_("If this application instance is remote"),
759                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
760
761   g_object_class_install_property (object_class, PROP_INACTIVITY_TIMEOUT,
762     g_param_spec_uint ("inactivity-timeout",
763                        P_("Inactivity timeout"),
764                        P_("Time (ms) to stay alive after becoming idle"),
765                        0, G_MAXUINT, 0,
766                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
767
768   g_object_class_install_property (object_class, PROP_ACTION_GROUP,
769     g_param_spec_object ("action-group",
770                          P_("Action group"),
771                          P_("The group of actions that the application exports"),
772                          G_TYPE_ACTION_GROUP,
773                          G_PARAM_DEPRECATED | G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
774
775   /**
776    * GApplication::startup:
777    * @application: the application
778    *
779    * The ::startup signal is emitted on the primary instance immediately
780    * after registration. See g_application_register().
781    */
782   g_application_signals[SIGNAL_STARTUP] =
783     g_signal_new ("startup", G_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
784                   G_STRUCT_OFFSET (GApplicationClass, startup),
785                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
786
787   /**
788    * GApplication::shutdown:
789    * @application: the application
790    *
791    * The ::shutdown signal is emitted only on the registered primary instance
792    * immediately after the main loop terminates.
793    */
794   g_application_signals[SIGNAL_SHUTDOWN] =
795     g_signal_new ("shutdown", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
796                   G_STRUCT_OFFSET (GApplicationClass, shutdown),
797                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
798
799   /**
800    * GApplication::activate:
801    * @application: the application
802    *
803    * The ::activate signal is emitted on the primary instance when an
804    * activation occurs. See g_application_activate().
805    */
806   g_application_signals[SIGNAL_ACTIVATE] =
807     g_signal_new ("activate", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
808                   G_STRUCT_OFFSET (GApplicationClass, activate),
809                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
810
811
812   /**
813    * GApplication::open:
814    * @application: the application
815    * @files: (array length=n_files) (element-type GFile): an array of #GFiles
816    * @n_files: the length of @files
817    * @hint: a hint provided by the calling instance
818    *
819    * The ::open signal is emitted on the primary instance when there are
820    * files to open. See g_application_open() for more information.
821    */
822   g_application_signals[SIGNAL_OPEN] =
823     g_signal_new ("open", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
824                   G_STRUCT_OFFSET (GApplicationClass, open),
825                   NULL, NULL, NULL,
826                   G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_STRING);
827
828   /**
829    * GApplication::command-line:
830    * @application: the application
831    * @command_line: a #GApplicationCommandLine representing the
832    *     passed commandline
833    *
834    * The ::command-line signal is emitted on the primary instance when
835    * a commandline is not handled locally. See g_application_run() and
836    * the #GApplicationCommandLine documentation for more information.
837    *
838    * Returns: An integer that is set as the exit status for the calling
839    *   process. See g_application_command_line_set_exit_status().
840    */
841   g_application_signals[SIGNAL_COMMAND_LINE] =
842     g_signal_new ("command-line", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
843                   G_STRUCT_OFFSET (GApplicationClass, command_line),
844                   g_signal_accumulator_first_wins, NULL,
845                   NULL,
846                   G_TYPE_INT, 1, G_TYPE_APPLICATION_COMMAND_LINE);
847
848   g_type_class_add_private (class, sizeof (GApplicationPrivate));
849 }
850
851 static GVariant *
852 get_platform_data (GApplication *application)
853 {
854   GVariantBuilder *builder;
855   GVariant *result;
856
857   builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
858
859   {
860     gchar *cwd = g_get_current_dir ();
861     g_variant_builder_add (builder, "{sv}", "cwd",
862                            g_variant_new_bytestring (cwd));
863     g_free (cwd);
864   }
865
866   if (application->priv->flags & G_APPLICATION_SEND_ENVIRONMENT)
867     {
868       GVariant *array;
869       gchar **envp;
870
871       envp = g_get_environ ();
872       array = g_variant_new_bytestring_array ((const gchar **) envp, -1);
873       g_strfreev (envp);
874
875       g_variant_builder_add (builder, "{sv}", "environ", array);
876     }
877
878   G_APPLICATION_GET_CLASS (application)->
879     add_platform_data (application, builder);
880
881   result = g_variant_builder_end (builder);
882   g_variant_builder_unref (builder);
883
884   return result;
885 }
886
887 /* Application ID validity {{{1 */
888
889 /**
890  * g_application_id_is_valid:
891  * @application_id: a potential application identifier
892  *
893  * Checks if @application_id is a valid application identifier.
894  *
895  * A valid ID is required for calls to g_application_new() and
896  * g_application_set_application_id().
897  *
898  * For convenience, the restrictions on application identifiers are
899  * reproduced here:
900  * <itemizedlist>
901  *   <listitem>Application identifiers must contain only the ASCII characters "[A-Z][a-z][0-9]_-." and must not begin with a digit.</listitem>
902  *   <listitem>Application identifiers must contain at least one '.' (period) character (and thus at least three elements).</listitem>
903  *   <listitem>Application identifiers must not begin or end with a '.' (period) character.</listitem>
904  *   <listitem>Application identifiers must not contain consecutive '.' (period) characters.</listitem>
905  *   <listitem>Application identifiers must not exceed 255 characters.</listitem>
906  * </itemizedlist>
907  *
908  * Returns: %TRUE if @application_id is valid
909  **/
910 gboolean
911 g_application_id_is_valid (const gchar *application_id)
912 {
913   gsize len;
914   gboolean allow_dot;
915   gboolean has_dot;
916
917   len = strlen (application_id);
918
919   if (len > 255)
920     return FALSE;
921
922   if (!g_ascii_isalpha (application_id[0]))
923     return FALSE;
924
925   if (application_id[len-1] == '.')
926     return FALSE;
927
928   application_id++;
929   allow_dot = TRUE;
930   has_dot = FALSE;
931   for (; *application_id; application_id++)
932     {
933       if (g_ascii_isalnum (*application_id) ||
934           (*application_id == '-') ||
935           (*application_id == '_'))
936         {
937           allow_dot = TRUE;
938         }
939       else if (allow_dot && *application_id == '.')
940         {
941           has_dot = TRUE;
942           allow_dot = FALSE;
943         }
944       else
945         return FALSE;
946     }
947
948   if (!has_dot)
949     return FALSE;
950
951   return TRUE;
952 }
953
954 /* Public Constructor {{{1 */
955 /**
956  * g_application_new:
957  * @application_id: (allow-none): the application id
958  * @flags: the application flags
959  *
960  * Creates a new #GApplication instance.
961  *
962  * This function calls g_type_init() for you.
963  *
964  * If non-%NULL, the application id must be valid.  See
965  * g_application_id_is_valid().
966  *
967  * If no application ID is given then some features of #GApplication
968  * (most notably application uniqueness) will be disabled.
969  *
970  * Returns: a new #GApplication instance
971  **/
972 GApplication *
973 g_application_new (const gchar       *application_id,
974                    GApplicationFlags  flags)
975 {
976   g_return_val_if_fail (application_id == NULL || g_application_id_is_valid (application_id), NULL);
977
978   g_type_init ();
979
980   return g_object_new (G_TYPE_APPLICATION,
981                        "application-id", application_id,
982                        "flags", flags,
983                        NULL);
984 }
985
986 /* Simple get/set: application id, flags, inactivity timeout {{{1 */
987 /**
988  * g_application_get_application_id:
989  * @application: a #GApplication
990  *
991  * Gets the unique identifier for @application.
992  *
993  * Returns: the identifier for @application, owned by @application
994  *
995  * Since: 2.28
996  **/
997 const gchar *
998 g_application_get_application_id (GApplication *application)
999 {
1000   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
1001
1002   return application->priv->id;
1003 }
1004
1005 /**
1006  * g_application_set_application_id:
1007  * @application: a #GApplication
1008  * @application_id: (allow-none): the identifier for @application
1009  *
1010  * Sets the unique identifier for @application.
1011  *
1012  * The application id can only be modified if @application has not yet
1013  * been registered.
1014  *
1015  * If non-%NULL, the application id must be valid.  See
1016  * g_application_id_is_valid().
1017  *
1018  * Since: 2.28
1019  **/
1020 void
1021 g_application_set_application_id (GApplication *application,
1022                                   const gchar  *application_id)
1023 {
1024   g_return_if_fail (G_IS_APPLICATION (application));
1025
1026   if (g_strcmp0 (application->priv->id, application_id) != 0)
1027     {
1028       g_return_if_fail (application_id == NULL || g_application_id_is_valid (application_id));
1029       g_return_if_fail (!application->priv->is_registered);
1030
1031       g_free (application->priv->id);
1032       application->priv->id = g_strdup (application_id);
1033
1034       g_object_notify (G_OBJECT (application), "application-id");
1035     }
1036 }
1037
1038 /**
1039  * g_application_get_flags:
1040  * @application: a #GApplication
1041  *
1042  * Gets the flags for @application.
1043  *
1044  * See #GApplicationFlags.
1045  *
1046  * Returns: the flags for @application
1047  *
1048  * Since: 2.28
1049  **/
1050 GApplicationFlags
1051 g_application_get_flags (GApplication *application)
1052 {
1053   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1054
1055   return application->priv->flags;
1056 }
1057
1058 /**
1059  * g_application_set_flags:
1060  * @application: a #GApplication
1061  * @flags: the flags for @application
1062  *
1063  * Sets the flags for @application.
1064  *
1065  * The flags can only be modified if @application has not yet been
1066  * registered.
1067  *
1068  * See #GApplicationFlags.
1069  *
1070  * Since: 2.28
1071  **/
1072 void
1073 g_application_set_flags (GApplication      *application,
1074                          GApplicationFlags  flags)
1075 {
1076   g_return_if_fail (G_IS_APPLICATION (application));
1077
1078   if (application->priv->flags != flags)
1079     {
1080       g_return_if_fail (!application->priv->is_registered);
1081
1082       application->priv->flags = flags;
1083
1084       g_object_notify (G_OBJECT (application), "flags");
1085     }
1086 }
1087
1088 /**
1089  * g_application_get_inactivity_timeout:
1090  * @application: a #GApplication
1091  *
1092  * Gets the current inactivity timeout for the application.
1093  *
1094  * This is the amount of time (in milliseconds) after the last call to
1095  * g_application_release() before the application stops running.
1096  *
1097  * Returns: the timeout, in milliseconds
1098  *
1099  * Since: 2.28
1100  **/
1101 guint
1102 g_application_get_inactivity_timeout (GApplication *application)
1103 {
1104   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1105
1106   return application->priv->inactivity_timeout;
1107 }
1108
1109 /**
1110  * g_application_set_inactivity_timeout:
1111  * @application: a #GApplication
1112  * @inactivity_timeout: the timeout, in milliseconds
1113  *
1114  * Sets the current inactivity timeout for the application.
1115  *
1116  * This is the amount of time (in milliseconds) after the last call to
1117  * g_application_release() before the application stops running.
1118  *
1119  * This call has no side effects of its own.  The value set here is only
1120  * used for next time g_application_release() drops the use count to
1121  * zero.  Any timeouts currently in progress are not impacted.
1122  *
1123  * Since: 2.28
1124  **/
1125 void
1126 g_application_set_inactivity_timeout (GApplication *application,
1127                                       guint         inactivity_timeout)
1128 {
1129   g_return_if_fail (G_IS_APPLICATION (application));
1130
1131   if (application->priv->inactivity_timeout != inactivity_timeout)
1132     {
1133       application->priv->inactivity_timeout = inactivity_timeout;
1134
1135       g_object_notify (G_OBJECT (application), "inactivity-timeout");
1136     }
1137 }
1138 /* Read-only property getters (is registered, is remote, dbus stuff) {{{1 */
1139 /**
1140  * g_application_get_is_registered:
1141  * @application: a #GApplication
1142  *
1143  * Checks if @application is registered.
1144  *
1145  * An application is registered if g_application_register() has been
1146  * successfully called.
1147  *
1148  * Returns: %TRUE if @application is registered
1149  *
1150  * Since: 2.28
1151  **/
1152 gboolean
1153 g_application_get_is_registered (GApplication *application)
1154 {
1155   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1156
1157   return application->priv->is_registered;
1158 }
1159
1160 /**
1161  * g_application_get_is_remote:
1162  * @application: a #GApplication
1163  *
1164  * Checks if @application is remote.
1165  *
1166  * If @application is remote then it means that another instance of
1167  * application already exists (the 'primary' instance).  Calls to
1168  * perform actions on @application will result in the actions being
1169  * performed by the primary instance.
1170  *
1171  * The value of this property cannot be accessed before
1172  * g_application_register() has been called.  See
1173  * g_application_get_is_registered().
1174  *
1175  * Returns: %TRUE if @application is remote
1176  *
1177  * Since: 2.28
1178  **/
1179 gboolean
1180 g_application_get_is_remote (GApplication *application)
1181 {
1182   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1183   g_return_val_if_fail (application->priv->is_registered, FALSE);
1184
1185   return application->priv->is_remote;
1186 }
1187
1188 /**
1189  * g_application_get_dbus_connection:
1190  * @application: a #GApplication
1191  *
1192  * Gets the #GDBusConnection being used by the application, or %NULL.
1193  *
1194  * If #GApplication is using its D-Bus backend then this function will
1195  * return the #GDBusConnection being used for uniqueness and
1196  * communication with the desktop environment and other instances of the
1197  * application.
1198  *
1199  * If #GApplication is not using D-Bus then this function will return
1200  * %NULL.  This includes the situation where the D-Bus backend would
1201  * normally be in use but we were unable to connect to the bus.
1202  *
1203  * This function must not be called before the application has been
1204  * registered.  See g_application_get_is_registered().
1205  *
1206  * Returns: (transfer none): a #GDBusConnection, or %NULL
1207  *
1208  * Since: 2.34
1209  **/
1210 GDBusConnection *
1211 g_application_get_dbus_connection (GApplication *application)
1212 {
1213   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1214   g_return_val_if_fail (application->priv->is_registered, FALSE);
1215
1216   return g_application_impl_get_dbus_connection (application->priv->impl);
1217 }
1218
1219 /**
1220  * g_application_get_dbus_object_path:
1221  * @application: a #GApplication
1222  *
1223  * Gets the D-Bus object path being used by the application, or %NULL.
1224  *
1225  * If #GApplication is using its D-Bus backend then this function will
1226  * return the D-Bus object path that #GApplication is using.  If the
1227  * application is the primary instance then there is an object published
1228  * at this path.  If the application is not the primary instance then
1229  * the result of this function is undefined.
1230  *
1231  * If #GApplication is not using D-Bus then this function will return
1232  * %NULL.  This includes the situation where the D-Bus backend would
1233  * normally be in use but we were unable to connect to the bus.
1234  *
1235  * This function must not be called before the application has been
1236  * registered.  See g_application_get_is_registered().
1237  *
1238  * Returns: the object path, or %NULL
1239  *
1240  * Since: 2.34
1241  **/
1242 const gchar *
1243 g_application_get_dbus_object_path (GApplication *application)
1244 {
1245   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1246   g_return_val_if_fail (application->priv->is_registered, FALSE);
1247
1248   return g_application_impl_get_dbus_object_path (application->priv->impl);
1249 }
1250
1251 /* Register {{{1 */
1252 /**
1253  * g_application_register:
1254  * @application: a #GApplication
1255  * @cancellable: (allow-none): a #GCancellable, or %NULL
1256  * @error: a pointer to a NULL #GError, or %NULL
1257  *
1258  * Attempts registration of the application.
1259  *
1260  * This is the point at which the application discovers if it is the
1261  * primary instance or merely acting as a remote for an already-existing
1262  * primary instance.  This is implemented by attempting to acquire the
1263  * application identifier as a unique bus name on the session bus using
1264  * GDBus.
1265  *
1266  * If there is no application ID or if %G_APPLICATION_NON_UNIQUE was
1267  * given, then this process will always become the primary instance.
1268  *
1269  * Due to the internal architecture of GDBus, method calls can be
1270  * dispatched at any time (even if a main loop is not running).  For
1271  * this reason, you must ensure that any object paths that you wish to
1272  * register are registered before calling this function.
1273  *
1274  * If the application has already been registered then %TRUE is
1275  * returned with no work performed.
1276  *
1277  * The #GApplication::startup signal is emitted if registration succeeds
1278  * and @application is the primary instance (including the non-unique
1279  * case).
1280  *
1281  * In the event of an error (such as @cancellable being cancelled, or a
1282  * failure to connect to the session bus), %FALSE is returned and @error
1283  * is set appropriately.
1284  *
1285  * Note: the return value of this function is not an indicator that this
1286  * instance is or is not the primary instance of the application.  See
1287  * g_application_get_is_remote() for that.
1288  *
1289  * Returns: %TRUE if registration succeeded
1290  *
1291  * Since: 2.28
1292  **/
1293 gboolean
1294 g_application_register (GApplication  *application,
1295                         GCancellable  *cancellable,
1296                         GError       **error)
1297 {
1298   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1299
1300   if (!application->priv->is_registered)
1301     {
1302       if (application->priv->id == NULL)
1303         application->priv->flags |= G_APPLICATION_NON_UNIQUE;
1304
1305       application->priv->impl =
1306         g_application_impl_register (application, application->priv->id,
1307                                      application->priv->flags,
1308                                      application->priv->actions,
1309                                      &application->priv->remote_actions,
1310                                      cancellable, error);
1311
1312       if (application->priv->impl == NULL)
1313         return FALSE;
1314
1315       application->priv->is_remote = application->priv->remote_actions != NULL;
1316       application->priv->is_registered = TRUE;
1317
1318       g_object_notify (G_OBJECT (application), "is-registered");
1319
1320       if (!application->priv->is_remote)
1321         {
1322           g_signal_emit (application, g_application_signals[SIGNAL_STARTUP], 0);
1323
1324           if (!application->priv->did_startup)
1325             g_critical ("GApplication subclass '%s' failed to chain up on"
1326                         " ::startup (from start of override function)",
1327                         G_OBJECT_TYPE_NAME (application));
1328         }
1329     }
1330
1331   return TRUE;
1332 }
1333
1334 /* Hold/release {{{1 */
1335 /**
1336  * g_application_hold:
1337  * @application: a #GApplication
1338  *
1339  * Increases the use count of @application.
1340  *
1341  * Use this function to indicate that the application has a reason to
1342  * continue to run.  For example, g_application_hold() is called by GTK+
1343  * when a toplevel window is on the screen.
1344  *
1345  * To cancel the hold, call g_application_release().
1346  **/
1347 void
1348 g_application_hold (GApplication *application)
1349 {
1350   g_return_if_fail (G_IS_APPLICATION (application));
1351
1352   if (application->priv->inactivity_timeout_id)
1353     {
1354       g_source_remove (application->priv->inactivity_timeout_id);
1355       application->priv->inactivity_timeout_id = 0;
1356     }
1357
1358   application->priv->use_count++;
1359 }
1360
1361 static gboolean
1362 inactivity_timeout_expired (gpointer data)
1363 {
1364   GApplication *application = G_APPLICATION (data);
1365
1366   application->priv->inactivity_timeout_id = 0;
1367
1368   return G_SOURCE_REMOVE;
1369 }
1370
1371
1372 /**
1373  * g_application_release:
1374  * @application: a #GApplication
1375  *
1376  * Decrease the use count of @application.
1377  *
1378  * When the use count reaches zero, the application will stop running.
1379  *
1380  * Never call this function except to cancel the effect of a previous
1381  * call to g_application_hold().
1382  **/
1383 void
1384 g_application_release (GApplication *application)
1385 {
1386   g_return_if_fail (G_IS_APPLICATION (application));
1387
1388   application->priv->use_count--;
1389
1390   if (application->priv->use_count == 0 && application->priv->inactivity_timeout)
1391     application->priv->inactivity_timeout_id = g_timeout_add (application->priv->inactivity_timeout,
1392                                                               inactivity_timeout_expired, application);
1393 }
1394
1395 /* Activate, Open {{{1 */
1396 /**
1397  * g_application_activate:
1398  * @application: a #GApplication
1399  *
1400  * Activates the application.
1401  *
1402  * In essence, this results in the #GApplication::activate signal being
1403  * emitted in the primary instance.
1404  *
1405  * The application must be registered before calling this function.
1406  *
1407  * Since: 2.28
1408  **/
1409 void
1410 g_application_activate (GApplication *application)
1411 {
1412   g_return_if_fail (G_IS_APPLICATION (application));
1413   g_return_if_fail (application->priv->is_registered);
1414
1415   if (application->priv->is_remote)
1416     g_application_impl_activate (application->priv->impl,
1417                                  get_platform_data (application));
1418
1419   else
1420     g_signal_emit (application, g_application_signals[SIGNAL_ACTIVATE], 0);
1421 }
1422
1423 /**
1424  * g_application_open:
1425  * @application: a #GApplication
1426  * @files: (array length=n_files): an array of #GFiles to open
1427  * @n_files: the length of the @files array
1428  * @hint: a hint (or ""), but never %NULL
1429  *
1430  * Opens the given files.
1431  *
1432  * In essence, this results in the #GApplication::open signal being emitted
1433  * in the primary instance.
1434  *
1435  * @n_files must be greater than zero.
1436  *
1437  * @hint is simply passed through to the ::open signal.  It is
1438  * intended to be used by applications that have multiple modes for
1439  * opening files (eg: "view" vs "edit", etc).  Unless you have a need
1440  * for this functionality, you should use "".
1441  *
1442  * The application must be registered before calling this function
1443  * and it must have the %G_APPLICATION_HANDLES_OPEN flag set.
1444  *
1445  * Since: 2.28
1446  **/
1447 void
1448 g_application_open (GApplication  *application,
1449                     GFile        **files,
1450                     gint           n_files,
1451                     const gchar   *hint)
1452 {
1453   g_return_if_fail (G_IS_APPLICATION (application));
1454   g_return_if_fail (application->priv->flags &
1455                     G_APPLICATION_HANDLES_OPEN);
1456   g_return_if_fail (application->priv->is_registered);
1457
1458   if (application->priv->is_remote)
1459     g_application_impl_open (application->priv->impl,
1460                              files, n_files, hint,
1461                              get_platform_data (application));
1462
1463   else
1464     g_signal_emit (application, g_application_signals[SIGNAL_OPEN],
1465                    0, files, n_files, hint);
1466 }
1467
1468 /* Run {{{1 */
1469 /**
1470  * g_application_run:
1471  * @application: a #GApplication
1472  * @argc: the argc from main() (or 0 if @argv is %NULL)
1473  * @argv: (array length=argc) (allow-none): the argv from main(), or %NULL
1474  *
1475  * Runs the application.
1476  *
1477  * This function is intended to be run from main() and its return value
1478  * is intended to be returned by main(). Although you are expected to pass
1479  * the @argc, @argv parameters from main() to this function, it is possible
1480  * to pass %NULL if @argv is not available or commandline handling is not
1481  * required.
1482  *
1483  * First, the local_command_line() virtual function is invoked.
1484  * This function always runs on the local instance. It gets passed a pointer
1485  * to a %NULL-terminated copy of @argv and is expected to remove the arguments
1486  * that it handled (shifting up remaining arguments). See
1487  * <xref linkend="gapplication-example-cmdline2"/> for an example of
1488  * parsing @argv manually. Alternatively, you may use the #GOptionContext API,
1489  * after setting <literal>argc = g_strv_length (argv);</literal>.
1490  *
1491  * The last argument to local_command_line() is a pointer to the @status
1492  * variable which can used to set the exit status that is returned from
1493  * g_application_run().
1494  *
1495  * If local_command_line() returns %TRUE, the command line is expected
1496  * to be completely handled, including possibly registering as the primary
1497  * instance, calling g_application_activate() or g_application_open(), etc.
1498  *
1499  * If local_command_line() returns %FALSE then the application is registered
1500  * and the #GApplication::command-line signal is emitted in the primary
1501  * instance (which may or may not be this instance). The signal handler
1502  * gets passed a #GApplicationCommandLine object that (among other things)
1503  * contains the remaining commandline arguments that have not been handled
1504  * by local_command_line().
1505  *
1506  * If the application has the %G_APPLICATION_HANDLES_COMMAND_LINE
1507  * flag set then the default implementation of local_command_line()
1508  * always returns %FALSE immediately, resulting in the commandline
1509  * always being handled in the primary instance.
1510  *
1511  * Otherwise, the default implementation of local_command_line() tries
1512  * to do a couple of things that are probably reasonable for most
1513  * applications.  First, g_application_register() is called to attempt
1514  * to register the application.  If that works, then the command line
1515  * arguments are inspected.  If no commandline arguments are given, then
1516  * g_application_activate() is called.  If commandline arguments are
1517  * given and the %G_APPLICATION_HANDLES_OPEN flag is set then they
1518  * are assumed to be filenames and g_application_open() is called.
1519  *
1520  * If you need to handle commandline arguments that are not filenames,
1521  * and you don't mind commandline handling to happen in the primary
1522  * instance, you should set %G_APPLICATION_HANDLES_COMMAND_LINE and
1523  * process the commandline arguments in your #GApplication::command-line
1524  * signal handler, either manually or using the #GOptionContext API.
1525  *
1526  * If you are interested in doing more complicated local handling of the
1527  * commandline then you should implement your own #GApplication subclass
1528  * and override local_command_line(). In this case, you most likely want
1529  * to return %TRUE from your local_command_line() implementation to
1530  * suppress the default handling. See
1531  * <xref linkend="gapplication-example-cmdline2"/> for an example.
1532  *
1533  * If, after the above is done, the use count of the application is zero
1534  * then the exit status is returned immediately.  If the use count is
1535  * non-zero then the default main context is iterated until the use count
1536  * falls to zero, at which point 0 is returned.
1537  *
1538  * If the %G_APPLICATION_IS_SERVICE flag is set, then the exiting at
1539  * use count of zero is delayed for a while (ie: the instance stays
1540  * around to provide its <emphasis>service</emphasis> to others).
1541  *
1542  * Returns: the exit status
1543  *
1544  * Since: 2.28
1545  **/
1546 int
1547 g_application_run (GApplication  *application,
1548                    int            argc,
1549                    char         **argv)
1550 {
1551   gchar **arguments;
1552   int status;
1553   gint i;
1554
1555   g_return_val_if_fail (G_IS_APPLICATION (application), 1);
1556   g_return_val_if_fail (argc == 0 || argv != NULL, 1);
1557   g_return_val_if_fail (!application->priv->must_quit_now, 1);
1558
1559   arguments = g_new (gchar *, argc + 1);
1560   for (i = 0; i < argc; i++)
1561     arguments[i] = g_strdup (argv[i]);
1562   arguments[i] = NULL;
1563
1564   if (g_get_prgname () == NULL && argc > 0)
1565     {
1566       gchar *prgname;
1567
1568       prgname = g_path_get_basename (argv[0]);
1569       g_set_prgname (prgname);
1570       g_free (prgname);
1571     }
1572
1573   if (!G_APPLICATION_GET_CLASS (application)
1574         ->local_command_line (application, &arguments, &status))
1575     {
1576       GError *error = NULL;
1577
1578       if (!g_application_register (application, NULL, &error))
1579         {
1580           g_printerr ("%s", error->message);
1581           g_error_free (error);
1582           return 1;
1583         }
1584
1585       if (application->priv->is_remote)
1586         {
1587           GVariant *platform_data;
1588
1589           platform_data = get_platform_data (application);
1590           status = g_application_impl_command_line (application->priv->impl,
1591                                                     arguments, platform_data);
1592         }
1593       else
1594         {
1595           GApplicationCommandLine *cmdline;
1596           GVariant *v;
1597
1598           v = g_variant_new_bytestring_array ((const gchar **) arguments, -1);
1599           cmdline = g_object_new (G_TYPE_APPLICATION_COMMAND_LINE,
1600                                   "arguments", v, NULL);
1601           g_signal_emit (application,
1602                          g_application_signals[SIGNAL_COMMAND_LINE],
1603                          0, cmdline, &status);
1604           g_object_unref (cmdline);
1605         }
1606     }
1607
1608   g_strfreev (arguments);
1609
1610   if (application->priv->flags & G_APPLICATION_IS_SERVICE &&
1611       application->priv->is_registered &&
1612       !application->priv->use_count &&
1613       !application->priv->inactivity_timeout_id)
1614     {
1615       application->priv->inactivity_timeout_id =
1616         g_timeout_add (10000, inactivity_timeout_expired, application);
1617     }
1618
1619   while (application->priv->use_count || application->priv->inactivity_timeout_id)
1620     {
1621       if (application->priv->must_quit_now)
1622         break;
1623
1624       g_main_context_iteration (NULL, TRUE);
1625       status = 0;
1626     }
1627
1628   if (!application->priv->is_remote)
1629     {
1630       g_signal_emit (application, g_application_signals[SIGNAL_SHUTDOWN], 0);
1631
1632       if (!application->priv->did_shutdown)
1633         g_critical ("GApplication subclass '%s' failed to chain up on"
1634                     " ::shutdown (from end of override function)",
1635                     G_OBJECT_TYPE_NAME (application));
1636     }
1637
1638   if (application->priv->impl)
1639     g_application_impl_flush (application->priv->impl);
1640
1641   g_settings_sync ();
1642
1643   return status;
1644 }
1645
1646 static gchar **
1647 g_application_list_actions (GActionGroup *action_group)
1648 {
1649   GApplication *application = G_APPLICATION (action_group);
1650
1651   g_return_val_if_fail (application->priv->is_registered, NULL);
1652
1653   if (application->priv->remote_actions != NULL)
1654     return g_action_group_list_actions (G_ACTION_GROUP (application->priv->remote_actions));
1655
1656   else if (application->priv->actions != NULL)
1657     return g_action_group_list_actions (application->priv->actions);
1658
1659   else
1660     /* empty string array */
1661     return g_new0 (gchar *, 1);
1662 }
1663
1664 static gboolean
1665 g_application_query_action (GActionGroup        *group,
1666                             const gchar         *action_name,
1667                             gboolean            *enabled,
1668                             const GVariantType **parameter_type,
1669                             const GVariantType **state_type,
1670                             GVariant           **state_hint,
1671                             GVariant           **state)
1672 {
1673   GApplication *application = G_APPLICATION (group);
1674
1675   g_return_val_if_fail (application->priv->is_registered, FALSE);
1676
1677   if (application->priv->remote_actions != NULL)
1678     return g_action_group_query_action (G_ACTION_GROUP (application->priv->remote_actions),
1679                                         action_name,
1680                                         enabled,
1681                                         parameter_type,
1682                                         state_type,
1683                                         state_hint,
1684                                         state);
1685
1686   if (application->priv->actions != NULL)
1687     return g_action_group_query_action (application->priv->actions,
1688                                         action_name,
1689                                         enabled,
1690                                         parameter_type,
1691                                         state_type,
1692                                         state_hint,
1693                                         state);
1694
1695   return FALSE;
1696 }
1697
1698 static void
1699 g_application_change_action_state (GActionGroup *action_group,
1700                                    const gchar  *action_name,
1701                                    GVariant     *value)
1702 {
1703   GApplication *application = G_APPLICATION (action_group);
1704
1705   g_return_if_fail (application->priv->is_remote ||
1706                     application->priv->actions != NULL);
1707   g_return_if_fail (application->priv->is_registered);
1708
1709   if (application->priv->remote_actions)
1710     g_remote_action_group_change_action_state_full (application->priv->remote_actions,
1711                                                     action_name, value, get_platform_data (application));
1712
1713   else
1714     g_action_group_change_action_state (application->priv->actions, action_name, value);
1715 }
1716
1717 static void
1718 g_application_activate_action (GActionGroup *action_group,
1719                                const gchar  *action_name,
1720                                GVariant     *parameter)
1721 {
1722   GApplication *application = G_APPLICATION (action_group);
1723
1724   g_return_if_fail (application->priv->is_remote ||
1725                     application->priv->actions != NULL);
1726   g_return_if_fail (application->priv->is_registered);
1727
1728   if (application->priv->remote_actions)
1729     g_remote_action_group_activate_action_full (application->priv->remote_actions,
1730                                                 action_name, parameter, get_platform_data (application));
1731
1732   else
1733     g_action_group_activate_action (application->priv->actions, action_name, parameter);
1734 }
1735
1736 static GAction *
1737 g_application_lookup_action (GActionMap  *action_map,
1738                              const gchar *action_name)
1739 {
1740   GApplication *application = G_APPLICATION (action_map);
1741
1742   g_return_val_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions), NULL);
1743
1744   return g_simple_action_group_lookup (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1745 }
1746
1747 static void
1748 g_application_add_action (GActionMap *action_map,
1749                           GAction    *action)
1750 {
1751   GApplication *application = G_APPLICATION (action_map);
1752
1753   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1754
1755   g_simple_action_group_insert (G_SIMPLE_ACTION_GROUP (application->priv->actions), action);
1756 }
1757
1758 static void
1759 g_application_remove_action (GActionMap  *action_map,
1760                              const gchar *action_name)
1761 {
1762   GApplication *application = G_APPLICATION (action_map);
1763
1764   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1765
1766   g_simple_action_group_remove (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1767 }
1768
1769 static void
1770 g_application_action_group_iface_init (GActionGroupInterface *iface)
1771 {
1772   iface->list_actions = g_application_list_actions;
1773   iface->query_action = g_application_query_action;
1774   iface->change_action_state = g_application_change_action_state;
1775   iface->activate_action = g_application_activate_action;
1776 }
1777
1778 static void
1779 g_application_action_map_iface_init (GActionMapInterface *iface)
1780 {
1781   iface->lookup_action = g_application_lookup_action;
1782   iface->add_action = g_application_add_action;
1783   iface->remove_action = g_application_remove_action;
1784 }
1785
1786 /* Default Application {{{1 */
1787
1788 static GApplication *default_app;
1789
1790 /**
1791  * g_application_get_default:
1792  *
1793  * Returns the default #GApplication instance for this process.
1794  *
1795  * Normally there is only one #GApplication per process and it becomes
1796  * the default when it is created.  You can exercise more control over
1797  * this by using g_application_set_default().
1798  *
1799  * If there is no default application then %NULL is returned.
1800  *
1801  * Returns: (transfer none): the default application for this process, or %NULL
1802  *
1803  * Since: 2.32
1804  **/
1805 GApplication *
1806 g_application_get_default (void)
1807 {
1808   return default_app;
1809 }
1810
1811 /**
1812  * g_application_set_default:
1813  * @application: (allow-none): the application to set as default, or %NULL
1814  *
1815  * Sets or unsets the default application for the process, as returned
1816  * by g_application_get_default().
1817  *
1818  * This function does not take its own reference on @application.  If
1819  * @application is destroyed then the default application will revert
1820  * back to %NULL.
1821  *
1822  * Since: 2.32
1823  **/
1824 void
1825 g_application_set_default (GApplication *application)
1826 {
1827   default_app = application;
1828 }
1829
1830 /**
1831  * g_application_quit:
1832  * @application: a #GApplication
1833  *
1834  * Immediately quits the application.
1835  *
1836  * Upon return to the mainloop, g_application_run() will return,
1837  * calling only the 'shutdown' function before doing so.
1838  *
1839  * The hold count is ignored.
1840  *
1841  * The result of calling g_application_run() again after it returns is
1842  * unspecified.
1843  *
1844  * Since: 2.32
1845  **/
1846 void
1847 g_application_quit (GApplication *application)
1848 {
1849   g_return_if_fail (G_IS_APPLICATION (application));
1850
1851   application->priv->must_quit_now = TRUE;
1852 }
1853
1854 /* Epilogue {{{1 */
1855 /* vim:set foldmethod=marker: */