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