## GApplication GApplication — Core application class |

## Synopsis

                        GApplication;
    struct              GApplicationClass;

    enum                GApplicationFlags;
    gboolean            g_application_id_is_valid           (const gchar *application_id);
    GApplication *           g_application_new              (const gchar *application_id,
                                                             GApplicationFlags flags);

    const gchar *            g_application_get_application_id
                                                            (GApplication *application);
    void                g_application_set_application_id    (GApplication *application,
                                                             const gchar *application_id);

    guint               g_application_get_inactivity_timeout
                                                            (GApplication *application);
    void                g_application_set_inactivity_timeout
                                                            (GApplication *application,
                                                             guint inactivity_timeout);

    GApplicationFlags   g_application_get_flags             (GApplication *application);
    void                g_application_set_flags             (GApplication *application,
                                                             GApplicationFlags flags);

    void                g_application_set_action_group      (GApplication *application,
                                                             GActionGroup *action_group);

    gboolean            g_application_get_is_registered     (GApplication *application);
    gboolean            g_application_get_is_remote         (GApplication *application);
    gboolean            g_application_register              (GApplication *application,
                                                             GCancellable *cancellable,
                                                             GError **error);

    void                g_application_hold                  (GApplication *application);
    void                g_application_release               (GApplication *application);

    void                g_application_activate              (GApplication *application);
    void                g_application_open                  (GApplication *application,
                                                             GFile **files,
                                                             gint n_files,
                                                             const gchar *hint);

    int                 g_application_run                   (GApplication *application,
                                                             int argc,
                                                             char **argv);

## Object Hierarchy

      GObject
       +----GApplication

      GFlags
       +----GApplicationFlags

## Implemented Interfaces

GApplication implements GActionGroup.

## Properties

      "action-group"             GActionGroup*         : Write
      "application-id"           gchar*                : Read / Write / Construct
      "flags"                    GApplicationFlags     : Read / Write
      "inactivity-timeout"       guint                 : Read / Write
      "is-registered"            gboolean              : Read
      "is-remote"                gboolean              : Read

## Signals

      "activate"                                       : Run Last
      "command-line"                                   : Run Last
      "open"                                           : Run Last
      "startup"                                        : Run Last

## Description

A GApplication is the foundation of an application, unique for a given application identifier. The GApplication class wraps some low-level platform-specific services and is intended to act as the foundation for higher-level application classes such as GtkApplication or MxApplication. In general, you should not use this class outside of a higher level framework.

One of the core features that GApplication provides is process uniqueness, in the context of a "session". The session concept is platform-dependent, but corresponds roughly to a graphical desktop login. When your application is launched again, its arguments are passed through platform communication to the already running program. The already running instance of the program is called the primary instance.

Before using GApplication, you must choose an "application identifier". The expected form of an application identifier is very close to that of of a DBus bus name. Examples include: "com.example.MyApp", "org.example.internal-apps.Calculator". For details on valid application identifiers, see `g_application_id_is_valid()`.

The application identifier is claimed by the application as a well-known bus name on the user's session bus. This means that the uniqueness of your application is scoped to the current session. It also means that your application may provide additional services (through registration of other object paths) at that bus name.

The registration of these object paths should be done with the shared GDBus session bus. Note that due to the internal architecture of GDBus, method calls can be dispatched at any time (even if a main loop is not running). For this reason, you must ensure that any object paths that you wish to register are registered before GApplication attempts to acquire the bus name of your application (which happens in `g_application_register()`). Unfortunately, this means that you can not use `g_application_get_is_remote()` to decide if you want to register object paths.

GApplication provides convenient life cycle management by maintaining a use count for the primary application instance. The use count can be changed using `g_application_hold()` and `g_application_release()`. If it drops to zero, the application exits.

GApplication also implements the GActionGroup interface and lets you easily export actions by adding them with `g_application_set_action_group()`. When invoking an action by calling `g_action_group_activate_action()` on the application, it is always invoked in the primary instance.

There is a number of different entry points into a GApplication:

- via 'Activate' (i.e. just starting the application)
- via 'Open' (i.e. opening some files)
- via activating an action

The "startup" signal lets you handle the application initialization for all of these in a single place.

