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