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