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