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