gio/tests/gsubprocess.c: Fix on Windows
[glib.git] / gio / gapplicationcommandline.c
blob9a0840ff0280dd1de16cf247d33a47a7f78e0a51
1 /*
2 * Copyright © 2010 Codethink Limited
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.
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.
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.
19 * Authors: Ryan Lortie <desrt@desrt.ca>
22 #include "config.h"
24 #include "gapplicationcommandline.h"
26 #include "glibintl.h"
27 #include "gfile.h"
29 #include <string.h>
30 #include <stdio.h>
32 #ifdef G_OS_UNIX
33 #include "gunixinputstream.h"
34 #endif
36 #ifdef G_OS_WIN32
37 #include <windows.h>
38 #undef environ
39 #include "gwin32inputstream.h"
40 #endif
42 /**
43 * SECTION:gapplicationcommandline
44 * @title: GApplicationCommandLine
45 * @short_description: A command-line invocation of an application
46 * @see_also: #GApplication
48 * #GApplicationCommandLine represents a command-line invocation of
49 * an application. It is created by #GApplication and emitted
50 * in the #GApplication::command-line signal and virtual function.
52 * The class contains the list of arguments that the program was invoked
53 * with. It is also possible to query if the commandline invocation was
54 * local (ie: the current process is running in direct response to the
55 * invocation) or remote (ie: some other process forwarded the
56 * commandline to this process).
58 * The GApplicationCommandLine object can provide the @argc and @argv
59 * parameters for use with the #GOptionContext command-line parsing API,
60 * with the g_application_command_line_get_arguments() function. See
61 * <xref linkend="gapplication-example-cmdline3"/> for an example.
63 * The exit status of the originally-invoked process may be set and
64 * messages can be printed to stdout or stderr of that process. The
65 * lifecycle of the originally-invoked process is tied to the lifecycle
66 * of this object (ie: the process exits when the last reference is
67 * dropped).
69 * The main use for #GApplicationCommandLine (and the
70 * #GApplication::command-line signal) is 'Emacs server' like use cases:
71 * You can set the <envar>EDITOR</envar> environment variable to have
72 * e.g. git use your favourite editor to edit commit messages, and if you
73 * already have an instance of the editor running, the editing will happen
74 * in the running instance, instead of opening a new one. An important
75 * aspect of this use case is that the process that gets started by git
76 * does not return until the editing is done.
78 * <example id="gapplication-example-cmdline"><title>Handling commandline arguments with GApplication</title>
79 * <para>
80 * A simple example where the commandline is completely handled
81 * in the #GApplication::command-line handler. The launching instance exits
82 * once the signal handler in the primary instance has returned, and the
83 * return value of the signal handler becomes the exit status of the launching
84 * instance.
85 * </para>
86 * <programlisting>
87 * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline.c">
88 * <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
89 * </xi:include>
90 * </programlisting>
91 * </example>
93 * <example id="gapplication-example-cmdline2"><title>Split commandline handling</title>
94 * <para>
95 * An example of split commandline handling. Options that start with
96 * <literal>--local-</literal> are handled locally, all other options are
97 * passed to the #GApplication::command-line handler which runs in the primary
98 * instance.
99 * </para>
100 * <programlisting>
101 * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline2.c">
102 * <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
103 * </xi:include>
104 * </programlisting>
105 * </example>
107 * <example id="gapplication-example-cmdline3"><title>Deferred commandline handling</title>
108 * <para>
109 * An example of deferred commandline handling. Here, the commandline is
110 * not completely handled before the #GApplication::command-line handler
111 * returns. Instead, we keep a reference to the GApplicationCommandLine
112 * object and handle it later(in this example, in an idle). Note that it
113 * is necessary to hold the application until you are done with the
114 * commandline.
115 * </para>
116 * <para>
117 * This example also shows how to use #GOptionContext for parsing the
118 * commandline arguments. Note that it is necessary to disable the
119 * built-in help-handling of #GOptionContext, since it calls exit()
120 * after printing help, which is not what you want to happen in
121 * the primary instance.
122 * </para>
123 * <programlisting>
124 * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline3.c">
125 * <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
126 * </xi:include>
127 * </programlisting>
128 * </example>
132 * GApplicationCommandLineClass:
134 * The <structname>GApplicationCommandLineClass</structname> structure
135 * contains private data only
137 * Since: 2.28
139 enum
141 PROP_NONE,
142 PROP_ARGUMENTS,
143 PROP_PLATFORM_DATA,
144 PROP_IS_REMOTE
147 struct _GApplicationCommandLinePrivate
149 GVariant *platform_data;
150 GVariant *arguments;
151 gchar *cwd;
153 gchar **environ;
154 gint exit_status;
157 G_DEFINE_TYPE_WITH_PRIVATE (GApplicationCommandLine, g_application_command_line, G_TYPE_OBJECT)
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)
163 static void
164 grok_platform_data (GApplicationCommandLine *cmdline)
166 GVariantIter iter;
167 const gchar *key;
168 GVariant *value;
170 g_variant_iter_init (&iter, cmdline->priv->platform_data);
172 while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
173 if (strcmp (key, "cwd") == 0)
175 if (!cmdline->priv->cwd)
176 cmdline->priv->cwd = g_variant_dup_bytestring (value, NULL);
179 else if (strcmp (key, "environ") == 0)
181 if (!cmdline->priv->environ)
182 cmdline->priv->environ =
183 g_variant_dup_bytestring_array (value, NULL);
187 static void
188 g_application_command_line_real_print_literal (GApplicationCommandLine *cmdline,
189 const gchar *message)
191 g_print ("%s", message);
194 static void
195 g_application_command_line_real_printerr_literal (GApplicationCommandLine *cmdline,
196 const gchar *message)
198 g_printerr ("%s", message);
201 static GInputStream *
202 g_application_command_line_real_get_stdin (GApplicationCommandLine *cmdline)
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
211 static void
212 g_application_command_line_get_property (GObject *object,
213 guint prop_id,
214 GValue *value,
215 GParamSpec *pspec)
217 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
219 switch (prop_id)
221 case PROP_ARGUMENTS:
222 g_value_set_variant (value, cmdline->priv->arguments);
223 break;
225 case PROP_PLATFORM_DATA:
226 g_value_set_variant (value, cmdline->priv->platform_data);
227 break;
229 case PROP_IS_REMOTE:
230 g_value_set_boolean (value, IS_REMOTE (cmdline));
231 break;
233 default:
234 g_assert_not_reached ();
238 static void
239 g_application_command_line_set_property (GObject *object,
240 guint prop_id,
241 const GValue *value,
242 GParamSpec *pspec)
244 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
246 switch (prop_id)
248 case PROP_ARGUMENTS:
249 g_assert (cmdline->priv->arguments == NULL);
250 cmdline->priv->arguments = g_value_dup_variant (value);
251 break;
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;
260 default:
261 g_assert_not_reached ();
265 static void
266 g_application_command_line_finalize (GObject *object)
268 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
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);
275 g_free (cmdline->priv->cwd);
276 g_strfreev (cmdline->priv->environ);
278 G_OBJECT_CLASS (g_application_command_line_parent_class)
279 ->finalize (object);
282 static void
283 g_application_command_line_init (GApplicationCommandLine *cmdline)
285 cmdline->priv = g_application_command_line_get_instance_private (cmdline);
288 static void
289 g_application_command_line_constructed (GObject *object)
291 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
293 if (IS_REMOTE (cmdline))
294 return;
296 /* In the local case, set cmd and environ */
297 if (!cmdline->priv->cwd)
298 cmdline->priv->cwd = g_get_current_dir ();
300 if (!cmdline->priv->environ)
301 cmdline->priv->environ = g_get_environ ();
304 static void
305 g_application_command_line_class_init (GApplicationCommandLineClass *class)
307 GObjectClass *object_class = G_OBJECT_CLASS (class);
309 object_class->get_property = g_application_command_line_get_property;
310 object_class->set_property = g_application_command_line_set_property;
311 object_class->finalize = g_application_command_line_finalize;
312 object_class->constructed = g_application_command_line_constructed;
314 class->printerr_literal = g_application_command_line_real_printerr_literal;
315 class->print_literal = g_application_command_line_real_print_literal;
316 class->get_stdin = g_application_command_line_real_get_stdin;
318 g_object_class_install_property (object_class, PROP_ARGUMENTS,
319 g_param_spec_variant ("arguments",
320 P_("Commandline arguments"),
321 P_("The commandline that caused this ::command-line signal emission"),
322 G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL,
323 G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
324 G_PARAM_STATIC_STRINGS));
326 g_object_class_install_property (object_class, PROP_PLATFORM_DATA,
327 g_param_spec_variant ("platform-data",
328 P_("Platform data"),
329 P_("Platform-specific data for the commandline"),
330 G_VARIANT_TYPE ("a{sv}"), NULL,
331 G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
332 G_PARAM_STATIC_STRINGS));
334 g_object_class_install_property (object_class, PROP_IS_REMOTE,
335 g_param_spec_boolean ("is-remote",
336 P_("Is remote"),
337 P_("TRUE if this is a remote commandline"),
338 FALSE,
339 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
344 * g_application_command_line_get_arguments:
345 * @cmdline: a #GApplicationCommandLine
346 * @argc: (out) (allow-none): the length of the arguments array, or %NULL
348 * Gets the list of arguments that was passed on the command line.
350 * The strings in the array may contain non-utf8 data.
352 * The return value is %NULL-terminated and should be freed using
353 * g_strfreev().
355 * Returns: (array length=argc) (transfer full): the string array
356 * containing the arguments (the argv)
358 * Since: 2.28
360 gchar **
361 g_application_command_line_get_arguments (GApplicationCommandLine *cmdline,
362 int *argc)
364 gchar **argv;
365 gsize len;
367 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
369 argv = g_variant_dup_bytestring_array (cmdline->priv->arguments, &len);
371 if (argc)
372 *argc = len;
374 return argv;
378 * g_application_command_line_get_stdin:
379 * @cmdline: a #GApplicationCommandLine
381 * Gets the stdin of the invoking process.
383 * The #GInputStream can be used to read data passed to the standard
384 * input of the invoking process.
385 * This doesn't work on all platforms. Presently, it is only available
386 * on UNIX when using a DBus daemon capable of passing file descriptors.
387 * If stdin is not available then %NULL will be returned. In the
388 * future, support may be expanded to other platforms.
390 * You must only call this function once per commandline invocation.
392 * Returns: (transfer full): a #GInputStream for stdin
394 * Since: 2.34
396 GInputStream *
397 g_application_command_line_get_stdin (GApplicationCommandLine *cmdline)
399 return G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)->get_stdin (cmdline);
403 * g_application_command_line_get_cwd:
404 * @cmdline: a #GApplicationCommandLine
406 * Gets the working directory of the command line invocation.
407 * The string may contain non-utf8 data.
409 * It is possible that the remote application did not send a working
410 * directory, so this may be %NULL.
412 * The return value should not be modified or freed and is valid for as
413 * long as @cmdline exists.
415 * Returns: the current directory, or %NULL
417 * Since: 2.28
419 const gchar *
420 g_application_command_line_get_cwd (GApplicationCommandLine *cmdline)
422 return cmdline->priv->cwd;
426 * g_application_command_line_get_environ:
427 * @cmdline: a #GApplicationCommandLine
429 * Gets the contents of the 'environ' variable of the command line
430 * invocation, as would be returned by g_get_environ(), ie as a
431 * %NULL-terminated list of strings in the form 'NAME=VALUE'.
432 * The strings may contain non-utf8 data.
434 * The remote application usually does not send an environment. Use
435 * %G_APPLICATION_SEND_ENVIRONMENT to affect that. Even with this flag
436 * set it is possible that the environment is still not available (due
437 * to invocation messages from other applications).
439 * The return value should not be modified or freed and is valid for as
440 * long as @cmdline exists.
442 * See g_application_command_line_getenv() if you are only interested
443 * in the value of a single environment variable.
445 * Returns: (array zero-terminated=1) (transfer none): the environment
446 * strings, or %NULL if they were not sent
448 * Since: 2.28
450 const gchar * const *
451 g_application_command_line_get_environ (GApplicationCommandLine *cmdline)
453 return (const gchar **)cmdline->priv->environ;
457 * g_application_command_line_getenv:
458 * @cmdline: a #GApplicationCommandLine
459 * @name: the environment variable to get
461 * Gets the value of a particular environment variable of the command
462 * line invocation, as would be returned by g_getenv(). The strings may
463 * contain non-utf8 data.
465 * The remote application usually does not send an environment. Use
466 * %G_APPLICATION_SEND_ENVIRONMENT to affect that. Even with this flag
467 * set it is possible that the environment is still not available (due
468 * to invocation messages from other applications).
470 * The return value should not be modified or freed and is valid for as
471 * long as @cmdline exists.
473 * Returns: the value of the variable, or %NULL if unset or unsent
475 * Since: 2.28
477 const gchar *
478 g_application_command_line_getenv (GApplicationCommandLine *cmdline,
479 const gchar *name)
481 gint length = strlen (name);
482 gint i;
484 /* TODO: expand on windows */
485 if (cmdline->priv->environ)
486 for (i = 0; cmdline->priv->environ[i]; i++)
487 if (strncmp (cmdline->priv->environ[i], name, length) == 0 &&
488 cmdline->priv->environ[i][length] == '=')
489 return cmdline->priv->environ[i] + length + 1;
491 return NULL;
495 * g_application_command_line_get_is_remote:
496 * @cmdline: a #GApplicationCommandLine
498 * Determines if @cmdline represents a remote invocation.
500 * Returns: %TRUE if the invocation was remote
502 * Since: 2.28
504 gboolean
505 g_application_command_line_get_is_remote (GApplicationCommandLine *cmdline)
507 return IS_REMOTE (cmdline);
511 * g_application_command_line_print:
512 * @cmdline: a #GApplicationCommandLine
513 * @format: a printf-style format string
514 * @...: arguments, as per @format
516 * Formats a message and prints it using the stdout print handler in the
517 * invoking process.
519 * If @cmdline is a local invocation then this is exactly equivalent to
520 * g_print(). If @cmdline is remote then this is equivalent to calling
521 * g_print() in the invoking process.
523 * Since: 2.28
525 void
526 g_application_command_line_print (GApplicationCommandLine *cmdline,
527 const gchar *format,
528 ...)
530 gchar *message;
531 va_list ap;
533 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
534 g_return_if_fail (format != NULL);
536 va_start (ap, format);
537 message = g_strdup_vprintf (format, ap);
538 va_end (ap);
540 G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
541 ->print_literal (cmdline, message);
542 g_free (message);
546 * g_application_command_line_printerr:
547 * @cmdline: a #GApplicationCommandLine
548 * @format: a printf-style format string
549 * @...: arguments, as per @format
551 * Formats a message and prints it using the stderr print handler in the
552 * invoking process.
554 * If @cmdline is a local invocation then this is exactly equivalent to
555 * g_printerr(). If @cmdline is remote then this is equivalent to
556 * calling g_printerr() in the invoking process.
558 * Since: 2.28
560 void
561 g_application_command_line_printerr (GApplicationCommandLine *cmdline,
562 const gchar *format,
563 ...)
565 gchar *message;
566 va_list ap;
568 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
569 g_return_if_fail (format != NULL);
571 va_start (ap, format);
572 message = g_strdup_vprintf (format, ap);
573 va_end (ap);
575 G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
576 ->printerr_literal (cmdline, message);
577 g_free (message);
581 * g_application_command_line_set_exit_status:
582 * @cmdline: a #GApplicationCommandLine
583 * @exit_status: the exit status
585 * Sets the exit status that will be used when the invoking process
586 * exits.
588 * The return value of the #GApplication::command-line signal is
589 * passed to this function when the handler returns. This is the usual
590 * way of setting the exit status.
592 * In the event that you want the remote invocation to continue running
593 * and want to decide on the exit status in the future, you can use this
594 * call. For the case of a remote invocation, the remote process will
595 * typically exit when the last reference is dropped on @cmdline. The
596 * exit status of the remote process will be equal to the last value
597 * that was set with this function.
599 * In the case that the commandline invocation is local, the situation
600 * is slightly more complicated. If the commandline invocation results
601 * in the mainloop running (ie: because the use-count of the application
602 * increased to a non-zero value) then the application is considered to
603 * have been 'successful' in a certain sense, and the exit status is
604 * always zero. If the application use count is zero, though, the exit
605 * status of the local #GApplicationCommandLine is used.
607 * Since: 2.28
609 void
610 g_application_command_line_set_exit_status (GApplicationCommandLine *cmdline,
611 int exit_status)
613 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
615 cmdline->priv->exit_status = exit_status;
619 * g_application_command_line_get_exit_status:
620 * @cmdline: a #GApplicationCommandLine
622 * Gets the exit status of @cmdline. See
623 * g_application_command_line_set_exit_status() for more information.
625 * Returns: the exit status
627 * Since: 2.28
630 g_application_command_line_get_exit_status (GApplicationCommandLine *cmdline)
632 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), -1);
634 return cmdline->priv->exit_status;
638 * g_application_command_line_get_platform_data:
639 * @cmdline: #GApplicationCommandLine
641 * Gets the platform data associated with the invocation of @cmdline.
643 * This is a #GVariant dictionary containing information about the
644 * context in which the invocation occurred. It typically contains
645 * information like the current working directory and the startup
646 * notification ID.
648 * For local invocation, it will be %NULL.
650 * Returns: (allow-none): the platform data, or %NULL
652 * Since: 2.28
654 GVariant *
655 g_application_command_line_get_platform_data (GApplicationCommandLine *cmdline)
657 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
659 if (cmdline->priv->platform_data)
660 return g_variant_ref (cmdline->priv->platform_data);
661 else
662 return NULL;
666 * g_application_command_line_create_file_for_arg:
667 * @cmdline: a #GApplicationCommandLine
668 * @arg: an argument from @cmdline
670 * Creates a #GFile corresponding to a filename that was given as part
671 * of the invocation of @cmdline.
673 * This differs from g_file_new_for_commandline_arg() in that it
674 * resolves relative pathnames using the current working directory of
675 * the invoking process rather than the local process.
677 * Returns: (transfer full): a new #GFile
679 * Since: 2.36
681 GFile *
682 g_application_command_line_create_file_for_arg (GApplicationCommandLine *cmdline,
683 const gchar *arg)
685 g_return_val_if_fail (arg != NULL, NULL);
687 if (cmdline->priv->cwd)
688 return g_file_new_for_commandline_arg_and_cwd (arg, cmdline->priv->cwd);
690 g_warning ("Requested creation of GFile for commandline invocation that did not send cwd. "
691 "Using cwd of local process to resolve relative path names.");
693 return g_file_new_for_commandline_arg (arg);