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