## GApplicationCommandLine

GApplicationCommandLine — A command-line invocation of an application

## Synopsis

                        GApplicationCommandLine;
    struct              GApplicationCommandLineClass;

    gchar **                 g_application_command_line_get_arguments
                                                            (GApplicationCommandLine *cmdline,
                                                             int *argc);
    const gchar *            g_application_command_line_get_cwd
                                                            (GApplicationCommandLine *cmdline);
    const gchar * const * g_application_command_line_get_environ
                                                            (GApplicationCommandLine *cmdline);
    const gchar *            g_application_command_line_getenv
                                                            (GApplicationCommandLine *cmdline,
                                                             const gchar *name);
    gboolean            g_application_command_line_get_is_remote
                                                            (GApplicationCommandLine *cmdline);
    GVariant *               g_application_command_line_get_platform_data
                                                            (GApplicationCommandLine *cmdline);

    void                g_application_command_line_set_exit_status
                                                            (GApplicationCommandLine *cmdline,
                                                             int exit_status);
    int                 g_application_command_line_get_exit_status
                                                            (GApplicationCommandLine *cmdline);

    void                g_application_command_line_print    (GApplicationCommandLine *cmdline,
                                                             const gchar *format,
                                                             ...);
    void                g_application_command_line_printerr (GApplicationCommandLine *cmdline,
                                                             const gchar *format,
                                                             ...);

## Object Hierarchy

      GObject
       +----GApplicationCommandLine

## Description

GApplicationCommandLine represents a command-line invocation of an application. It is created by GApplication and emitted in the "command-line" signal and virtual function.

The class contains the list of arguments that the program was invoked with. It is also possible to query if the commandline invocation was local (ie: the current process is running in direct response to the invocation) or remote (ie: some other process forwarded the commandline to this process).

The GApplicationCommandLine object can provide the `argc` and `argv` parameters for use with the GOptionContext command-line parsing API, with the `g_application_command_line_get_arguments()` function. See Example 17, “Deferred commandline handling” for an example.

The exit status of the originally-invoked process may be set and messages can be printed to stdout or stderr of that process. The lifecycle of the originally-invoked process is tied to the lifecycle of this object (ie: the process exits when the last reference is dropped).

The main use for GApplicationCommandline (and the "command-line" signal) is 'Emacs server' like use cases: You can set the `EDITOR` environment variable to have e.g. git use your favourite editor to edit commit messages, and if you already have an instance of the editor running, the editing will happen in the running instance, instead of opening a new one. An important aspect of this use case is that the process that gets started by git does not return until the editing is done.

Example 15. Handling commandline arguments with GApplication

A simple example where the commandline is completely handled in the "command-line" handler. The launching instance exits once the signal handler in the primary instance has returned, and the return value of the signal handler becomes the exit status of the launching instance.

    #include <gio/gio.h>
    #include <stdlib.h>
    #include <string.h>

    static int
    command_line (GApplication            *application,
                  GApplicationCommandLine *cmdline)
    {
      gchar **argv;
      gint argc;
      gint i;

      argv = g_application_command_line_get_arguments (cmdline, &argc);

      g_application_command_line_print (cmdline,
                                        "This text is written back\n"
                                        "to stdout of the caller\n");

      for (i = 0; i < argc; i++)
        g_print ("argument %d: %s\n", i, argv[i]);

      g_strfreev (argv);

      return 0;
    }

    int
    main (int argc, char **argv)
    {
      GApplication *app;
      int status;

      app = g_application_new ("org.gtk.TestApplication",
                               G_APPLICATION_HANDLES_COMMAND_LINE);
      g_signal_connect (app, "command-line", G_CALLBACK (command_line), NULL);
      g_application_set_inactivity_timeout (app, 10000);

      status = g_application_run (app, argc, argv);

      g_object_unref (app);

      return status;
    }

Example 16. Split commandline handling