Example 13. Opening files with a GApplication

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    #include <gio/gio.h>
    #include <stdlib.h>
    #include <string.h>

    static void
    activate (GApplication *application)
    {
      g_print ("activated\n");

      /* Note: when doing a longer-lasting action here that returns
       * to the mainloop, you should use g_application_hold() and
       * g_application_release() to keep the application alive until
       * the action is completed.
       */
    }

    static void
    open (GApplication  *application,
          GFile        **files,
          gint           n_files,
          const gchar   *hint)
    {
      gint i;

      for (i = 0; i < n_files; i++)
        {
          gchar *uri = g_file_get_uri (files[i]);
          g_print ("open %s\n", uri);
          g_free (uri);
        }

      /* Note: when doing a longer-lasting action here that returns
       * to the mainloop, you should use g_application_hold() and
       * g_application_release() to keep the application alive until
       * the action is completed.
       */
    }

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

      app = g_application_new ("org.gtk.TestApplication",
                               G_APPLICATION_HANDLES_OPEN);
      g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
      g_signal_connect (app, "open", G_CALLBACK (open), NULL);
      g_application_set_inactivity_timeout (app, 10000);

      status = g_application_run (app, argc, argv);

      g_object_unref (app);

      return status;
    }

Example 14. A GApplication with actions

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    #include <gio/gio.h>
    #include <stdlib.h>
    #include <string.h>

    static void
    activate (GApplication *application)
    {
      g_print ("activated\n");
    }

    static void
    activate_action (GAction  *action,
                     GVariant *parameter,
                     gpointer  data)
    {
      g_print ("action %s activated\n", g_action_get_name (action));
    }

    static void
    activate_toggle_action (GAction  *action,
                            GVariant *parameter,
                            gpointer  data)
    {
      GVariant *state;
      gboolean b;

      g_print ("action %s activated\n", g_action_get_name (action));

      state = g_action_get_state (action);
      b = g_variant_get_boolean (state);
      g_variant_unref (state);
      g_action_set_state (action, g_variant_new_boolean (!b));
      g_print ("state change %d -> %d\n", b, !b);
    }

    static void
    add_actions (GApplication *app)
    {
      GSimpleActionGroup *actions;
      GSimpleAction *action;

      actions = g_simple_action_group_new ();

      action = g_simple_action_new ("simple-action", NULL);
      g_signal_connect (action, "activate", G_CALLBACK (activate_action), app);
      g_simple_action_group_insert (actions, G_ACTION (action));
      g_object_unref (action);

      action = g_simple_action_new_stateful ("toggle-action", NULL,
                                             g_variant_new_boolean (FALSE));
      g_signal_connect (action, "activate", G_CALLBACK (activate_toggle_action), app);
      g_simple_action_group_insert (actions, G_ACTION (action));
      g_object_unref (action);

      g_application_set_action_group (app, G_ACTION_GROUP (actions));
      g_object_unref (actions);
    }

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

      app = g_application_new ("org.gtk.TestApplication", 0);
      g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
      g_application_set_inactivity_timeout (app, 10000);

      add_actions (app);

      if (argc > 1 && strcmp (argv[1], "--simple-action") == 0)
        {
          g_application_register (app, NULL, NULL);
          g_action_group_activate_action (G_ACTION_GROUP (app), "simple-action", NULL);
          exit (0);
        }
      else if (argc > 1 && strcmp (argv[1], "--toggle-action") == 0)
        {
          g_application_register (app, NULL, NULL);
          g_action_group_activate_action (G_ACTION_GROUP (app), "toggle-action", NULL);
          exit (0);
        }

      status = g_application_run (app, argc, argv);

      g_object_unref (app);

      return status;
    }

## Details

### GApplication

    typedef struct _GApplication GApplication;

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

Since 2.28

### struct GApplicationClass

    struct GApplicationClass {
      /* signals */
      void                      (* startup)             (GApplication              *application);

      void                      (* activate)            (GApplication              *application);

      void                      (* open)                (GApplication              *application,
                                                         GFile                    **files,
                                                         gint                       n_files,
                                                         const gchar               *hint);

      int                       (* command_line)        (GApplication              *application,
                                                         GApplicationCommandLine   *command_line);

      /* vfuncs */
      gboolean                  (* local_command_line)  (GApplication              *application,
                                                         gchar                   ***arguments,
                                                         int                       *exit_status);

      void                      (* before_emit)         (GApplication              *application,
                                                         GVariant                  *platform_data);
      void                      (* after_emit)          (GApplication              *application,
                                                         GVariant                  *platform_data);
      void                      (* add_platform_data)   (GApplication              *application,
                                                         GVariantBuilder           *builder);
      void                      (* quit_mainloop)       (GApplication              *application);
      void                      (* run_mainloop)        (GApplication              *application);
    };

