Drop public menu APIs from GApplication
[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         g_application_set_app_menu (GApplication *application,
512                                                 GMenuModel   *app_menu);
513 static GMenuModel * g_application_get_app_menu (GApplication *application);
514 static void         g_application_set_menubar  (GApplication *application,
515                                                 GMenuModel   *menubar);
516 static GMenuModel * g_application_get_menubar  (GApplication *application);
517
518 static void
519 g_application_set_property (GObject      *object,
520                             guint         prop_id,
521                             const GValue *value,
522                             GParamSpec   *pspec)
523 {
524   GApplication *application = G_APPLICATION (object);
525
526   switch (prop_id)
527     {
528     case PROP_APPLICATION_ID:
529       g_application_set_application_id (application,
530                                         g_value_get_string (value));
531       break;
532
533     case PROP_FLAGS:
534       g_application_set_flags (application, g_value_get_flags (value));
535       break;
536
537     case PROP_INACTIVITY_TIMEOUT:
538       g_application_set_inactivity_timeout (application,
539                                             g_value_get_uint (value));
540       break;
541
542     case PROP_ACTION_GROUP:
543       g_clear_object (&application->priv->actions);
544       application->priv->actions = g_value_dup_object (value);
545       break;
546
547     case PROP_APP_MENU:
548       g_application_set_app_menu (application, g_value_get_object (value));
549       break;
550
551     case PROP_MENUBAR:
552       g_application_set_menubar (application, g_value_get_object (value));
553       break;
554
555     default:
556       g_assert_not_reached ();
557     }
558 }
559
560 /**
561  * g_application_set_action_group:
562  * @application: a #GApplication
563  * @action_group: (allow-none): a #GActionGroup, or %NULL
564  *
565  * This used to be how actions were associated with a #GApplication.
566  * Now there is #GActionMap for that.
567  *
568  * Since: 2.28
569  *
570  * Deprecated:2.32:Use the #GActionMap interface instead.  Never ever
571  * mix use of this API with use of #GActionMap on the same @application
572  * or things will go very badly wrong.  This function is known to
573  * introduce buggy behaviour (ie: signals not emitted on changes to the
574  * action group), so you should really use #GActionMap instead.
575  **/
576 void
577 g_application_set_action_group (GApplication *application,
578                                 GActionGroup *action_group)
579 {
580   g_return_if_fail (G_IS_APPLICATION (application));
581   g_return_if_fail (!application->priv->is_registered);
582
583   if (application->priv->actions != NULL)
584     g_object_unref (application->priv->actions);
585
586   application->priv->actions = action_group;
587
588   if (application->priv->actions != NULL)
589     g_object_ref (application->priv->actions);
590 }
591
592 static void
593 g_application_set_app_menu (GApplication *application,
594                             GMenuModel   *app_menu)
595 {
596   g_return_if_fail (G_IS_APPLICATION (application));
597
598   if (app_menu != application->priv->app_menu)
599     {
600       if (application->priv->app_menu != NULL)
601         g_object_unref (application->priv->app_menu);
602
603       application->priv->app_menu = app_menu;
604
605       if (application->priv->app_menu != NULL)
606         g_object_ref (application->priv->app_menu);
607
608       g_object_notify (G_OBJECT (application), "app-menu");
609     }
610 }
611
612 static GMenuModel *
613 g_application_get_app_menu (GApplication *application)
614 {
615   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
616
617   return application->priv->app_menu;
618 }
619
620 static void
621 g_application_set_menubar (GApplication *application,
622                             GMenuModel   *menubar)
623 {
624   g_return_if_fail (G_IS_APPLICATION (application));
625
626   if (menubar != application->priv->menubar)
627     {
628       if (application->priv->menubar != NULL)
629         g_object_unref (application->priv->menubar);
630
631       application->priv->menubar = menubar;
632
633       if (application->priv->menubar != NULL)
634         g_object_ref (application->priv->menubar);
635
636       g_object_notify (G_OBJECT (application), "menubar");
637     }
638 }
639
640 static GMenuModel *
641 g_application_get_menubar (GApplication *application)
642 {
643   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
644
645   return application->priv->menubar;
646 }
647
648 static void
649 g_application_get_property (GObject    *object,
650                             guint       prop_id,
651                             GValue     *value,
652                             GParamSpec *pspec)
653 {
654   GApplication *application = G_APPLICATION (object);
655
656   switch (prop_id)
657     {
658     case PROP_APPLICATION_ID:
659       g_value_set_string (value,
660                           g_application_get_application_id (application));
661       break;
662
663     case PROP_FLAGS:
664       g_value_set_flags (value,
665                          g_application_get_flags (application));
666       break;
667
668     case PROP_IS_REGISTERED:
669       g_value_set_boolean (value,
670                            g_application_get_is_registered (application));
671       break;
672
673     case PROP_IS_REMOTE:
674       g_value_set_boolean (value,
675                            g_application_get_is_remote (application));
676       break;
677
678     case PROP_INACTIVITY_TIMEOUT:
679       g_value_set_uint (value,
680                         g_application_get_inactivity_timeout (application));
681       break;
682
683     case PROP_APP_MENU:
684       g_value_set_object (value,
685                           g_application_get_app_menu (application));
686       break;
687
688     case PROP_MENUBAR:
689       g_value_set_object (value,
690                           g_application_get_menubar (application));
691       break;
692
693     default:
694       g_assert_not_reached ();
695     }
696 }
697
698 static void
699 g_application_constructed (GObject *object)
700 {
701   GApplication *application = G_APPLICATION (object);
702
703   g_assert (application->priv->id != NULL);
704
705   if (g_application_get_default () == NULL)
706     g_application_set_default (application);
707 }
708
709 static void
710 g_application_finalize (GObject *object)
711 {
712   GApplication *application = G_APPLICATION (object);
713
714   if (application->priv->impl)
715     g_application_impl_destroy (application->priv->impl);
716   g_free (application->priv->id);
717
718   if (g_application_get_default () == application)
719     g_application_set_default (NULL);
720
721   if (application->priv->app_menu)
722     g_object_unref (application->priv->app_menu);
723
724   if (application->priv->menubar)
725     g_object_unref (application->priv->menubar);
726
727   if (application->priv->actions)
728     g_object_unref (application->priv->actions);
729
730   G_OBJECT_CLASS (g_application_parent_class)
731     ->finalize (object);
732 }
733
734 static void
735 g_application_init (GApplication *application)
736 {
737   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application,
738                                                    G_TYPE_APPLICATION,
739                                                    GApplicationPrivate);
740
741   application->priv->actions = g_application_exported_actions_new (application);
742
743   /* application->priv->actions is the one and only ref on the group, so when
744    * we dispose, the action group will die, disconnecting all signals.
745    */
746   g_signal_connect_swapped (application->priv->actions, "action-added",
747                             G_CALLBACK (g_action_group_action_added), application);
748   g_signal_connect_swapped (application->priv->actions, "action-enabled-changed",
749                             G_CALLBACK (g_action_group_action_enabled_changed), application);
750   g_signal_connect_swapped (application->priv->actions, "action-state-changed",
751                             G_CALLBACK (g_action_group_action_state_changed), application);
752   g_signal_connect_swapped (application->priv->actions, "action-removed",
753                             G_CALLBACK (g_action_group_action_removed), application);
754 }
755
756 static void
757 g_application_class_init (GApplicationClass *class)
758 {
759   GObjectClass *object_class = G_OBJECT_CLASS (class);
760
761   object_class->constructed = g_application_constructed;
762   object_class->finalize = g_application_finalize;
763   object_class->get_property = g_application_get_property;
764   object_class->set_property = g_application_set_property;
765
766   class->before_emit = g_application_real_before_emit;
767   class->after_emit = g_application_real_after_emit;
768   class->startup = g_application_real_startup;
769   class->shutdown = g_application_real_shutdown;
770   class->activate = g_application_real_activate;
771   class->open = g_application_real_open;
772   class->command_line = g_application_real_command_line;
773   class->local_command_line = g_application_real_local_command_line;
774   class->add_platform_data = g_application_real_add_platform_data;
775
776   g_object_class_install_property (object_class, PROP_APPLICATION_ID,
777     g_param_spec_string ("application-id",
778                          P_("Application identifier"),
779                          P_("The unique identifier for the application"),
780                          NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
781                          G_PARAM_STATIC_STRINGS));
782
783   g_object_class_install_property (object_class, PROP_FLAGS,
784     g_param_spec_flags ("flags",
785                         P_("Application flags"),
786                         P_("Flags specifying the behaviour of the application"),
787                         G_TYPE_APPLICATION_FLAGS, G_APPLICATION_FLAGS_NONE,
788                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
789
790   g_object_class_install_property (object_class, PROP_IS_REGISTERED,
791     g_param_spec_boolean ("is-registered",
792                           P_("Is registered"),
793                           P_("If g_application_register() has been called"),
794                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
795
796   g_object_class_install_property (object_class, PROP_IS_REMOTE,
797     g_param_spec_boolean ("is-remote",
798                           P_("Is remote"),
799                           P_("If this application instance is remote"),
800                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
801
802   g_object_class_install_property (object_class, PROP_INACTIVITY_TIMEOUT,
803     g_param_spec_uint ("inactivity-timeout",
804                        P_("Inactivity timeout"),
805                        P_("Time (ms) to stay alive after becoming idle"),
806                        0, G_MAXUINT, 0,
807                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
808
809   g_object_class_install_property (object_class, PROP_ACTION_GROUP,
810     g_param_spec_object ("action-group",
811                          P_("Action group"),
812                          P_("The group of actions that the application exports"),
813                          G_TYPE_ACTION_GROUP,
814                          G_PARAM_DEPRECATED | G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
815
816   g_object_class_install_property (object_class, PROP_APP_MENU,
817     g_param_spec_object ("app-menu",
818                          P_("Application menu"),
819                          P_("The GMenuModel for the application menu"),
820                          G_TYPE_MENU_MODEL,
821                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
822
823   g_object_class_install_property (object_class, PROP_MENUBAR,
824     g_param_spec_object ("menubar",
825                          P_("Menubar"),
826                          P_("The GMenuModel for the menubar"),
827                          G_TYPE_MENU_MODEL,
828                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
829
830   /**
831    * GApplication::startup:
832    * @application: the application
833    *
834    * The ::startup signal is emitted on the primary instance immediately
835    * after registration. See g_application_register().
836    */
837   g_application_signals[SIGNAL_STARTUP] =
838     g_signal_new ("startup", G_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
839                   G_STRUCT_OFFSET (GApplicationClass, startup),
840                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
841
842   /**
843    * GApplication::shutdown:
844    * @application: the application
845    *
846    * The ::shutdown signal is emitted only on the registered primary instance
847    * immediately after the main loop terminates.
848    */
849   g_application_signals[SIGNAL_SHUTDOWN] =
850     g_signal_new ("shutdown", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
851                   G_STRUCT_OFFSET (GApplicationClass, shutdown),
852                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
853
854   /**
855    * GApplication::activate:
856    * @application: the application
857    *
858    * The ::activate signal is emitted on the primary instance when an
859    * activation occurs. See g_application_activate().
860    */
861   g_application_signals[SIGNAL_ACTIVATE] =
862     g_signal_new ("activate", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
863                   G_STRUCT_OFFSET (GApplicationClass, activate),
864                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
865
866
867   /**
868    * GApplication::open:
869    * @application: the application
870    * @files: (array length=n_files) (element-type GFile): an array of #GFiles
871    * @n_files: the length of @files
872    * @hint: a hint provided by the calling instance
873    *
874    * The ::open signal is emitted on the primary instance when there are
875    * files to open. See g_application_open() for more information.
876    */
877   g_application_signals[SIGNAL_OPEN] =
878     g_signal_new ("open", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
879                   G_STRUCT_OFFSET (GApplicationClass, open),
880                   NULL, NULL, NULL,
881                   G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_STRING);
882
883   /**
884    * GApplication::command-line:
885    * @application: the application
886    * @command_line: a #GApplicationCommandLine representing the
887    *     passed commandline
888    *
889    * The ::command-line signal is emitted on the primary instance when
890    * a commandline is not handled locally. See g_application_run() and
891    * the #GApplicationCommandline documentation for more information.
892    *
893    * Returns: An integer that is set as the exit status for the calling
894    *   process. See g_application_command_line_set_exit_status().
895    */
896   g_application_signals[SIGNAL_COMMAND_LINE] =
897     g_signal_new ("command-line", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
898                   G_STRUCT_OFFSET (GApplicationClass, command_line),
899                   g_signal_accumulator_first_wins, NULL,
900                   NULL,
901                   G_TYPE_INT, 1, G_TYPE_APPLICATION_COMMAND_LINE);
902
903   g_type_class_add_private (class, sizeof (GApplicationPrivate));
904 }
905
906 static GVariant *
907 get_platform_data (GApplication *application)
908 {
909   GVariantBuilder *builder;
910   GVariant *result;
911
912   builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
913
914   {
915     gchar *cwd = g_get_current_dir ();
916     g_variant_builder_add (builder, "{sv}", "cwd",
917                            g_variant_new_bytestring (cwd));
918     g_free (cwd);
919   }
920
921   if (application->priv->flags & G_APPLICATION_SEND_ENVIRONMENT)
922     {
923       GVariant *array;
924       gchar **envp;
925
926       envp = g_get_environ ();
927       array = g_variant_new_bytestring_array ((const gchar **) envp, -1);
928       g_strfreev (envp);
929
930       g_variant_builder_add (builder, "{sv}", "environ", array);
931     }
932
933   G_APPLICATION_GET_CLASS (application)->
934     add_platform_data (application, builder);
935
936   result = g_variant_builder_end (builder);
937   g_variant_builder_unref (builder);
938
939   return result;
940 }
941
942 /* Application ID validity {{{1 */
943
944 /**
945  * g_application_id_is_valid:
946  * @application_id: a potential application identifier
947  *
948  * Checks if @application_id is a valid application identifier.
949  *
950  * A valid ID is required for calls to g_application_new() and
951  * g_application_set_application_id().
952  *
953  * For convenience, the restrictions on application identifiers are
954  * reproduced here:
955  * <itemizedlist>
956  *   <listitem>Application identifiers must contain only the ASCII characters "[A-Z][a-z][0-9]_-." and must not begin with a digit.</listitem>
957  *   <listitem>Application identifiers must contain at least one '.' (period) character (and thus at least three elements).</listitem>
958  *   <listitem>Application identifiers must not begin or end with a '.' (period) character.</listitem>
959  *   <listitem>Application identifiers must not contain consecutive '.' (period) characters.</listitem>
960  *   <listitem>Application identifiers must not exceed 255 characters.</listitem>
961  * </itemizedlist>
962  *
963  * Returns: %TRUE if @application_id is valid
964  **/
965 gboolean
966 g_application_id_is_valid (const gchar *application_id)
967 {
968   gsize len;
969   gboolean allow_dot;
970   gboolean has_dot;
971
972   len = strlen (application_id);
973
974   if (len > 255)
975     return FALSE;
976
977   if (!g_ascii_isalpha (application_id[0]))
978     return FALSE;
979
980   if (application_id[len-1] == '.')
981     return FALSE;
982
983   application_id++;
984   allow_dot = TRUE;
985   has_dot = FALSE;
986   for (; *application_id; application_id++)
987     {
988       if (g_ascii_isalnum (*application_id) ||
989           (*application_id == '-') ||
990           (*application_id == '_'))
991         {
992           allow_dot = TRUE;
993         }
994       else if (allow_dot && *application_id == '.')
995         {
996           has_dot = TRUE;
997           allow_dot = FALSE;
998         }
999       else
1000         return FALSE;
1001     }
1002
1003   if (!has_dot)
1004     return FALSE;
1005
1006   return TRUE;
1007 }
1008
1009 /* Public Constructor {{{1 */
1010 /**
1011  * g_application_new:
1012  * @application_id: the application id
1013  * @flags: the application flags
1014  *
1015  * Creates a new #GApplication instance.
1016  *
1017  * This function calls g_type_init() for you.
1018  *
1019  * The application id must be valid.  See g_application_id_is_valid().
1020  *
1021  * Returns: a new #GApplication instance
1022  **/
1023 GApplication *
1024 g_application_new (const gchar       *application_id,
1025                    GApplicationFlags  flags)
1026 {
1027   g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);
1028
1029   g_type_init ();
1030
1031   return g_object_new (G_TYPE_APPLICATION,
1032                        "application-id", application_id,
1033                        "flags", flags,
1034                        NULL);
1035 }
1036
1037 /* Simple get/set: application id, flags, inactivity timeout {{{1 */
1038 /**
1039  * g_application_get_application_id:
1040  * @application: a #GApplication
1041  *
1042  * Gets the unique identifier for @application.
1043  *
1044  * Returns: the identifier for @application, owned by @application
1045  *
1046  * Since: 2.28
1047  **/
1048 const gchar *
1049 g_application_get_application_id (GApplication *application)
1050 {
1051   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
1052
1053   return application->priv->id;
1054 }
1055
1056 /**
1057  * g_application_set_application_id:
1058  * @application: a #GApplication
1059  * @application_id: the identifier for @application
1060  *
1061  * Sets the unique identifier for @application.
1062  *
1063  * The application id can only be modified if @application has not yet
1064  * been registered.
1065  *
1066  * The application id must be valid.  See g_application_id_is_valid().
1067  *
1068  * Since: 2.28
1069  **/
1070 void
1071 g_application_set_application_id (GApplication *application,
1072                                   const gchar  *application_id)
1073 {
1074   g_return_if_fail (G_IS_APPLICATION (application));
1075
1076   if (g_strcmp0 (application->priv->id, application_id) != 0)
1077     {
1078       g_return_if_fail (g_application_id_is_valid (application_id));
1079       g_return_if_fail (!application->priv->is_registered);
1080
1081       g_free (application->priv->id);
1082       application->priv->id = g_strdup (application_id);
1083
1084       g_object_notify (G_OBJECT (application), "application-id");
1085     }
1086 }
1087
1088 /**
1089  * g_application_get_flags:
1090  * @application: a #GApplication
1091  *
1092  * Gets the flags for @application.
1093  *
1094  * See #GApplicationFlags.
1095  *
1096  * Returns: the flags for @application
1097  *
1098  * Since: 2.28
1099  **/
1100 GApplicationFlags
1101 g_application_get_flags (GApplication *application)
1102 {
1103   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1104
1105   return application->priv->flags;
1106 }
1107
1108 /**
1109  * g_application_set_flags:
1110  * @application: a #GApplication
1111  * @flags: the flags for @application
1112  *
1113  * Sets the flags for @application.
1114  *
1115  * The flags can only be modified if @application has not yet been
1116  * registered.
1117  *
1118  * See #GApplicationFlags.
1119  *
1120  * Since: 2.28
1121  **/
1122 void
1123 g_application_set_flags (GApplication      *application,
1124                          GApplicationFlags  flags)
1125 {
1126   g_return_if_fail (G_IS_APPLICATION (application));
1127
1128   if (application->priv->flags != flags)
1129     {
1130       g_return_if_fail (!application->priv->is_registered);
1131
1132       application->priv->flags = flags;
1133
1134       g_object_notify (G_OBJECT (application), "flags");
1135     }
1136 }
1137
1138 /**
1139  * g_application_get_inactivity_timeout:
1140  * @application: a #GApplication
1141  *
1142  * Gets the current inactivity timeout for the application.
1143  *
1144  * This is the amount of time (in milliseconds) after the last call to
1145  * g_application_release() before the application stops running.
1146  *
1147  * Returns: the timeout, in milliseconds
1148  *
1149  * Since: 2.28
1150  **/
1151 guint
1152 g_application_get_inactivity_timeout (GApplication *application)
1153 {
1154   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
1155
1156   return application->priv->inactivity_timeout;
1157 }
1158
1159 /**
1160  * g_application_set_inactivity_timeout:
1161  * @application: a #GApplication
1162  * @inactivity_timeout: the timeout, in milliseconds
1163  *
1164  * Sets the current inactivity timeout for the application.
1165  *
1166  * This is the amount of time (in milliseconds) after the last call to
1167  * g_application_release() before the application stops running.
1168  *
1169  * This call has no side effects of its own.  The value set here is only
1170  * used for next time g_application_release() drops the use count to
1171  * zero.  Any timeouts currently in progress are not impacted.
1172  *
1173  * Since: 2.28
1174  **/
1175 void
1176 g_application_set_inactivity_timeout (GApplication *application,
1177                                       guint         inactivity_timeout)
1178 {
1179   g_return_if_fail (G_IS_APPLICATION (application));
1180
1181   if (application->priv->inactivity_timeout != inactivity_timeout)
1182     {
1183       application->priv->inactivity_timeout = inactivity_timeout;
1184
1185       g_object_notify (G_OBJECT (application), "inactivity-timeout");
1186     }
1187 }
1188 /* Read-only property getters (is registered, is remote) {{{1 */
1189 /**
1190  * g_application_get_is_registered:
1191  * @application: a #GApplication
1192  *
1193  * Checks if @application is registered.
1194  *
1195  * An application is registered if g_application_register() has been
1196  * successfully called.
1197  *
1198  * Returns: %TRUE if @application is registered
1199  *
1200  * Since: 2.28
1201  **/
1202 gboolean
1203 g_application_get_is_registered (GApplication *application)
1204 {
1205   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1206
1207   return application->priv->is_registered;
1208 }
1209
1210 /**
1211  * g_application_get_is_remote:
1212  * @application: a #GApplication
1213  *
1214  * Checks if @application is remote.
1215  *
1216  * If @application is remote then it means that another instance of
1217  * application already exists (the 'primary' instance).  Calls to
1218  * perform actions on @application will result in the actions being
1219  * performed by the primary instance.
1220  *
1221  * The value of this property cannot be accessed before
1222  * g_application_register() has been called.  See
1223  * g_application_get_is_registered().
1224  *
1225  * Returns: %TRUE if @application is remote
1226  *
1227  * Since: 2.28
1228  **/
1229 gboolean
1230 g_application_get_is_remote (GApplication *application)
1231 {
1232   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1233   g_return_val_if_fail (application->priv->is_registered, FALSE);
1234
1235   return application->priv->is_remote;
1236 }
1237
1238 /* Register {{{1 */
1239 /**
1240  * g_application_register:
1241  * @application: a #GApplication
1242  * @cancellable: a #GCancellable, or %NULL
1243  * @error: a pointer to a NULL #GError, or %NULL
1244  *
1245  * Attempts registration of the application.
1246  *
1247  * This is the point at which the application discovers if it is the
1248  * primary instance or merely acting as a remote for an already-existing
1249  * primary instance.  This is implemented by attempting to acquire the
1250  * application identifier as a unique bus name on the session bus using
1251  * GDBus.
1252  *
1253  * Due to the internal architecture of GDBus, method calls can be
1254  * dispatched at any time (even if a main loop is not running).  For
1255  * this reason, you must ensure that any object paths that you wish to
1256  * register are registered before calling this function.
1257  *
1258  * If the application has already been registered then %TRUE is
1259  * returned with no work performed.
1260  *
1261  * The #GApplication::startup signal is emitted if registration succeeds
1262  * and @application is the primary instance.
1263  *
1264  * In the event of an error (such as @cancellable being cancelled, or a
1265  * failure to connect to the session bus), %FALSE is returned and @error
1266  * is set appropriately.
1267  *
1268  * Note: the return value of this function is not an indicator that this
1269  * instance is or is not the primary instance of the application.  See
1270  * g_application_get_is_remote() for that.
1271  *
1272  * Returns: %TRUE if registration succeeded
1273  *
1274  * Since: 2.28
1275  **/
1276 gboolean
1277 g_application_register (GApplication  *application,
1278                         GCancellable  *cancellable,
1279                         GError       **error)
1280 {
1281   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
1282
1283   if (!application->priv->is_registered)
1284     {
1285       if (~application->priv->flags & G_APPLICATION_NON_UNIQUE)
1286         {
1287           application->priv->impl =
1288             g_application_impl_register (application, application->priv->id,
1289                                          application->priv->flags,
1290                                          application->priv->actions,
1291                                          &application->priv->remote_actions,
1292                                          cancellable, error);
1293
1294           if (application->priv->impl == NULL)
1295             return FALSE;
1296         }
1297
1298       application->priv->is_remote = application->priv->remote_actions != NULL;
1299       application->priv->is_registered = TRUE;
1300
1301       g_object_notify (G_OBJECT (application), "is-registered");
1302
1303       if (!application->priv->is_remote)
1304         {
1305           g_signal_emit (application, g_application_signals[SIGNAL_STARTUP], 0);
1306
1307           if (!application->priv->did_startup)
1308             g_critical ("GApplication subclass '%s' failed to chain up on"
1309                         " ::startup (from start of override function)",
1310                         G_OBJECT_TYPE_NAME (application));
1311         }
1312     }
1313
1314   return TRUE;
1315 }
1316
1317 /* Hold/release {{{1 */
1318 /**
1319  * g_application_hold:
1320  * @application: a #GApplication
1321  *
1322  * Increases the use count of @application.
1323  *
1324  * Use this function to indicate that the application has a reason to
1325  * continue to run.  For example, g_application_hold() is called by GTK+
1326  * when a toplevel window is on the screen.
1327  *
1328  * To cancel the hold, call g_application_release().
1329  **/
1330 void
1331 g_application_hold (GApplication *application)
1332 {
1333   if (application->priv->inactivity_timeout_id)
1334     {
1335       g_source_remove (application->priv->inactivity_timeout_id);
1336       application->priv->inactivity_timeout_id = 0;
1337     }
1338
1339   application->priv->use_count++;
1340 }
1341
1342 static gboolean
1343 inactivity_timeout_expired (gpointer data)
1344 {
1345   GApplication *application = G_APPLICATION (data);
1346
1347   application->priv->inactivity_timeout_id = 0;
1348
1349   return FALSE;
1350 }
1351
1352
1353 /**
1354  * g_application_release:
1355  * @application: a #GApplication
1356  *
1357  * Decrease the use count of @application.
1358  *
1359  * When the use count reaches zero, the application will stop running.
1360  *
1361  * Never call this function except to cancel the effect of a previous
1362  * call to g_application_hold().
1363  **/
1364 void
1365 g_application_release (GApplication *application)
1366 {
1367   application->priv->use_count--;
1368
1369   if (application->priv->use_count == 0 && application->priv->inactivity_timeout)
1370     application->priv->inactivity_timeout_id = g_timeout_add (application->priv->inactivity_timeout,
1371                                                               inactivity_timeout_expired, application);
1372 }
1373
1374 /* Activate, Open {{{1 */
1375 /**
1376  * g_application_activate:
1377  * @application: a #GApplication
1378  *
1379  * Activates the application.
1380  *
1381  * In essence, this results in the #GApplication::activate() signal being
1382  * emitted in the primary instance.
1383  *
1384  * The application must be registered before calling this function.
1385  *
1386  * Since: 2.28
1387  **/
1388 void
1389 g_application_activate (GApplication *application)
1390 {
1391   g_return_if_fail (G_IS_APPLICATION (application));
1392   g_return_if_fail (application->priv->is_registered);
1393
1394   if (application->priv->is_remote)
1395     g_application_impl_activate (application->priv->impl,
1396                                  get_platform_data (application));
1397
1398   else
1399     g_signal_emit (application, g_application_signals[SIGNAL_ACTIVATE], 0);
1400 }
1401
1402 /**
1403  * g_application_open:
1404  * @application: a #GApplication
1405  * @files: (array length=n_files): an array of #GFiles to open
1406  * @n_files: the length of the @files array
1407  * @hint: a hint (or ""), but never %NULL
1408  *
1409  * Opens the given files.
1410  *
1411  * In essence, this results in the #GApplication::open signal being emitted
1412  * in the primary instance.
1413  *
1414  * @n_files must be greater than zero.
1415  *
1416  * @hint is simply passed through to the ::open signal.  It is
1417  * intended to be used by applications that have multiple modes for
1418  * opening files (eg: "view" vs "edit", etc).  Unless you have a need
1419  * for this functionality, you should use "".
1420  *
1421  * The application must be registered before calling this function
1422  * and it must have the %G_APPLICATION_HANDLES_OPEN flag set.
1423  *
1424  * Since: 2.28
1425  **/
1426 void
1427 g_application_open (GApplication  *application,
1428                     GFile        **files,
1429                     gint           n_files,
1430                     const gchar   *hint)
1431 {
1432   g_return_if_fail (G_IS_APPLICATION (application));
1433   g_return_if_fail (application->priv->flags &
1434                     G_APPLICATION_HANDLES_OPEN);
1435   g_return_if_fail (application->priv->is_registered);
1436
1437   if (application->priv->is_remote)
1438     g_application_impl_open (application->priv->impl,
1439                              files, n_files, hint,
1440                              get_platform_data (application));
1441
1442   else
1443     g_signal_emit (application, g_application_signals[SIGNAL_OPEN],
1444                    0, files, n_files, hint);
1445 }
1446
1447 /* Run {{{1 */
1448 /**
1449  * g_application_run:
1450  * @application: a #GApplication
1451  * @argc: the argc from main() (or 0 if @argv is %NULL)
1452  * @argv: (array length=argc) (allow-none): the argv from main(), or %NULL
1453  *
1454  * Runs the application.
1455  *
1456  * This function is intended to be run from main() and its return value
1457  * is intended to be returned by main(). Although you are expected to pass
1458  * the @argc, @argv parameters from main() to this function, it is possible
1459  * to pass %NULL if @argv is not available or commandline handling is not
1460  * required.
1461  *
1462  * First, the local_command_line() virtual function is invoked.
1463  * This function always runs on the local instance. It gets passed a pointer
1464  * to a %NULL-terminated copy of @argv and is expected to remove the arguments
1465  * that it handled (shifting up remaining arguments). See
1466  * <xref linkend="gapplication-example-cmdline2"/> for an example of
1467  * parsing @argv manually. Alternatively, you may use the #GOptionContext API,
1468  * after setting <literal>argc = g_strv_length (argv);</literal>.
1469  *
1470  * The last argument to local_command_line() is a pointer to the @status
1471  * variable which can used to set the exit status that is returned from
1472  * g_application_run().
1473  *
1474  * If local_command_line() returns %TRUE, the command line is expected
1475  * to be completely handled, including possibly registering as the primary
1476  * instance, calling g_application_activate() or g_application_open(), etc.
1477  *
1478  * If local_command_line() returns %FALSE then the application is registered
1479  * and the #GApplication::command-line signal is emitted in the primary
1480  * instance (which may or may not be this instance). The signal handler
1481  * gets passed a #GApplicationCommandline object that (among other things)
1482  * contains the remaining commandline arguments that have not been handled
1483  * by local_command_line().
1484  *
1485  * If the application has the %G_APPLICATION_HANDLES_COMMAND_LINE
1486  * flag set then the default implementation of local_command_line()
1487  * always returns %FALSE immediately, resulting in the commandline
1488  * always being handled in the primary instance.
1489  *
1490  * Otherwise, the default implementation of local_command_line() tries
1491  * to do a couple of things that are probably reasonable for most
1492  * applications.  First, g_application_register() is called to attempt
1493  * to register the application.  If that works, then the command line
1494  * arguments are inspected.  If no commandline arguments are given, then
1495  * g_application_activate() is called.  If commandline arguments are
1496  * given and the %G_APPLICATION_HANDLES_OPEN flag is set then they
1497  * are assumed to be filenames and g_application_open() is called.
1498  *
1499  * If you need to handle commandline arguments that are not filenames,
1500  * and you don't mind commandline handling to happen in the primary
1501  * instance, you should set %G_APPLICATION_HANDLED_COMMAND_LINE and
1502  * process the commandline arguments in your #GApplication::command-line
1503  * signal handler, either manually or using the #GOptionContext API.
1504  *
1505  * If you are interested in doing more complicated local handling of the
1506  * commandline then you should implement your own #GApplication subclass
1507  * and override local_command_line(). In this case, you most likely want
1508  * to return %TRUE from your local_command_line() implementation to
1509  * suppress the default handling. See
1510  * <xref linkend="gapplication-example-cmdline2"/> for an example.
1511  *
1512  * If, after the above is done, the use count of the application is zero
1513  * then the exit status is returned immediately.  If the use count is
1514  * non-zero then the default main context is iterated until the use count
1515  * falls to zero, at which point 0 is returned.
1516  *
1517  * If the %G_APPLICATION_IS_SERVICE flag is set, then the exiting at
1518  * use count of zero is delayed for a while (ie: the instance stays
1519  * around to provide its <emphasis>service</emphasis> to others).
1520  *
1521  * Returns: the exit status
1522  *
1523  * Since: 2.28
1524  **/
1525 int
1526 g_application_run (GApplication  *application,
1527                    int            argc,
1528                    char         **argv)
1529 {
1530   gchar **arguments;
1531   int status;
1532   gint i;
1533
1534   g_return_val_if_fail (G_IS_APPLICATION (application), 1);
1535   g_return_val_if_fail (argc == 0 || argv != NULL, 1);
1536
1537   arguments = g_new (gchar *, argc + 1);
1538   for (i = 0; i < argc; i++)
1539     arguments[i] = g_strdup (argv[i]);
1540   arguments[i] = NULL;
1541
1542   if (g_get_prgname () == NULL && argc > 0)
1543     {
1544       gchar *prgname;
1545
1546       prgname = g_path_get_basename (argv[0]);
1547       g_set_prgname (prgname);
1548       g_free (prgname);
1549     }
1550
1551   if (!G_APPLICATION_GET_CLASS (application)
1552         ->local_command_line (application, &arguments, &status))
1553     {
1554       GError *error = NULL;
1555
1556       if (!g_application_register (application, NULL, &error))
1557         {
1558           g_printerr ("%s", error->message);
1559           g_error_free (error);
1560           return 1;
1561         }
1562
1563       if (application->priv->is_remote)
1564         {
1565           GVariant *platform_data;
1566
1567           platform_data = get_platform_data (application);
1568           status = g_application_impl_command_line (application->priv->impl,
1569                                                     arguments, platform_data);
1570         }
1571       else
1572         {
1573           GApplicationCommandLine *cmdline;
1574           GVariant *v;
1575
1576           v = g_variant_new_bytestring_array ((const gchar **) arguments, -1);
1577           cmdline = g_object_new (G_TYPE_APPLICATION_COMMAND_LINE,
1578                                   "arguments", v, NULL);
1579           g_signal_emit (application,
1580                          g_application_signals[SIGNAL_COMMAND_LINE],
1581                          0, cmdline, &status);
1582           g_object_unref (cmdline);
1583         }
1584     }
1585
1586   g_strfreev (arguments);
1587
1588   if (application->priv->flags & G_APPLICATION_IS_SERVICE &&
1589       application->priv->is_registered &&
1590       !application->priv->use_count &&
1591       !application->priv->inactivity_timeout_id)
1592     {
1593       application->priv->inactivity_timeout_id =
1594         g_timeout_add (10000, inactivity_timeout_expired, application);
1595     }
1596
1597   while (application->priv->use_count || application->priv->inactivity_timeout_id)
1598     {
1599       g_main_context_iteration (NULL, TRUE);
1600       status = 0;
1601     }
1602
1603   if (!application->priv->is_remote)
1604     {
1605       g_signal_emit (application, g_application_signals[SIGNAL_SHUTDOWN], 0);
1606
1607       if (!application->priv->did_shutdown)
1608         g_critical ("GApplication subclass '%s' failed to chain up on"
1609                     " ::shutdown (from end of override function)",
1610                     G_OBJECT_TYPE_NAME (application));
1611     }
1612
1613   if (application->priv->impl)
1614     g_application_impl_flush (application->priv->impl);
1615
1616   g_settings_sync ();
1617
1618   return status;
1619 }
1620
1621 static gchar **
1622 g_application_list_actions (GActionGroup *action_group)
1623 {
1624   GApplication *application = G_APPLICATION (action_group);
1625
1626   g_return_val_if_fail (application->priv->is_registered, NULL);
1627
1628   if (application->priv->remote_actions != NULL)
1629     return g_action_group_list_actions (G_ACTION_GROUP (application->priv->remote_actions));
1630
1631   else if (application->priv->actions != NULL)
1632     return g_action_group_list_actions (application->priv->actions);
1633
1634   else
1635     /* empty string array */
1636     return g_new0 (gchar *, 1);
1637 }
1638
1639 static gboolean
1640 g_application_query_action (GActionGroup        *group,
1641                             const gchar         *action_name,
1642                             gboolean            *enabled,
1643                             const GVariantType **parameter_type,
1644                             const GVariantType **state_type,
1645                             GVariant           **state_hint,
1646                             GVariant           **state)
1647 {
1648   GApplication *application = G_APPLICATION (group);
1649
1650   g_return_val_if_fail (application->priv->is_registered, FALSE);
1651
1652   if (application->priv->remote_actions != NULL)
1653     return g_action_group_query_action (G_ACTION_GROUP (application->priv->remote_actions),
1654                                         action_name,
1655                                         enabled,
1656                                         parameter_type,
1657                                         state_type,
1658                                         state_hint,
1659                                         state);
1660
1661   if (application->priv->actions != NULL)
1662     return g_action_group_query_action (application->priv->actions,
1663                                         action_name,
1664                                         enabled,
1665                                         parameter_type,
1666                                         state_type,
1667                                         state_hint,
1668                                         state);
1669
1670   return FALSE;
1671 }
1672
1673 static void
1674 g_application_change_action_state (GActionGroup *action_group,
1675                                    const gchar  *action_name,
1676                                    GVariant     *value)
1677 {
1678   GApplication *application = G_APPLICATION (action_group);
1679
1680   g_return_if_fail (application->priv->is_remote ||
1681                     application->priv->actions != NULL);
1682   g_return_if_fail (application->priv->is_registered);
1683
1684   if (application->priv->remote_actions)
1685     g_remote_action_group_change_action_state_full (application->priv->remote_actions,
1686                                                     action_name, value, get_platform_data (application));
1687
1688   else
1689     g_action_group_change_action_state (application->priv->actions, action_name, value);
1690 }
1691
1692 static void
1693 g_application_activate_action (GActionGroup *action_group,
1694                                const gchar  *action_name,
1695                                GVariant     *parameter)
1696 {
1697   GApplication *application = G_APPLICATION (action_group);
1698
1699   g_return_if_fail (application->priv->is_remote ||
1700                     application->priv->actions != NULL);
1701   g_return_if_fail (application->priv->is_registered);
1702
1703   if (application->priv->remote_actions)
1704     g_remote_action_group_activate_action_full (application->priv->remote_actions,
1705                                                 action_name, parameter, get_platform_data (application));
1706
1707   else
1708     g_action_group_activate_action (application->priv->actions, action_name, parameter);
1709 }
1710
1711 static GAction *
1712 g_application_lookup_action (GActionMap  *action_map,
1713                              const gchar *action_name)
1714 {
1715   GApplication *application = G_APPLICATION (action_map);
1716
1717   g_return_val_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions), NULL);
1718
1719   return g_simple_action_group_lookup (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1720 }
1721
1722 static void
1723 g_application_add_action (GActionMap *action_map,
1724                           GAction    *action)
1725 {
1726   GApplication *application = G_APPLICATION (action_map);
1727
1728   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1729
1730   g_simple_action_group_insert (G_SIMPLE_ACTION_GROUP (application->priv->actions), action);
1731 }
1732
1733 static void
1734 g_application_remove_action (GActionMap  *action_map,
1735                              const gchar *action_name)
1736 {
1737   GApplication *application = G_APPLICATION (action_map);
1738
1739   g_return_if_fail (G_IS_SIMPLE_ACTION_GROUP (application->priv->actions));
1740
1741   g_simple_action_group_remove (G_SIMPLE_ACTION_GROUP (application->priv->actions), action_name);
1742 }
1743
1744 static void
1745 g_application_action_group_iface_init (GActionGroupInterface *iface)
1746 {
1747   iface->list_actions = g_application_list_actions;
1748   iface->query_action = g_application_query_action;
1749   iface->change_action_state = g_application_change_action_state;
1750   iface->activate_action = g_application_activate_action;
1751 }
1752
1753 static void
1754 g_application_action_map_iface_init (GActionMapInterface *iface)
1755 {
1756   iface->lookup_action = g_application_lookup_action;
1757   iface->add_action = g_application_add_action;
1758   iface->remove_action = g_application_remove_action;
1759 }
1760
1761 /* Default Application {{{1 */
1762
1763 static GApplication *default_app;
1764
1765 /**
1766  * g_application_get_default:
1767  * @returns: (transfer none): the default application for this process, or %NULL
1768  *
1769  * Returns the default #GApplication instance for this process.
1770  *
1771  * Normally there is only one #GApplication per process and it becomes
1772  * the default when it is created.  You can exercise more control over
1773  * this by using g_application_set_default().
1774  *
1775  * If there is no default application then %NULL is returned.
1776  *
1777  * Since: 2.32
1778  **/
1779 GApplication *
1780 g_application_get_default (void)
1781 {
1782   return default_app;
1783 }
1784
1785 /**
1786  * g_application_set_default:
1787  * @application: the application to set as default, or %NULL
1788  *
1789  * Sets or unsets the default application for the process, as returned
1790  * by g_application_get_default().
1791  *
1792  * This function does not take its own reference on @application.  If
1793  * @application is destroyed then the default application will revert
1794  * back to %NULL.
1795  *
1796  * Since: 2.32
1797  **/
1798 void
1799 g_application_set_default (GApplication *application)
1800 {
1801   default_app = application;
1802 }
1803
1804 /* Epilogue {{{1 */
1805 /* vim:set foldmethod=marker: */