An example of split commandline handling. Options that start with `--local-` are handled locally, all other options are passed to the "command-line" handler which runs in the primary instance.

    #include <gio/gio.h>
    #include <stdlib.h>
    #include <string.h>

    static int
    command_line (GApplication            *application,
                  GApplicationCommandLine *cmdline)
    {
      gchar **argv;
      gint argc;
      gint i;

      argv = g_application_command_line_get_arguments (cmdline, &argc);

      for (i = 0; i < argc; i++)
        g_print ("handling argument %s remotely\n", argv[i]);

      g_strfreev (argv);

      return 0;
    }

    static gboolean
    test_local_cmdline (GApplication   *application,
                        gchar        ***arguments,
                        gint           *exit_status)
    {
      gint i, j;
      gchar **argv;

      argv = *arguments;

      i = 1;
      while (argv[i])
        {
          if (g_str_has_prefix (argv[i], "--local-"))
            {
              g_print ("handling argument %s locally\n", argv[i]);
              g_free (argv[i]);
              for (j = i; argv[j]; j++)
                argv[j] = argv[j + 1];
            }
          else
            {
              g_print ("not handling argument %s locally\n", argv[i]);
              i++;
            }
        }

      *exit_status = 0;

      return FALSE;
    }

    typedef GApplication TestApplication;
    typedef GApplicationClass TestApplicationClass;

    G_DEFINE_TYPE (TestApplication, test_application, G_TYPE_APPLICATION)

    static void
    test_application_finalize (GObject *object)
    {
      G_OBJECT_CLASS (test_application_parent_class)->finalize (object);
    }

    static void
    test_application_init (TestApplication *app)
    {
    }

    static void
    test_application_class_init (TestApplicationClass *class)
    {
      G_OBJECT_CLASS (class)->finalize = test_application_finalize;
      G_APPLICATION_CLASS (class)->local_command_line = test_local_cmdline;
    }

    GApplication *
    test_application_new (const gchar       *application_id,
                          GApplicationFlags  flags)
    {
      g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);

      g_type_init ();

      return g_object_new (test_application_get_type (),
                           "application-id", application_id,
                           "flags", flags,
                           NULL);
    }

    int
    main (int argc, char **argv)
    {
      GApplication *app;
      int status;

      app = test_application_new ("org.gtk.TestApplication", 0);
      g_application_set_inactivity_timeout (app, 10000);
      g_signal_connect (app, "command-line", G_CALLBACK (command_line), NULL);

      status = g_application_run (app, argc, argv);

      g_object_unref (app);

      return status;
    }

Example 17. Deferred commandline handling

An example of deferred commandline handling. Here, the commandline is not completely handled before the "command-line" handler returns. Instead, we keep a reference to the GApplicationCommandline object and handle it later(in this example, in an idle). Note that it is necessary to hold the application until you are done with the commandline.