`startup` () | invoked on the primary instance immediately after registration
`activate` () | invoked on the primary instance when an activation occurs
`open` () | invoked on the primary instance when there are files to open
`command_line` () | invoked on the primary instance when a command-line is not handled locally
`local_command_line` () | invoked (locally) when the process has been invoked via commandline execution. The virtual function has the chance to inspect (and possibly replace) the list of command line arguments. See `g_application_run()` for more information.
`before_emit` () | invoked on the primary instance before 'activate', 'open' or any action invocation
`after_emit` () | invoked on the primary instance after 'activate', 'open' or any action invocation
`add_platform_data` () | invoked (locally) to add 'platform data' to be sent to the primary instance when activating, opening or invoking actions
`quit_mainloop` () | invoked on the primary instance when the use count of the application drops to zero (and after any inactivity timeout, if requested)
`run_mainloop` () | invoked on the primary instance from `g_application_run()` if the use-count is non-zero

Since 2.28

### enum GApplicationFlags

    typedef enum
    {
      G_APPLICATION_FLAGS_NONE,
      G_APPLICATION_IS_SERVICE  =          (1 << 0),
      G_APPLICATION_IS_LAUNCHER =          (1 << 1),

      G_APPLICATION_HANDLES_OPEN =         (1 << 2),
      G_APPLICATION_HANDLES_COMMAND_LINE = (1 << 3),
      G_APPLICATION_SEND_ENVIRONMENT    =  (1 << 4)
    } GApplicationFlags;

Flags used to define the behaviour of a GApplication.

`G_APPLICATION_FLAGS_NONE` | Default
`G_APPLICATION_IS_SERVICE` | Run as a service. In this mode, registration fails if the service is already running, and the application will stay around for a while when the use count falls to zero.
`G_APPLICATION_IS_LAUNCHER` | Don't try to become the primary instance.
`G_APPLICATION_HANDLES_OPEN` | This application handles opening files (in the primary instance)
`G_APPLICATION_HANDLES_COMMAND_LINE` | This application handles command line arguments (in the primary instance)
`G_APPLICATION_SEND_ENVIRONMENT` | Send the environment of the launching process to the primary instance

Since 2.28

### g_application_id_is_valid ()

    gboolean            g_application_id_is_valid           (const gchar *application_id);

Checks if `application_id` is a valid application identifier.

A valid ID is required for calls to `g_application_new()` and `g_application_set_application_id()`.

For convenience, the restrictions on application identifiers are reproduced here:

- Application identifiers must contain only the ASCII characters "[A-Z][a-z][0-9]_-" and must not begin with a digit.
- Application identifiers must contain at least one '.' (period) character (and thus at least two elements).
- Application identifiers must not begin with a '.' (period) character.
- Application identifiers must not contain consecutive '.' (period) characters.
- Application identifiers must not exceed 255 characters.

`application_id` : | a potential application identifier
Returns : | `TRUE` if `application_id` is valid

### g_application_new ()

    GApplication *           g_application_new              (const gchar *application_id,
                                                             GApplicationFlags flags);

Creates a new GApplication instance.

This function calls `g_type_init()` for you.

The application id must be valid. See `g_application_id_is_valid()`.

`application_id` : | the application id
`flags` : | the application flags
Returns : | a new GApplication instance

### g_application_get_application_id ()

    const gchar *            g_application_get_application_id
                                                            (GApplication *application);

Gets the unique identifier for `application`.

`application` : | a GApplication
Returns : | the identifier for `application`, owned by `application`

Since 2.28

### g_application_set_application_id ()

    void                g_application_set_application_id    (GApplication *application,
                                                             const gchar *application_id);

Sets the unique identifier for `application`.

The application id can only be modified if `application` has not yet been registered.

The application id must be valid. See `g_application_id_is_valid()`.

`application` : | a GApplication
`application_id` : | the identifier for `application`

Since 2.28

### g_application_get_inactivity_timeout ()

    guint               g_application_get_inactivity_timeout
                                                            (GApplication *application);

Gets the current inactivity timeout for the application.

This is the amount of time (in milliseconds) after the last call to `g_application_release()` before the application stops running.

`application` : | a GApplication
Returns : | the timeout, in milliseconds

Since 2.28

### g_application_set_inactivity_timeout ()

    void                g_application_set_inactivity_timeout
                                                            (GApplication *application,
                                                             guint inactivity_timeout);

