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, see <http://www.gnu.org/licenses/>.
17 * Authors: Ryan Lortie <desrt@desrt.ca>
22 #include "gapplicationcommandline.h"
31 #include "gunixinputstream.h"
37 #include "gwin32inputstream.h"
41 * SECTION:gapplicationcommandline
42 * @title: GApplicationCommandLine
43 * @short_description: A command-line invocation of an application
45 * @see_also: #GApplication
47 * #GApplicationCommandLine represents a command-line invocation of
48 * an application. It is created by #GApplication and emitted
49 * in the #GApplication::command-line signal and virtual function.
51 * The class contains the list of arguments that the program was invoked
52 * with. It is also possible to query if the commandline invocation was
53 * local (ie: the current process is running in direct response to the
54 * invocation) or remote (ie: some other process forwarded the
55 * commandline to this process).
57 * The GApplicationCommandLine object can provide the @argc and @argv
58 * parameters for use with the #GOptionContext command-line parsing API,
59 * with the g_application_command_line_get_arguments() function. See
60 * [gapplication-example-cmdline3.c][gapplication-example-cmdline3]
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
69 * The main use for #GApplicationCommandLine (and the
70 * #GApplication::command-line signal) is 'Emacs server' like use cases:
71 * You can set the `EDITOR` environment variable to have e.g. git use
72 * your favourite editor to edit commit messages, and if you already
73 * 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 * Normally, the commandline is completely handled in the
79 * #GApplication::command-line handler. The launching instance exits
80 * once the signal handler in the primary instance has returned, and
81 * the return value of the signal handler becomes the exit status
82 * of the launching instance.
83 * |[<!-- language="C" -->
85 * command_line (GApplication *application,
86 * GApplicationCommandLine *cmdline)
92 * argv = g_application_command_line_get_arguments (cmdline, &argc);
94 * g_application_command_line_print (cmdline,
95 * "This text is written back\n"
96 * "to stdout of the caller\n");
98 * for (i = 0; i < argc; i++)
99 * g_print ("argument %d: %s\n", i, argv[i]);
106 * The complete example can be found here:
107 * [gapplication-example-cmdline.c](https://git.gnome.org/browse/glib/tree/gio/tests/gapplication-example-cmdline.c)
109 * In more complicated cases, the handling of the comandline can be
110 * split between the launcher and the primary instance.
111 * |[<!-- language="C" -->
113 * test_local_cmdline (GApplication *application,
114 * gchar ***arguments,
125 * if (g_str_has_prefix (argv[i], "--local-"))
127 * g_print ("handling argument %s locally\n", argv[i]);
129 * for (j = i; argv[j]; j++)
130 * argv[j] = argv[j + 1];
134 * g_print ("not handling argument %s locally\n", argv[i]);
145 * test_application_class_init (TestApplicationClass *class)
147 * G_APPLICATION_CLASS (class)->local_command_line = test_local_cmdline;
152 * In this example of split commandline handling, options that start
153 * with `--local-` are handled locally, all other options are passed
154 * to the #GApplication::command-line handler which runs in the primary
157 * The complete example can be found here:
158 * [gapplication-example-cmdline2.c](https://git.gnome.org/browse/glib/tree/gio/tests/gapplication-example-cmdline2.c)
160 * If handling the commandline requires a lot of work, it may
161 * be better to defer it.
162 * |[<!-- language="C" -->
164 * my_cmdline_handler (gpointer data)
166 * GApplicationCommandLine *cmdline = data;
168 * // do the heavy lifting in an idle
170 * g_application_command_line_set_exit_status (cmdline, 0);
171 * g_object_unref (cmdline); // this releases the application
173 * return G_SOURCE_REMOVE;
177 * command_line (GApplication *application,
178 * GApplicationCommandLine *cmdline)
180 * // keep the application running until we are done with this commandline
181 * g_application_hold (application);
183 * g_object_set_data_full (G_OBJECT (cmdline),
184 * "application", application,
185 * (GDestroyNotify)g_application_release);
187 * g_object_ref (cmdline);
188 * g_idle_add (my_cmdline_handler, cmdline);
193 * In this example the commandline is not completely handled before
194 * the #GApplication::command-line handler returns. Instead, we keep
195 * a reference to the #GApplicationCommandLine object and handle it
196 * later (in this example, in an idle). Note that it is necessary to
197 * hold the application until you are done with the commandline.
199 * The complete example can be found here:
200 * [gapplication-example-cmdline3.c](https://git.gnome.org/browse/glib/tree/gio/tests/gapplication-example-cmdline3.c)
204 * GApplicationCommandLineClass:
206 * The #GApplicationCommandLineClass-struct
207 * contains private data only.
220 struct _GApplicationCommandLinePrivate
222 GVariant *platform_data;
225 GVariantDict *options_dict;
232 G_DEFINE_TYPE_WITH_PRIVATE (GApplicationCommandLine, g_application_command_line, G_TYPE_OBJECT)
234 /* All subclasses represent remote invocations of some kind. */
235 #define IS_REMOTE(cmdline) (G_TYPE_FROM_INSTANCE (cmdline) != \
236 G_TYPE_APPLICATION_COMMAND_LINE)
239 grok_platform_data (GApplicationCommandLine *cmdline)
245 g_variant_iter_init (&iter, cmdline->priv->platform_data);
247 while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
248 if (strcmp (key, "cwd") == 0)
250 if (!cmdline->priv->cwd)
251 cmdline->priv->cwd = g_variant_dup_bytestring (value, NULL);
254 else if (strcmp (key, "environ") == 0)
256 if (!cmdline->priv->environ)
257 cmdline->priv->environ =
258 g_variant_dup_bytestring_array (value, NULL);
261 else if (strcmp (key, "options") == 0)
263 if (!cmdline->priv->options)
264 cmdline->priv->options = g_variant_ref (value);
269 g_application_command_line_real_print_literal (GApplicationCommandLine *cmdline,
270 const gchar *message)
272 g_print ("%s", message);
276 g_application_command_line_real_printerr_literal (GApplicationCommandLine *cmdline,
277 const gchar *message)
279 g_printerr ("%s", message);
282 static GInputStream *
283 g_application_command_line_real_get_stdin (GApplicationCommandLine *cmdline)
286 return g_unix_input_stream_new (0, FALSE);
288 return g_win32_input_stream_new (GetStdHandle (STD_INPUT_HANDLE), FALSE);
293 g_application_command_line_get_property (GObject *object,
298 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
303 g_value_set_variant (value, cmdline->priv->arguments);
306 case PROP_PLATFORM_DATA:
307 g_value_set_variant (value, cmdline->priv->platform_data);
311 g_value_set_boolean (value, IS_REMOTE (cmdline));
315 g_assert_not_reached ();
320 g_application_command_line_set_property (GObject *object,
325 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
330 g_assert (cmdline->priv->arguments == NULL);
331 cmdline->priv->arguments = g_value_dup_variant (value);
335 g_assert (cmdline->priv->options == NULL);
336 cmdline->priv->options = g_value_dup_variant (value);
339 case PROP_PLATFORM_DATA:
340 g_assert (cmdline->priv->platform_data == NULL);
341 cmdline->priv->platform_data = g_value_dup_variant (value);
342 if (cmdline->priv->platform_data != NULL)
343 grok_platform_data (cmdline);
347 g_assert_not_reached ();
352 g_application_command_line_finalize (GObject *object)
354 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
356 if (cmdline->priv->options_dict)
357 g_variant_dict_unref (cmdline->priv->options_dict);
359 if (cmdline->priv->options)
360 g_variant_unref (cmdline->priv->options);
362 if (cmdline->priv->platform_data)
363 g_variant_unref (cmdline->priv->platform_data);
364 if (cmdline->priv->arguments)
365 g_variant_unref (cmdline->priv->arguments);
367 g_free (cmdline->priv->cwd);
368 g_strfreev (cmdline->priv->environ);
370 G_OBJECT_CLASS (g_application_command_line_parent_class)
375 g_application_command_line_init (GApplicationCommandLine *cmdline)
377 cmdline->priv = g_application_command_line_get_instance_private (cmdline);
381 g_application_command_line_constructed (GObject *object)
383 GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
385 if (IS_REMOTE (cmdline))
388 /* In the local case, set cmd and environ */
389 if (!cmdline->priv->cwd)
390 cmdline->priv->cwd = g_get_current_dir ();
392 if (!cmdline->priv->environ)
393 cmdline->priv->environ = g_get_environ ();
397 g_application_command_line_class_init (GApplicationCommandLineClass *class)
399 GObjectClass *object_class = G_OBJECT_CLASS (class);
401 object_class->get_property = g_application_command_line_get_property;
402 object_class->set_property = g_application_command_line_set_property;
403 object_class->finalize = g_application_command_line_finalize;
404 object_class->constructed = g_application_command_line_constructed;
406 class->printerr_literal = g_application_command_line_real_printerr_literal;
407 class->print_literal = g_application_command_line_real_print_literal;
408 class->get_stdin = g_application_command_line_real_get_stdin;
410 g_object_class_install_property (object_class, PROP_ARGUMENTS,
411 g_param_spec_variant ("arguments",
412 P_("Commandline arguments"),
413 P_("The commandline that caused this ::command-line signal emission"),
414 G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL,
415 G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
416 G_PARAM_STATIC_STRINGS));
418 g_object_class_install_property (object_class, PROP_OPTIONS,
419 g_param_spec_variant ("options",
421 P_("The options sent along with the commandline"),
422 G_VARIANT_TYPE_VARDICT, NULL, G_PARAM_WRITABLE |
423 G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
425 g_object_class_install_property (object_class, PROP_PLATFORM_DATA,
426 g_param_spec_variant ("platform-data",
428 P_("Platform-specific data for the commandline"),
429 G_VARIANT_TYPE ("a{sv}"), NULL,
430 G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
431 G_PARAM_STATIC_STRINGS));
433 g_object_class_install_property (object_class, PROP_IS_REMOTE,
434 g_param_spec_boolean ("is-remote",
436 P_("TRUE if this is a remote commandline"),
438 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
443 * g_application_command_line_get_arguments:
444 * @cmdline: a #GApplicationCommandLine
445 * @argc: (out) (allow-none): the length of the arguments array, or %NULL
447 * Gets the list of arguments that was passed on the command line.
449 * The strings in the array may contain non-UTF-8 data on UNIX (such as
450 * filenames or arguments given in the system locale) but are always in
453 * If you wish to use the return value with #GOptionContext, you must
454 * use g_option_context_parse_strv().
456 * The return value is %NULL-terminated and should be freed using
459 * Returns: (array length=argc) (transfer full): the string array
460 * containing the arguments (the argv)
465 g_application_command_line_get_arguments (GApplicationCommandLine *cmdline,
471 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
473 argv = g_variant_dup_bytestring_array (cmdline->priv->arguments, &len);
482 * g_application_command_line_get_options_dict:
483 * @cmdline: a #GApplicationCommandLine
485 * Gets the options there were passed to g_application_command_line().
487 * If you did not override local_command_line() then these are the same
488 * options that were parsed according to the #GOptionEntrys added to the
489 * application with g_application_add_main_option_entries() and possibly
490 * modified from your GApplication::handle-local-options handler.
492 * If no options were sent then an empty dictionary is returned so that
493 * you don't need to check for %NULL.
495 * Returns: (transfer none): a #GVariantDict with the options
500 g_application_command_line_get_options_dict (GApplicationCommandLine *cmdline)
502 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
504 if (!cmdline->priv->options_dict)
505 cmdline->priv->options_dict = g_variant_dict_new (cmdline->priv->options);
507 return cmdline->priv->options_dict;
511 * g_application_command_line_get_stdin:
512 * @cmdline: a #GApplicationCommandLine
514 * Gets the stdin of the invoking process.
516 * The #GInputStream can be used to read data passed to the standard
517 * input of the invoking process.
518 * This doesn't work on all platforms. Presently, it is only available
519 * on UNIX when using a DBus daemon capable of passing file descriptors.
520 * If stdin is not available then %NULL will be returned. In the
521 * future, support may be expanded to other platforms.
523 * You must only call this function once per commandline invocation.
525 * Returns: (transfer full): a #GInputStream for stdin
530 g_application_command_line_get_stdin (GApplicationCommandLine *cmdline)
532 return G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)->get_stdin (cmdline);
536 * g_application_command_line_get_cwd:
537 * @cmdline: a #GApplicationCommandLine
539 * Gets the working directory of the command line invocation.
540 * The string may contain non-utf8 data.
542 * It is possible that the remote application did not send a working
543 * directory, so this may be %NULL.
545 * The return value should not be modified or freed and is valid for as
546 * long as @cmdline exists.
548 * Returns: the current directory, or %NULL
553 g_application_command_line_get_cwd (GApplicationCommandLine *cmdline)
555 return cmdline->priv->cwd;
559 * g_application_command_line_get_environ:
560 * @cmdline: a #GApplicationCommandLine
562 * Gets the contents of the 'environ' variable of the command line
563 * invocation, as would be returned by g_get_environ(), ie as a
564 * %NULL-terminated list of strings in the form 'NAME=VALUE'.
565 * The strings may contain non-utf8 data.
567 * The remote application usually does not send an environment. Use
568 * %G_APPLICATION_SEND_ENVIRONMENT to affect that. Even with this flag
569 * set it is possible that the environment is still not available (due
570 * to invocation messages from other applications).
572 * The return value should not be modified or freed and is valid for as
573 * long as @cmdline exists.
575 * See g_application_command_line_getenv() if you are only interested
576 * in the value of a single environment variable.
578 * Returns: (array zero-terminated=1) (transfer none): the environment
579 * strings, or %NULL if they were not sent
583 const gchar * const *
584 g_application_command_line_get_environ (GApplicationCommandLine *cmdline)
586 return (const gchar **)cmdline->priv->environ;
590 * g_application_command_line_getenv:
591 * @cmdline: a #GApplicationCommandLine
592 * @name: the environment variable to get
594 * Gets the value of a particular environment variable of the command
595 * line invocation, as would be returned by g_getenv(). The strings may
596 * contain non-utf8 data.
598 * The remote application usually does not send an environment. Use
599 * %G_APPLICATION_SEND_ENVIRONMENT to affect that. Even with this flag
600 * set it is possible that the environment is still not available (due
601 * to invocation messages from other applications).
603 * The return value should not be modified or freed and is valid for as
604 * long as @cmdline exists.
606 * Returns: the value of the variable, or %NULL if unset or unsent
611 g_application_command_line_getenv (GApplicationCommandLine *cmdline,
614 gint length = strlen (name);
617 /* TODO: expand on windows */
618 if (cmdline->priv->environ)
619 for (i = 0; cmdline->priv->environ[i]; i++)
620 if (strncmp (cmdline->priv->environ[i], name, length) == 0 &&
621 cmdline->priv->environ[i][length] == '=')
622 return cmdline->priv->environ[i] + length + 1;
628 * g_application_command_line_get_is_remote:
629 * @cmdline: a #GApplicationCommandLine
631 * Determines if @cmdline represents a remote invocation.
633 * Returns: %TRUE if the invocation was remote
638 g_application_command_line_get_is_remote (GApplicationCommandLine *cmdline)
640 return IS_REMOTE (cmdline);
644 * g_application_command_line_print:
645 * @cmdline: a #GApplicationCommandLine
646 * @format: a printf-style format string
647 * @...: arguments, as per @format
649 * Formats a message and prints it using the stdout print handler in the
652 * If @cmdline is a local invocation then this is exactly equivalent to
653 * g_print(). If @cmdline is remote then this is equivalent to calling
654 * g_print() in the invoking process.
659 g_application_command_line_print (GApplicationCommandLine *cmdline,
666 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
667 g_return_if_fail (format != NULL);
669 va_start (ap, format);
670 message = g_strdup_vprintf (format, ap);
673 G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
674 ->print_literal (cmdline, message);
679 * g_application_command_line_printerr:
680 * @cmdline: a #GApplicationCommandLine
681 * @format: a printf-style format string
682 * @...: arguments, as per @format
684 * Formats a message and prints it using the stderr print handler in the
687 * If @cmdline is a local invocation then this is exactly equivalent to
688 * g_printerr(). If @cmdline is remote then this is equivalent to
689 * calling g_printerr() in the invoking process.
694 g_application_command_line_printerr (GApplicationCommandLine *cmdline,
701 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
702 g_return_if_fail (format != NULL);
704 va_start (ap, format);
705 message = g_strdup_vprintf (format, ap);
708 G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
709 ->printerr_literal (cmdline, message);
714 * g_application_command_line_set_exit_status:
715 * @cmdline: a #GApplicationCommandLine
716 * @exit_status: the exit status
718 * Sets the exit status that will be used when the invoking process
721 * The return value of the #GApplication::command-line signal is
722 * passed to this function when the handler returns. This is the usual
723 * way of setting the exit status.
725 * In the event that you want the remote invocation to continue running
726 * and want to decide on the exit status in the future, you can use this
727 * call. For the case of a remote invocation, the remote process will
728 * typically exit when the last reference is dropped on @cmdline. The
729 * exit status of the remote process will be equal to the last value
730 * that was set with this function.
732 * In the case that the commandline invocation is local, the situation
733 * is slightly more complicated. If the commandline invocation results
734 * in the mainloop running (ie: because the use-count of the application
735 * increased to a non-zero value) then the application is considered to
736 * have been 'successful' in a certain sense, and the exit status is
737 * always zero. If the application use count is zero, though, the exit
738 * status of the local #GApplicationCommandLine is used.
743 g_application_command_line_set_exit_status (GApplicationCommandLine *cmdline,
746 g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
748 cmdline->priv->exit_status = exit_status;
752 * g_application_command_line_get_exit_status:
753 * @cmdline: a #GApplicationCommandLine
755 * Gets the exit status of @cmdline. See
756 * g_application_command_line_set_exit_status() for more information.
758 * Returns: the exit status
763 g_application_command_line_get_exit_status (GApplicationCommandLine *cmdline)
765 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), -1);
767 return cmdline->priv->exit_status;
771 * g_application_command_line_get_platform_data:
772 * @cmdline: #GApplicationCommandLine
774 * Gets the platform data associated with the invocation of @cmdline.
776 * This is a #GVariant dictionary containing information about the
777 * context in which the invocation occurred. It typically contains
778 * information like the current working directory and the startup
781 * For local invocation, it will be %NULL.
783 * Returns: (nullable): the platform data, or %NULL
788 g_application_command_line_get_platform_data (GApplicationCommandLine *cmdline)
790 g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
792 if (cmdline->priv->platform_data)
793 return g_variant_ref (cmdline->priv->platform_data);
799 * g_application_command_line_create_file_for_arg:
800 * @cmdline: a #GApplicationCommandLine
801 * @arg: an argument from @cmdline
803 * Creates a #GFile corresponding to a filename that was given as part
804 * of the invocation of @cmdline.
806 * This differs from g_file_new_for_commandline_arg() in that it
807 * resolves relative pathnames using the current working directory of
808 * the invoking process rather than the local process.
810 * Returns: (transfer full): a new #GFile
815 g_application_command_line_create_file_for_arg (GApplicationCommandLine *cmdline,
818 g_return_val_if_fail (arg != NULL, NULL);
820 if (cmdline->priv->cwd)
821 return g_file_new_for_commandline_arg_and_cwd (arg, cmdline->priv->cwd);
823 g_warning ("Requested creation of GFile for commandline invocation that did not send cwd. "
824 "Using cwd of local process to resolve relative path names.");
826 return g_file_new_for_commandline_arg (arg);