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