This example also shows how to use GOptionContext for parsing the commandline arguments. Note that it is necessary to disable the built-in help-handling of GOptionContext, since it calls `exit()` after printing help, which is not what you want to happen in the primary instance.

    #include <gio/gio.h>
    #include <stdlib.h>
    #include <string.h>

    static gboolean
    my_cmdline_handler (gpointer data)
    {
      GApplicationCommandLine *cmdline = data;
      gchar **args;
      gchar **argv;
      gint argc;
      gint arg1;
      gboolean arg2;
      gboolean help;
      GOptionContext *context;
      GOptionEntry entries[] = {
        { "arg1", 0, 0, G_OPTION_ARG_INT, &arg1, NULL, NULL },
        { "arg2", 0, 0, G_OPTION_ARG_NONE, &arg2, NULL, NULL },
        { "help", '?', 0, G_OPTION_ARG_NONE, &help, NULL, NULL },
        { NULL }
      };
      GError *error;
      gint i;

      args = g_application_command_line_get_arguments (cmdline, &argc);

      /* We have to make an extra copy of the array, since g_option_context_parse()
       * assumes that it can remove strings from the array without freeing them.
       */
      argv = g_new (gchar*, argc + 1);
      for (i = 0; i <= argc; i++)
        argv[i] = args[i];

      context = g_option_context_new (NULL);
      g_option_context_set_help_enabled (context, FALSE);
      g_option_context_add_main_entries (context, entries, NULL);

      arg1 = 0;
      arg2 = FALSE;
      help = FALSE;
      error = NULL;
      if (!g_option_context_parse (context, &argc, &argv, &error))
        {
          g_application_command_line_printerr (cmdline, "%s\n", error->message);
          g_error_free (error);
          g_application_command_line_set_exit_status (cmdline, 1);
        }
      else if (help)
        {
          gchar *text;
          text = g_option_context_get_help (context, FALSE, NULL);
          g_application_command_line_print (cmdline, "%s",  text);
          g_free (text);
        }
      else
        {
          g_application_command_line_print (cmdline, "arg1 is %d and arg2 is %s\n",
                                            arg1, arg2 ? "TRUE" : "FALSE");
          g_application_command_line_set_exit_status (cmdline, 0);
        }

      g_free (argv);
      g_strfreev (args);

      g_option_context_free (context);

      /* we are done handling this commandline */
      g_object_unref (cmdline);

      return FALSE;
    }

    static int
    command_line (GApplication            *application,
                  GApplicationCommandLine *cmdline)
    {
      /* keep the application running until we are done with this commandline */
      g_application_hold (application);

      g_object_set_data_full (G_OBJECT (cmdline),
                              "application", application,
                              (GDestroyNotify)g_application_release);

      g_object_ref (cmdline);
      g_idle_add (my_cmdline_handler, cmdline);

      return 0;
    }

    int
    main (int argc, char **argv)
    {
      GApplication *app;
      int status;

      app = g_application_new ("org.gtk.TestApplication",
                               G_APPLICATION_HANDLES_COMMAND_LINE);
      g_signal_connect (app, "command-line", G_CALLBACK (command_line), NULL);
      g_application_set_inactivity_timeout (app, 10000);

      status = g_application_run (app, argc, argv);

      g_object_unref (app);

      return status;
    }

## Details

### GApplicationCommandLine

    typedef struct _GApplicationCommandLine GApplicationCommandLine;

The GApplicationCommandLine structure contains private data and should only be accessed using the provided API

Since 2.28

### struct GApplicationCommandLineClass

    struct GApplicationCommandLineClass {
    };

The GApplicationCommandLineClass structure contains private data only

Since 2.28

### g_application_command_line_get_arguments ()

    gchar **                 g_application_command_line_get_arguments
                                                            (GApplicationCommandLine *cmdline,
                                                             int *argc);

Gets the list of arguments that was passed on the command line.

The strings in the array may contain non-utf8 data.

The return value is `NULL`-terminated and should be freed using `g_strfreev()`.

`cmdline` : | a GApplicationCommandLine
`argc` : | the length of the arguments array, or `NULL`. [out]
Returns : | the string array containing the arguments (the argv). [array length=argc][transfer full]

Since 2.28

### g_application_command_line_get_cwd ()

    const gchar *            g_application_command_line_get_cwd
                                                            (GApplicationCommandLine *cmdline);

Gets the working directory of the command line invocation. The string may contain non-utf8 data.

It is possible that the remote application did not send a working directory, so this may be `NULL`.

The return value should not be modified or freed and is valid for as long as `cmdline` exists.

`cmdline` : | a GApplicationCommandLine
Returns : | the current directory, or `NULL`

Since 2.28

### g_application_command_line_get_environ ()

    const gchar * const * g_application_command_line_get_environ
                                                            (GApplicationCommandLine *cmdline);

Gets the contents of the 'environ' variable of the command line invocation, as would be returned by `g_get_environ()`, ie as a `NULL`-terminated list of strings in the form 'NAME=VALUE'. The strings may contain non-utf8 data.

The remote application usually does not send an environment. Use `G_APPLICATION_SEND_ENVIRONMENT` to affect that. Even with this flag set it is possible that the environment is still not available (due to invocation messages from other applications).

The return value should not be modified or freed and is valid for as long as `cmdline` exists.

See `g_application_command_line_getenv()` if you are only interested in the value of a single environment variable.

