Add includes to all gio 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  * @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_HANDLES_COMMAND_LINE)
475     return FALSE;
476
477   else
478     {
479       GError *error = NULL;
480       gint n_args;
481
482       if (!g_application_register (application, NULL, &error))
483         {
484           g_printerr ("Failed to register: %s\n", error->message);
485           g_error_free (error);
486           *exit_status = 1;
487           return TRUE;
488         }
489
490       n_args = g_strv_length (*arguments);
491
492       if (application->priv->flags & G_APPLICATION_IS_SERVICE)
493         {
494           if ((*exit_status = n_args > 1))
495             {
496               g_printerr ("GApplication service mode takes no arguments.\n");
497               application->priv->flags &= ~G_APPLICATION_IS_SERVICE;
498             }
499
500           return TRUE;
501         }
502
503       if (n_args <= 1)
504         {
505           g_application_activate (application);
506           *exit_status = 0;
507         }
508
509       else
510         {
511           if (~application->priv->flags & G_APPLICATION_HANDLES_OPEN)
512             {
513               g_critical ("This application can not open files.");
514               *exit_status = 1;
515             }
516           else
517             {
518               GFile **files;
519               gint n_files;
520               gint i;
521
522               n_files = n_args - 1;
523               files = g_new (GFile *, n_files);
524
525               for (i = 0; i < n_files; i++)
526                 files[i] = g_file_new_for_commandline_arg ((*arguments)[i + 1]);
527
528               g_application_open (application, files, n_files, "");
529
530               for (i = 0; i < n_files; i++)
531                 g_object_unref (files[i]);
532               g_free (files);
533
534               *exit_status = 0;
535             }
536         }
537
538       return TRUE;
539     }
540 }
541
542 static void
543 g_application_real_add_platform_data (GApplication    *application,
544                                       GVariantBuilder *builder)
545 {
546 }
547
548 static gboolean
549 g_application_real_dbus_register (GApplication    *application,
550                                   GDBusConnection *connection,
551                                   const gchar     *object_path,
552                                   GError         **error)
553 {
554   return TRUE;
555 }
556
557 static void
558 g_application_real_dbus_unregister (GApplication    *application,
559                                     GDBusConnection *connection,
560                                     const gchar     *object_path)
561 {
562 }
563
564 /* GObject implementation stuff {{{1 */
565 static void
566 g_application_set_property (GObject      *object,
567                             guint         prop_id,
568                             const GValue *value,
569                             GParamSpec   *pspec)
570 {
571   GApplication *application = G_APPLICATION (object);
572
573   switch (prop_id)
574     {
575     case PROP_APPLICATION_ID:
576       g_application_set_application_id (application,
577                                         g_value_get_string (value));
578       break;
579
580     case PROP_FLAGS:
581       g_application_set_flags (application, g_value_get_flags (value));
582       break;
583
584     case PROP_INACTIVITY_TIMEOUT:
585       g_application_set_inactivity_timeout (application,
586                                             g_value_get_uint (value));
587       break;
588
589     case PROP_ACTION_GROUP:
590       g_clear_object (&application->priv->actions);
591       application->priv->actions = g_value_dup_object (value);
592       break;
593
594     default:
595       g_assert_not_reached ();
596     }
597 }
598
599 /**
600  * g_application_set_action_group:
601  * @application: a #GApplication
602  * @action_group: (allow-none): a #GActionGroup, or %NULL
603  *
604  * This used to be how actions were associated with a #GApplication.
605  * Now there is #GActionMap for that.
606  *
607  * Since: 2.28
608  *
609  * Deprecated:2.32:Use the #GActionMap interface instead.  Never ever
610  * mix use of this API with use of #GActionMap on the same @application
611  * or things will go very badly wrong.  This function is known to
612  * introduce buggy behaviour (ie: signals not emitted on changes to the
613  * action group), so you should really use #GActionMap instead.
614  **/
615 void
616 g_application_set_action_group (GApplication *application,
617                                 GActionGroup *action_group)
618 {
619   g_return_if_fail (G_IS_APPLICATION (application));
620   g_return_if_fail (!application->priv->is_registered);
621
622   if (application->priv->actions != NULL)
623     g_object_unref (application->priv->actions);
624
625   application->priv->actions = action_group;
626
627   if (application->priv->actions != NULL)
628     g_object_ref (application->priv->actions);
629 }
630
631 static void
632 g_application_get_property (GObject    *object,
633                             guint       prop_id,
634                             GValue     *value,
635                             GParamSpec *pspec)
636 {
637   GApplication *application = G_APPLICATION (object);
638
639   switch (prop_id)
640     {
641     case PROP_APPLICATION_ID:
642       g_value_set_string (value,
643                           g_application_get_application_id (application));
644       break;
645
646     case PROP_FLAGS:
647       g_value_set_flags (value,
648                          g_application_get_flags (application));
649       break;
650
651     case PROP_IS_REGISTERED:
652       g_value_set_boolean (value,
653                            g_application_get_is_registered (application));
654       break;
655
656     case PROP_IS_REMOTE:
657       g_value_set_boolean (value,
658                            g_application_get_is_remote (application));
659       break;
660
661     case PROP_INACTIVITY_TIMEOUT:
662       g_value_set_uint (value,
663                         g_application_get_inactivity_timeout (application));
664       break;
665
666     default:
667       g_assert_not_reached ();
668     }
669 }
670
671 static void
672 g_application_constructed (GObject *object)
673 {
674   GApplication *application = G_APPLICATION (object);
675
676   if (g_application_get_default () == NULL)
677     g_application_set_default (application);
678 }
679
680 static void
681 g_application_finalize (GObject *object)
682 {
683   GApplication *application = G_APPLICATION (object);
684
685   if (application->priv->impl)
686     g_application_impl_destroy (application->priv->impl);
687   g_free (application->priv->id);
688
689   if (g_application_get_default () == application)
690     g_application_set_default (NULL);
691
692   if (application->priv->actions)
693     g_object_unref (application->priv->actions);
694
695   if (application->priv->notifications)
696     g_object_unref (application->priv->notifications);
697
698   G_OBJECT_CLASS (g_application_parent_class)
699     ->finalize (object);
700 }
701
702 static void
703 g_application_init (GApplication *application)
704 {
705   application->priv = g_application_get_instance_private (application);
706
707   application->priv->actions = g_application_exported_actions_new (application);
708
709   /* application->priv->actions is the one and only ref on the group, so when
710    * we dispose, the action group will die, disconnecting all signals.
711    */
712   g_signal_connect_swapped (application->priv->actions, "action-added",
713                             G_CALLBACK (g_action_group_action_added), application);
714   g_signal_connect_swapped (application->priv->actions, "action-enabled-changed",
715                             G_CALLBACK (g_action_group_action_enabled_changed), application);
716   g_signal_connect_swapped (application->priv->actions, "action-state-changed",
717                             G_CALLBACK (g_action_group_action_state_changed), application);
718   g_signal_connect_swapped (application->priv->actions, "action-removed",
719                             G_CALLBACK (g_action_group_action_removed), application);
720 }
721
722 static void
723 g_application_class_init (GApplicationClass *class)
724 {
725   GObjectClass *object_class = G_OBJECT_CLASS (class);
726
727   object_class->constructed = g_application_constructed;
728   object_class->finalize = g_application_finalize;
729   object_class->get_property = g_application_get_property;
730   object_class->set_property = g_application_set_property;
731
732   class->before_emit = g_application_real_before_emit;
733   class->after_emit = g_application_real_after_emit;
734   class->startup = g_application_real_startup;
735   class->shutdown = g_application_real_shutdown;
736   class->activate = g_application_real_activate;
737   class->open = g_application_real_open;
738   class->command_line = g_application_real_command_line;
739   class->local_command_line = g_application_real_local_command_line;
740   class->add_platform_data = g_application_real_add_platform_data;
741   class->dbus_register = g_application_real_dbus_register;
742   class->dbus_unregister = g_application_real_dbus_unregister;
743
744   g_object_class_install_property (object_class, PROP_APPLICATION_ID,
745     g_param_spec_string ("application-id",
746                          P_("Application identifier"),
747                          P_("The unique identifier for the application"),
748                          NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
749                          G_PARAM_STATIC_STRINGS));
750
751   g_object_class_install_property (object_class, PROP_FLAGS,
752     g_param_spec_flags ("flags",
753                         P_("Application flags"),
754                         P_("Flags specifying the behaviour of the application"),
755                         G_TYPE_APPLICATION_FLAGS, G_APPLICATION_FLAGS_NONE,
756                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
757
758   g_object_class_install_property (object_class, PROP_IS_REGISTERED,
759     g_param_spec_boolean ("is-registered",
760                           P_("Is registered"),
761                           P_("If g_application_register() has been called"),
762                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
763
764   g_object_class_install_property (object_class, PROP_IS_REMOTE,
765     g_param_spec_boolean ("is-remote",
766                           P_("Is remote"),
767                           P_("If this application instance is remote"),
768                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
769
770   g_object_class_install_property (object_class, PROP_INACTIVITY_TIMEOUT,
771     g_param_spec_uint ("inactivity-timeout",
772                        P_("Inactivity timeout"),
773                        P_("Time (ms) to stay alive after becoming idle"),
774                        0, G_MAXUINT, 0,
775                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
776
777   g_object_class_install_property (object_class, PROP_ACTION_GROUP,
778     g_param_spec_object ("action-group",
779                          P_("Action group"),
780                          P_("The group of actions that the application exports"),
781                          G_TYPE_ACTION_GROUP,
782                          G_PARAM_DEPRECATED | G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
783
784   /**
785    * GApplication::startup:
786    * @application: the application
787    *
788    * The ::startup signal is emitted on the primary instance immediately
789    * after registration. See g_application_register().
790    */
791   g_application_signals[SIGNAL_STARTUP] =
792     g_signal_new ("startup", G_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
793                   G_STRUCT_OFFSET (GApplicationClass, startup),
794                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
795
796   /**
797    * GApplication::shutdown:
798    * @application: the application
799    *
800    * The ::shutdown signal is emitted only on the registered primary instance
801    * immediately after the main loop terminates.
802    */
803   g_application_signals[SIGNAL_SHUTDOWN] =
804     g_signal_new ("shutdown", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
805                   G_STRUCT_OFFSET (GApplicationClass, shutdown),
806                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
807
808   /**
809    * GApplication::activate:
810    * @application: the application
811    *
812    * The ::activate signal is emitted on the primary instance when an
813    * activation occurs. See g_application_activate().
814    */
815   g_application_signals[SIGNAL_ACTIVATE] =
816     g_signal_new ("activate", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
817                   G_STRUCT_OFFSET (GApplicationClass, activate),
818                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
819
820
821   /**
822    * GApplication::open:
823    * @application: the application
824    * @files: (array length=n_files) (element-type GFile): an array of #GFiles
825    * @n_files: the length of @files
826    * @hint: a hint provided by the calling instance
827    *
828    * The ::open signal is emitted on the primary instance when there are
829    * files to open. See g_application_open() for more information.
830    */
831   g_application_signals[SIGNAL_OPEN] =
832     g_signal_new ("open", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
833                   G_STRUCT_OFFSET (GApplicationClass, open),
834                   NULL, NULL, NULL,
835                   G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_STRING);
836
837   /**
838    * GApplication::command-line:
839    * @application: the application
840    * @command_line: a #GApplicationCommandLine representing the
841    *     passed commandline
842    *
843    * The ::command-line signal is emitted on the primary instance when
844    * a commandline is not handled locally. See g_application_run() and
845    * the #GApplicationCommandLine documentation for more information.
846    *
847    * Returns: An integer that is set as the exit status for the calling
848    *   process. See g_application_command_line_set_exit_status().
849    */
850   g_application_signals[SIGNAL_COMMAND_LINE] =
851     g_signal_new ("command-line", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
852                   G_STRUCT_OFFSET (GApplicationClass, command_line),
853                   g_signal_accumulator_first_wins, NULL,
854                   NULL,
855                   G_TYPE_INT, 1, G_TYPE_APPLICATION_COMMAND_LINE);
856 }
857
858 static GVariant *
859 get_platform_data (GApplication *application)
860 {
861   GVariantBuilder *builder;
862   GVariant *result;
863
864   builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
865
866   {
867     gchar *cwd = g_get_current_dir ();
868     g_variant_builder_add (builder, "{sv}", "cwd",
869                            g_variant_new_bytestring (cwd));
870     g_free (cwd);
871   }
872
873   if (application->priv->flags & G_APPLICATION_SEND_ENVIRONMENT)
874     {
875       GVariant *array;
876       gchar **envp;
877
878       envp = g_get_environ ();
879       array = g_variant_new_bytestring_array ((const gchar **) envp, -1);
880       g_strfreev (envp);
881
882       g_variant_builder_add (builder, "{sv}", "environ", array);
883     }
884
885   G_APPLICATION_GET_CLASS (application)->
886     add_platform_data (application, builder);
887
888   result = g_variant_builder_end (builder);
889   g_variant_builder_unref (builder);
890
891   return result;
892 }
893
894 /* Application ID validity {{{1 */
895
896 /**
897  * g_application_id_is_valid:
898  * @application_id: a potential application identifier
899  *
900  * Checks if @application_id is a valid application identifier.
901  *
902  * A valid ID is required for calls to g_application_new() and
903  * g_application_set_application_id().
904  *
905  * For convenience, the restrictions on application identifiers are
906  * reproduced here:
907  * <itemizedlist>
908  *   <listitem>Application identifiers must contain only the ASCII characters "[A-Z][a-z][0-9]_-." and must not begin with a digit.</listitem>
909  *   <listitem>Application identifiers must contain at least one '.' (period) character (and thus at least three elements).</listitem>
910  *   <listitem>Application identifiers must not begin or end with a '.' (period) character.</listitem>
911  *   <listitem>Application identifiers must not contain consecutive '.' (period) characters.</listitem>
912  *   <listitem>Application identifiers must not exceed 255 characters.</listitem>
913  * </itemizedlist>
914  *
915  * Returns: %TRUE if @application_id is valid
916  **/
917 gboolean
918 g_application_id_is_valid (const gchar *application_id)
919 {
920   gsize len;
921   gboolean allow_dot;
922   gboolean has_dot;
923
924   len = strlen (application_id);
925
926   if (len > 255)
927     return FALSE;
928
929   if (!g_ascii_isalpha (application_id[0]))
930     return FALSE;
931
932   if (application_id[len-1] == '.')
933     return FALSE;
934
935   application_id++;
936   allow_dot = TRUE;
937   has_dot = FALSE;
938   for (; *application_id; application_id++)
939     {
940       if (g_ascii_isalnum (*application_id) ||
941           (*application_id == '-') ||
942           (*application_id == '_'))
943         {
944           allow_dot = TRUE;
945         }
946       else if (allow_dot && *application_id == '.')
947         {
948           has_dot = TRUE;
949           allow_dot = FALSE;
950         }
951       else
952         return FALSE;
953     }
954
955   if (!has_dot)
956     return FALSE;
957
958   return TRUE;
959 }
960
961 /* Public Constructor {{{1 */
962 /**
963  * g_application_new:
964  * @application_id: (allow-none): the application id
965  * @flags: the application flags
966  *
967  * Creates a new #GApplication instance.
968  *
969  * If non-%NULL, the application id must be valid.  See
970  * g_application_id_is_valid().
971  *
972  * If no application ID is given then some features of #GApplication
973  * (most notably application uniqueness) will be disabled.
974  *
975  * Returns: a new #GApplication instance
976  **/
977 GApplication *
978 g_application_new (const gchar       *application_id,
979                    GApplicationFlags  flags)
980 {
981   g_return_val_if_fail (application_id == NULL || g_application_id_is_valid (application_id), NULL);
982
983   return g_object_new (G_TYPE_APPLICATION,
984                        "application-id", application_id,
985                        "flags", flags,
986                        NULL);
987 }
988
989 /* Simple get/set: application id, flags, inactivity timeout {{{1 */
990 /**
991  * g_application_get_application_id:
992  * @application: a #GApplication
993  *
994  * Gets the unique identifier for @application.
995  *
996  * Returns: the identifier for @application, owned by @application
997  *
998  * Since: 2.28
999  **/
1000 const gchar *
1001 g_application_get_application_id (GApplication *application)
1002 {
1003   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
1004
1005   return application->priv->id;
1006 }
1007
1008 /**
1009  * g_application_set_application_id:
1010  * @application: a #GApplication
1011  * @application_id: (allow-none): the identifier for @application
1012  *
1013  * Sets the unique identifier for @application.
1014  *
1015  * The application id can only be modified if @application has not yet
1016  * been registered.
1017  *
1018  * If non-%NULL, the application id must be valid.  See
1019  * g_application_id_is_valid().
1020  *
1021  * Since: 2.28
1022  **/
1023 void
1024 g_application_set_application_id (GApplication *application,
1025                                   const gchar  *application_id)
1026 {
1027   g_return_if_fail (G_IS_APPLICATION (application));
1028
1029   if (g_strcmp0 (application->priv->id, application_id) != 0)
1030     {
1031       g_return_if_fail (application_id == NULL || g_application_id_is_valid (application_id));
1032       g_return_if_fail (!application->priv->is_registered);
1033
1034       g_free (application->priv->id);
1035       application->priv->id = g_strdup (application_id);
1036
1037       g_object_notify (G_OBJECT (application), "application-id");
1038     }
1039 }
1040
1041 /**
1042  * g_application_get_flags:
1043  * @application: a #GApplication
1044  *
1045  * Gets the flags for @application.
1046  *
1047  * See #GApplicationFlags.
1048  *
1049  * Returns: the flags for @application
1050  *
1051  * Since: 2.28
1052  **/
1053 GApplicationFlags
1054 g_application_get_flags (GApplication *application)
1055 {
1056   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1057
1058   return application->priv->flags;
1059 }
1060
1061 /**
1062  * g_application_set_flags:
1063  * @application: a #GApplication
1064  * @flags: the flags for @application
1065  *
1066  * Sets the flags for @application.
1067  *
1068  * The flags can only be modified if @application has not yet been
1069  * registered.
1070  *
1071  * See #GApplicationFlags.
1072  *
1073  * Since: 2.28
1074  **/
1075 void
1076 g_application_set_flags (GApplication      *application,
1077                          GApplicationFlags  flags)
1078 {
1079   g_return_if_fail (G_IS_APPLICATION (application));
1080
1081   if (application->priv->flags != flags)
1082     {
1083       g_return_if_fail (!application->priv->is_registered);
1084
1085       application->priv->flags = flags;
1086
1087       g_object_notify (G_OBJECT (application), "flags");
1088     }
1089 }
1090
1091 /**
1092  * g_application_get_inactivity_timeout:
1093  * @application: a #GApplication
1094  *
1095  * Gets the current inactivity timeout for the application.
1096  *
1097  * This is the amount of time (in milliseconds) after the last call to
1098  * g_application_release() before the application stops running.
1099  *
1100  * Returns: the timeout, in milliseconds
1101  *
1102  * Since: 2.28
1103  **/
1104 guint
1105 g_application_get_inactivity_timeout (GApplication *application)
1106 {
1107   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1108
1109   return application->priv->inactivity_timeout;
1110 }
1111
1112 /**
1113  * g_application_set_inactivity_timeout:
1114  * @application: a #GApplication
1115  * @inactivity_timeout: the timeout, in milliseconds
1116  *
1117  * Sets the current inactivity timeout for the application.
1118  *
1119  * This is the amount of time (in milliseconds) after the last call to
1120  * g_application_release() before the application stops running.
1121  *
1122  * This call has no side effects of its own.  The value set here is only
1123  * used for next time g_application_release() drops the use count to
1124  * zero.  Any timeouts currently in progress are not impacted.
1125  *
1126  * Since: 2.28
1127  **/
1128 void
1129 g_application_set_inactivity_timeout (GApplication *application,
1130                                       guint         inactivity_timeout)
1131 {
1132   g_return_if_fail (G_IS_APPLICATION (application));
1133
1134   if (application->priv->inactivity_timeout != inactivity_timeout)
1135     {
1136       application->priv->inactivity_timeout = inactivity_timeout;
1137
1138       g_object_notify (G_OBJECT (application), "inactivity-timeout");
1139     }
1140 }
1141 /* Read-only property getters (is registered, is remote, dbus stuff) {{{1 */
1142 /**
1143  * g_application_get_is_registered:
1144  * @application: a #GApplication
1145  *
1146  * Checks if @application is registered.
1147  *
1148  * An application is registered if g_application_register() has been
1149  * successfully called.
1150  *
1151  * Returns: %TRUE if @application is registered
1152  *
1153  * Since: 2.28
1154  **/
1155 gboolean
1156 g_application_get_is_registered (GApplication *application)
1157 {
1158   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1159
1160   return application->priv->is_registered;
1161 }
1162
1163 /**
1164  * g_application_get_is_remote:
1165  * @application: a #GApplication
1166  *
1167  * Checks if @application is remote.
1168  *
1169  * If @application is remote then it means that another instance of
1170  * application already exists (the 'primary' instance).  Calls to
1171  * perform actions on @application will result in the actions being
1172  * performed by the primary instance.
1173  *
1174  * The value of this property cannot be accessed before
1175  * g_application_register() has been called.  See
1176  * g_application_get_is_registered().
1177  *
1178  * Returns: %TRUE if @application is remote
1179  *
1180  * Since: 2.28
1181  **/
1182 gboolean
1183 g_application_get_is_remote (GApplication *application)
1184 {
1185   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1186   g_return_val_if_fail (application->priv->is_registered, FALSE);
1187
1188   return application->priv->is_remote;
1189 }
1190
1191 /**
1192  * g_application_get_dbus_connection:
1193  * @application: a #GApplication
1194  *
1195  * Gets the #GDBusConnection being used by the application, or %NULL.
1196  *
1197  * If #GApplication is using its D-Bus backend then this function will
1198  * return the #GDBusConnection being used for uniqueness and
1199  * communication with the desktop environment and other instances of the
1200  * application.
1201  *
1202  * If #GApplication is not using D-Bus then this function will return
1203  * %NULL.  This includes the situation where the D-Bus backend would
1204  * normally be in use but we were unable to connect to the bus.
1205  *
1206  * This function must not be called before the application has been
1207  * registered.  See g_application_get_is_registered().
1208  *
1209  * Returns: (transfer none): a #GDBusConnection, or %NULL
1210  *
1211  * Since: 2.34
1212  **/
1213 GDBusConnection *
1214 g_application_get_dbus_connection (GApplication *application)
1215 {
1216   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1217   g_return_val_if_fail (application->priv->is_registered, FALSE);
1218
1219   return g_application_impl_get_dbus_connection (application->priv->impl);
1220 }
1221
1222 /**
1223  * g_application_get_dbus_object_path:
1224  * @application: a #GApplication
1225  *
1226  * Gets the D-Bus object path being used by the application, or %NULL.
1227  *
1228  * If #GApplication is using its D-Bus backend then this function will
1229  * return the D-Bus object path that #GApplication is using.  If the
1230  * application is the primary instance then there is an object published
1231  * at this path.  If the application is not the primary instance then
1232  * the result of this function is undefined.
1233  *
1234  * If #GApplication is not using D-Bus then this function will return
1235  * %NULL.  This includes the situation where the D-Bus backend would
1236  * normally be in use but we were unable to connect to the bus.
1237  *
1238  * This function must not be called before the application has been
1239  * registered.  See g_application_get_is_registered().
1240  *
1241  * Returns: the object path, or %NULL
1242  *
1243  * Since: 2.34
1244  **/
1245 const gchar *
1246 g_application_get_dbus_object_path (GApplication *application)
1247 {
1248   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1249   g_return_val_if_fail (application->priv->is_registered, FALSE);
1250
1251   return g_application_impl_get_dbus_object_path (application->priv->impl);
1252 }
1253
1254 /* Register {{{1 */
1255 /**
1256  * g_application_register:
1257  * @application: a #GApplication
1258  * @cancellable: (allow-none): a #GCancellable, or %NULL
1259  * @error: a pointer to a NULL #GError, or %NULL
1260  *
1261  * Attempts registration of the application.
1262  *
1263  * This is the point at which the application discovers if it is the
1264  * primary instance or merely acting as a remote for an already-existing
1265  * primary instance.  This is implemented by attempting to acquire the
1266  * application identifier as a unique bus name on the session bus using
1267  * GDBus.
1268  *
1269  * If there is no application ID or if %G_APPLICATION_NON_UNIQUE was
1270  * given, then this process will always become the primary instance.
1271  *
1272  * Due to the internal architecture of GDBus, method calls can be
1273  * dispatched at any time (even if a main loop is not running).  For
1274  * this reason, you must ensure that any object paths that you wish to
1275  * register are registered before calling this function.
1276  *
1277  * If the application has already been registered then %TRUE is
1278  * returned with no work performed.
1279  *
1280  * The #GApplication::startup signal is emitted if registration succeeds
1281  * and @application is the primary instance (including the non-unique
1282  * case).
1283  *
1284  * In the event of an error (such as @cancellable being cancelled, or a
1285  * failure to connect to the session bus), %FALSE is returned and @error
1286  * is set appropriately.
1287  *
1288  * Note: the return value of this function is not an indicator that this
1289  * instance is or is not the primary instance of the application.  See
1290  * g_application_get_is_remote() for that.
1291  *
1292  * Returns: %TRUE if registration succeeded
1293  *
1294  * Since: 2.28
1295  **/
1296 gboolean
1297 g_application_register (GApplication  *application,
1298                         GCancellable  *cancellable,
1299                         GError       **error)
1300 {
1301   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1302
1303   if (!application->priv->is_registered)
1304     {
1305       if (application->priv->id == NULL)
1306         application->priv->flags |= G_APPLICATION_NON_UNIQUE;
1307
1308       application->priv->impl =
1309         g_application_impl_register (application, application->priv->id,
1310                                      application->priv->flags,
1311                                      application->priv->actions,
1312                                      &application->priv->remote_actions,
1313                                      cancellable, error);
1314
1315       if (application->priv->impl == NULL)
1316         return FALSE;
1317
1318       application->priv->is_remote = application->priv->remote_actions != NULL;
1319       application->priv->is_registered = TRUE;
1320
1321       g_object_notify (G_OBJECT (application), "is-registered");
1322
1323       if (!application->priv->is_remote)
1324         {
1325           g_signal_emit (application, g_application_signals[SIGNAL_STARTUP], 0);
1326
1327           if (!application->priv->did_startup)
1328             g_critical ("GApplication subclass '%s' failed to chain up on"
1329                         " ::startup (from start of override function)",
1330                         G_OBJECT_TYPE_NAME (application));
1331         }
1332     }
1333
1334   return TRUE;
1335 }
1336
1337 /* Hold/release {{{1 */
1338 /**
1339  * g_application_hold:
1340  * @application: a #GApplication
1341  *
1342  * Increases the use count of @application.
1343  *
1344  * Use this function to indicate that the application has a reason to
1345  * continue to run.  For example, g_application_hold() is called by GTK+
1346  * when a toplevel window is on the screen.
1347  *
1348  * To cancel the hold, call g_application_release().
1349  **/
1350 void
1351 g_application_hold (GApplication *application)
1352 {
1353   g_return_if_fail (G_IS_APPLICATION (application));
1354
1355   if (application->priv->inactivity_timeout_id)
1356     {
1357       g_source_remove (application->priv->inactivity_timeout_id);
1358       application->priv->inactivity_timeout_id = 0;
1359     }
1360
1361   application->priv->use_count++;
1362 }
1363
1364 static gboolean
1365 inactivity_timeout_expired (gpointer data)
1366 {
1367   GApplication *application = G_APPLICATION (data);
1368
1369   application->priv->inactivity_timeout_id = 0;
1370
1371   return G_SOURCE_REMOVE;
1372 }
1373
1374
1375 /**
1376  * g_application_release:
1377  * @application: a #GApplication
1378  *
1379  * Decrease the use count of @application.
1380  *
1381  * When the use count reaches zero, the application will stop running.
1382  *
1383  * Never call this function except to cancel the effect of a previous
1384  * call to g_application_hold().
1385  **/
1386 void
1387 g_application_release (GApplication *application)
1388 {
1389   g_return_if_fail (G_IS_APPLICATION (application));
1390
1391   application->priv->use_count--;
1392
1393   if (application->priv->use_count == 0 && application->priv->inactivity_timeout)
1394     application->priv->inactivity_timeout_id = g_timeout_add (application->priv->inactivity_timeout,
1395                                                               inactivity_timeout_expired, application);
1396 }
1397
1398 /* Activate, Open {{{1 */
1399 /**
1400  * g_application_activate:
1401  * @application: a #GApplication
1402  *
1403  * Activates the application.
1404  *
1405  * In essence, this results in the #GApplication::activate signal being
1406  * emitted in the primary instance.
1407  *
1408  * The application must be registered before calling this function.
1409  *
1410  * Since: 2.28
1411  **/
1412 void
1413 g_application_activate (GApplication *application)
1414 {
1415   g_return_if_fail (G_IS_APPLICATION (application));
1416   g_return_if_fail (application->priv->is_registered);
1417
1418   if (application->priv->is_remote)
1419     g_application_impl_activate (application->priv->impl,
1420                                  get_platform_data (application));
1421
1422   else
1423     g_signal_emit (application, g_application_signals[SIGNAL_ACTIVATE], 0);
1424 }
1425
1426 /**
1427  * g_application_open:
1428  * @application: a #GApplication
1429  * @files: (array length=n_files): an array of #GFiles to open
1430  * @n_files: the length of the @files array
1431  * @hint: a hint (or ""), but never %NULL
1432  *
1433  * Opens the given files.
1434  *
1435  * In essence, this results in the #GApplication::open signal being emitted
1436  * in the primary instance.
1437  *
1438  * @n_files must be greater than zero.
1439  *
1440  * @hint is simply passed through to the ::open signal.  It is
1441  * intended to be used by applications that have multiple modes for
1442  * opening files (eg: "view" vs "edit", etc).  Unless you have a need
1443  * for this functionality, you should use "".
1444  *
1445  * The application must be registered before calling this function
1446  * and it must have the %G_APPLICATION_HANDLES_OPEN flag set.
1447  *
1448  * Since: 2.28
1449  **/
1450 void
1451 g_application_open (GApplication  *application,
1452                     GFile        **files,
1453                     gint           n_files,
1454                     const gchar   *hint)
1455 {
1456   g_return_if_fail (G_IS_APPLICATION (application));
1457   g_return_if_fail (application->priv->flags &
1458                     G_APPLICATION_HANDLES_OPEN);
1459   g_return_if_fail (application->priv->is_registered);
1460
1461   if (application->priv->is_remote)
1462     g_application_impl_open (application->priv->impl,
1463                              files, n_files, hint,
1464                              get_platform_data (application));
1465
1466   else
1467     g_signal_emit (application, g_application_signals[SIGNAL_OPEN],
1468                    0, files, n_files, hint);
1469 }
1470
1471 /* Run {{{1 */
1472 /**
1473  * g_application_run:
1474  * @application: a #GApplication
1475  * @argc: the argc from main() (or 0 if @argv is %NULL)
1476  * @argv: (array length=argc) (allow-none): the argv from main(), or %NULL
1477  *
1478  * Runs the application.
1479  *
1480  * This function is intended to be run from main() and its return value
1481  * is intended to be returned by main(). Although you are expected to pass
1482  * the @argc, @argv parameters from main() to this function, it is possible
1483  * to pass %NULL if @argv is not available or commandline handling is not
1484  * required.
1485  *
1486  * First, the local_command_line() virtual function is invoked.
1487  * This function always runs on the local instance. It gets passed a pointer
1488  * to a %NULL-terminated copy of @argv and is expected to remove the arguments
1489  * that it handled (shifting up remaining arguments). See
1490  * <xref linkend="gapplication-example-cmdline2"/> for an example of
1491  * parsing @argv manually. Alternatively, you may use the #GOptionContext API,
1492  * after setting <literal>argc = g_strv_length (argv);</literal>.
1493  *
1494  * The last argument to local_command_line() is a pointer to the @status
1495  * variable which can used to set the exit status that is returned from
1496  * g_application_run().
1497  *
1498  * If local_command_line() returns %TRUE, the command line is expected
1499  * to be completely handled, including possibly registering as the primary
1500  * instance, calling g_application_activate() or g_application_open(), etc.
1501  *
1502  * If local_command_line() returns %FALSE then the application is registered
1503  * and the #GApplication::command-line signal is emitted in the primary
1504  * instance (which may or may not be this instance). The signal handler
1505  * gets passed a #GApplicationCommandLine object that (among other things)
1506  * contains the remaining commandline arguments that have not been handled
1507  * by local_command_line().
1508  *
1509  * If the application has the %G_APPLICATION_HANDLES_COMMAND_LINE
1510  * flag set then the default implementation of local_command_line()
1511  * always returns %FALSE immediately, resulting in the commandline
1512  * always being handled in the primary instance.
1513  *
1514  * Otherwise, the default implementation of local_command_line() tries
1515  * to do a couple of things that are probably reasonable for most
1516  * applications.  First, g_application_register() is called to attempt
1517  * to register the application.  If that works, then the command line
1518  * arguments are inspected.  If no commandline arguments are given, then
1519  * g_application_activate() is called.  If commandline arguments are
1520  * given and the %G_APPLICATION_HANDLES_OPEN flag is set then they
1521  * are assumed to be filenames and g_application_open() is called.
1522  *
1523  * If you need to handle commandline arguments that are not filenames,
1524  * and you don't mind commandline handling to happen in the primary
1525  * instance, you should set %G_APPLICATION_HANDLES_COMMAND_LINE and
1526  * process the commandline arguments in your #GApplication::command-line
1527  * signal handler, either manually or using the #GOptionContext API.
1528  *
1529  * If you are interested in doing more complicated local handling of the
1530  * commandline then you should implement your own #GApplication subclass
1531  * and override local_command_line(). In this case, you most likely want
1532  * to return %TRUE from your local_command_line() implementation to
1533  * suppress the default handling. See
1534  * <xref linkend="gapplication-example-cmdline2"/> for an example.
1535  *
1536  * If, after the above is done, the use count of the application is zero
1537  * then the exit status is returned immediately.  If the use count is
1538  * non-zero then the default main context is iterated until the use count
1539  * falls to zero, at which point 0 is returned.
1540  *
1541  * If the %G_APPLICATION_IS_SERVICE flag is set, then the service will
1542  * run for as much as 10 seconds with a use count of zero while waiting
1543  * for the message that caused the activation to arrive.  After that,
1544  * if the use count falls to zero the application will exit immediately,
1545  * except in the case that g_application_set_inactivity_timeout() is in
1546  * use.
1547  *
1548  * This function sets the prgname (g_set_prgname()), if not already set,
1549  * to the basename of argv[0].  Since 2.38, if %G_APPLICATION_IS_SERVICE
1550  * is specified, the prgname is set to the application ID.  The main
1551  * impact of this is is that the wmclass of windows created by Gtk+ will
1552  * be set accordingly, which helps the window manager determine which
1553  * application is showing the window.
1554  *
1555  * Returns: the exit status
1556  *
1557  * Since: 2.28
1558  **/
1559 int
1560 g_application_run (GApplication  *application,
1561                    int            argc,
1562                    char         **argv)
1563 {
1564   gchar **arguments;
1565   int status;
1566   gint i;
1567
1568   g_return_val_if_fail (G_IS_APPLICATION (application), 1);
1569   g_return_val_if_fail (argc == 0 || argv != NULL, 1);
1570   g_return_val_if_fail (!application->priv->must_quit_now, 1);
1571
1572   arguments = g_new (gchar *, argc + 1);
1573   for (i = 0; i < argc; i++)
1574     arguments[i] = g_strdup (argv[i]);
1575   arguments[i] = NULL;
1576
1577   if (g_get_prgname () == NULL)
1578     {
1579       if (application->priv->flags & G_APPLICATION_IS_SERVICE)
1580         {
1581           g_set_prgname (application->priv->id);
1582         }
1583       else if (argc > 0)
1584         {
1585           gchar *prgname;
1586
1587           prgname = g_path_get_basename (argv[0]);
1588           g_set_prgname (prgname);
1589           g_free (prgname);
1590         }
1591     }
1592
1593   if (!G_APPLICATION_GET_CLASS (application)
1594         ->local_command_line (application, &arguments, &status))
1595     {
1596       GError *error = NULL;
1597
1598       if (!g_application_register (application, NULL, &error))
1599         {
1600           g_printerr ("Failed to register: %s\n", error->message);
1601           g_error_free (error);
1602           return 1;
1603         }
1604
1605       if (application->priv->is_remote)
1606         {
1607           GVariant *platform_data;
1608
1609           platform_data = get_platform_data (application);
1610           status = g_application_impl_command_line (application->priv->impl,
1611                                                     arguments, platform_data);
1612         }
1613       else
1614         {
1615           GApplicationCommandLine *cmdline;
1616           GVariant *v;
1617
1618           v = g_variant_new_bytestring_array ((const gchar **) arguments, -1);
1619           cmdline = g_object_new (G_TYPE_APPLICATION_COMMAND_LINE,
1620                                   "arguments", v, NULL);
1621           g_signal_emit (application,
1622                          g_application_signals[SIGNAL_COMMAND_LINE],
1623                          0, cmdline, &status);
1624           g_object_unref (cmdline);
1625         }
1626     }
1627
1628   g_strfreev (arguments);
1629
1630   if (application->priv->flags & G_APPLICATION_IS_SERVICE &&
1631       application->priv->is_registered &&
1632       !application->priv->use_count &&
1633       !application->priv->inactivity_timeout_id)
1634     {
1635       application->priv->inactivity_timeout_id =
1636         g_timeout_add (10000, inactivity_timeout_expired, application);
1637     }
1638
1639   while (application->priv->use_count || application->priv->inactivity_timeout_id)
1640     {
1641       if (application->priv->must_quit_now)
1642         break;
1643
1644       g_main_context_iteration (NULL, TRUE);
1645       status = 0;
1646     }
1647
1648   if (application->priv->is_registered && !application->priv->is_remote)
1649     {
1650       g_signal_emit (application, g_application_signals[SIGNAL_SHUTDOWN], 0);
1651
1652       if (!application->priv->did_shutdown)
1653         g_critical ("GApplication subclass '%s' failed to chain up on"
1654                     " ::shutdown (from end of override function)",
1655                     G_OBJECT_TYPE_NAME (application));
1656     }
1657
1658   if (application->priv->impl)
1659     g_application_impl_flush (application->priv->impl);
1660
1661   g_settings_sync ();
1662
1663   return status;
1664 }
1665
1666 static gchar **
1667 g_application_list_actions (GActionGroup *action_group)
1668 {
1669   GApplication *application = G_APPLICATION (action_group);
1670
1671   g_return_val_if_fail (application->priv->is_registered, NULL);
1672
1673   if (application->priv->remote_actions != NULL)
1674     return g_action_group_list_actions (G_ACTION_GROUP (application->priv->remote_actions));
1675
1676   else if (application->priv->actions != NULL)
1677     return g_action_group_list_actions (application->priv->actions);
1678
1679   else
1680     /* empty string array */
1681     return g_new0 (gchar *, 1);
1682 }
1683
1684 static gboolean
1685 g_application_query_action (GActionGroup        *group,
1686                             const gchar         *action_name,
1687                             gboolean            *enabled,
1688                             const GVariantType **parameter_type,
1689                             const GVariantType **state_type,
1690                             GVariant           **state_hint,
1691                             GVariant           **state)
1692 {
1693   GApplication *application = G_APPLICATION (group);
1694
1695   g_return_val_if_fail (application->priv->is_registered, FALSE);
1696
1697   if (application->priv->remote_actions != NULL)
1698     return g_action_group_query_action (G_ACTION_GROUP (application->priv->remote_actions),
1699                                         action_name,
1700                                         enabled,
1701                                         parameter_type,
1702                                         state_type,
1703                                         state_hint,
1704                                         state);
1705
1706   if (application->priv->actions != NULL)
1707     return g_action_group_query_action (application->priv->actions,
1708                                         action_name,
1709                                         enabled,
1710                                         parameter_type,
1711                                         state_type,
1712                                         state_hint,
1713                                         state);
1714
1715   return FALSE;
1716 }
1717
1718 static void
1719 g_application_change_action_state (GActionGroup *action_group,
1720                                    const gchar  *action_name,
1721                                    GVariant     *value)
1722 {
1723   GApplication *application = G_APPLICATION (action_group);
1724
1725   g_return_if_fail (application->priv->is_remote ||
1726                     application->priv->actions != NULL);
1727   g_return_if_fail (application->priv->is_registered);
1728
1729   if (application->priv->remote_actions)
1730     g_remote_action_group_change_action_state_full (application->priv->remote_actions,
1731                                                     action_name, value, get_platform_data (application));
1732
1733   else
1734     g_action_group_change_action_state (application->priv->actions, action_name, value);
1735 }
1736
1737 static void
1738 g_application_activate_action (GActionGroup *action_group,
1739                                const gchar  *action_name,
1740                                GVariant     *parameter)
1741 {
1742   GApplication *application = G_APPLICATION (action_group);
1743
1744   g_return_if_fail (application->priv->is_remote ||
1745                     application->priv->actions != NULL);
1746   g_return_if_fail (application->priv->is_registered);
1747
1748   if (application->priv->remote_actions)
1749     g_remote_action_group_activate_action_full (application->priv->remote_actions,
1750                                                 action_name, parameter, get_platform_data (application));
1751
1752   else
1753     g_action_group_activate_action (application->priv->actions, action_name, parameter);
1754 }
1755
1756 static GAction *
1757 g_application_lookup_action (GActionMap  *action_map,
1758                              const gchar *action_name)
1759 {
1760   GApplication *application = G_APPLICATION (action_map);
1761
1762   g_return_val_if_fail (G_IS_ACTION_MAP (application->priv->actions), NULL);
1763
1764   return g_action_map_lookup_action (G_ACTION_MAP (application->priv->actions), action_name);
1765 }
1766
1767 static void
1768 g_application_add_action (GActionMap *action_map,
1769                           GAction    *action)
1770 {
1771   GApplication *application = G_APPLICATION (action_map);
1772
1773   g_return_if_fail (G_IS_ACTION_MAP (application->priv->actions));
1774
1775   g_action_map_add_action (G_ACTION_MAP (application->priv->actions), action);
1776 }
1777
1778 static void
1779 g_application_remove_action (GActionMap  *action_map,
1780                              const gchar *action_name)
1781 {
1782   GApplication *application = G_APPLICATION (action_map);
1783
1784   g_return_if_fail (G_IS_ACTION_MAP (application->priv->actions));
1785
1786   g_action_map_remove_action (G_ACTION_MAP (application->priv->actions), action_name);
1787 }
1788
1789 static void
1790 g_application_action_group_iface_init (GActionGroupInterface *iface)
1791 {
1792   iface->list_actions = g_application_list_actions;
1793   iface->query_action = g_application_query_action;
1794   iface->change_action_state = g_application_change_action_state;
1795   iface->activate_action = g_application_activate_action;
1796 }
1797
1798 static void
1799 g_application_action_map_iface_init (GActionMapInterface *iface)
1800 {
1801   iface->lookup_action = g_application_lookup_action;
1802   iface->add_action = g_application_add_action;
1803   iface->remove_action = g_application_remove_action;
1804 }
1805
1806 /* Default Application {{{1 */
1807
1808 static GApplication *default_app;
1809
1810 /**
1811  * g_application_get_default:
1812  *
1813  * Returns the default #GApplication instance for this process.
1814  *
1815  * Normally there is only one #GApplication per process and it becomes
1816  * the default when it is created.  You can exercise more control over
1817  * this by using g_application_set_default().
1818  *
1819  * If there is no default application then %NULL is returned.
1820  *
1821  * Returns: (transfer none): the default application for this process, or %NULL
1822  *
1823  * Since: 2.32
1824  **/
1825 GApplication *
1826 g_application_get_default (void)
1827 {
1828   return default_app;
1829 }
1830
1831 /**
1832  * g_application_set_default:
1833  * @application: (allow-none): the application to set as default, or %NULL
1834  *
1835  * Sets or unsets the default application for the process, as returned
1836  * by g_application_get_default().
1837  *
1838  * This function does not take its own reference on @application.  If
1839  * @application is destroyed then the default application will revert
1840  * back to %NULL.
1841  *
1842  * Since: 2.32
1843  **/
1844 void
1845 g_application_set_default (GApplication *application)
1846 {
1847   default_app = application;
1848 }
1849
1850 /**
1851  * g_application_quit:
1852  * @application: a #GApplication
1853  *
1854  * Immediately quits the application.
1855  *
1856  * Upon return to the mainloop, g_application_run() will return,
1857  * calling only the 'shutdown' function before doing so.
1858  *
1859  * The hold count is ignored.
1860  *
1861  * The result of calling g_application_run() again after it returns is
1862  * unspecified.
1863  *
1864  * Since: 2.32
1865  **/
1866 void
1867 g_application_quit (GApplication *application)
1868 {
1869   g_return_if_fail (G_IS_APPLICATION (application));
1870
1871   application->priv->must_quit_now = TRUE;
1872 }
1873
1874 /**
1875  * g_application_mark_busy:
1876  * @application: a #GApplication
1877  *
1878  * Increases the busy count of @application.
1879  *
1880  * Use this function to indicate that the application is busy, for instance
1881  * while a long running operation is pending.
1882  *
1883  * The busy state will be exposed to other processes, so a session shell will
1884  * use that information to indicate the state to the user (e.g. with a
1885  * spinner).
1886  *
1887  * To cancel the busy indication, use g_application_unmark_busy().
1888  *
1889  * Since: 2.38
1890  **/
1891 void
1892 g_application_mark_busy (GApplication *application)
1893 {
1894   gboolean was_busy;
1895
1896   g_return_if_fail (G_IS_APPLICATION (application));
1897
1898   was_busy = (application->priv->busy_count > 0);
1899   application->priv->busy_count++;
1900
1901   if (!was_busy)
1902     g_application_impl_set_busy_state (application->priv->impl, TRUE);
1903 }
1904
1905 /**
1906  * g_application_unmark_busy:
1907  * @application: a #GApplication
1908  *
1909  * Decreases the busy count of @application.
1910  *
1911  * When the busy count reaches zero, the new state will be propagated
1912  * to other processes.
1913  *
1914  * This function must only be called to cancel the effect of a previous
1915  * call to g_application_mark_busy().
1916  *
1917  * Since: 2.38
1918  **/
1919 void
1920 g_application_unmark_busy (GApplication *application)
1921 {
1922   g_return_if_fail (G_IS_APPLICATION (application));
1923   g_return_if_fail (application->priv->busy_count > 0);
1924
1925   application->priv->busy_count--;
1926
1927   if (application->priv->busy_count == 0)
1928     g_application_impl_set_busy_state (application->priv->impl, FALSE);
1929 }
1930
1931 /* Notifications {{{1 */
1932
1933 /**
1934  * g_application_send_notification:
1935  * @application: a #GApplication
1936  * @id: (allow-none): id of the notification, or %NULL
1937  * @notification: the #GNotification to send
1938  *
1939  * Sends a notification on behalf of @application to the desktop shell.
1940  * There is no guarantee that the notification is displayed immediately,
1941  * or even at all.
1942  *
1943  * Notifications may persist after the application exits. It will be
1944  * D-Bus-activated when the notification or one of its actions is
1945  * activated.
1946  *
1947  * Modifying @notification after this call has no effect. However, the
1948  * object can be reused for a later call to this function.
1949  *
1950  * @id may be any string that uniquely identifies the event for the
1951  * application. It does not need to be in any special format. For
1952  * example, "new-message" might be appropriate for a notification about
1953  * new messages.
1954  *
1955  * If a previous notification was sent with the same @id, it will be
1956  * replaced with @notification and shown again as if it was a new
1957  * notification. This works even for notifications sent from a previous
1958  * execution of the application, as long as @id is the same string.
1959  *
1960  * @id may be %NULL, but it is impossible to replace or withdraw
1961  * notifications without an id.
1962  *
1963  * If @notification is no longer relevant, it can be withdrawn with
1964  * g_application_withdraw_notification().
1965  *
1966  * Since: 2.40
1967  */
1968 void
1969 g_application_send_notification (GApplication  *application,
1970                                  const gchar   *id,
1971                                  GNotification *notification)
1972 {
1973   gchar *generated_id = NULL;
1974
1975   g_return_if_fail (G_IS_APPLICATION (application));
1976   g_return_if_fail (G_IS_NOTIFICATION (notification));
1977   g_return_if_fail (g_application_get_is_registered (application));
1978   g_return_if_fail (!g_application_get_is_remote (application));
1979
1980   if (application->priv->notifications == NULL)
1981     application->priv->notifications = g_notification_backend_new_default (application);
1982
1983   if (id == NULL)
1984     {
1985       generated_id = g_dbus_generate_guid ();
1986       id = generated_id;
1987     }
1988
1989   g_notification_backend_send_notification (application->priv->notifications, id, notification);
1990
1991   g_free (generated_id);
1992 }
1993
1994 /**
1995  * g_application_withdraw_notification:
1996  * @application: a #GApplication
1997  * @id: id of a previously sent notification
1998  *
1999  * Withdraws a notification that was sent with
2000  * g_application_send_notification().
2001  *
2002  * This call does nothing if a notification with @id doesn't exist or
2003  * the notification was never sent.
2004  *
2005  * This function works even for notifications sent in previous
2006  * executions of this application, as long @id is the same as it was for
2007  * the sent notification.
2008  *
2009  * Note that notifications are dismissed when the user clicks on one
2010  * of the buttons in a notification or triggers its default action, so
2011  * there is no need to explicitly withdraw the notification in that case.
2012  *
2013  * Since: 2.40
2014  */
2015 void
2016 g_application_withdraw_notification (GApplication *application,
2017                                      const gchar  *id)
2018 {
2019   g_return_if_fail (G_IS_APPLICATION (application));
2020   g_return_if_fail (id != NULL);
2021
2022   if (application->priv->notifications)
2023     g_notification_backend_withdraw_notification (application->priv->notifications, id);
2024 }
2025
2026 /* Epilogue {{{1 */
2027 /* vim:set foldmethod=marker: */