Class Application
- All Implemented Interfaces:
ActionGroup,ActionMap,Proxy
- Direct Known Subclasses:
Application
GApplication is the core class for application support.
A GApplication is the foundation of an application. It 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.
GApplication provides convenient life-cycle management by maintaining
a "use count" for the primary application instance. The use count can
be changed using hold() and
release(). If it drops to zero, the application
exits. Higher-level classes such as GtkApplication employ the use count
to ensure that the application stays alive as long as it has any opened
windows.
Another feature that GApplication (optionally) provides is process
uniqueness. Applications can make use of this functionality by
providing a unique application ID. If given, only one application
with this ID can be running at a time per 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"; for non-unique applications this is
always the current instance. On Linux, the D-Bus session bus
is used for communication.
The use of GApplication differs from some other commonly-used
uniqueness libraries (such as libunique) in important ways. The
application is not expected to manually register itself and check
if it is the primary instance. Instead, the main() function of a
GApplication should do very little more than instantiating the
application instance, possibly connecting signal handlers, then
calling run(java.lang.String[]). All checks for uniqueness are done
internally. If the application is the primary instance then the
startup signal is emitted and the mainloop runs. If the application
is not the primary instance then a signal is sent to the primary
instance and run(java.lang.String[]) promptly returns. See the code
examples below.
If used, the expected form of an application identifier is the
same as that of a
D-Bus well-known bus name.
Examples include: com.example.MyApp, org.example.internal_apps.Calculator,
org._7_zip.Archiver.
For details on valid application identifiers, see idIsValid(java.lang.String).
On Linux, the application identifier is claimed 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
register(org.gnome.gio.Cancellable)). Unfortunately, this means that you cannot
use Gio.Application:is-remote to decide if you want to register
object paths.
GApplication also implements the ActionGroup and ActionMap
interfaces and lets you easily export actions by adding them with
ActionMap.addAction(org.gnome.gio.Action). When invoking an action by calling
ActionGroup.activateAction(java.lang.String, org.gnome.glib.Variant) on the application, it is always
invoked in the primary instance. The actions are also exported on
the session bus, and GIO provides the DBusActionGroup wrapper to
conveniently access them remotely. GIO provides a DBusMenuModel wrapper
for remote access to exported MenuModels.
Note: Due to the fact that actions are exported on the session bus,
using maybe parameters is not supported, since D-Bus does not support
maybe types.
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)
- by handling a command-line
- via activating an action
The Gio.Application::startup signal lets you handle the application
initialization for all of these in a single place.
Regardless of which of these entry points is used to start the
application, GApplication passes some ‘platform data’ from the
launching instance to the primary instance, in the form of a
GLib.Variant dictionary mapping strings to variants. To use platform
data, override the beforeEmit(org.gnome.glib.Variant) or
afterEmit(org.gnome.glib.Variant) virtual functions
in your GApplication subclass. When dealing with
ApplicationCommandLine objects, the platform data is
directly available via ApplicationCommandLine.getCwd(),
ApplicationCommandLine.getEnviron() and
ApplicationCommandLine.getPlatformData().
As the name indicates, the platform data may vary depending on the
operating system, but it always includes the current directory (key
cwd), and optionally the environment (ie the set of environment
variables and their values) of the calling process (key environ).
The environment is only added to the platform data if the
G_APPLICATION_SEND_ENVIRONMENT flag is set. GApplication subclasses
can add their own platform data by overriding the
addPlatformData(org.gnome.glib.VariantBuilder) virtual function. For instance,
GtkApplication adds startup notification data in this way.
To parse commandline arguments you may handle the
Gio.Application::command-line signal or override the
localCommandLine(org.javagi.base.Out<java.lang.String[]>, org.javagi.base.Out<java.lang.Integer>) virtual function, to parse them in
either the primary instance or the local instance, respectively.
For an example of opening files with a GApplication, see
gapplication-example-open.c.
For an example of using actions with GApplication, see
gapplication-example-actions.c.
For an example of using extra D-Bus hooks with GApplication, see
gapplication-example-dbushooks.c.
- Since:
- 2.28
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceFunctional interface declaration of theActivateCallbackcallback.static classVirtual function table forGApplication.static classApplication.Builder<B extends Application.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static interfaceFunctional interface declaration of theCommandLineCallbackcallback.static interfaceFunctional interface declaration of theHandleLocalOptionsCallbackcallback.static interfaceFunctional interface declaration of theNameLostCallbackcallback.static interfaceFunctional interface declaration of theOpenCallbackcallback.static interfaceFunctional interface declaration of theShutdownCallbackcallback.static interfaceFunctional interface declaration of theStartupCallbackcallback.Nested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClassNested classes/interfaces inherited from interface org.gnome.gio.ActionGroup
ActionGroup.ActionAddedCallback, ActionGroup.ActionEnabledChangedCallback, ActionGroup.ActionGroup$Impl, ActionGroup.ActionGroupInterface, ActionGroup.ActionRemovedCallback, ActionGroup.ActionStateChangedCallbackNested classes/interfaces inherited from interface org.gnome.gio.ActionMap
ActionMap.ActionMap$Impl, ActionMap.ActionMapInterface -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new Application.Application(@Nullable String applicationId, Set<ApplicationFlags> flags) Creates a newGApplicationinstance.Application(@Nullable String applicationId, ApplicationFlags... flags) Creates a newGApplicationinstance.Application(MemorySegment address) Create a Application proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionvoidactivate()Activates the application.voidaddMainOption(String longName, byte shortName, Set<OptionFlags> flags, OptionArg arg, String description, @Nullable String argDescription) Add an option to be handled byapplication.voidaddMainOption(String longName, byte shortName, OptionFlags flags, OptionArg arg, String description, @Nullable String argDescription) Add an option to be handled byapplication.voidaddMainOptionEntries(@Nullable OptionEntry @Nullable [] entries) Adds main option entries to be handled byapplication.voidaddOptionGroup(OptionGroup group) Adds aGOptionGroupto the commandline handling ofapplication.protected voidaddPlatformData(VariantBuilder builder) invoked (locally) to add 'platform data' to be sent to the primary instance when activating, opening or invoking actions.protected voidinvoked on the primary instance after 'activate', 'open', 'command-line' or any action invocation, gets the 'platform data' from the calling instance.protected ApplicationasParent()Returns this instance as if it were its parent type.protected voidbeforeEmit(Variant platformData) invoked on the primary instance before 'activate', 'open', 'command-line' or any action invocation, gets the 'platform data' from the calling instance.voidbindBusyProperty(GObject object, String property) Marks this Application as busy (see g_application_mark_busy()) whilepropertyonobjectistrue.static Application.Builder<? extends Application.Builder> builder()AApplication.Builderobject constructs aApplicationwith the specified properties.protected intcommandLine(ApplicationCommandLine commandLine) invoked on the primary instance when a command-line is not handled locallyprotected booleandbusRegister(DBusConnection connection, String objectPath) invoked locally during registration, if the application is using its D-Bus backend.protected voiddbusUnregister(DBusConnection connection, String objectPath) invoked locally during unregistration, if the application is using its D-Bus backend.voidEmits the "activate" signal.intemitCommandLine(@Nullable ApplicationCommandLine commandLine) Emits the "command-line" signal.intemitHandleLocalOptions(@Nullable VariantDict options) Emits the "handle-local-options" signal.booleanEmits the "name-lost" signal.voidEmits the "open" signal.voidEmits the "shutdown" signal.voidEmits the "startup" signal.@Nullable StringGets the unique identifier forapplication.@Nullable DBusConnectionGets theGDBusConnectionbeing used by the application, ornull.@Nullable StringGets the D-Bus object path being used by the application, ornull.static @Nullable ApplicationReturns the defaultGApplicationinstance for this process.getFlags()Gets the flags forapplication.intGets the current inactivity timeout for the application.booleanGets the application's current busy state, as set through g_application_mark_busy() or g_application_bind_busy_property().booleanChecks if this Application is registered.booleanChecks if this Application is remote.static MemoryLayoutThe memory layout of the native struct.@Nullable StringGets the resource base path ofapplication.static @Nullable TypegetType()Get the GType of the Application class@Nullable StringGets the version ofapplication.protected inthandleLocalOptions(VariantDict options) invoked locally after the parsing of the commandline options has occurred.voidhold()Increases the use count ofapplication.static booleanChecks ifapplicationIdis a valid application identifier.protected booleanlocalCommandLine(@Nullable Out<String[]> arguments, Out<Integer> exitStatus) This virtual function is always invoked in the local instance.voidmarkBusy()Increases the busy count ofapplication.protected booleannameLost()invoked when another instance is taking over the name.onActivate(Application.ActivateCallback handler) The ::activate signal is emitted on the primary instance when an activation occurs.The ::command-line signal is emitted on the primary instance when a commandline is not handled locally.The ::handle-local-options signal is emitted on the local instance after the parsing of the commandline options has occurred.onNameLost(Application.NameLostCallback handler) The ::name-lost signal is emitted only on the registered primary instance when a new instance has taken over.onOpen(Application.OpenCallback handler) The ::open signal is emitted on the primary instance when there are files to open.onShutdown(Application.ShutdownCallback handler) The ::shutdown signal is emitted only on the registered primary instance immediately after the main loop terminates.onStartup(Application.StartupCallback handler) The ::startup signal is emitted on the primary instance immediately after registration.voidOpens the given files.voidquit()Immediately quits the application.protected voidUsed to be invoked on the primary instance when the use count of the application drops to zero (and after any inactivity timeout, if requested).booleanregister(@Nullable Cancellable cancellable) Attempts registration of the application.voidrelease()Decrease the use count ofapplication.intRuns the application.protected voidUsed to be invoked on the primary instance from g_application_run() if the use-count is non-zero.voidsendNotification(@Nullable String id, Notification notification) Sends a notification on behalf of this Application to the desktop shell.voidsetActionGroup(@Nullable ActionGroup actionGroup) Deprecated.voidsetApplicationId(@Nullable String applicationId) Sets the unique identifier forapplication.voidSets or unsets the default application for the process, as returned by g_application_get_default().voidsetFlags(Set<ApplicationFlags> flags) Sets the flags forapplication.voidsetFlags(ApplicationFlags... flags) Sets the flags forapplication.voidsetInactivityTimeout(int inactivityTimeout) Sets the current inactivity timeout for the application.voidsetOptionContextDescription(@Nullable String description) Adds a description to the this Application option context.voidsetOptionContextParameterString(@Nullable String parameterString) Sets the parameter string to be used by the commandline handling ofapplication.voidsetOptionContextSummary(@Nullable String summary) Adds a summary to the this Application option context.voidsetResourceBasePath(@Nullable String resourcePath) Sets (or unsets) the base resource path ofapplication.voidsetVersion(String version) Sets the version number ofapplication.This will be used to implement a--versioncommand line argumentprotected voidshutdown()invoked only on the registered primary instance immediately after the main loop terminatesprotected voidstartup()invoked on the primary instance immediately after registrationvoidunbindBusyProperty(GObject object, String property) Destroys a binding betweenpropertyand the busy state of this Application that was previously created with g_application_bind_busy_property().voidDecreases the busy count ofapplication.voidWithdraws a notification that was sent with g_application_send_notification().Methods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCodeMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.gnome.gio.ActionGroup
actionAdded, actionEnabledChanged, actionRemoved, actionStateChanged, activateAction, changeActionState, emitActionAdded, emitActionEnabledChanged, emitActionRemoved, emitActionStateChanged, getActionEnabled, getActionParameterType, getActionState, getActionStateHint, getActionStateType, hasAction, listActions, onActionAdded, onActionEnabledChanged, onActionRemoved, onActionStateChanged, queryActionMethods inherited from interface org.gnome.gio.ActionMap
addAction, addActionEntries, lookupAction, removeAction, removeActionEntries
-
Constructor Details
-
Application
Create a Application proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
Application
Creates a newGApplicationinstance.If non-
null, the application id must be valid. See g_application_id_is_valid().If no application ID is given then some features of
GApplication(most notably application uniqueness) will be disabled.- Parameters:
applicationId- the application idflags- the application flags
-
Application
Creates a newGApplicationinstance.If non-
null, the application id must be valid. See g_application_id_is_valid().If no application ID is given then some features of
GApplication(most notably application uniqueness) will be disabled.- Parameters:
applicationId- the application idflags- the application flags
-
Application
public Application()Creates a new Application.
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type. -
getDefault
Returns the defaultGApplicationinstance for this process.Normally there is only one
GApplicationper process and it becomes the default when it is created. You can exercise more control over this by using g_application_set_default().If there is no default application then
nullis returned.- Returns:
- the default application for this process, or
null - Since:
- 2.32
-
idIsValid
Checks ifapplicationIdis a valid application identifier.A valid ID is required for calls to g_application_new() and g_application_set_application_id().
Application identifiers follow the same format as D-Bus well-known bus names. For convenience, the restrictions on application identifiers are reproduced here:
- Application identifiers are composed of 1 or more elements separated by a
period (
.) character. All elements must contain at least one character.
- Each element must only contain the ASCII characters
[A-Z][a-z][0-9]_-, with-discouraged in new application identifiers. Each element 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 exceed 255 characters.
Note that the hyphen (
-) character is allowed in application identifiers, but is problematic or not allowed in various specifications and APIs that refer to D-Bus, such as Flatpak application IDs, theDBusActivatableinterface in the Desktop Entry Specification, and the convention that an application's "main" interface and object path resemble its application identifier and bus name. To avoid situations that require special-case handling, it is recommended that new application identifiers consistently replace hyphens with underscores.Like D-Bus interface names, application identifiers should start with the reversed DNS domain name of the author of the interface (in lower-case), and it is conventional for the rest of the application identifier to consist of words run together, with initial capital letters.
As with D-Bus interface names, if the author's DNS domain name contains hyphen/minus characters they should be replaced by underscores, and if it contains leading digits they should be escaped by prepending an underscore. For example, if the owner of 7-zip.org used an application identifier for an archiving application, it might be named
org._7_zip.Archiver.- Parameters:
applicationId- a potential application identifier- Returns:
trueifapplicationIdis valid
- Application identifiers are composed of 1 or more elements separated by a
period (
-
activate
public void activate()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.
- Since:
- 2.28
-
addMainOption
public void addMainOption(String longName, byte shortName, Set<OptionFlags> flags, OptionArg arg, String description, @Nullable String argDescription) Add an option to be handled byapplication.Calling this function is the equivalent of calling g_application_add_main_option_entries() with a single
GOptionEntrythat has its arg_data member set tonull.The parsed arguments will be packed into a
GVariantDictwhich is passed toGApplication::handle-local-options. IfApplicationFlags.HANDLES_COMMAND_LINEis set, then it will also be sent to the primary instance. See g_application_add_main_option_entries() for more details.See
GOptionEntryfor more documentation of the arguments.- Parameters:
longName- the long name of an option used to specify it in a commandlineshortName- the short name of an optionflags- flags fromGOptionFlagsarg- the type of the option, as aGOptionArgdescription- the description for the option in--helpoutputargDescription- the placeholder to use for the extra argument parsed by the option in--helpoutput- Since:
- 2.42
-
addMainOption
public void addMainOption(String longName, byte shortName, OptionFlags flags, OptionArg arg, String description, @Nullable String argDescription) Add an option to be handled byapplication.Calling this function is the equivalent of calling g_application_add_main_option_entries() with a single
GOptionEntrythat has its arg_data member set tonull.The parsed arguments will be packed into a
GVariantDictwhich is passed toGApplication::handle-local-options. IfApplicationFlags.HANDLES_COMMAND_LINEis set, then it will also be sent to the primary instance. See g_application_add_main_option_entries() for more details.See
GOptionEntryfor more documentation of the arguments.- Parameters:
longName- the long name of an option used to specify it in a commandlineshortName- the short name of an optionflags- flags fromGOptionFlagsarg- the type of the option, as aGOptionArgdescription- the description for the option in--helpoutputargDescription- the placeholder to use for the extra argument parsed by the option in--helpoutput- Since:
- 2.42
-
addMainOptionEntries
Adds main option entries to be handled byapplication.This function is comparable to g_option_context_add_main_entries().
After the commandline arguments are parsed, the
GApplication::handle-local-options signal will be emitted. At this point, the application can inspect the values pointed to byargDatain the givenGOptionEntrys.Unlike
GOptionContext,GApplicationsupports giving anullargDatafor a non-callbackGOptionEntry. This results in the argument in question being packed into aGVariantDictwhich is also passed toGApplication::handle-local-options, where it can be inspected and modified. IfApplicationFlags.HANDLES_COMMAND_LINEis set, then the resulting dictionary is sent to the primary instance, where g_application_command_line_get_options_dict() will return it. As it has been passed outside the process at this point, the types of all values in the options dict must be checked before being used. This "packing" is done according to the type of the argument -- booleans for normal flags, strings for strings, bytestrings for filenames, etc. The packing only occurs if the flag is given (ie: we do not pack a "false"GVariantin the case that a flag is missing).In general, it is recommended that all commandline arguments are parsed locally. The options dictionary should then be used to transmit the result of the parsing to the primary instance, where g_variant_dict_lookup() can be used. For local options, it is possible to either use
argDatain the usual way, or to consult (and potentially remove) the option from the options dictionary.This function is new in GLib 2.40. Before then, the only real choice was to send all of the commandline arguments (options and all) to the primary instance for handling.
GApplicationignored them completely on the local side. Calling this function "opts in" to the new behaviour, and in particular, means that unrecognized options will be treated as errors. Unrecognized options have never been ignored whenApplicationFlags.HANDLES_COMMAND_LINEis unset.If
GApplication::handle-local-options needs to see the list of filenames, then the use ofG_OPTION_REMAININGis recommended. IfargDataisnullthenG_OPTION_REMAININGcan be used as a key into the options dictionary. If you do useG_OPTION_REMAININGthen you need to handle these arguments for yourself because once they are consumed, they will no longer be visible to the default handling (which treats them as filenames to be opened).It is important to use the proper GVariant format when retrieving the options with g_variant_dict_lookup():
- for
OptionArg.NONE, useb - for
OptionArg.STRING, use&s - for
OptionArg.INT, usei - for
OptionArg.INT64, usex - for
OptionArg.DOUBLE, used - for
OptionArg.FILENAME, use^&ay - for
OptionArg.STRING_ARRAY, use^a&s - for
OptionArg.FILENAME_ARRAY, use^a&ay
- Parameters:
entries- the main options for the application- Since:
- 2.40
- for
-
addOptionGroup
Adds aGOptionGroupto the commandline handling ofapplication.This function is comparable to g_option_context_add_group().
Unlike g_application_add_main_option_entries(), this function does not deal with
nullargDataand never transmits options to the primary instance.The reason for that is because, by the time the options arrive at the primary instance, it is typically too late to do anything with them. Taking the GTK option group as an example: GTK will already have been initialised by the time the
GApplication::command-line handler runs. In the case that this is not the first-running instance of the application, the existing instance may already have been running for a very long time.This means that the options from
GOptionGroupare only really usable in the case that the instance of the application being run is the first instance. Passing options like--display=or--gdk-debug=on future runs will have no effect on the existing primary instance.Calling this function will cause the options in the supplied option group to be parsed, but it does not cause you to be "opted in" to the new functionality whereby unrecognized options are rejected even if
ApplicationFlags.HANDLES_COMMAND_LINEwas given.- Parameters:
group- aGOptionGroup- Since:
- 2.40
-
bindBusyProperty
Marks this Application as busy (see g_application_mark_busy()) whilepropertyonobjectistrue.The binding holds a reference to this Application while it is active, but not to
object.Instead, the binding is destroyed whenobjectis finalized.- Parameters:
object- aGObjectproperty- the name of a boolean property ofobject- Since:
- 2.44
-
getApplicationId
Gets the unique identifier forapplication.- Returns:
- the identifier for
application,owned by this Application - Since:
- 2.28
-
getDbusConnection
Gets theGDBusConnectionbeing used by the application, ornull.If
GApplicationis using its D-Bus backend then this function will return theGDBusConnectionbeing used for uniqueness and communication with the desktop environment and other instances of the application.If
GApplicationis not using D-Bus then this function will returnnull. This includes the situation where the D-Bus backend would normally be in use but we were unable to connect to the bus.This function must not be called before the application has been registered. See g_application_get_is_registered().
- Returns:
- a
GDBusConnection, ornull - Since:
- 2.34
-
getDbusObjectPath
Gets the D-Bus object path being used by the application, ornull.If
GApplicationis using its D-Bus backend then this function will return the D-Bus object path thatGApplicationis using. If the application is the primary instance then there is an object published at this path. If the application is not the primary instance then the result of this function is undefined.If
GApplicationis not using D-Bus then this function will returnnull. This includes the situation where the D-Bus backend would normally be in use but we were unable to connect to the bus.This function must not be called before the application has been registered. See g_application_get_is_registered().
- Returns:
- the object path, or
null - Since:
- 2.34
-
getFlags
Gets the flags forapplication.See
GApplicationFlags.- Returns:
- the flags for this Application
- Since:
- 2.28
-
getInactivityTimeout
public int getInactivityTimeout()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.
- Returns:
- the timeout, in milliseconds
- Since:
- 2.28
-
getIsBusy
public boolean getIsBusy()Gets the application's current busy state, as set through g_application_mark_busy() or g_application_bind_busy_property().- Returns:
trueif this Application is currently marked as busy- Since:
- 2.44
-
getIsRegistered
public boolean getIsRegistered()Checks if this Application is registered.An application is registered if g_application_register() has been successfully called.
- Returns:
trueif this Application is registered- Since:
- 2.28
-
getIsRemote
public boolean getIsRemote()Checks if this Application is remote.If this Application is remote then it means that another instance of application already exists (the 'primary' instance). Calls to perform actions on this Application will result in the actions being performed by the primary instance.
The value of this property cannot be accessed before g_application_register() has been called. See g_application_get_is_registered().
- Returns:
trueif this Application is remote- Since:
- 2.28
-
getResourceBasePath
Gets the resource base path ofapplication.See g_application_set_resource_base_path() for more information.
- Returns:
- the base resource path, if one is set
- Since:
- 2.42
-
getVersion
Gets the version ofapplication.- Returns:
- the version of this Application
- Since:
- 2.80
-
hold
public void hold()Increases the use count ofapplication.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().
-
markBusy
public void markBusy()Increases the busy count ofapplication.Use this function to indicate that the application is busy, for instance while a long running operation is pending.
The busy state will be exposed to other processes, so a session shell will use that information to indicate the state to the user (e.g. with a spinner).
To cancel the busy indication, use g_application_unmark_busy().
The application must be registered before calling this function.
- Since:
- 2.38
-
open
Opens the given files.In essence, this results in the
GApplication::open signal being emitted in the primary instance.nFilesmust be greater than zero.hintis 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
ApplicationFlags.HANDLES_OPENflag set.- Parameters:
files- an array ofGFilesto openhint- a hint (or ""), but nevernull- Since:
- 2.28
-
quit
public void quit()Immediately quits the application.Upon return to the mainloop, g_application_run() will return, calling only the 'shutdown' function before doing so.
The hold count is ignored. Take care if your code has called g_application_hold() on the application and is therefore still expecting it to exist. (Note that you may have called g_application_hold() indirectly, for example through gtk_application_add_window().)
The result of calling g_application_run() again after it returns is unspecified.
- Since:
- 2.32
-
register
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 unique bus name on the session bus using GDBus.
If there is no application ID or if
ApplicationFlags.NON_UNIQUEwas given, then this process will always become the primary instance.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
trueis returned with no work performed.The
GApplication::startup signal is emitted if registration succeeds and this Application is the primary instance (including the non-unique case).In the event of an error (such as
cancellablebeing cancelled, or a failure to connect to the session bus),falseis returned anderroris 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.
- Parameters:
cancellable- aGCancellable, ornull- Returns:
trueif registration succeeded- Throws:
GErrorException- seeGError- Since:
- 2.28
-
release
public void release()Decrease the use count ofapplication.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().
-
run
Runs the application.This function is intended to be run from main() and its return value is intended to be returned by main(). Although you are expected to pass the
argc,argvparameters from main() to this function, it is possible to passnullifargvis not available or commandline handling is not required. Note that on Windows,argcandargvare ignored, and g_win32_get_command_line() is called internally (for proper support of Unicode commandline arguments).GApplicationwill attempt to parse the commandline arguments. You can add commandline flags to the list of recognised options by way of g_application_add_main_option_entries(). After this, theGApplication::handle-local-options signal is emitted, from which the application can inspect the values of itsGOptionEntrys.GApplication::handle-local-options is a good place to handle options such as--version, where an immediate reply from the local process is desired (instead of communicating with an already-running instance). AGApplication::handle-local-options handler can stop further processing by returning a non-negative value, which then becomes the exit status of the process.What happens next depends on the flags: if
ApplicationFlags.HANDLES_COMMAND_LINEwas specified then the remaining commandline arguments are sent to the primary instance, where aGApplication::command-line signal is emitted. Otherwise, the remaining commandline arguments are assumed to be a list of files. If there are no files listed, the application is activated via theGApplication::activate signal. If there are one or more files, andApplicationFlags.HANDLES_OPENwas specified then the files are opened via theGApplication::open signal.If you are interested in doing more complicated local handling of the commandline then you should implement your own
GApplicationsubclass and override local_command_line(). In this case, you most likely want to returntruefrom your local_command_line() implementation to suppress the default handling. See [gapplication-example-cmdline2.c][https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gapplication-example-cmdline2.c] 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 default main context is iterated until the use count falls to zero, at which point 0 is returned.
If the
ApplicationFlags.IS_SERVICEflag is set, then the service will run for as much as 10 seconds with a use count of zero while waiting for the message that caused the activation to arrive. After that, if the use count falls to zero the application will exit immediately, except in the case that g_application_set_inactivity_timeout() is in use.This function sets the prgname (g_set_prgname()), if not already set, to the basename of argv[0].
Much like g_main_loop_run(), this function will acquire the main context for the duration that the application is running.
Since 2.40, applications that are not explicitly flagged as services or launchers (ie: neither
ApplicationFlags.IS_SERVICEorApplicationFlags.IS_LAUNCHERare given as flags) will check (from the default handler for local_command_line) if "--gapplication-service" was given in the command line. If this flag is present then normal commandline processing is interrupted and theApplicationFlags.IS_SERVICEflag is set. This provides a "compromise" solution whereby running an application directly from the commandline will invoke it in the normal way (which can be useful for debugging) while still allowing applications to be D-Bus activated in service mode. The D-Bus service file should invoke the executable with "--gapplication-service" as the sole commandline argument. This approach is suitable for use by most graphical applications but should not be used from applications like editors that need precise control over when processes invoked via the commandline will exit and what their exit status will be.- Parameters:
argv- the argv from main(), ornull- Returns:
- the exit status
- Since:
- 2.28
-
sendNotification
Sends a notification on behalf of this Application to the desktop shell. There is no guarantee that the notification is displayed immediately, or even at all.Notifications may persist after the application exits. It will be D-Bus-activated when the notification or one of its actions is activated.
Modifying
notificationafter this call has no effect. However, the object can be reused for a later call to this function.idmay be any string that uniquely identifies the event for the application. It does not need to be in any special format. For example, "new-message" might be appropriate for a notification about new messages.If a previous notification was sent with the same
id,it will be replaced withnotificationand shown again as if it was a new notification. This works even for notifications sent from a previous execution of the application, as long asidis the same string.idmay beNULL, but it is impossible to replace or withdraw notifications without an id.If
notificationis no longer relevant, it can be withdrawn withwithdrawNotification(java.lang.String).It is an error to call this function if this Application has no application ID.
- Parameters:
id- id of the notification, ornullnotification- theGNotificationto send- Since:
- 2.40
-
setActionGroup
Deprecated.Use theGActionMapinterface instead. Never ever mix use of this API with use ofGActionMapon the same this Application or things will go very badly wrong. This function is known to introduce buggy behaviour (ie: signals not emitted on changes to the action group), so you should really useGActionMapinstead.This used to be how actions were associated with aGApplication. Now there isGActionMapfor that.- Parameters:
actionGroup- aGActionGroup, ornull- Since:
- 2.28
-
setApplicationId
Sets the unique identifier forapplication.The application id can only be modified if this Application has not yet been registered.
If non-
null, the application id must be valid. See g_application_id_is_valid().- Parameters:
applicationId- the identifier for this Application- Since:
- 2.28
-
setDefault
public void setDefault()Sets or unsets the default application for the process, as returned by g_application_get_default().This function does not take its own reference on
application.If this Application is destroyed then the default application will revert back tonull.- Since:
- 2.32
-
setFlags
Sets the flags forapplication.The flags can only be modified if this Application has not yet been registered.
See
GApplicationFlags.- Parameters:
flags- the flags for this Application- Since:
- 2.28
-
setFlags
Sets the flags forapplication.The flags can only be modified if this Application has not yet been registered.
See
GApplicationFlags.- Parameters:
flags- the flags for this Application- Since:
- 2.28
-
setInactivityTimeout
public void setInactivityTimeout(int inactivityTimeout) 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.
- Parameters:
inactivityTimeout- the timeout, in milliseconds- Since:
- 2.28
-
setOptionContextDescription
Adds a description to the this Application option context.See g_option_context_set_description() for more information.
- Parameters:
description- a string to be shown in--helpoutput after the list of options, ornull- Since:
- 2.56
-
setOptionContextParameterString
Sets the parameter string to be used by the commandline handling ofapplication.This function registers the argument to be passed to g_option_context_new() when the internal
GOptionContextof this Application is created.See g_option_context_new() for more information about
parameterString.- Parameters:
parameterString- a string which is displayed in the first line of--helpoutput, after the usage summaryprogramname [OPTION...].- Since:
- 2.56
-
setOptionContextSummary
Adds a summary to the this Application option context.See g_option_context_set_summary() for more information.
- Parameters:
summary- a string to be shown in--helpoutput before the list of options, ornull- Since:
- 2.56
-
setResourceBasePath
Sets (or unsets) the base resource path ofapplication.The path is used to automatically load various
Gio.Resourcesuch as menu layouts and action descriptions. The various types of resources will be found at fixed names relative to the given base path.By default, the resource base path is determined from the application ID by prefixing '/' and replacing each '.' with '/'. This is done at the time that the
GApplicationobject is constructed. Changes to the application ID after that point will not have an impact on the resource base path.As an example, if the application has an ID of "org.example.app" then the default resource base path will be "/org/example/app". If this is a
GtkApplication(and you have not manually changed the path) then Gtk will then search for the menus of the application at "/org/example/app/gtk/menus.ui".See
GResourcefor more information about adding resources to your application.You can disable automatic resource loading functionality by setting the path to
null.Changing the resource base path once the application is running is not recommended. The point at which the resource path is consulted for forming paths for various purposes is unspecified. When writing a sub-class of
GApplicationyou should either set theGApplication:resource-base-path property at construction time, or call this function during the instance initialization. Alternatively, you can call this function in theGApplicationClass.startup virtual function, before chaining up to the parent implementation.- Parameters:
resourcePath- the resource path to use- Since:
- 2.42
-
setVersion
Sets the version number ofapplication.This will be used to implement a--versioncommand line argumentThe application version can only be modified if this Application has not yet been registered.
- Parameters:
version- the version of this Application- Since:
- 2.80
-
unbindBusyProperty
Destroys a binding betweenpropertyand the busy state of this Application that was previously created with g_application_bind_busy_property().- Parameters:
object- aGObjectproperty- the name of a boolean property ofobject- Since:
- 2.44
-
unmarkBusy
public void unmarkBusy()Decreases the busy count ofapplication.When the busy count reaches zero, the new state will be propagated to other processes.
This function must only be called to cancel the effect of a previous call to g_application_mark_busy().
- Since:
- 2.38
-
withdrawNotification
Withdraws a notification that was sent with g_application_send_notification().This call does nothing if a notification with
iddoesn't exist or the notification was never sent.This function works even for notifications sent in previous executions of this application, as long
idis the same as it was for the sent notification.Note that notifications are dismissed when the user clicks on one of the buttons in a notification or triggers its default action, so there is no need to explicitly withdraw the notification in that case.
- Parameters:
id- id of a previously sent notification- Since:
- 2.40
-
addPlatformData
invoked (locally) to add 'platform data' to be sent to the primary instance when activating, opening or invoking actions. Must chain up -
afterEmit
invoked on the primary instance after 'activate', 'open', 'command-line' or any action invocation, gets the 'platform data' from the calling instance. Must chain up -
beforeEmit
invoked on the primary instance before 'activate', 'open', 'command-line' or any action invocation, gets the 'platform data' from the calling instance. Must chain up -
commandLine
invoked on the primary instance when a command-line is not handled locally -
dbusRegister
invoked locally during registration, if the application is using its D-Bus backend. You can use this to export extra objects on the bus, that need to exist before the application tries to own the bus name. The function is passed theGDBusConnectionto to session bus, and the object path thatGApplicationwill use to export its D-Bus API. If this function returnstrue, registration will proceed; otherwise registration will abort. Since: 2.34- Throws:
GErrorException- seeGError
-
dbusUnregister
invoked locally during unregistration, if the application is using its D-Bus backend. Use this to undo anything done by thedbusRegistervfunc. Since: 2.34 -
handleLocalOptions
invoked locally after the parsing of the commandline options has occurred. Since: 2.40 -
localCommandLine
This virtual function is always invoked in the local instance. It gets passed a pointer to anull-terminated copy ofargvand is expected to remove arguments that it handled (shifting up remaining arguments).The last argument to local_command_line() is a pointer to the
statusvariable which can used to set the exit status that is returned from g_application_run().See g_application_run() for more details on
GApplicationstartup.- Parameters:
arguments- array of command line argumentsexitStatus- exit status to fill after processing the command line.- Returns:
trueif the commandline has been completely handled
-
nameLost
protected boolean nameLost()invoked when another instance is taking over the name. Since: 2.60 -
quitMainloop
protected void quitMainloop()Used to be invoked on the primary instance when the use count of the application drops to zero (and after any inactivity timeout, if requested). Not used anymore since 2.32 -
runMainloop
protected void runMainloop()Used to be invoked on the primary instance from g_application_run() if the use-count is non-zero. Since 2.32, GApplication is iterating the main context directly and is not usingrunMainloopanymore -
shutdown
protected void shutdown()invoked only on the registered primary instance immediately after the main loop terminates -
startup
protected void startup()invoked on the primary instance immediately after registration -
onActivate
public SignalConnection<Application.ActivateCallback> onActivate(Application.ActivateCallback handler) The ::activate signal is emitted on the primary instance when an activation occurs. See g_application_activate().- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitActivate
public void emitActivate()Emits the "activate" signal. SeeonActivate(org.gnome.gio.Application.ActivateCallback). -
onCommandLine
public SignalConnection<Application.CommandLineCallback> onCommandLine(Application.CommandLineCallback handler) The ::command-line signal is emitted on the primary instance when a commandline is not handled locally. See g_application_run() and theGApplicationCommandLinedocumentation for more information.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitCommandLine
Emits the "command-line" signal. SeeonCommandLine(org.gnome.gio.Application.CommandLineCallback). -
onHandleLocalOptions
public SignalConnection<Application.HandleLocalOptionsCallback> onHandleLocalOptions(Application.HandleLocalOptionsCallback handler) The ::handle-local-options signal is emitted on the local instance after the parsing of the commandline options has occurred.You can add options to be recognised during commandline option parsing using g_application_add_main_option_entries() and g_application_add_option_group().
Signal handlers can inspect
options(along with values pointed to from theargDataof an installedGOptionEntrys) in order to decide to perform certain actions, including direct local handling (which may be useful for options like --version).In the event that the application is marked
ApplicationFlags.HANDLES_COMMAND_LINEthe "normal processing" will send theoptionsdictionary to the primary instance where it can be read with g_application_command_line_get_options_dict(). The signal handler can modify the dictionary before returning, and the modified dictionary will be sent.In the event that
ApplicationFlags.HANDLES_COMMAND_LINEis not set, "normal processing" will treat the remaining uncollected command line arguments as filenames or URIs. If there are no arguments, the application is activated by g_application_activate(). One or more arguments results in a call to g_application_open().If you want to handle the local commandline arguments for yourself by converting them to calls to g_application_open() or g_action_group_activate_action() then you must be sure to register the application first. You should probably not call g_application_activate() for yourself, however: just return -1 and allow the default handler to do it for you. This will ensure that the
--gapplication-serviceswitch works properly (i.e. no activation in that case).Note that this signal is emitted from the default implementation of local_command_line(). If you override that function and don't chain up then this signal will never be emitted.
You can override local_command_line() if you need more powerful capabilities than what is provided here, but this should not normally be required.
- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- Since:
- 2.40
- See Also:
-
emitHandleLocalOptions
Emits the "handle-local-options" signal. SeeonHandleLocalOptions(org.gnome.gio.Application.HandleLocalOptionsCallback). -
onNameLost
public SignalConnection<Application.NameLostCallback> onNameLost(Application.NameLostCallback handler) The ::name-lost signal is emitted only on the registered primary instance when a new instance has taken over. This can only happen if the application is using theApplicationFlags.ALLOW_REPLACEMENTflag.The default handler for this signal calls g_application_quit().
- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- Since:
- 2.60
- See Also:
-
emitNameLost
public boolean emitNameLost()Emits the "name-lost" signal. SeeonNameLost(org.gnome.gio.Application.NameLostCallback). -
onOpen
The ::open signal is emitted on the primary instance when there are files to open. See g_application_open() for more information.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitOpen
Emits the "open" signal. SeeonOpen(org.gnome.gio.Application.OpenCallback). -
onShutdown
public SignalConnection<Application.ShutdownCallback> onShutdown(Application.ShutdownCallback handler) The ::shutdown signal is emitted only on the registered primary instance immediately after the main loop terminates.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitShutdown
public void emitShutdown()Emits the "shutdown" signal. SeeonShutdown(org.gnome.gio.Application.ShutdownCallback). -
onStartup
The ::startup signal is emitted on the primary instance immediately after registration. See g_application_register().- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitStartup
public void emitStartup()Emits the "startup" signal. SeeonStartup(org.gnome.gio.Application.StartupCallback). -
builder
AApplication.Builderobject constructs aApplicationwith the specified properties. Use the variousset...()methods to set properties, and finish construction withApplication.Builder.build().- Returns:
- the builder object
-
GActionMapinterface instead.