Sets the current inactivity timeout for the application.

This is the amount of time (in milliseconds) after the last call to `g_application_release()` before the application stops running.

This call has no side effects of its own. The value set here is only used for next time `g_application_release()` drops the use count to zero. Any timeouts currently in progress are not impacted.

`application` : | a GApplication
`inactivity_timeout` : | the timeout, in milliseconds

Since 2.28

### g_application_get_flags ()

    GApplicationFlags   g_application_get_flags             (GApplication *application);

Gets the flags for `application`.

See GApplicationFlags.

`application` : | a GApplication
Returns : | the flags for `application`

Since 2.28

### g_application_set_flags ()

    void                g_application_set_flags             (GApplication *application,
                                                             GApplicationFlags flags);

Sets the flags for `application`.

The flags can only be modified if `application` has not yet been registered.

See GApplicationFlags.

`application` : | a GApplication
`flags` : | the flags for `application`

Since 2.28

### g_application_set_action_group ()

    void                g_application_set_action_group      (GApplication *application,
                                                             GActionGroup *action_group);

Sets or unsets the group of actions associated with the application.

These actions are the actions that can be remotely invoked.

It is an error to call this function after the application has been registered.

`application` : | a GApplication
`action_group` : | a GActionGroup, or `NULL`. [allow-none]

Since 2.28

### g_application_get_is_registered ()

    gboolean            g_application_get_is_registered     (GApplication *application);

Checks if `application` is registered.

An application is registered if `g_application_register()` has been successfully called.

`application` : | a GApplication
Returns : | `TRUE` if `application` is registered

Since 2.28

### g_application_get_is_remote ()

    gboolean            g_application_get_is_remote         (GApplication *application);

Checks if `application` is remote.

If `application` is remote then it means that another instance of application already exists (the 'primary' instance). Calls to perform actions on `application` will result in the actions being performed by the primary instance.

The value of this property can not be accessed before `g_application_register()` has been called. See `g_application_get_is_registered()`.

`application` : | a GApplication
Returns : | `TRUE` if `application` is remote

Since 2.28

### g_application_register ()

    gboolean            g_application_register              (GApplication *application,
                                                             GCancellable *cancellable,
                                                             GError **error);

Attempts registration of the application.

This is the point at which the application discovers if it is the primary instance or merely acting as a remote for an already-existing primary instance. This is implemented by attempting to acquire the application identifier as a uniue bus name on the session bus using GDBus.

Due to the internal architecture of GDBus, method calls can be dispatched at any time (even if a main loop is not running). For this reason, you must ensure that any object paths that you wish to register are registered before calling this function.

If the application has already been registered then `TRUE` is returned with no work performed.

The "startup" signal is emitted if registration succeeds and `application` is the primary instance.

In the event of an error (such as `cancellable` being cancelled, or a failure to connect to the session bus), `FALSE` is returned and `error` is set appropriately.

Note: the return value of this function is not an indicator that this instance is or is not the primary instance of the application. See `g_application_get_is_remote()` for that.

`application` : | a GApplication
`cancellable` : | a GCancellable, or `NULL`
`error` : | a pointer to a NULL GError, or `NULL`
Returns : | `TRUE` if registration succeeded

Since 2.28

### g_application_hold ()

    void                g_application_hold                  (GApplication *application);

Increases the use count of `application`.

Use this function to indicate that the application has a reason to continue to run. For example, `g_application_hold()` is called by GTK+ when a toplevel window is on the screen.

To cancel the hold, call `g_application_release()`.

`application` : | a GApplication

### g_application_release ()

    void                g_application_release               (GApplication *application);

Decrease the use count of `application`.

When the use count reaches zero, the application will stop running.

Never call this function except to cancel the effect of a previous call to `g_application_hold()`.

`application` : | a GApplication

### g_application_activate ()

    void                g_application_activate              (GApplication *application);

Activates the application.

In essence, this results in the GApplication::`activate()` signal being emitted in the primary instance.

The application must be registered before calling this function.

`application` : | a GApplication

Since 2.28

### g_application_open ()

    void                g_application_open                  (GApplication *application,
                                                             GFile **files,
                                                             gint n_files,
                                                             const gchar *hint);

Opens the given files.

In essence, this results in the "open" signal being emitted in the primary instance.

`n_files` must be greater than zero.