`cmdline` : | a GApplicationCommandLine
Returns : | the environment strings, or `NULL` if they were not sent. [array zero-terminated=1][transfer none]

Since 2.28

### g_application_command_line_getenv ()

    const gchar *            g_application_command_line_getenv
                                                            (GApplicationCommandLine *cmdline,
                                                             const gchar *name);

Gets the value of a particular environment variable of the command line invocation, as would be returned by `g_getenv()`. The strings may contain non-utf8 data.

The remote application usually does not send an environment. Use `G_APPLICATION_SEND_ENVIRONMENT` to affect that. Even with this flag set it is possible that the environment is still not available (due to invocation messages from other applications).

The return value should not be modified or freed and is valid for as long as `cmdline` exists.

`cmdline` : | a GApplicationCommandLine
`name` : | the environment variable to get
Returns : | the value of the variable, or `NULL` if unset or unsent

Since 2.28

### g_application_command_line_get_is_remote ()

    gboolean            g_application_command_line_get_is_remote
                                                            (GApplicationCommandLine *cmdline);

Determines if `cmdline` represents a remote invocation.

`cmdline` : | a GApplicationCommandLine
Returns : | `TRUE` if the invocation was remote

Since 2.28

### g_application_command_line_get_platform_data ()

    GVariant *               g_application_command_line_get_platform_data
                                                            (GApplicationCommandLine *cmdline);

Gets the platform data associated with the invocation of `cmdline`.

This is a GVariant dictionary containing information about the context in which the invocation occured. It typically contains information like the current working directory and the startup notification ID.

For local invocation, it will be `NULL`.

`cmdline` : | GApplicationCommandLine
Returns : | the platform data, or `NULL`

Since 2.28

### g_application_command_line_set_exit_status ()

    void                g_application_command_line_set_exit_status
                                                            (GApplicationCommandLine *cmdline,
                                                             int exit_status);

Sets the exit status that will be used when the invoking process exits.

The return value of the "command-line" signal is passed to this function when the handler returns. This is the usual way of setting the exit status.

In the event that you want the remote invocation to continue running and want to decide on the exit status in the future, you can use this call. For the case of a remote invocation, the remote process will typically exit when the last reference is dropped on `cmdline`. The exit status of the remote process will be equal to the last value that was set with this function.

In the case that the commandline invocation is local, the situation is slightly more complicated. If the commandline invocation results in the mainloop running (ie: because the use-count of the application increased to a non-zero value) then the application is considered to have been 'successful' in a certain sense, and the exit status is always zero. If the application use count is zero, though, the exit status of the local GApplicationCommandLine is used.

`cmdline` : | a GApplicationCommandLine
`exit_status` : | the exit status

Since 2.28

### g_application_command_line_get_exit_status ()

    int                 g_application_command_line_get_exit_status
                                                            (GApplicationCommandLine *cmdline);

Gets the exit status of `cmdline`. See `g_application_command_line_set_exit_status()` for more information.

`cmdline` : | a GApplicationCommandLine
Returns : | the exit status

Since 2.28

### g_application_command_line_print ()

    void                g_application_command_line_print    (GApplicationCommandLine *cmdline,
                                                             const gchar *format,
                                                             ...);

Formats a message and prints it using the stdout print handler in the invoking process.

If `cmdline` is a local invocation then this is exactly equivalent to `g_print()`. If `cmdline` is remote then this is equivalent to calling `g_print()` in the invoking process.

`cmdline` : | a GApplicationCommandLine
`format` : | a printf-style format string
`...` : | arguments, as per `format`

Since 2.28

### g_application_command_line_printerr ()

    void                g_application_command_line_printerr (GApplicationCommandLine *cmdline,
                                                             const gchar *format,
                                                             ...);

Formats a message and prints it using the stderr print handler in the invoking process.

If `cmdline` is a local invocation then this is exactly equivalent to `g_printerr()`. If `cmdline` is remote then this is equivalent to calling `g_printerr()` in the invoking process.

`cmdline` : | a GApplicationCommandLine
`format` : | a printf-style format string
`...` : | arguments, as per `format`

Since 2.28

## See Also

GApplication