Small doc correction
[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 "gapplicationimpl.h"
29 #include "gactiongroup.h"
30
31 #include "gioenumtypes.h"
32 #include "gio-marshal.h"
33 #include "gioenums.h"
34 #include "gfile.h"
35
36 #include "glibintl.h"
37
38 #include <string.h>
39
40 /**
41  * SECTION:gapplication
42  * @title: GApplication
43  * @short_description: Core application class
44  *
45  * A #GApplication is the foundation of an application, unique for a
46  * given application identifier.  The GApplication class wraps some
47  * low-level platform-specific services and is intended to act as the
48  * foundation for higher-level application classes such as
49  * #GtkApplication or #MxApplication.  In general, you should not use
50  * this class outside of a higher level framework.
51  *
52  * One of the core features that GApplication provides is process
53  * uniqueness, in the context of a "session".  The session concept is
54  * platform-dependent, but corresponds roughly to a graphical desktop
55  * login.  When your application is launched again, its arguments
56  * are passed through platform communication to the already running
57  * program. The already running instance of the program is called the
58  * <firstterm>primary instance</firstterm>.
59  *
60  * Before using GApplication, you must choose an "application identifier".
61  * The expected form of an application identifier is very close to that of
62  * of a <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-interface">DBus bus name</ulink>.
63  * Examples include: "com.example.MyApp", "org.example.internal-apps.Calculator".
64  * For details on valid application identifiers, see
65  * g_application_id_is_valid().
66  *
67  * The application identifier is claimed by the application as a
68  * well-known bus name on the user's session bus.  This means that the
69  * uniqueness of your application is scoped to the current session.  It
70  * also means that your application may provide additional services
71  * (through registration of other object paths) at that bus name.
72  *
73  * The registration of these object paths should be done with the shared
74  * GDBus session bus.  Note that due to the internal architecture of
75  * GDBus, method calls can be dispatched at any time (even if a main
76  * loop is not running).  For this reason, you must ensure that any
77  * object paths that you wish to register are registered before
78  * #GApplication attempts to acquire the bus name of your application
79  * (which happens in g_application_register()).  Unfortunately, this
80  * means that you can not use g_application_get_is_remote() to decide if
81  * you want to register object paths.
82  *
83  * GApplication provides convenient life cycle management by maintaining
84  * a <firstterm>use count</firstterm> for the primary application instance.
85  * The use count can be changed using g_application_hold() and
86  * g_application_release(). If it drops to zero, the application exits.
87  *
88  * GApplication also implements the #GActionGroup interface and lets you
89  * easily export actions by adding them with g_application_set_action_group().
90  * When invoking an action by calling g_action_group_activate_action() on
91  * the application, it is always invoked in the primary instance.
92  *
93  * There is a number of different entry points into a #GApplication:
94  * <itemizedlist>
95  * <listitem>via 'Activate' (i.e. just starting the application)</listitem>
96  * <listitem>via 'Open' (i.e. opening some files)</listitem>
97  * <listitem>by handling a command-line</listitem>
98  * <listitem>via activating an action</listitem>
99  * </itemizedlist>
100  * The #GApplication::startup signal lets you handle the application
101  * initialization for all of these in a single place.
102  *
103  * Regardless of which of these entry points is used to start the application,
104  * GApplication passes some <firstterm id="platform-data">platform
105  * data</firstterm> from the launching instance to the primary instance,
106  * in the form of a #GVariant dictionary mapping strings to variants.
107  * To use platform data, override the @before_emit or @after_emit virtual
108  * functions in your #GApplication subclass.
109  *
110  * As the name indicates, the platform data may vary depending on the
111  * operating system, but it always includes the current directory (key
112  * "cwd"), and optionally the environment (ie the set of environment
113  * variables and their values) of the calling process (key "environ").
114  * The environment is only added to the platform data if the
115  * #G_APPLICATION_SEND_ENVIONMENT flag is set. GApplication subclasses
116  * can add their own platform data by overriding the @add_platform_data
117  * virtual function. For instance, #GtkApplication adds startup notification
118  * information in this way.
119  *
120  * <example id="gapplication-example-open"><title>Opening files with a GApplication</title>
121  * <programlisting>
122  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-open.c">
123  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
124  * </xi:include>
125  * </programlisting>
126  * </example>
127  *
128  * <example id="gapplication-example-actions"><title>A GApplication with actions</title>
129  * <programlisting>
130  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-actions.c">
131  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
132  * </xi:include>
133  * </programlisting>
134  * </example>
135  */
136
137 struct _GApplicationPrivate
138 {
139   GApplicationFlags  flags;
140   gchar             *id;
141
142   GActionGroup      *actions;
143   GMainLoop         *mainloop;
144
145   guint              inactivity_timeout_id;
146   guint              inactivity_timeout;
147   guint              use_count;
148
149   guint              is_registered : 1;
150   guint              is_remote : 1;
151
152   GHashTable        *remote_actions;  /* string -> RemoteActionInfo */
153   GApplicationImpl  *impl;
154 };
155
156 enum
157 {
158   PROP_NONE,
159   PROP_APPLICATION_ID,
160   PROP_FLAGS,
161   PROP_IS_REGISTERED,
162   PROP_IS_REMOTE,
163   PROP_INACTIVITY_TIMEOUT,
164   PROP_ACTION_GROUP
165 };
166
167 enum
168 {
169   SIGNAL_STARTUP,
170   SIGNAL_ACTIVATE,
171   SIGNAL_OPEN,
172   SIGNAL_ACTION,
173   SIGNAL_COMMAND_LINE,
174   NR_SIGNALS
175 };
176
177 static guint g_application_signals[NR_SIGNALS];
178
179 static void g_application_action_group_iface_init (GActionGroupInterface *);
180 G_DEFINE_TYPE_WITH_CODE (GApplication, g_application, G_TYPE_OBJECT,
181  G_IMPLEMENT_INTERFACE (G_TYPE_ACTION_GROUP,
182    g_application_action_group_iface_init))
183
184 /* vfunc defaults {{{1 */
185 static void
186 g_application_real_before_emit (GApplication *application,
187                                 GVariant     *platform_data)
188 {
189 }
190
191 static void
192 g_application_real_after_emit (GApplication *application,
193                                GVariant     *platform_data)
194 {
195 }
196
197 static void
198 g_application_real_startup (GApplication *application)
199 {
200 }
201
202 static void
203 g_application_real_activate (GApplication *application)
204 {
205   if (!g_signal_has_handler_pending (application,
206                                      g_application_signals[SIGNAL_ACTIVATE],
207                                      0, TRUE) &&
208       G_APPLICATION_GET_CLASS (application)->activate == g_application_real_activate)
209     {
210       static gboolean warned;
211
212       if (warned)
213         return;
214
215       g_warning ("Your application does not implement "
216                  "g_application_activate() and has no handlers connected "
217                  "to the 'activate' signal.  It should do one of these.");
218       warned = TRUE;
219     }
220 }
221
222 static void
223 g_application_real_open (GApplication  *application,
224                          GFile        **files,
225                          gint           n_files,
226                          const gchar   *hint)
227 {
228   if (!g_signal_has_handler_pending (application,
229                                      g_application_signals[SIGNAL_OPEN],
230                                      0, TRUE) &&
231       G_APPLICATION_GET_CLASS (application)->open == g_application_real_open)
232     {
233       static gboolean warned;
234
235       if (warned)
236         return;
237
238       g_warning ("Your application claims to support opening files "
239                  "but does not implement g_application_open() and has no "
240                  "handlers connected to the 'open' signal.");
241       warned = TRUE;
242     }
243 }
244
245 static int
246 g_application_real_command_line (GApplication            *application,
247                                  GApplicationCommandLine *cmdline)
248 {
249   static gboolean warned;
250
251   if (warned) 
252     return 1;
253
254   g_warning ("Your application claims to support custom command line "
255              "handling but does not implement g_application_command_line() "
256              "and has no handlers connected to the 'command-line' signal.");
257
258   warned = TRUE;
259
260   return 1;
261 }
262
263 static gboolean
264 g_application_real_local_command_line (GApplication   *application,
265                                        gchar        ***arguments,
266                                        int            *exit_status)
267 {
268   if (application->priv->flags & G_APPLICATION_HANDLES_COMMAND_LINE)
269     return FALSE;
270
271   else
272     {
273       GError *error = NULL;
274       gint n_args;
275
276       if (!g_application_register (application, NULL, &error))
277         {
278           g_critical ("%s", error->message);
279           g_error_free (error);
280           *exit_status = 1;
281           return TRUE;
282         }
283
284       n_args = g_strv_length (*arguments);
285
286       if (application->priv->flags & G_APPLICATION_IS_SERVICE)
287         {
288           if ((*exit_status = n_args > 1))
289             {
290               g_printerr ("GApplication service mode takes no arguments.\n");
291               application->priv->flags &= ~G_APPLICATION_IS_SERVICE;
292             }
293
294           return TRUE;
295         }
296
297       if (n_args <= 1)
298         {
299           g_application_activate (application);
300           *exit_status = 0;
301         }
302
303       else
304         {
305           if (~application->priv->flags & G_APPLICATION_HANDLES_OPEN)
306             {
307               g_critical ("This application can not open files.");
308               *exit_status = 1;
309             }
310           else
311             {
312               GFile **files;
313               gint n_files;
314               gint i;
315
316               n_files = n_args - 1;
317               files = g_new (GFile *, n_files);
318
319               for (i = 0; i < n_files; i++)
320                 files[i] = g_file_new_for_commandline_arg ((*arguments)[i + 1]);
321
322               g_application_open (application, files, n_files, "");
323
324               for (i = 0; i < n_files; i++)
325                 g_object_unref (files[i]);
326               g_free (files);
327
328               *exit_status = 0;
329             }
330         }
331
332       return TRUE;
333     }
334 }
335
336 static void
337 g_application_real_add_platform_data (GApplication    *application,
338                                       GVariantBuilder *builder)
339 {
340 }
341
342 static void
343 g_application_real_quit_mainloop (GApplication *application)
344 {
345   if (application->priv->mainloop != NULL)
346     g_main_loop_quit (application->priv->mainloop);
347 }
348
349 static void
350 g_application_real_run_mainloop (GApplication *application)
351 {
352   if (application->priv->mainloop == NULL)
353     application->priv->mainloop = g_main_loop_new (NULL, FALSE);
354
355   g_main_loop_run (application->priv->mainloop);
356 }
357
358 /* GObject implementation stuff {{{1 */
359 static void
360 g_application_set_property (GObject      *object,
361                             guint         prop_id,
362                             const GValue *value,
363                             GParamSpec   *pspec)
364 {
365   GApplication *application = G_APPLICATION (object);
366
367   switch (prop_id)
368     {
369     case PROP_APPLICATION_ID:
370       g_application_set_application_id (application,
371                                         g_value_get_string (value));
372       break;
373
374     case PROP_FLAGS:
375       g_application_set_flags (application, g_value_get_flags (value));
376       break;
377
378     case PROP_INACTIVITY_TIMEOUT:
379       g_application_set_inactivity_timeout (application,
380                                             g_value_get_uint (value));
381       break;
382
383     case PROP_ACTION_GROUP:
384       g_application_set_action_group (application,
385                                       g_value_get_object (value));
386       break;
387
388     default:
389       g_assert_not_reached ();
390     }
391 }
392
393 /**
394  * g_application_set_action_group:
395  * @application: a #GApplication
396  * @action_group: (allow-none): a #GActionGroup, or %NULL
397  *
398  * Sets or unsets the group of actions associated with the application.
399  *
400  * These actions are the actions that can be remotely invoked.
401  *
402  * It is an error to call this function after the application has been
403  * registered.
404  *
405  * Since: 2.28
406  **/
407 void
408 g_application_set_action_group (GApplication *application,
409                                 GActionGroup *action_group)
410 {
411   g_return_if_fail (G_IS_APPLICATION (application));
412   g_return_if_fail (!application->priv->is_registered);
413
414   if (application->priv->actions != NULL)
415     g_object_unref (application->priv->actions);
416
417   application->priv->actions = action_group;
418
419   if (application->priv->actions != NULL)
420     g_object_ref (application->priv->actions);
421 }
422
423 static void
424 g_application_get_property (GObject    *object,
425                             guint       prop_id,
426                             GValue     *value,
427                             GParamSpec *pspec)
428 {
429   GApplication *application = G_APPLICATION (object);
430
431   switch (prop_id)
432     {
433     case PROP_APPLICATION_ID:
434       g_value_set_string (value,
435                           g_application_get_application_id (application));
436       break;
437
438     case PROP_FLAGS:
439       g_value_set_flags (value,
440                          g_application_get_flags (application));
441       break;
442
443     case PROP_IS_REGISTERED:
444       g_value_set_boolean (value,
445                            g_application_get_is_registered (application));
446       break;
447
448     case PROP_IS_REMOTE:
449       g_value_set_boolean (value,
450                            g_application_get_is_remote (application));
451       break;
452
453     case PROP_INACTIVITY_TIMEOUT:
454       g_value_set_uint (value,
455                         g_application_get_inactivity_timeout (application));
456       break;
457
458     default:
459       g_assert_not_reached ();
460     }
461 }
462
463 static void
464 g_application_constructed (GObject *object)
465 {
466   GApplication *application = G_APPLICATION (object);
467
468   g_assert (application->priv->id != NULL);
469 }
470
471 static void
472 g_application_finalize (GObject *object)
473 {
474   GApplication *application = G_APPLICATION (object);
475
476   if (application->priv->impl)
477     g_application_impl_destroy (application->priv->impl);
478   g_free (application->priv->id);
479
480   if (application->priv->mainloop)
481     g_main_loop_unref (application->priv->mainloop);
482
483   G_OBJECT_CLASS (g_application_parent_class)
484     ->finalize (object);
485 }
486
487 static void
488 g_application_init (GApplication *application)
489 {
490   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application,
491                                                    G_TYPE_APPLICATION,
492                                                    GApplicationPrivate);
493 }
494
495 static void
496 g_application_class_init (GApplicationClass *class)
497 {
498   GObjectClass *object_class = G_OBJECT_CLASS (class);
499
500   object_class->constructed = g_application_constructed;
501   object_class->finalize = g_application_finalize;
502   object_class->get_property = g_application_get_property;
503   object_class->set_property = g_application_set_property;
504
505   class->before_emit = g_application_real_before_emit;
506   class->after_emit = g_application_real_after_emit;
507   class->startup = g_application_real_startup;
508   class->activate = g_application_real_activate;
509   class->open = g_application_real_open;
510   class->command_line = g_application_real_command_line;
511   class->local_command_line = g_application_real_local_command_line;
512   class->add_platform_data = g_application_real_add_platform_data;
513   class->quit_mainloop = g_application_real_quit_mainloop;
514   class->run_mainloop = g_application_real_run_mainloop;
515
516   g_object_class_install_property (object_class, PROP_APPLICATION_ID,
517     g_param_spec_string ("application-id",
518                          P_("Application identifier"),
519                          P_("The unique identifier for the application"),
520                          NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
521                          G_PARAM_STATIC_STRINGS));
522
523   g_object_class_install_property (object_class, PROP_FLAGS,
524     g_param_spec_flags ("flags",
525                         P_("Application flags"),
526                         P_("Flags specifying the behaviour of the application"),
527                         G_TYPE_APPLICATION_FLAGS, G_APPLICATION_FLAGS_NONE,
528                         G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
529
530   g_object_class_install_property (object_class, PROP_IS_REGISTERED,
531     g_param_spec_boolean ("is-registered",
532                           P_("Is registered"),
533                           P_("If g_application_register() has been called"),
534                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
535
536   g_object_class_install_property (object_class, PROP_IS_REMOTE,
537     g_param_spec_boolean ("is-remote",
538                           P_("Is remote"),
539                           P_("If this application instance is remote"),
540                           FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
541
542   g_object_class_install_property (object_class, PROP_INACTIVITY_TIMEOUT,
543     g_param_spec_uint ("inactivity-timeout",
544                        P_("Inactivity timeout"),
545                        P_("Iime (ms) to stay alive after becoming idle"),
546                        0, G_MAXUINT, 0,
547                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
548
549   g_object_class_install_property (object_class, PROP_ACTION_GROUP,
550     g_param_spec_object ("action-group",
551                          P_("Action group"),
552                          P_("The group of actions that the application exports"),
553                          G_TYPE_ACTION_GROUP, 
554                          G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
555
556   /**
557    * GApplication::startup:
558    * @application: the application
559    *
560    * The ::startup signal is emitted on the primary instance immediately
561    * after registration. See g_application_register().
562    */
563   g_application_signals[SIGNAL_STARTUP] =
564     g_signal_new ("startup", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
565                   G_STRUCT_OFFSET (GApplicationClass, startup),
566                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
567
568   /**
569    * GApplication::activate:
570    * @application: the application
571    *
572    * The ::activate signal is emitted on the primary instance when an
573    * activation occurs. See g_application_activate().
574    */
575   g_application_signals[SIGNAL_ACTIVATE] =
576     g_signal_new ("activate", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
577                   G_STRUCT_OFFSET (GApplicationClass, activate),
578                   NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
579
580
581   /**
582    * GApplication::open:
583    * @application: the application
584    * @files: (array length=n_files) (element-type GFile): an array of #GFiles
585    * @n_files: the length of @files
586    * @hint: a hint provided by the calling instance
587    *
588    * The ::open signal is emitted on the primary instance when there are
589    * files to open. See g_application_open() for more information.
590    */
591   g_application_signals[SIGNAL_OPEN] =
592     g_signal_new ("open", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
593                   G_STRUCT_OFFSET (GApplicationClass, open),
594                   NULL, NULL, _gio_marshal_VOID__POINTER_INT_STRING,
595                   G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_INT, G_TYPE_STRING);
596
597   /**
598    * GApplication::command-line:
599    * @application: the application
600    * @command_line: a #GApplicationCommandLine representing the
601    *     passed commandline
602    *
603    * The ::command-line signal is emitted on the primary instance when
604    * a commandline is not handled locally. See g_application_run() and
605    * the #GApplicationCommandline documentation for more information.
606    *
607    * Returns: An integer that is set as the exit status for the calling
608    *   process. See g_application_command_line_set_exit_status().
609    */
610   g_application_signals[SIGNAL_COMMAND_LINE] =
611     g_signal_new ("command-line", G_TYPE_APPLICATION, G_SIGNAL_RUN_LAST,
612                   G_STRUCT_OFFSET (GApplicationClass, command_line),
613                   g_signal_accumulator_first_wins, NULL,
614                   _gio_marshal_INT__OBJECT,
615                   G_TYPE_INT, 1, G_TYPE_APPLICATION_COMMAND_LINE);
616
617   g_type_class_add_private (class, sizeof (GApplicationPrivate));
618 }
619
620 static GVariant *
621 get_platform_data (GApplication *application)
622 {
623   GVariantBuilder *builder;
624   GVariant *result;
625
626   builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
627
628   {
629     gchar *cwd = g_get_current_dir ();
630     g_variant_builder_add (builder, "{sv}", "cwd",
631                            g_variant_new_bytestring (cwd));
632     g_free (cwd);
633   }
634
635   if (application->priv->flags & G_APPLICATION_SEND_ENVIRONMENT)
636     {
637       GVariant *array;
638       gchar **envp;
639      
640       envp = g_get_environ ();
641       array = g_variant_new_bytestring_array ((const gchar **) envp, -1);
642       g_strfreev (envp);
643
644       g_variant_builder_add (builder, "{sv}", "environ", array);
645     }
646
647   G_APPLICATION_GET_CLASS (application)->
648     add_platform_data (application, builder);
649
650   result = g_variant_builder_end (builder);
651   g_variant_builder_unref (builder);
652
653   return result;
654 }
655
656 /* Application ID validity {{{1 */
657
658 /**
659  * g_application_id_is_valid:
660  * @application_id: a potential application identifier
661  * @returns: %TRUE if @application_id is valid
662  *
663  * Checks if @application_id is a valid application identifier.
664  *
665  * A valid ID is required for calls to g_application_new() and
666  * g_application_set_application_id().
667  *
668  * For convenience, the restrictions on application identifiers are
669  * reproduced here:
670  * <itemizedlist>
671  *   <listitem>Application identifiers must contain only the ASCII characters "[A-Z][a-z][0-9]_-." and must not begin with a digit.</listitem>
672  *   <listitem>Application identifiers must contain at least one '.' (period) character (and thus at least three elements).</listitem>
673  *   <listitem>Application identifiers must not begin or end with a '.' (period) character.</listitem>
674  *   <listitem>Application identifiers must not contain consecutive '.' (period) characters.</listitem>
675  *   <listitem>Application identifiers must not exceed 255 characters.</listitem>
676  * </itemizedlist>
677  **/
678 gboolean
679 g_application_id_is_valid (const gchar *application_id)
680 {
681   gsize len;
682   gboolean allow_dot;
683   gboolean has_dot;
684
685   len = strlen (application_id);
686
687   if (len > 255)
688     return FALSE;
689
690   if (!g_ascii_isalpha (application_id[0]))
691     return FALSE;
692
693   if (application_id[len-1] == '.')
694     return FALSE;
695
696   application_id++;
697   allow_dot = TRUE;
698   has_dot = FALSE;
699   for (; *application_id; application_id++)
700     {
701       if (g_ascii_isalnum (*application_id) ||
702           (*application_id == '-') ||
703           (*application_id == '_'))
704         {
705           allow_dot = TRUE;
706         }
707       else if (allow_dot && *application_id == '.')
708         {
709           has_dot = TRUE;
710           allow_dot = FALSE;
711         }
712       else
713         return FALSE;
714     }
715
716   if (!has_dot)
717     return FALSE;
718
719   return TRUE;
720 }
721  
722 /* Public Constructor {{{1 */
723 /**
724  * g_application_new:
725  * @application_id: the application id
726  * @flags: the application flags
727  * @returns: a new #GApplication instance
728  *
729  * Creates a new #GApplication instance.
730  *
731  * This function calls g_type_init() for you.
732  *
733  * The application id must be valid.  See g_application_id_is_valid().
734  **/
735 GApplication *
736 g_application_new (const gchar       *application_id,
737                    GApplicationFlags  flags)
738 {
739   g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);
740
741   g_type_init ();
742
743   return g_object_new (G_TYPE_APPLICATION,
744                        "application-id", application_id,
745                        "flags", flags,
746                        NULL);
747 }
748
749 /* Simple get/set: application id, flags, inactivity timeout {{{1 */
750 /**
751  * g_application_get_application_id:
752  * @application: a #GApplication
753  * @returns: the identifier for @application, owned by @application
754  *
755  * Gets the unique identifier for @application.
756  *
757  * Since: 2.28
758  **/
759 const gchar *
760 g_application_get_application_id (GApplication *application)
761 {
762   g_return_val_if_fail (G_IS_APPLICATION (application), NULL);
763
764   return application->priv->id;
765 }
766
767 /**
768  * g_application_set_application_id:
769  * @application: a #GApplication
770  * @application_id: the identifier for @application
771  *
772  * Sets the unique identifier for @application.
773  *
774  * The application id can only be modified if @application has not yet
775  * been registered.
776  *
777  * The application id must be valid.  See g_application_id_is_valid().
778  *
779  * Since: 2.28
780  **/
781 void
782 g_application_set_application_id (GApplication *application,
783                                   const gchar  *application_id)
784 {
785   g_return_if_fail (G_IS_APPLICATION (application));
786
787   if (g_strcmp0 (application->priv->id, application_id) != 0)
788     {
789       g_return_if_fail (g_application_id_is_valid (application_id));
790       g_return_if_fail (!application->priv->is_registered);
791
792       g_free (application->priv->id);
793       application->priv->id = g_strdup (application_id);
794
795       g_object_notify (G_OBJECT (application), "application-id");
796     }
797 }
798
799 /**
800  * g_application_get_flags:
801  * @application: a #GApplication
802  * @returns: the flags for @application
803  *
804  * Gets the flags for @application.
805  *
806  * See #GApplicationFlags.
807  *
808  * Since: 2.28
809  **/
810 GApplicationFlags
811 g_application_get_flags (GApplication *application)
812 {
813   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
814
815   return application->priv->flags;
816 }
817
818 /**
819  * g_application_set_flags:
820  * @application: a #GApplication
821  * @flags: the flags for @application
822  *
823  * Sets the flags for @application.
824  *
825  * The flags can only be modified if @application has not yet been
826  * registered.
827  *
828  * See #GApplicationFlags.
829  *
830  * Since: 2.28
831  **/
832 void
833 g_application_set_flags (GApplication      *application,
834                          GApplicationFlags  flags)
835 {
836   g_return_if_fail (G_IS_APPLICATION (application));
837
838   if (application->priv->flags != flags)
839     {
840       g_return_if_fail (!application->priv->is_registered);
841
842       application->priv->flags = flags;
843
844       g_object_notify (G_OBJECT (application), "flags");
845     }
846 }
847
848 /**
849  * g_application_get_inactivity_timeout:
850  * @application: a #GApplication
851  *
852  * Gets the current inactivity timeout for the application.
853  *
854  * This is the amount of time (in milliseconds) after the last call to
855  * g_application_release() before the application stops running.
856  *
857  * Returns: the timeout, in milliseconds
858  *
859  * Since: 2.28
860  **/
861 guint
862 g_application_get_inactivity_timeout (GApplication *application)
863 {
864   g_return_val_if_fail (G_IS_APPLICATION (application), 0);
865
866   return application->priv->inactivity_timeout;
867 }
868
869 /**
870  * g_application_set_inactivity_timeout:
871  * @application: a #GApplication
872  * @inactivity_timeout: the timeout, in milliseconds
873  *
874  * Sets the current inactivity timeout for the application.
875  *
876  * This is the amount of time (in milliseconds) after the last call to
877  * g_application_release() before the application stops running.
878  *
879  * This call has no side effects of its own.  The value set here is only
880  * used for next time g_application_release() drops the use count to
881  * zero.  Any timeouts currently in progress are not impacted.
882  *
883  * Returns: the timeout, in milliseconds
884  *
885  * Since: 2.28
886  **/
887 void
888 g_application_set_inactivity_timeout (GApplication *application,
889                                       guint         inactivity_timeout)
890 {
891   g_return_if_fail (G_IS_APPLICATION (application));
892
893   if (application->priv->inactivity_timeout != inactivity_timeout)
894     {
895       application->priv->inactivity_timeout = inactivity_timeout;
896
897       g_object_notify (G_OBJECT (application), "inactivity-timeout");
898     }
899 }
900 /* Read-only property getters (is registered, is remote) {{{1 */
901 /**
902  * g_application_get_is_registered:
903  * @application: a #GApplication
904  * @returns: %TRUE if @application is registered
905  *
906  * Checks if @application is registered.
907  *
908  * An application is registered if g_application_register() has been
909  * successfully called.
910  *
911  * Since: 2.28
912  **/
913 gboolean
914 g_application_get_is_registered (GApplication *application)
915 {
916   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
917
918   return application->priv->is_registered;
919 }
920
921 /**
922  * g_application_get_is_remote:
923  * @application: a #GApplication
924  * @returns: %TRUE if @application is remote
925  *
926  * Checks if @application is remote.
927  *
928  * If @application is remote then it means that another instance of
929  * application already exists (the 'primary' instance).  Calls to
930  * perform actions on @application will result in the actions being
931  * performed by the primary instance.
932  *
933  * The value of this property can not be accessed before
934  * g_application_register() has been called.  See
935  * g_application_get_is_registered().
936  *
937  * Since: 2.28
938  **/
939 gboolean
940 g_application_get_is_remote (GApplication *application)
941 {
942   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
943   g_return_val_if_fail (application->priv->is_registered, FALSE);
944
945   return application->priv->is_remote;
946 }
947
948 /* Register {{{1 */
949 /**
950  * g_application_register:
951  * @application: a #GApplication
952  * @cancellable: a #GCancellable, or %NULL
953  * @error: a pointer to a NULL #GError, or %NULL
954  * @returns: %TRUE if registration succeeded
955  *
956  * Attempts registration of the application.
957  *
958  * This is the point at which the application discovers if it is the
959  * primary instance or merely acting as a remote for an already-existing
960  * primary instance.  This is implemented by attempting to acquire the
961  * application identifier as a unique bus name on the session bus using
962  * GDBus.
963  *
964  * Due to the internal architecture of GDBus, method calls can be
965  * dispatched at any time (even if a main loop is not running).  For
966  * this reason, you must ensure that any object paths that you wish to
967  * register are registered before calling this function.
968  *
969  * If the application has already been registered then %TRUE is
970  * returned with no work performed.
971  *
972  * The #GApplication::startup signal is emitted if registration succeeds
973  * and @application is the primary instance.
974  *
975  * In the event of an error (such as @cancellable being cancelled, or a
976  * failure to connect to the session bus), %FALSE is returned and @error
977  * is set appropriately.
978  *
979  * Note: the return value of this function is not an indicator that this
980  * instance is or is not the primary instance of the application.  See
981  * g_application_get_is_remote() for that.
982  *
983  * Since: 2.28
984  **/
985 gboolean
986 g_application_register (GApplication  *application,
987                         GCancellable  *cancellable,
988                         GError       **error)
989 {
990   g_return_val_if_fail (G_IS_APPLICATION (application), FALSE);
991
992   if (!application->priv->is_registered)
993     {
994       application->priv->impl =
995         g_application_impl_register (application, application->priv->id,
996                                      application->priv->flags,
997                                      &application->priv->remote_actions,
998                                      cancellable, error);
999
1000       if (application->priv->impl == NULL)
1001         return FALSE;
1002
1003       application->priv->is_remote = application->priv->remote_actions != NULL;
1004       application->priv->is_registered = TRUE;
1005
1006       g_object_notify (G_OBJECT (application), "is-registered");
1007
1008       if (!application->priv->is_remote)
1009         g_signal_emit (application, g_application_signals[SIGNAL_STARTUP], 0);
1010     }
1011
1012   return TRUE;
1013 }
1014
1015 /* Hold/release {{{1 */
1016 /**
1017  * g_application_hold:
1018  * @application: a #GApplication
1019  *
1020  * Increases the use count of @application.
1021  *
1022  * Use this function to indicate that the application has a reason to
1023  * continue to run.  For example, g_application_hold() is called by GTK+ 
1024  * when a toplevel window is on the screen.
1025  *
1026  * To cancel the hold, call g_application_release().
1027  **/
1028 void
1029 g_application_hold (GApplication *application)
1030 {
1031   if (application->priv->inactivity_timeout_id)
1032     {
1033       g_source_remove (application->priv->inactivity_timeout_id);
1034       application->priv->inactivity_timeout_id = 0;
1035     }
1036
1037   application->priv->use_count++;
1038 }
1039
1040 static gboolean
1041 inactivity_timeout_expired (gpointer data)
1042 {
1043   GApplication *application = G_APPLICATION (data);
1044
1045   G_APPLICATION_GET_CLASS (application)
1046     ->quit_mainloop (application);
1047
1048   return FALSE;
1049 }
1050
1051
1052 /**
1053  * g_application_release:
1054  * @application: a #GApplication
1055  *
1056  * Decrease the use count of @application.
1057  *
1058  * When the use count reaches zero, the application will stop running.
1059  *
1060  * Never call this function except to cancel the effect of a previous
1061  * call to g_application_hold().
1062  **/
1063 void
1064 g_application_release (GApplication *application)
1065 {
1066   application->priv->use_count--;
1067
1068   if (application->priv->use_count == 0)
1069     {
1070       if (application->priv->inactivity_timeout)
1071         application->priv->inactivity_timeout_id =
1072           g_timeout_add (application->priv->inactivity_timeout,
1073                          inactivity_timeout_expired, application);
1074
1075       else
1076         G_APPLICATION_GET_CLASS (application)
1077           ->quit_mainloop (application);
1078     }
1079 }
1080
1081 /* Activate, Open {{{1 */
1082 /**
1083  * g_application_activate:
1084  * @application: a #GApplication
1085  *
1086  * Activates the application.
1087  *
1088  * In essence, this results in the #GApplication::activate() signal being
1089  * emitted in the primary instance.
1090  *
1091  * The application must be registered before calling this function.
1092  *
1093  * Since: 2.28
1094  **/
1095 void
1096 g_application_activate (GApplication *application)
1097 {
1098   g_return_if_fail (G_IS_APPLICATION (application));
1099   g_return_if_fail (application->priv->is_registered);
1100
1101   if (application->priv->is_remote)
1102     g_application_impl_activate (application->priv->impl,
1103                                  get_platform_data (application));
1104
1105   else
1106     g_signal_emit (application, g_application_signals[SIGNAL_ACTIVATE], 0);
1107 }
1108
1109 /**
1110  * g_application_open:
1111  * @application: a #GApplication
1112  * @files: (array length=n_files): an array of #GFiles to open
1113  * @n_files: the length of the @files array
1114  * @hint: a hint (or ""), but never %NULL
1115  *
1116  * Opens the given files.
1117  *
1118  * In essence, this results in the #GApplication::open signal being emitted
1119  * in the primary instance.
1120  *
1121  * @n_files must be greater than zero.
1122  *
1123  * @hint is simply passed through to the ::open signal.  It is
1124  * intended to be used by applications that have multiple modes for
1125  * opening files (eg: "view" vs "edit", etc).  Unless you have a need
1126  * for this functionality, you should use "".
1127  *
1128  * The application must be registered before calling this function
1129  * and it must have the %G_APPLICATION_HANDLES_OPEN flag set.
1130  *
1131  * Since: 2.28
1132  **/
1133 void
1134 g_application_open (GApplication  *application,
1135                     GFile        **files,
1136                     gint           n_files,
1137                     const gchar   *hint)
1138 {
1139   g_return_if_fail (G_IS_APPLICATION (application));
1140   g_return_if_fail (application->priv->flags &
1141                     G_APPLICATION_HANDLES_OPEN);
1142   g_return_if_fail (application->priv->is_registered);
1143
1144   if (application->priv->is_remote)
1145     g_application_impl_open (application->priv->impl,
1146                              files, n_files, hint,
1147                              get_platform_data (application));
1148
1149   else
1150     g_signal_emit (application, g_application_signals[SIGNAL_OPEN],
1151                    0, files, n_files, hint);
1152 }
1153
1154 /* Run {{{1 */
1155 /**
1156  * g_application_run:
1157  * @application: a #GApplication
1158  * @argc: the argc from main() (or 0 if @argv is %NULL)
1159  * @argv: (array length=argc): the argv from main(), or %NULL
1160  * @returns: the exit status
1161  *
1162  * Runs the application.
1163  *
1164  * This function is intended to be run from main() and its return value
1165  * is intended to be returned by main(). Although you are expected to pass
1166  * the @argc, @argv parameters from main() to this function, it is possible
1167  * to pass %NULL if @argv is not available or commandline handling is not
1168  * required.
1169  *
1170  * First, the local_command_line() virtual function is invoked.
1171  * This function always runs on the local instance. It gets passed
1172  * a pointer to a copy of @argv and is expected to remove the arguments
1173  * that it handled (shifting up remaining arguments). See
1174  * <xref linkend="gapplication-example-cmdline2"/> for an example.
1175  * The last argument to local_command_line() is a pointer to the @status
1176  * variable which can used to set the exit status that is returned from
1177  * g_application_run().
1178  *
1179  * If local_command_line() returns %TRUE, the command line is expected
1180  * to be completely handled, including possibly registering as the primary
1181  * instance, calling g_application_activate() or g_application_open(), etc.
1182  *
1183  * If local_command_line() returns %FALSE then the application is registered
1184  * and the #GApplication::command-line signal is emitted in the primary
1185  * instance (which may or may not be this instance).
1186  *
1187  * If the application has the %G_APPLICATION_HANDLES_COMMAND_LINE
1188  * flag set then the default implementation of local_command_line()
1189  * always returns %FALSE immediately, resulting in the commandline
1190  * always being handled in the primary instance.
1191  *
1192  * Otherwise, the default implementation of local_command_line() tries
1193  * to do a couple of things that are probably reasonable for most
1194  * applications.  First, g_application_register() is called to attempt
1195  * to register the application.  If that works, then the command line
1196  * arguments are inspected.  If no commandline arguments are given, then
1197  * g_application_activate() is called.  If commandline arguments are
1198  * given and the %G_APPLICATION_HANDLES_OPEN flag is set then they
1199  * are assumed to be filenames and g_application_open() is called.
1200  *
1201  * If you are interested in doing more complicated local handling of the
1202  * commandline then you should implement your own #GApplication subclass
1203  * and override local_command_line(). In this case, you most likely want
1204  * to return %TRUE from your local_command_line() implementation to
1205  * suppress the default handling. See
1206  * <xref linkend="gapplication-example-cmdline2"/> for an example.
1207  *
1208  * If, after the above is done, the use count of the application is zero
1209  * then the exit status is returned immediately.  If the use count is
1210  * non-zero then the mainloop is run until the use count falls to zero,
1211  * at which point 0 is returned.
1212  *
1213  * If the %G_APPLICATION_IS_SERVICE flag is set, then the exiting at
1214  * use count of zero is delayed for a while (ie: the instance stays
1215  * around to provide its <emphasis>service</emphasis> to others).
1216  *
1217  * Since: 2.28
1218  **/
1219 int
1220 g_application_run (GApplication  *application,
1221                    int            argc,
1222                    char         **argv)
1223 {
1224   gchar **arguments;
1225   int status;
1226   gint i;
1227
1228   g_return_val_if_fail (G_IS_APPLICATION (application), 1);
1229   g_return_val_if_fail (argc == 0 || argv != NULL, 1);
1230
1231   arguments = g_new (gchar *, argc + 1);
1232   for (i = 0; i < argc; i++)
1233     arguments[i] = g_strdup (argv[i]);
1234   arguments[i] = NULL;
1235
1236   if (g_get_prgname () == NULL && argc > 0)
1237     {
1238       gchar *prgname;
1239
1240       prgname = g_path_get_basename (argv[0]);
1241       g_set_prgname (prgname);
1242       g_free (prgname);
1243     }
1244
1245   if (!G_APPLICATION_GET_CLASS (application)
1246         ->local_command_line (application, &arguments, &status))
1247     {
1248       GError *error = NULL;
1249
1250       if (!g_application_register (application, NULL, &error))
1251         {
1252           g_printerr ("%s", error->message);
1253           g_error_free (error);
1254           return 1;
1255         }
1256
1257       if (application->priv->is_remote)
1258         {
1259           GVariant *platform_data;
1260
1261           platform_data = get_platform_data (application);
1262           status = g_application_impl_command_line (application->priv->impl,
1263                                                     arguments, platform_data);
1264         }
1265       else
1266         {
1267           GApplicationCommandLine *cmdline;
1268           GVariant *v;
1269
1270           v = g_variant_new_bytestring_array ((const gchar **) arguments, -1);
1271           cmdline = g_object_new (G_TYPE_APPLICATION_COMMAND_LINE,
1272                                   "arguments", v, NULL);
1273           g_signal_emit (application,
1274                          g_application_signals[SIGNAL_COMMAND_LINE],
1275                          0, cmdline, &status);
1276           g_object_unref (cmdline);
1277         }
1278     }
1279
1280   g_strfreev (arguments);
1281
1282   if (application->priv->flags & G_APPLICATION_IS_SERVICE &&
1283       application->priv->is_registered &&
1284       !application->priv->use_count &&
1285       !application->priv->inactivity_timeout_id)
1286     {
1287       application->priv->inactivity_timeout_id =
1288         g_timeout_add (10000, inactivity_timeout_expired, application);
1289     }
1290
1291   if (application->priv->use_count ||
1292       application->priv->inactivity_timeout_id)
1293     {
1294       G_APPLICATION_GET_CLASS (application)
1295         ->run_mainloop (application);
1296       status = 0;
1297     }
1298
1299   if (application->priv->impl)
1300     g_application_impl_flush (application->priv->impl);
1301
1302   return status;
1303 }
1304
1305 static gboolean
1306 g_application_has_action (GActionGroup *action_group,
1307                           const gchar  *action_name)
1308 {
1309   GApplication *application = G_APPLICATION (action_group);
1310
1311   g_return_val_if_fail (application->priv->is_registered, FALSE);
1312
1313   if (application->priv->remote_actions != NULL)
1314     return g_hash_table_lookup (application->priv->remote_actions,
1315                                 action_name) != NULL;
1316
1317   return application->priv->actions &&
1318          g_action_group_has_action (application->priv->actions, action_name);
1319 }
1320
1321 static gchar **
1322 g_application_list_actions (GActionGroup *action_group)
1323 {
1324   GApplication *application = G_APPLICATION (action_group);
1325
1326   g_return_val_if_fail (application->priv->is_registered, NULL);
1327
1328   if (application->priv->remote_actions != NULL)
1329     {
1330       GHashTableIter iter;
1331       gint n, i = 0;
1332       gchar **keys;
1333       gpointer key;
1334
1335       n = g_hash_table_size (application->priv->remote_actions);
1336       keys = g_new (gchar *, n + 1);
1337
1338       g_hash_table_iter_init (&iter, application->priv->remote_actions);
1339       while (g_hash_table_iter_next (&iter, &key, NULL))
1340         keys[i++] = g_strdup (key);
1341       g_assert_cmpint (i, ==, n);
1342       keys[n] = NULL;
1343
1344       return keys;
1345     }
1346
1347   else if (application->priv->actions != NULL)
1348     return g_action_group_list_actions (application->priv->actions);
1349
1350   else
1351     /* empty string array */
1352     return g_new0 (gchar *, 1);
1353 }
1354
1355 static gboolean
1356 g_application_get_action_enabled (GActionGroup *action_group,
1357                                   const gchar  *action_name)
1358 {
1359   GApplication *application = G_APPLICATION (action_group);
1360
1361   g_return_val_if_fail (application->priv->actions != NULL, FALSE);
1362   g_return_val_if_fail (application->priv->is_registered, FALSE);
1363
1364   if (application->priv->remote_actions)
1365     {
1366       RemoteActionInfo *info;
1367
1368       info = g_hash_table_lookup (application->priv->remote_actions,
1369                                   action_name);
1370
1371       return info && info->enabled;
1372     }
1373
1374   return g_action_group_get_action_enabled (application->priv->actions,
1375                                             action_name);
1376 }
1377
1378 static const GVariantType *
1379 g_application_get_action_parameter_type (GActionGroup *action_group,
1380                                          const gchar  *action_name)
1381 {
1382   GApplication *application = G_APPLICATION (action_group);
1383
1384   g_return_val_if_fail (application->priv->actions != NULL, NULL);
1385   g_return_val_if_fail (application->priv->is_registered, NULL);
1386
1387   if (application->priv->remote_actions)
1388     {
1389       RemoteActionInfo *info;
1390
1391       info = g_hash_table_lookup (application->priv->remote_actions,
1392                                   action_name);
1393
1394       if (info)
1395         return info->parameter_type;
1396       else
1397         return NULL;
1398     }
1399
1400   return g_action_group_get_action_parameter_type (application->priv->actions,
1401                                                    action_name);
1402 }
1403
1404 static const GVariantType *
1405 g_application_get_action_state_type (GActionGroup *action_group,
1406                                      const gchar  *action_name)
1407 {
1408   GApplication *application = G_APPLICATION (action_group);
1409
1410   g_return_val_if_fail (application->priv->actions != NULL, NULL);
1411   g_return_val_if_fail (application->priv->is_registered, NULL);
1412
1413   if (application->priv->remote_actions)
1414     {
1415       RemoteActionInfo *info;
1416
1417       info = g_hash_table_lookup (application->priv->remote_actions,
1418                                   action_name);
1419
1420       if (info && info->state)
1421         return g_variant_get_type (info->state);
1422       else
1423         return NULL;
1424     }
1425
1426   return g_action_group_get_action_state_type (application->priv->actions,
1427                                                action_name);
1428 }
1429
1430 static GVariant *
1431 g_application_get_action_state (GActionGroup *action_group,
1432                                 const gchar  *action_name)
1433 {
1434   GApplication *application = G_APPLICATION (action_group);
1435
1436   g_return_val_if_fail (application->priv->actions != NULL, NULL);
1437   g_return_val_if_fail (application->priv->is_registered, NULL);
1438
1439   if (application->priv->remote_actions)
1440     {
1441       RemoteActionInfo *info;
1442
1443       info = g_hash_table_lookup (application->priv->remote_actions,
1444                                   action_name);
1445
1446       if (info && info->state)
1447         return g_variant_ref (info->state);
1448       else
1449         return NULL;
1450     }
1451
1452   return g_action_group_get_action_state (application->priv->actions,
1453                                           action_name);
1454 }
1455
1456 static void
1457 g_application_change_action_state (GActionGroup *action_group,
1458                                    const gchar  *action_name,
1459                                    GVariant     *value)
1460 {
1461   GApplication *application = G_APPLICATION (action_group);
1462
1463   g_return_if_fail (application->priv->is_registered);
1464
1465   if (application->priv->is_remote)
1466     g_application_impl_change_action_state (application->priv->impl,
1467                                             action_name, value,
1468                                             get_platform_data (application));
1469
1470   else
1471     g_action_group_change_action_state (application->priv->actions,
1472                                         action_name, value);
1473 }
1474
1475 static void
1476 g_application_activate_action (GActionGroup *action_group,
1477                                const gchar  *action_name,
1478                                GVariant     *parameter)
1479 {
1480   GApplication *application = G_APPLICATION (action_group);
1481
1482   g_return_if_fail (application->priv->is_registered);
1483
1484   if (application->priv->is_remote)
1485     g_application_impl_activate_action (application->priv->impl,
1486                                         action_name, parameter,
1487                                         get_platform_data (application));
1488
1489   else
1490     g_action_group_activate_action (application->priv->actions,
1491                                     action_name, parameter);
1492 }
1493
1494 static void
1495 g_application_action_group_iface_init (GActionGroupInterface *iface)
1496 {
1497   iface->has_action = g_application_has_action;
1498   iface->list_actions = g_application_list_actions;
1499
1500   iface->get_action_enabled = g_application_get_action_enabled;
1501   iface->get_action_parameter_type = g_application_get_action_parameter_type;
1502   iface->get_action_state_type = g_application_get_action_state_type;
1503   iface->get_action_state = g_application_get_action_state;
1504   iface->change_action_state = g_application_change_action_state;
1505   iface->activate_action = g_application_activate_action;
1506 }
1507
1508 /* Epilogue {{{1 */
1509 /* vim:set foldmethod=marker: */