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