Docs: don't use the structname tag
[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 #GApplicationCommandLineClass-struct 
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-UTF-8 data on UNIX (such as
352  * filenames or arguments given in the system locale) but are always in
353  * UTF-8 on Windows.
354  *
355  * If you wish to use the return value with #GOptionContext, you must
356  * use g_option_context_parse_strv().
357  *
358  * The return value is %NULL-terminated and should be freed using
359  * g_strfreev().
360  *
361  * Returns: (array length=argc) (transfer full): the string array
362  * containing the arguments (the argv)
363  *
364  * Since: 2.28
365  **/
366 gchar **
367 g_application_command_line_get_arguments (GApplicationCommandLine *cmdline,
368                                           int                     *argc)
369 {
370   gchar **argv;
371   gsize len;
372
373   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
374
375   argv = g_variant_dup_bytestring_array (cmdline->priv->arguments, &len);
376
377   if (argc)
378     *argc = len;
379
380   return argv;
381 }
382
383 /**
384  * g_application_command_line_get_stdin:
385  * @cmdline: a #GApplicationCommandLine
386  *
387  * Gets the stdin of the invoking process.
388  *
389  * The #GInputStream can be used to read data passed to the standard
390  * input of the invoking process.
391  * This doesn't work on all platforms.  Presently, it is only available
392  * on UNIX when using a DBus daemon capable of passing file descriptors.
393  * If stdin is not available then %NULL will be returned.  In the
394  * future, support may be expanded to other platforms.
395  *
396  * You must only call this function once per commandline invocation.
397  *
398  * Returns: (transfer full): a #GInputStream for stdin
399  *
400  * Since: 2.34
401  **/
402 GInputStream *
403 g_application_command_line_get_stdin (GApplicationCommandLine *cmdline)
404 {
405   return G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)->get_stdin (cmdline);
406 }
407
408 /**
409  * g_application_command_line_get_cwd:
410  * @cmdline: a #GApplicationCommandLine
411  *
412  * Gets the working directory of the command line invocation.
413  * The string may contain non-utf8 data.
414  *
415  * It is possible that the remote application did not send a working
416  * directory, so this may be %NULL.
417  *
418  * The return value should not be modified or freed and is valid for as
419  * long as @cmdline exists.
420  *
421  * Returns: the current directory, or %NULL
422  *
423  * Since: 2.28
424  **/
425 const gchar *
426 g_application_command_line_get_cwd (GApplicationCommandLine *cmdline)
427 {
428   return cmdline->priv->cwd;
429 }
430
431 /**
432  * g_application_command_line_get_environ:
433  * @cmdline: a #GApplicationCommandLine
434  *
435  * Gets the contents of the 'environ' variable of the command line
436  * invocation, as would be returned by g_get_environ(), ie as a
437  * %NULL-terminated list of strings in the form 'NAME=VALUE'.
438  * The strings may contain non-utf8 data.
439  *
440  * The remote application usually does not send an environment.  Use
441  * %G_APPLICATION_SEND_ENVIRONMENT to affect that.  Even with this flag
442  * set it is possible that the environment is still not available (due
443  * to invocation messages from other applications).
444  *
445  * The return value should not be modified or freed and is valid for as
446  * long as @cmdline exists.
447  *
448  * See g_application_command_line_getenv() if you are only interested
449  * in the value of a single environment variable.
450  *
451  * Returns: (array zero-terminated=1) (transfer none): the environment
452  * strings, or %NULL if they were not sent
453  *
454  * Since: 2.28
455  **/
456 const gchar * const *
457 g_application_command_line_get_environ (GApplicationCommandLine *cmdline)
458 {
459   return (const gchar **)cmdline->priv->environ;
460 }
461
462 /**
463  * g_application_command_line_getenv:
464  * @cmdline: a #GApplicationCommandLine
465  * @name: the environment variable to get
466  *
467  * Gets the value of a particular environment variable of the command
468  * line invocation, as would be returned by g_getenv().  The strings may
469  * contain non-utf8 data.
470  *
471  * The remote application usually does not send an environment.  Use
472  * %G_APPLICATION_SEND_ENVIRONMENT to affect that.  Even with this flag
473  * set it is possible that the environment is still not available (due
474  * to invocation messages from other applications).
475  *
476  * The return value should not be modified or freed and is valid for as
477  * long as @cmdline exists.
478  *
479  * Returns: the value of the variable, or %NULL if unset or unsent
480  *
481  * Since: 2.28
482  **/
483 const gchar *
484 g_application_command_line_getenv (GApplicationCommandLine *cmdline,
485                                    const gchar             *name)
486 {
487   gint length = strlen (name);
488   gint i;
489
490   /* TODO: expand on windows */
491   if (cmdline->priv->environ)
492     for (i = 0; cmdline->priv->environ[i]; i++)
493       if (strncmp (cmdline->priv->environ[i], name, length) == 0 &&
494           cmdline->priv->environ[i][length] == '=')
495         return cmdline->priv->environ[i] + length + 1;
496
497   return NULL;
498 }
499
500 /**
501  * g_application_command_line_get_is_remote:
502  * @cmdline: a #GApplicationCommandLine
503  *
504  * Determines if @cmdline represents a remote invocation.
505  *
506  * Returns: %TRUE if the invocation was remote
507  *
508  * Since: 2.28
509  **/
510 gboolean
511 g_application_command_line_get_is_remote (GApplicationCommandLine *cmdline)
512 {
513   return IS_REMOTE (cmdline);
514 }
515
516 /**
517  * g_application_command_line_print:
518  * @cmdline: a #GApplicationCommandLine
519  * @format: a printf-style format string
520  * @...: arguments, as per @format
521  *
522  * Formats a message and prints it using the stdout print handler in the
523  * invoking process.
524  *
525  * If @cmdline is a local invocation then this is exactly equivalent to
526  * g_print().  If @cmdline is remote then this is equivalent to calling
527  * g_print() in the invoking process.
528  *
529  * Since: 2.28
530  **/
531 void
532 g_application_command_line_print (GApplicationCommandLine *cmdline,
533                                   const gchar             *format,
534                                   ...)
535 {
536   gchar *message;
537   va_list ap;
538
539   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
540   g_return_if_fail (format != NULL);
541
542   va_start (ap, format);
543   message = g_strdup_vprintf (format, ap);
544   va_end (ap);
545
546   G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
547     ->print_literal (cmdline, message);
548   g_free (message);
549 }
550
551 /**
552  * g_application_command_line_printerr:
553  * @cmdline: a #GApplicationCommandLine
554  * @format: a printf-style format string
555  * @...: arguments, as per @format
556  *
557  * Formats a message and prints it using the stderr print handler in the
558  * invoking process.
559  *
560  * If @cmdline is a local invocation then this is exactly equivalent to
561  * g_printerr().  If @cmdline is remote then this is equivalent to
562  * calling g_printerr() in the invoking process.
563  *
564  * Since: 2.28
565  **/
566 void
567 g_application_command_line_printerr (GApplicationCommandLine *cmdline,
568                                      const gchar             *format,
569                                      ...)
570 {
571   gchar *message;
572   va_list ap;
573
574   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
575   g_return_if_fail (format != NULL);
576
577   va_start (ap, format);
578   message = g_strdup_vprintf (format, ap);
579   va_end (ap);
580
581   G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
582     ->printerr_literal (cmdline, message);
583   g_free (message);
584 }
585
586 /**
587  * g_application_command_line_set_exit_status:
588  * @cmdline: a #GApplicationCommandLine
589  * @exit_status: the exit status
590  *
591  * Sets the exit status that will be used when the invoking process
592  * exits.
593  *
594  * The return value of the #GApplication::command-line signal is
595  * passed to this function when the handler returns.  This is the usual
596  * way of setting the exit status.
597  *
598  * In the event that you want the remote invocation to continue running
599  * and want to decide on the exit status in the future, you can use this
600  * call.  For the case of a remote invocation, the remote process will
601  * typically exit when the last reference is dropped on @cmdline.  The
602  * exit status of the remote process will be equal to the last value
603  * that was set with this function.
604  *
605  * In the case that the commandline invocation is local, the situation
606  * is slightly more complicated.  If the commandline invocation results
607  * in the mainloop running (ie: because the use-count of the application
608  * increased to a non-zero value) then the application is considered to
609  * have been 'successful' in a certain sense, and the exit status is
610  * always zero.  If the application use count is zero, though, the exit
611  * status of the local #GApplicationCommandLine is used.
612  *
613  * Since: 2.28
614  **/
615 void
616 g_application_command_line_set_exit_status (GApplicationCommandLine *cmdline,
617                                             int                      exit_status)
618 {
619   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
620
621   cmdline->priv->exit_status = exit_status;
622 }
623
624 /**
625  * g_application_command_line_get_exit_status:
626  * @cmdline: a #GApplicationCommandLine
627  *
628  * Gets the exit status of @cmdline.  See
629  * g_application_command_line_set_exit_status() for more information.
630  *
631  * Returns: the exit status
632  *
633  * Since: 2.28
634  **/
635 int
636 g_application_command_line_get_exit_status (GApplicationCommandLine *cmdline)
637 {
638   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), -1);
639
640   return cmdline->priv->exit_status;
641 }
642
643 /**
644  * g_application_command_line_get_platform_data:
645  * @cmdline: #GApplicationCommandLine
646  *
647  * Gets the platform data associated with the invocation of @cmdline.
648  *
649  * This is a #GVariant dictionary containing information about the
650  * context in which the invocation occurred.  It typically contains
651  * information like the current working directory and the startup
652  * notification ID.
653  *
654  * For local invocation, it will be %NULL.
655  *
656  * Returns: (allow-none): the platform data, or %NULL
657  *
658  * Since: 2.28
659  **/
660 GVariant *
661 g_application_command_line_get_platform_data (GApplicationCommandLine *cmdline)
662 {
663   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
664
665   if (cmdline->priv->platform_data)
666     return g_variant_ref (cmdline->priv->platform_data);
667   else
668       return NULL;
669 }
670
671 /**
672  * g_application_command_line_create_file_for_arg:
673  * @cmdline: a #GApplicationCommandLine
674  * @arg: an argument from @cmdline
675  *
676  * Creates a #GFile corresponding to a filename that was given as part
677  * of the invocation of @cmdline.
678  *
679  * This differs from g_file_new_for_commandline_arg() in that it
680  * resolves relative pathnames using the current working directory of
681  * the invoking process rather than the local process.
682  *
683  * Returns: (transfer full): a new #GFile
684  *
685  * Since: 2.36
686  **/
687 GFile *
688 g_application_command_line_create_file_for_arg (GApplicationCommandLine *cmdline,
689                                                 const gchar             *arg)
690 {
691   g_return_val_if_fail (arg != NULL, NULL);
692
693   if (cmdline->priv->cwd)
694     return g_file_new_for_commandline_arg_and_cwd (arg, cmdline->priv->cwd);
695
696   g_warning ("Requested creation of GFile for commandline invocation that did not send cwd. "
697              "Using cwd of local process to resolve relative path names.");
698
699   return g_file_new_for_commandline_arg (arg);
700 }