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