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