Add includes to all gio docs
[platform/upstream/glib.git] / gio / gapplicationcommandline.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
6  * published by the Free Software Foundation; either version 2 of the
7  * licence or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful, but
10  * 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 Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
17  * USA.
18  *
19  * Authors: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include "gapplicationcommandline.h"
25
26 #include "glibintl.h"
27 #include "gfile.h"
28
29 #include <string.h>
30 #include <stdio.h>
31
32 #ifdef G_OS_UNIX
33 #include "gunixinputstream.h"
34 #endif
35
36 #ifdef G_OS_WIN32
37 #include <windows.h>
38 #undef environ
39 #include "gwin32inputstream.h"
40 #endif
41
42 /**
43  * SECTION:gapplicationcommandline
44  * @title: GApplicationCommandLine
45  * @short_description: A command-line invocation of an application
46  * @include: gio/gio.h
47  * @see_also: #GApplication
48  *
49  * #GApplicationCommandLine represents a command-line invocation of
50  * an application.  It is created by #GApplication and emitted
51  * in the #GApplication::command-line signal and virtual function.
52  *
53  * The class contains the list of arguments that the program was invoked
54  * with.  It is also possible to query if the commandline invocation was
55  * local (ie: the current process is running in direct response to the
56  * invocation) or remote (ie: some other process forwarded the
57  * commandline to this process).
58  *
59  * The GApplicationCommandLine object can provide the @argc and @argv
60  * parameters for use with the #GOptionContext command-line parsing API,
61  * with the g_application_command_line_get_arguments() function. See
62  * <xref linkend="gapplication-example-cmdline3"/> for an example.
63  *
64  * The exit status of the originally-invoked process may be set and
65  * messages can be printed to stdout or stderr of that process.  The
66  * lifecycle of the originally-invoked process is tied to the lifecycle
67  * of this object (ie: the process exits when the last reference is
68  * dropped).
69  *
70  * The main use for #GApplicationCommandLine (and the
71  * #GApplication::command-line signal) is 'Emacs server' like use cases:
72  * You can set the <envar>EDITOR</envar> environment variable to have
73  * e.g. git use your favourite editor to edit commit messages, and if you
74  * already have an instance of the editor running, the editing will happen
75  * in the running instance, instead of opening a new one. An important
76  * aspect of this use case is that the process that gets started by git
77  * does not return until the editing is done.
78  *
79  * <example id="gapplication-example-cmdline"><title>Handling commandline arguments with GApplication</title>
80  * <para>
81  * A simple example where the commandline is completely handled
82  * in the #GApplication::command-line handler. The launching instance exits
83  * once the signal handler in the primary instance has returned, and the
84  * return value of the signal handler becomes the exit status of the launching
85  * instance.
86  * </para>
87  * <programlisting>
88  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline.c">
89  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
90  * </xi:include>
91  * </programlisting>
92  * </example>
93  *
94  * <example id="gapplication-example-cmdline2"><title>Split commandline handling</title>
95  * <para>
96  * An example of split commandline handling. Options that start with
97  * <literal>--local-</literal> are handled locally, all other options are
98  * passed to the #GApplication::command-line handler which runs in the primary
99  * instance.
100  * </para>
101  * <programlisting>
102  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline2.c">
103  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
104  * </xi:include>
105  * </programlisting>
106  * </example>
107  *
108  * <example id="gapplication-example-cmdline3"><title>Deferred commandline handling</title>
109  * <para>
110  * An example of deferred commandline handling. Here, the commandline is
111  * not completely handled before the #GApplication::command-line handler
112  * returns. Instead, we keep a reference to the GApplicationCommandLine
113  * object and handle it later(in this example, in an idle). Note that it
114  * is necessary to hold the application until you are done with the
115  * commandline.
116  * </para>
117  * <para>
118  * This example also shows how to use #GOptionContext for parsing the
119  * commandline arguments. Note that it is necessary to disable the
120  * built-in help-handling of #GOptionContext, since it calls exit()
121  * after printing help, which is not what you want to happen in
122  * the primary instance.
123  * </para>
124  * <programlisting>
125  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline3.c">
126  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
127  * </xi:include>
128  * </programlisting>
129  * </example>
130  **/
131
132 /**
133  * GApplicationCommandLineClass:
134  *
135  * The <structname>GApplicationCommandLineClass</structname> structure
136  * contains private data only
137  *
138  * Since: 2.28
139  **/
140 enum
141 {
142   PROP_NONE,
143   PROP_ARGUMENTS,
144   PROP_PLATFORM_DATA,
145   PROP_IS_REMOTE
146 };
147
148 struct _GApplicationCommandLinePrivate
149 {
150   GVariant *platform_data;
151   GVariant *arguments;
152   gchar *cwd;
153
154   gchar **environ;
155   gint exit_status;
156 };
157
158 G_DEFINE_TYPE_WITH_PRIVATE (GApplicationCommandLine, g_application_command_line, G_TYPE_OBJECT)
159
160 /* All subclasses represent remote invocations of some kind. */
161 #define IS_REMOTE(cmdline) (G_TYPE_FROM_INSTANCE (cmdline) != \
162                             G_TYPE_APPLICATION_COMMAND_LINE)
163
164 static void
165 grok_platform_data (GApplicationCommandLine *cmdline)
166 {
167   GVariantIter iter;
168   const gchar *key;
169   GVariant *value;
170
171   g_variant_iter_init (&iter, cmdline->priv->platform_data);
172
173   while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
174     if (strcmp (key, "cwd") == 0)
175       {
176         if (!cmdline->priv->cwd)
177           cmdline->priv->cwd = g_variant_dup_bytestring (value, NULL);
178       }
179
180     else if (strcmp (key, "environ") == 0)
181       {
182         if (!cmdline->priv->environ)
183           cmdline->priv->environ =
184             g_variant_dup_bytestring_array (value, NULL);
185       }
186 }
187
188 static void
189 g_application_command_line_real_print_literal (GApplicationCommandLine *cmdline,
190                                                const gchar             *message)
191 {
192   g_print ("%s", message);
193 }
194
195 static void
196 g_application_command_line_real_printerr_literal (GApplicationCommandLine *cmdline,
197                                                   const gchar             *message)
198 {
199   g_printerr ("%s", message);
200 }
201
202 static GInputStream *
203 g_application_command_line_real_get_stdin (GApplicationCommandLine *cmdline)
204 {
205 #ifdef G_OS_UNIX
206   return g_unix_input_stream_new (0, FALSE);
207 #else
208   return g_win32_input_stream_new (GetStdHandle (STD_INPUT_HANDLE), FALSE);
209 #endif
210 }
211
212 static void
213 g_application_command_line_get_property (GObject    *object,
214                                          guint       prop_id,
215                                          GValue     *value,
216                                          GParamSpec *pspec)
217 {
218   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
219
220   switch (prop_id)
221     {
222     case PROP_ARGUMENTS:
223       g_value_set_variant (value, cmdline->priv->arguments);
224       break;
225
226     case PROP_PLATFORM_DATA:
227       g_value_set_variant (value, cmdline->priv->platform_data);
228       break;
229
230     case PROP_IS_REMOTE:
231       g_value_set_boolean (value, IS_REMOTE (cmdline));
232       break;
233
234     default:
235       g_assert_not_reached ();
236     }
237 }
238
239 static void
240 g_application_command_line_set_property (GObject      *object,
241                                          guint         prop_id,
242                                          const GValue *value,
243                                          GParamSpec   *pspec)
244 {
245   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
246
247   switch (prop_id)
248     {
249     case PROP_ARGUMENTS:
250       g_assert (cmdline->priv->arguments == NULL);
251       cmdline->priv->arguments = g_value_dup_variant (value);
252       break;
253
254     case PROP_PLATFORM_DATA:
255       g_assert (cmdline->priv->platform_data == NULL);
256       cmdline->priv->platform_data = g_value_dup_variant (value);
257       if (cmdline->priv->platform_data != NULL)
258         grok_platform_data (cmdline);
259       break;
260
261     default:
262       g_assert_not_reached ();
263     }
264 }
265
266 static void
267 g_application_command_line_finalize (GObject *object)
268 {
269   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
270
271   if (cmdline->priv->platform_data)
272     g_variant_unref (cmdline->priv->platform_data);
273   if (cmdline->priv->arguments)
274     g_variant_unref (cmdline->priv->arguments);
275
276   g_free (cmdline->priv->cwd);
277   g_strfreev (cmdline->priv->environ);
278
279   G_OBJECT_CLASS (g_application_command_line_parent_class)
280     ->finalize (object);
281 }
282
283 static void
284 g_application_command_line_init (GApplicationCommandLine *cmdline)
285 {
286   cmdline->priv = g_application_command_line_get_instance_private (cmdline);
287 }
288
289 static void
290 g_application_command_line_constructed (GObject *object)
291 {
292   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
293
294   if (IS_REMOTE (cmdline))
295     return;
296
297   /* In the local case, set cmd and environ */
298   if (!cmdline->priv->cwd)
299     cmdline->priv->cwd = g_get_current_dir ();
300
301   if (!cmdline->priv->environ)
302     cmdline->priv->environ = g_get_environ ();
303 }
304
305 static void
306 g_application_command_line_class_init (GApplicationCommandLineClass *class)
307 {
308   GObjectClass *object_class = G_OBJECT_CLASS (class);
309
310   object_class->get_property = g_application_command_line_get_property;
311   object_class->set_property = g_application_command_line_set_property;
312   object_class->finalize = g_application_command_line_finalize;
313   object_class->constructed = g_application_command_line_constructed;
314
315   class->printerr_literal = g_application_command_line_real_printerr_literal;
316   class->print_literal = g_application_command_line_real_print_literal;
317   class->get_stdin = g_application_command_line_real_get_stdin;
318
319   g_object_class_install_property (object_class, PROP_ARGUMENTS,
320     g_param_spec_variant ("arguments",
321                           P_("Commandline arguments"),
322                           P_("The commandline that caused this ::command-line signal emission"),
323                           G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL,
324                           G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
325                           G_PARAM_STATIC_STRINGS));
326
327   g_object_class_install_property (object_class, PROP_PLATFORM_DATA,
328     g_param_spec_variant ("platform-data",
329                           P_("Platform data"),
330                           P_("Platform-specific data for the commandline"),
331                           G_VARIANT_TYPE ("a{sv}"), NULL,
332                           G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
333                           G_PARAM_STATIC_STRINGS));
334
335   g_object_class_install_property (object_class, PROP_IS_REMOTE,
336     g_param_spec_boolean ("is-remote",
337                           P_("Is remote"),
338                           P_("TRUE if this is a remote commandline"),
339                           FALSE,
340                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
341 }
342
343
344 /**
345  * g_application_command_line_get_arguments:
346  * @cmdline: a #GApplicationCommandLine
347  * @argc: (out) (allow-none): the length of the arguments array, or %NULL
348  *
349  * Gets the list of arguments that was passed on the command line.
350  *
351  * The strings in the array may contain non-utf8 data.
352  *
353  * The return value is %NULL-terminated and should be freed using
354  * g_strfreev().
355  *
356  * Returns: (array length=argc) (transfer full): the string array
357  * containing the arguments (the argv)
358  *
359  * Since: 2.28
360  **/
361 gchar **
362 g_application_command_line_get_arguments (GApplicationCommandLine *cmdline,
363                                           int                     *argc)
364 {
365   gchar **argv;
366   gsize len;
367
368   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
369
370   argv = g_variant_dup_bytestring_array (cmdline->priv->arguments, &len);
371
372   if (argc)
373     *argc = len;
374
375   return argv;
376 }
377
378 /**
379  * g_application_command_line_get_stdin:
380  * @cmdline: a #GApplicationCommandLine
381  *
382  * Gets the stdin of the invoking process.
383  *
384  * The #GInputStream can be used to read data passed to the standard
385  * input of the invoking process.
386  * This doesn't work on all platforms.  Presently, it is only available
387  * on UNIX when using a DBus daemon capable of passing file descriptors.
388  * If stdin is not available then %NULL will be returned.  In the
389  * future, support may be expanded to other platforms.
390  *
391  * You must only call this function once per commandline invocation.
392  *
393  * Returns: (transfer full): a #GInputStream for stdin
394  *
395  * Since: 2.34
396  **/
397 GInputStream *
398 g_application_command_line_get_stdin (GApplicationCommandLine *cmdline)
399 {
400   return G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)->get_stdin (cmdline);
401 }
402
403 /**
404  * g_application_command_line_get_cwd:
405  * @cmdline: a #GApplicationCommandLine
406  *
407  * Gets the working directory of the command line invocation.
408  * The string may contain non-utf8 data.
409  *
410  * It is possible that the remote application did not send a working
411  * directory, so this may be %NULL.
412  *
413  * The return value should not be modified or freed and is valid for as
414  * long as @cmdline exists.
415  *
416  * Returns: the current directory, or %NULL
417  *
418  * Since: 2.28
419  **/
420 const gchar *
421 g_application_command_line_get_cwd (GApplicationCommandLine *cmdline)
422 {
423   return cmdline->priv->cwd;
424 }
425
426 /**
427  * g_application_command_line_get_environ:
428  * @cmdline: a #GApplicationCommandLine
429  *
430  * Gets the contents of the 'environ' variable of the command line
431  * invocation, as would be returned by g_get_environ(), ie as a
432  * %NULL-terminated list of strings in the form 'NAME=VALUE'.
433  * The strings may contain non-utf8 data.
434  *
435  * The remote application usually does not send an environment.  Use
436  * %G_APPLICATION_SEND_ENVIRONMENT to affect that.  Even with this flag
437  * set it is possible that the environment is still not available (due
438  * to invocation messages from other applications).
439  *
440  * The return value should not be modified or freed and is valid for as
441  * long as @cmdline exists.
442  *
443  * See g_application_command_line_getenv() if you are only interested
444  * in the value of a single environment variable.
445  *
446  * Returns: (array zero-terminated=1) (transfer none): the environment
447  * strings, or %NULL if they were not sent
448  *
449  * Since: 2.28
450  **/
451 const gchar * const *
452 g_application_command_line_get_environ (GApplicationCommandLine *cmdline)
453 {
454   return (const gchar **)cmdline->priv->environ;
455 }
456
457 /**
458  * g_application_command_line_getenv:
459  * @cmdline: a #GApplicationCommandLine
460  * @name: the environment variable to get
461  *
462  * Gets the value of a particular environment variable of the command
463  * line invocation, as would be returned by g_getenv().  The strings may
464  * contain non-utf8 data.
465  *
466  * The remote application usually does not send an environment.  Use
467  * %G_APPLICATION_SEND_ENVIRONMENT to affect that.  Even with this flag
468  * set it is possible that the environment is still not available (due
469  * to invocation messages from other applications).
470  *
471  * The return value should not be modified or freed and is valid for as
472  * long as @cmdline exists.
473  *
474  * Returns: the value of the variable, or %NULL if unset or unsent
475  *
476  * Since: 2.28
477  **/
478 const gchar *
479 g_application_command_line_getenv (GApplicationCommandLine *cmdline,
480                                    const gchar             *name)
481 {
482   gint length = strlen (name);
483   gint i;
484
485   /* TODO: expand on windows */
486   if (cmdline->priv->environ)
487     for (i = 0; cmdline->priv->environ[i]; i++)
488       if (strncmp (cmdline->priv->environ[i], name, length) == 0 &&
489           cmdline->priv->environ[i][length] == '=')
490         return cmdline->priv->environ[i] + length + 1;
491
492   return NULL;
493 }
494
495 /**
496  * g_application_command_line_get_is_remote:
497  * @cmdline: a #GApplicationCommandLine
498  *
499  * Determines if @cmdline represents a remote invocation.
500  *
501  * Returns: %TRUE if the invocation was remote
502  *
503  * Since: 2.28
504  **/
505 gboolean
506 g_application_command_line_get_is_remote (GApplicationCommandLine *cmdline)
507 {
508   return IS_REMOTE (cmdline);
509 }
510
511 /**
512  * g_application_command_line_print:
513  * @cmdline: a #GApplicationCommandLine
514  * @format: a printf-style format string
515  * @...: arguments, as per @format
516  *
517  * Formats a message and prints it using the stdout print handler in the
518  * invoking process.
519  *
520  * If @cmdline is a local invocation then this is exactly equivalent to
521  * g_print().  If @cmdline is remote then this is equivalent to calling
522  * g_print() in the invoking process.
523  *
524  * Since: 2.28
525  **/
526 void
527 g_application_command_line_print (GApplicationCommandLine *cmdline,
528                                   const gchar             *format,
529                                   ...)
530 {
531   gchar *message;
532   va_list ap;
533
534   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
535   g_return_if_fail (format != NULL);
536
537   va_start (ap, format);
538   message = g_strdup_vprintf (format, ap);
539   va_end (ap);
540
541   G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
542     ->print_literal (cmdline, message);
543   g_free (message);
544 }
545
546 /**
547  * g_application_command_line_printerr:
548  * @cmdline: a #GApplicationCommandLine
549  * @format: a printf-style format string
550  * @...: arguments, as per @format
551  *
552  * Formats a message and prints it using the stderr print handler in the
553  * invoking process.
554  *
555  * If @cmdline is a local invocation then this is exactly equivalent to
556  * g_printerr().  If @cmdline is remote then this is equivalent to
557  * calling g_printerr() in the invoking process.
558  *
559  * Since: 2.28
560  **/
561 void
562 g_application_command_line_printerr (GApplicationCommandLine *cmdline,
563                                      const gchar             *format,
564                                      ...)
565 {
566   gchar *message;
567   va_list ap;
568
569   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
570   g_return_if_fail (format != NULL);
571
572   va_start (ap, format);
573   message = g_strdup_vprintf (format, ap);
574   va_end (ap);
575
576   G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
577     ->printerr_literal (cmdline, message);
578   g_free (message);
579 }
580
581 /**
582  * g_application_command_line_set_exit_status:
583  * @cmdline: a #GApplicationCommandLine
584  * @exit_status: the exit status
585  *
586  * Sets the exit status that will be used when the invoking process
587  * exits.
588  *
589  * The return value of the #GApplication::command-line signal is
590  * passed to this function when the handler returns.  This is the usual
591  * way of setting the exit status.
592  *
593  * In the event that you want the remote invocation to continue running
594  * and want to decide on the exit status in the future, you can use this
595  * call.  For the case of a remote invocation, the remote process will
596  * typically exit when the last reference is dropped on @cmdline.  The
597  * exit status of the remote process will be equal to the last value
598  * that was set with this function.
599  *
600  * In the case that the commandline invocation is local, the situation
601  * is slightly more complicated.  If the commandline invocation results
602  * in the mainloop running (ie: because the use-count of the application
603  * increased to a non-zero value) then the application is considered to
604  * have been 'successful' in a certain sense, and the exit status is
605  * always zero.  If the application use count is zero, though, the exit
606  * status of the local #GApplicationCommandLine is used.
607  *
608  * Since: 2.28
609  **/
610 void
611 g_application_command_line_set_exit_status (GApplicationCommandLine *cmdline,
612                                             int                      exit_status)
613 {
614   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
615
616   cmdline->priv->exit_status = exit_status;
617 }
618
619 /**
620  * g_application_command_line_get_exit_status:
621  * @cmdline: a #GApplicationCommandLine
622  *
623  * Gets the exit status of @cmdline.  See
624  * g_application_command_line_set_exit_status() for more information.
625  *
626  * Returns: the exit status
627  *
628  * Since: 2.28
629  **/
630 int
631 g_application_command_line_get_exit_status (GApplicationCommandLine *cmdline)
632 {
633   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), -1);
634
635   return cmdline->priv->exit_status;
636 }
637
638 /**
639  * g_application_command_line_get_platform_data:
640  * @cmdline: #GApplicationCommandLine
641  *
642  * Gets the platform data associated with the invocation of @cmdline.
643  *
644  * This is a #GVariant dictionary containing information about the
645  * context in which the invocation occurred.  It typically contains
646  * information like the current working directory and the startup
647  * notification ID.
648  *
649  * For local invocation, it will be %NULL.
650  *
651  * Returns: (allow-none): the platform data, or %NULL
652  *
653  * Since: 2.28
654  **/
655 GVariant *
656 g_application_command_line_get_platform_data (GApplicationCommandLine *cmdline)
657 {
658   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
659
660   if (cmdline->priv->platform_data)
661     return g_variant_ref (cmdline->priv->platform_data);
662   else
663       return NULL;
664 }
665
666 /**
667  * g_application_command_line_create_file_for_arg:
668  * @cmdline: a #GApplicationCommandLine
669  * @arg: an argument from @cmdline
670  *
671  * Creates a #GFile corresponding to a filename that was given as part
672  * of the invocation of @cmdline.
673  *
674  * This differs from g_file_new_for_commandline_arg() in that it
675  * resolves relative pathnames using the current working directory of
676  * the invoking process rather than the local process.
677  *
678  * Returns: (transfer full): a new #GFile
679  *
680  * Since: 2.36
681  **/
682 GFile *
683 g_application_command_line_create_file_for_arg (GApplicationCommandLine *cmdline,
684                                                 const gchar             *arg)
685 {
686   g_return_val_if_fail (arg != NULL, NULL);
687
688   if (cmdline->priv->cwd)
689     return g_file_new_for_commandline_arg_and_cwd (arg, cmdline->priv->cwd);
690
691   g_warning ("Requested creation of GFile for commandline invocation that did not send cwd. "
692              "Using cwd of local process to resolve relative path names.");
693
694   return g_file_new_for_commandline_arg (arg);
695 }