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