`hint` is simply passed through to the ::open signal. It is intended to be used by applications that have multiple modes for opening files (eg: "view" vs "edit", etc). Unless you have a need for this functionality, you should use "".

The application must be registered before calling this function and it must have the `G_APPLICATION_HANDLES_OPEN` flag set.

`application` : | a GApplication
`files` : | an array of GFiles to open. [array length=n_files]
`n_files` : | the length of the `files` array
`hint` : | a hint (or ""), but never `NULL`

Since 2.28

### g_application_run ()

    int                 g_application_run                   (GApplication *application,
                                                             int argc,
                                                             char **argv);

Runs the application.

This function is intended to be run from `main()` and its return value is intended to be returned by `main()`.

First, the `local_command_line()` virtual function is invoked. This function always runs on the local instance. If that function returns `FALSE` then the application is registered and the "command-line" signal is emitted in the primary instance (which may or may not be this instance).

If the application has the `G_APPLICATION_HANDLES_COMMAND_LINE` flag set then the default implementation of `local_command_line()` always returns `FALSE` immediately, resulting in the commandline always being handled in the primary instance.

Otherwise, the default implementation of `local_command_line()` tries to do a couple of things that are probably reasonable for most applications. First, `g_application_register()` is called to attempt to register the application. If that works, then the command line arguments are inspected. If no commandline arguments are given, then `g_application_activate()` is called. If commandline arguments are given and the `G_APPLICATION_HANDLES_OPEN` flag is set then they are assumed to be filenames and `g_application_open()` is called.

If you are interested in doing more complicated local handling of the commandline then you should implement your own GApplication subclass and override `local_command_line()`. See Example 16, “Complicated commandline handling” for an example.

If, after the above is done, the use count of the application is zero then the exit status is returned immediately. If the use count is non-zero then the mainloop is run until the use count falls to zero, at which point 0 is returned.

If the `G_APPLICATION_IS_SERVICE` flag is set, then the exiting at use count of zero is delayed for a while (ie: the instance stays around to provide its service to others).

`application` : | a GApplication
`argc` : | the argc from `main()`
`argv` : | the argv from `main()`. [array length=argc]
Returns : | the exit status

Since 2.28

## Property Details

### The `"action-group"` property

      "action-group"             GActionGroup*         : Write

The group of actions that the application exports.

### The `"application-id"` property

      "application-id"           gchar*                : Read / Write / Construct

The unique identifier for the application.

Default value: NULL

### The `"flags"` property

      "flags"                    GApplicationFlags     : Read / Write

Flags specifying the behaviour of the application.

### The `"inactivity-timeout"` property

      "inactivity-timeout"       guint                 : Read / Write

Iime (ms) to stay alive after becoming idle.

Default value: 0

### The `"is-registered"` property

      "is-registered"            gboolean              : Read

If g_application_register() has been called.

Default value: FALSE

### The `"is-remote"` property

      "is-remote"                gboolean              : Read

If this application instance is remote.

Default value: FALSE

## Signal Details

### The `"activate"` signal

    void                user_function                      (GApplication *application,
                                                            gpointer      user_data)        : Run Last

The ::activate signal is emitted on the primary instance when an activation occurs. See `g_application_activate()`.

`application` : | the application
`user_data` : | user data set when the signal handler was connected.

### The `"command-line"` signal

    gint                user_function                      (GApplication            *application,
                                                            GApplicationCommandLine *command_line,
                                                            gpointer                 user_data)         : Run Last

The ::command-line signal is emitted on the primary instance when a commandline is not handled locally. See `g_application_run()` for more information.

`application` : | the application
`command_line` : | a GApplicationCommandLine representing the passed commandline
`user_data` : | user data set when the signal handler was connected.

### The `"open"` signal

    void                user_function                      (GApplication *application,
                                                            gpointer      files,
                                                            gint          n_files,
                                                            gchar        *hint,
                                                            gpointer      user_data)        : Run Last

The ::open signal is emitted on the primary instance when there are files to open. See `g_application_open()` for more information.

`application` : | the application
`files` : | an array of GFiles. [array length=n_files][element-type GFile]
`n_files` : | the length of `files`
`hint` : | a hint provided by the calling instance
`user_data` : | user data set when the signal handler was connected.

### The `"startup"` signal

    void                user_function                      (GApplication *application,
                                                            gpointer      user_data)        : Run Last

The ::startup signal is emitted on the primary instance immediately after registration. See `g_activation_register()`.

`application` : | the application
`user_data` : | user data set when the signal handler was connected.