2 * Copyright © 2010 Codethink Limited
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Authors: Ryan Lortie <desrt@desrt.ca>
24 #include "gapplicationcommandline.h"
33 #include "gunixinputstream.h"
39 #include "gwin32inputstream.h"
43 * SECTION:gapplicationcommandline
44 * @title: GApplicationCommandLine
45 * @short_description: A command-line invocation of an application
47 * @see_also: #GApplication
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.
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).
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 * [gapplication-example-cmdline3.c][gapplication-example-cmdline3]
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
71 * The main use for #GApplicationCommandLine (and the
72 * #GApplication::command-line signal) is 'Emacs server' like use cases:
73 * You can set the `EDITOR` environment variable to have e.g. git use
74 * your favourite editor to edit commit messages, and if you already
75 * 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.
80 * Normally, the commandline is completely handled in the
81 * #GApplication::command-line handler. The launching instance exits
82 * once the signal handler in the primary instance has returned, and
83 * the return value of the signal handler becomes the exit status
84 * of the launching instance.
85 * |[<!-- language="C" -->
87 * command_line (GApplication *application,
88 * GApplicationCommandLine *cmdline)
94 * argv = g_application_command_line_get_arguments (cmdline, &argc);
96 * g_application_command_line_print (cmdline,
97 * "This text is written back\n"
98 * "to stdout of the caller\n");
100 * for (i = 0; i < argc; i++)
101 * g_print ("argument %d: %s\n", i, argv[i]);
108 * The complete example can be found here:
109 * [gapplication-example-cmdline.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gapplication-example-cmdline.c)
111 * In more complicated cases, the handling of the commandline can be
112 * split between the launcher and the primary instance.
113 * |[<!-- language="C" -->
115 * test_local_cmdline (GApplication *application,
116 * gchar ***arguments,
124 * if (argv[0] == NULL)
133 * if (g_str_has_prefix (argv[i], "--local-"))
135 * g_print ("handling argument %s locally\n", argv[i]);
137 * for (j = i; argv[j]; j++)
138 * argv[j] = argv[j + 1];
142 * g_print ("not handling argument %s locally\n", argv[i]);
153 * test_application_class_init (TestApplicationClass *class)
155 * G_APPLICATION_CLASS (class)->local_command_line = test_local_cmdline;
160 * In this example of split commandline handling, options that start
161 * with `--local-` are handled locally, all other options are passed
162 * to the #GApplication::command-line handler which runs in the primary
165 * The complete example can be found here:
166 * [gapplication-example-cmdline2.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gapplication-example-cmdline2.c)
168 * If handling the commandline requires a lot of work, it may
169 * be better to defer it.
170 * |[<!-- language="C" -->
172 * my_cmdline_handler (gpointer data)
174 * GApplicationCommandLine *cmdline = data;
176 * // do the heavy lifting in an idle
178 * g_application_command_line_set_exit_status (cmdline, 0);
179 * g_object_unref (cmdline); // this releases the application
181 * return G_SOURCE_REMOVE;
185 * command_line (GApplication *application,
186 * GApplicationCommandLine *cmdline)
188 * // keep the application running until we are done with this commandline
189 * g_application_hold (application);
191 * g_object_set_data_full (G_OBJECT (cmdline),
192 * "application", application,
193 * (GDestroyNotify)g_application_release);
195 * g_object_ref (cmdline);
196 * g_idle_add (my_cmdline_handler, cmdline);
201 * In this example the commandline is not completely handled before
202 * the #GApplication::command-line handler returns. Instead, we keep
203 * a reference to the #GApplicationCommandLine object and handle it
204 * later (in this example, in an idle). Note that it is necessary to
205 * hold the application until you are done with the commandline.
207 * The complete example can be found here:
208 * [gapplication-example-cmdline3.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gapplication-example-cmdline3.c)
212 * GApplicationCommandLine:
214 * #GApplicationCommandLine is an opaque data structure and can only be accessed
215 * using the following functions.
219 * GApplicationCommandLineClass:
221 * The #GApplicationCommandLineClass-struct
222 * contains private data only.
235 struct _GApplicationCommandLinePrivate
237 GVariant *platform_data;
240 GVariantDict *options_dict;
241 gchar *cwd; /* in GLib filename encoding, not UTF-8 */
247 G_DEFINE_TYPE_WITH_PRIVATE (GApplicationCommandLine, g_application_command_line, G_TYPE_OBJECT)
249 /* All subclasses represent remote invocations of some kind. */
250 #define IS_REMOTE(cmdline) (G_TYPE_FROM_INSTANCE (cmdline) != \
251 G_TYPE_APPLICATION_COMMAND_LINE)
254 grok_platform_data (GApplicationCommandLine *cmdline)
260 g_variant_iter_init (&iter, cmdline->priv->platform_data);
262 while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
263 if (strcmp (key, "cwd") == 0 && g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
265 if (!cmdline->priv->cwd)
266 cmdline->priv->cwd = g_variant_dup_bytestring (value, NULL);
269 else if (strcmp (key, "environ") == 0 && g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING_ARRAY))
271 if (!cmdline->priv->environ)
272 cmdline->priv->environ =
273 g_variant_dup_bytestring_array (value, NULL);
276 else if (strcmp (key, "options") == 0 && g_variant_is_of_type (value, G_VARIANT_TYPE_VARDICT))
278 if (!cmdline->priv->options)
279 cmdline->priv->options = g_variant_ref (value);
284 g_application_command_line_real_print_literal (GApplicationCommandLine *cmdline,
285 const gchar *message)
287 g_print ("%s", message);
291 g_application_command_line_real_printerr_literal (GApplicationCommandLine *cmdline,
292 const gchar *message)
294 g_printerr ("%s", message);
297 static GInputStream *
298 g_application_command_line_real_get_stdin (GApplicationCommandLine *cmdline)
301 return g_unix_input_stream_new (0, FALSE);
303 return g_win32_input_stream_new (GetStdHandle (STD_INPUT_HANDLE), FALSE);
308 g_application_command_line_get_property (GObject *object,
313 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
318 g_value_set_variant (value, cmdline->priv->arguments);
321 case PROP_PLATFORM_DATA:
322 g_value_set_variant (value, cmdline->priv->platform_data);
326 g_value_set_boolean (value, IS_REMOTE (cmdline));
330 g_assert_not_reached ();
335 g_application_command_line_set_property (GObject *object,
340 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
345 g_assert (cmdline->priv->arguments == NULL);
346 cmdline->priv->arguments = g_value_dup_variant (value);
350 g_assert (cmdline->priv->options == NULL);
351 cmdline->priv->options = g_value_dup_variant (value);
354 case PROP_PLATFORM_DATA:
355 g_assert (cmdline->priv->platform_data == NULL);
356 cmdline->priv->platform_data = g_value_dup_variant (value);
357 if (cmdline->priv->platform_data != NULL)
358 grok_platform_data (cmdline);
362 g_assert_not_reached ();
367 g_application_command_line_finalize (GObject *object)
369 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
371 if (cmdline->priv->options_dict)
372 g_variant_dict_unref (cmdline->priv->options_dict);
374 if (cmdline->priv->options)
375 g_variant_unref (cmdline->priv->options);
377 if (cmdline->priv->platform_data)
378 g_variant_unref (cmdline->priv->platform_data);
379 if (cmdline->priv->arguments)
380 g_variant_unref (cmdline->priv->arguments);
382 g_free (cmdline->priv->cwd);
383 g_strfreev (cmdline->priv->environ);
385 G_OBJECT_CLASS (g_application_command_line_parent_class)
390 g_application_command_line_init (GApplicationCommandLine *cmdline)
392 cmdline->priv = g_application_command_line_get_instance_private (cmdline);
396 g_application_command_line_constructed (GObject *object)
398 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
400 if (IS_REMOTE (cmdline))
403 /* In the local case, set cmd and environ */
404 if (!cmdline->priv->cwd)
405 cmdline->priv->cwd = g_get_current_dir ();
407 if (!cmdline->priv->environ)
408 cmdline->priv->environ = g_get_environ ();
412 g_application_command_line_class_init (GApplicationCommandLineClass *class)
414 GObjectClass *object_class = G_OBJECT_CLASS (class);
416 object_class->get_property = g_application_command_line_get_property;
417 object_class->set_property = g_application_command_line_set_property;
418 object_class->finalize = g_application_command_line_finalize;
419 object_class->constructed = g_application_command_line_constructed;
421 class->printerr_literal = g_application_command_line_real_printerr_literal;
422 class->print_literal = g_application_command_line_real_print_literal;
423 class->get_stdin = g_application_command_line_real_get_stdin;
425 g_object_class_install_property (object_class, PROP_ARGUMENTS,
426 g_param_spec_variant ("arguments",
427 P_("Commandline arguments"),
428 P_("The commandline that caused this ::command-line signal emission"),
429 G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL,
430 G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
431 G_PARAM_STATIC_STRINGS));
433 g_object_class_install_property (object_class, PROP_OPTIONS,
434 g_param_spec_variant ("options",
436 P_("The options sent along with the commandline"),
437 G_VARIANT_TYPE_VARDICT, NULL, G_PARAM_WRITABLE |
438 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
440 g_object_class_install_property (object_class, PROP_PLATFORM_DATA,
441 g_param_spec_variant ("platform-data",
443 P_("Platform-specific data for the commandline"),
444 G_VARIANT_TYPE ("a{sv}"), NULL,
445 G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
446 G_PARAM_STATIC_STRINGS));
448 g_object_class_install_property (object_class, PROP_IS_REMOTE,
449 g_param_spec_boolean ("is-remote",
451 P_("TRUE if this is a remote commandline"),
453 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
458 * g_application_command_line_get_arguments:
459 * @cmdline: a #GApplicationCommandLine
460 * @argc: (out) (optional): the length of the arguments array, or %NULL
462 * Gets the list of arguments that was passed on the command line.
464 * The strings in the array may contain non-UTF-8 data on UNIX (such as
465 * filenames or arguments given in the system locale) but are always in
468 * If you wish to use the return value with #GOptionContext, you must
469 * use g_option_context_parse_strv().
471 * The return value is %NULL-terminated and should be freed using
474 * Returns: (array length=argc) (element-type filename) (transfer full)
475 * the string array containing the arguments (the argv)
480 g_application_command_line_get_arguments (GApplicationCommandLine *cmdline,
486 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
488 argv = g_variant_dup_bytestring_array (cmdline->priv->arguments, &len);
497 * g_application_command_line_get_options_dict:
498 * @cmdline: a #GApplicationCommandLine
500 * Gets the options that were passed to g_application_command_line().
502 * If you did not override local_command_line() then these are the same
503 * options that were parsed according to the #GOptionEntrys added to the
504 * application with g_application_add_main_option_entries() and possibly
505 * modified from your GApplication::handle-local-options handler.
507 * If no options were sent then an empty dictionary is returned so that
508 * you don't need to check for %NULL.
510 * The data has been passed via an untrusted external process, so the types of
511 * all values must be checked before being used.
513 * Returns: (transfer none): a #GVariantDict with the options
518 g_application_command_line_get_options_dict (GApplicationCommandLine *cmdline)
520 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
522 if (!cmdline->priv->options_dict)
523 cmdline->priv->options_dict = g_variant_dict_new (cmdline->priv->options);
525 return cmdline->priv->options_dict;
529 * g_application_command_line_get_stdin:
530 * @cmdline: a #GApplicationCommandLine
532 * Gets the stdin of the invoking process.
534 * The #GInputStream can be used to read data passed to the standard
535 * input of the invoking process.
536 * This doesn't work on all platforms. Presently, it is only available
537 * on UNIX when using a D-Bus daemon capable of passing file descriptors.
538 * If stdin is not available then %NULL will be returned. In the
539 * future, support may be expanded to other platforms.
541 * You must only call this function once per commandline invocation.
543 * Returns: (nullable) (transfer full): a #GInputStream for stdin
548 g_application_command_line_get_stdin (GApplicationCommandLine *cmdline)
550 return G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)->get_stdin (cmdline);
554 * g_application_command_line_get_cwd:
555 * @cmdline: a #GApplicationCommandLine
557 * Gets the working directory of the command line invocation.
558 * The string may contain non-utf8 data.
560 * It is possible that the remote application did not send a working
561 * directory, so this may be %NULL.
563 * The return value should not be modified or freed and is valid for as
564 * long as @cmdline exists.
566 * Returns: (nullable) (type filename): the current directory, or %NULL
571 g_application_command_line_get_cwd (GApplicationCommandLine *cmdline)
573 return cmdline->priv->cwd;
577 * g_application_command_line_get_environ:
578 * @cmdline: a #GApplicationCommandLine
580 * Gets the contents of the 'environ' variable of the command line
581 * invocation, as would be returned by g_get_environ(), ie as a
582 * %NULL-terminated list of strings in the form 'NAME=VALUE'.
583 * The strings may contain non-utf8 data.
585 * The remote application usually does not send an environment. Use
586 * %G_APPLICATION_SEND_ENVIRONMENT to affect that. Even with this flag
587 * set it is possible that the environment is still not available (due
588 * to invocation messages from other applications).
590 * The return value should not be modified or freed and is valid for as
591 * long as @cmdline exists.
593 * See g_application_command_line_getenv() if you are only interested
594 * in the value of a single environment variable.
596 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
597 * the environment strings, or %NULL if they were not sent
601 const gchar * const *
602 g_application_command_line_get_environ (GApplicationCommandLine *cmdline)
604 return (const gchar **)cmdline->priv->environ;
608 * g_application_command_line_getenv:
609 * @cmdline: a #GApplicationCommandLine
610 * @name: (type filename): the environment variable to get
612 * Gets the value of a particular environment variable of the command
613 * line invocation, as would be returned by g_getenv(). The strings may
614 * contain non-utf8 data.
616 * The remote application usually does not send an environment. Use
617 * %G_APPLICATION_SEND_ENVIRONMENT to affect that. Even with this flag
618 * set it is possible that the environment is still not available (due
619 * to invocation messages from other applications).
621 * The return value should not be modified or freed and is valid for as
622 * long as @cmdline exists.
624 * Returns: (nullable): the value of the variable, or %NULL if unset or unsent
629 g_application_command_line_getenv (GApplicationCommandLine *cmdline,
632 gint length = strlen (name);
635 /* TODO: expand on windows */
636 if (cmdline->priv->environ)
637 for (i = 0; cmdline->priv->environ[i]; i++)
638 if (strncmp (cmdline->priv->environ[i], name, length) == 0 &&
639 cmdline->priv->environ[i][length] == '=')
640 return cmdline->priv->environ[i] + length + 1;
646 * g_application_command_line_get_is_remote:
647 * @cmdline: a #GApplicationCommandLine
649 * Determines if @cmdline represents a remote invocation.
651 * Returns: %TRUE if the invocation was remote
656 g_application_command_line_get_is_remote (GApplicationCommandLine *cmdline)
658 return IS_REMOTE (cmdline);
662 * g_application_command_line_print:
663 * @cmdline: a #GApplicationCommandLine
664 * @format: a printf-style format string
665 * @...: arguments, as per @format
667 * Formats a message and prints it using the stdout print handler in the
670 * If @cmdline is a local invocation then this is exactly equivalent to
671 * g_print(). If @cmdline is remote then this is equivalent to calling
672 * g_print() in the invoking process.
677 g_application_command_line_print (GApplicationCommandLine *cmdline,
684 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
685 g_return_if_fail (format != NULL);
687 va_start (ap, format);
688 message = g_strdup_vprintf (format, ap);
691 G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
692 ->print_literal (cmdline, message);
697 * g_application_command_line_printerr:
698 * @cmdline: a #GApplicationCommandLine
699 * @format: a printf-style format string
700 * @...: arguments, as per @format
702 * Formats a message and prints it using the stderr print handler in the
705 * If @cmdline is a local invocation then this is exactly equivalent to
706 * g_printerr(). If @cmdline is remote then this is equivalent to
707 * calling g_printerr() in the invoking process.
712 g_application_command_line_printerr (GApplicationCommandLine *cmdline,
719 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
720 g_return_if_fail (format != NULL);
722 va_start (ap, format);
723 message = g_strdup_vprintf (format, ap);
726 G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
727 ->printerr_literal (cmdline, message);
732 * g_application_command_line_set_exit_status:
733 * @cmdline: a #GApplicationCommandLine
734 * @exit_status: the exit status
736 * Sets the exit status that will be used when the invoking process
739 * The return value of the #GApplication::command-line signal is
740 * passed to this function when the handler returns. This is the usual
741 * way of setting the exit status.
743 * In the event that you want the remote invocation to continue running
744 * and want to decide on the exit status in the future, you can use this
745 * call. For the case of a remote invocation, the remote process will
746 * typically exit when the last reference is dropped on @cmdline. The
747 * exit status of the remote process will be equal to the last value
748 * that was set with this function.
750 * In the case that the commandline invocation is local, the situation
751 * is slightly more complicated. If the commandline invocation results
752 * in the mainloop running (ie: because the use-count of the application
753 * increased to a non-zero value) then the application is considered to
754 * have been 'successful' in a certain sense, and the exit status is
755 * always zero. If the application use count is zero, though, the exit
756 * status of the local #GApplicationCommandLine is used.
761 g_application_command_line_set_exit_status (GApplicationCommandLine *cmdline,
764 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
766 cmdline->priv->exit_status = exit_status;
770 * g_application_command_line_get_exit_status:
771 * @cmdline: a #GApplicationCommandLine
773 * Gets the exit status of @cmdline. See
774 * g_application_command_line_set_exit_status() for more information.
776 * Returns: the exit status
781 g_application_command_line_get_exit_status (GApplicationCommandLine *cmdline)
783 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), -1);
785 return cmdline->priv->exit_status;
789 * g_application_command_line_get_platform_data:
790 * @cmdline: #GApplicationCommandLine
792 * Gets the platform data associated with the invocation of @cmdline.
794 * This is a #GVariant dictionary containing information about the
795 * context in which the invocation occurred. It typically contains
796 * information like the current working directory and the startup
799 * It comes from an untrusted external process and hence the types of all
800 * values must be validated before being used.
802 * For local invocation, it will be %NULL.
804 * Returns: (nullable) (transfer full): the platform data, or %NULL
809 g_application_command_line_get_platform_data (GApplicationCommandLine *cmdline)
811 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
813 if (cmdline->priv->platform_data)
814 return g_variant_ref (cmdline->priv->platform_data);
820 * g_application_command_line_create_file_for_arg:
821 * @cmdline: a #GApplicationCommandLine
822 * @arg: (type filename): an argument from @cmdline
824 * Creates a #GFile corresponding to a filename that was given as part
825 * of the invocation of @cmdline.
827 * This differs from g_file_new_for_commandline_arg() in that it
828 * resolves relative pathnames using the current working directory of
829 * the invoking process rather than the local process.
831 * Returns: (transfer full): a new #GFile
836 g_application_command_line_create_file_for_arg (GApplicationCommandLine *cmdline,
839 g_return_val_if_fail (arg != NULL, NULL);
841 if (cmdline->priv->cwd)
842 return g_file_new_for_commandline_arg_and_cwd (arg, cmdline->priv->cwd);
844 g_warning ("Requested creation of GFile for commandline invocation that did not send cwd. "
845 "Using cwd of local process to resolve relative path names.");
847 return g_file_new_for_commandline_arg (arg);