Calling Native APIs
Most generated methods take and return plain JavaScript values. Operations that finish later return promises, and a few native types, such as GTypes, GValues, variants and integers, follow the rules below.
Async operations
GTKX turns compatible GIR async/finish pairs into promise-returning methods. Await the method and handle failures with try/catch.
The promise resolves to what the finish function returns: one value directly, several as a tuple. When a finish function that can fail returns a success boolean along with output values, the promise drops the boolean, because failure rejects instead. For example, loadContentsAsync resolves to [contents, etag] and replaceContentsAsync to the new etag. A finish function that returns only a boolean still resolves to it, and calling a finish method such as loadContentsFinish yourself returns its full native tuple.
Check the generated signature for the libraries your project binds. Not every method ending in Async returns a promise. Some GIO operations, including the closure-based copyAsync and moveAsync, retain their callback form. GIR types their progress and ready handlers only as GObject.Closure, so annotate the parameters with the types the C documentation gives them; 64-bit integers such as the goffset byte counts of a progress handler arrive as bigint.
Awaiting async operations
Create the file dialog through JSX and keep its instance in a callback ref. The portal gives the non-widget object React ownership without placing it inside the button:
import type * as Gio from "@gtkx/gi/gio";
import * as Gtk from "@gtkx/gi/gtk";
import { GCancellable } from "@gtkx/jsx/gio";
import { GtkButton, GtkFileDialog } from "@gtkx/jsx/gtk";
import { createPortal, rootElement, useParentWindow } from "@gtkx/react";
import { useState } from "react";
type OpenButtonProps = {
onFile: (file: Gio.File) => void;
onError: (error: unknown) => void;
};
const OpenButton = ({ onFile, onError }: OpenButtonProps) => {
const parentWindow = useParentWindow();
const [dialog, setDialog] = useState<Gtk.FileDialog | null>(null);
const [cancellable, setCancellable] = useState<Gio.Cancellable | null>(
null,
);
const [cancellableGeneration, setCancellableGeneration] = useState(0);
const [isOpening, setIsOpening] = useState(false);
const open = async (
fileDialog: Gtk.FileDialog,
current: Gio.Cancellable,
) => {
setIsOpening(true);
try {
onFile(await fileDialog.open(parentWindow, current));
} catch (error) {
if (Gtk.DialogError.isDismissal(error)) {
return;
}
onError(error);
} finally {
setIsOpening(false);
setCancellableGeneration((generation) => generation + 1);
}
};
return (
<>
{createPortal(<GtkFileDialog ref={setDialog} />, rootElement)}
{createPortal(
<GCancellable
key={cancellableGeneration}
ref={setCancellable}
/>,
rootElement,
)}
<GtkButton
iconName="document-open-symbolic"
sensitive={
dialog !== null && cancellable !== null && !isOpening
}
onClicked={() => {
if (dialog && cancellable) void open(dialog, cancellable);
}}
/>
<GtkButton
iconName="process-stop-symbolic"
sensitive={isOpening && cancellable !== null}
onClicked={() => cancellable?.cancel()}
/>
</>
);
};Dismissing this dialog rejects with Gtk.DialogError.DISMISSED. Gtk.DialogError.isDismissal(error) recognizes that code and CANCELLED; for other expected outcomes, match the generated domain and code. Pass the remaining failures to the application's error handling. Outside production, the rejection's cause holds the stack of the call that started the operation, unless the error already has a cause.
Cancellation with Gio.Cancellable
Promisified methods retain their Gio.Cancellable argument.
Cancellation rejects the promise. GIO operations report Gio.IOErrorEnum.CANCELLED; GTK dialogs use Gtk.DialogError.CANCELLED.
A cancelled instance stays cancelled. Before starting another operation, replace its JSX element, for example by changing its key, and wait for the callback ref to receive the fresh instance. This also applies to an instance that an effect cleanup cancelled.
Callback-only methods and external finish owners
A method whose finish function codegen cannot pair stays callback-based, and its declaration names the annotated finish owner. Follow that library's async contract and finish the result on its actual owning instance; see Gio.AsyncResult for the native completion model.
Passing a GType
GTKX accepts a registered class wherever a binding takes a GType:
import * as GObject from "@gtkx/gi/gobject";
import * as Gtk from "@gtkx/gi/gtk";
const isWidget = GObject.typeIsA(Gtk.Label, Gtk.Widget);Generated classes and interfaces, and subclasses registered with registerClass, can be passed this way. A plain JavaScript subclass that skipped registerClass has no GType of its own, and passing it throws a TypeError. GTypes returned by bindings or passed to signal handlers remain bigint values.
Generated enumerations, flags and error domains whose type is registered with GObject can be passed the same way, and carry their GType as __type__, like classes. Reading it registers the type, so use it rather than GObject.typeFromName, which finds a type only once something has registered it. JSX props that take a GType accept the __type__ value:
import * as GObject from "@gtkx/gi/gobject";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwEnumListModel } from "@gtkx/jsx/adw";
const isEnum = GObject.typeIsA(Gtk.SortType, GObject.TYPE_ENUM);
const orders = <AdwEnumListModel enumType={Gtk.SortType.__type__} />;A GType that GObject rejects for a construct property, such as the 0n typeFromName returns for a type nobody registered, throws a RangeError instead of constructing the object without it.
Passing a GValue
When a binding takes a GObject.Value, pass the JavaScript payload and GTKX infers its type: a string becomes a gchararray, a number a gint or gdouble, and an object its own class's type. For example, a GtkDragSource can use this onPrepare handler:
import * as Gdk from "@gtkx/gi/gdk";
const prepareDrag = () => Gdk.ContentProvider.newForValue("Copied text");onPrepare returns its provider synchronously, so the handler creates it directly. Create long-lived GObjects through JSX.
When the operation needs a type inference cannot select, such as an enumeration or an interface, initialize a GObject.Value yourself. Clipboards and drop targets match content by GType, and a file passed directly is offered as its implementation class, GLocalFile, rather than GFile:
import * as Gdk from "@gtkx/gi/gdk";
import * as Gio from "@gtkx/gi/gio";
import * as GObject from "@gtkx/gi/gobject";
const fileProvider = (file: Gio.File) => {
const value = new GObject.Value();
value.init(Gio.File);
value.setObject(file);
return Gdk.ContentProvider.newForValue(value);
};A binding that fills a value, such as Gdk.ContentProvider.getValue, takes a GObject.Value you create; its documentation says whether to initialize it first. Signal handlers receive the value object rather than its payload.
For nullable value parameters, null means no value object. To represent a typed null payload, create a value with the required type and set its payload to null.
GVariant values
Construct a variant with new Variant(signature, value) from @gtkx/gi/glib, as in GJS. Variants expose the GJS unpacking methods:
| Method | Behavior |
|---|---|
unpack() | Opens the outer container, leaving its children as variants. Dictionary keys are unpacked. |
deepUnpack() | Opens arrays, tuples, dictionaries, and maybes recursively, retaining the variants held inside v values. |
recursiveUnpack() | Opens every container, including nested v values. |
Basic values unpack directly. Byte arrays (ay) return Uint8Array in every mode, and dictionaries return objects, including dictionaries with numeric keys. deep_unpack() aliases deepUnpack(), and Variant.new(signature, value) aliases construction for compatibility with older GJS code.
Passing a string to new Variant("ay", text) produces UTF-8 bytes with a trailing NUL, as in GJS; passing a byte array preserves its bytes. GTKX keeps signed and unsigned 64-bit values as bigint to preserve their full precision. Construction accepts bigint or safe integer numbers for those types.
Unpacking always reads the variant's actual runtime type. An explicit type parameter describes the signature your code expects; it does not validate that signature at runtime. Without a known constructor signature or explicit type parameter, the result is unknown.
Generated return values
Returned byte arrays are Uint8Array; byte inputs accept Uint8Array, Uint8ClampedArray or number[]. A returned GObject.Value is unpacked to its payload, typed as unknown. Inout records and boxed values are updated in place rather than repeated in the return value. Async operations covers what promisified operations resolve to.
Records passed to callbacks
A record that a signal handler or callback receives stays valid until the handler returns. Reference-counted records, such as WebKit.ScriptMessageReply, are the exception: the handler may keep one and use it later, for example to answer once an asynchronous operation finishes.
Passing integers
Integer parameters, properties and vfunc results take whole numbers within their native type's range. GTKX throws a RangeError for any other number, such as Value 10922.4 is not an integer, int32 expects a whole number, where GJS truncates a fractional number silently. Code ported from GJS that computes sizes or positions with fractional arithmetic must round each value before passing it:
import * as Pango from "@gtkx/gi/pango";
const shrinkFont = (description: Pango.FontDescription, size: number) =>
description.setSize(Math.round(size * 0.8));The same applies to sizes a vfunc returns and to fields of records such as Gdk.Rectangle. Use Math.trunc to keep GJS's behavior exactly.
Reading embedded records
A record or union field that embeds another record by value, such as Pango.Item.analysis or the members of a Poppler.Action (action.any.title), reads as a view into the parent's memory, as in GJS:
import * as Pango from "@gtkx/gi/pango";
const isRightToLeft = (item: Pango.Item) => item.analysis.level % 2 === 1;A view reflects later changes to the parent and keeps the parent alive while it is reachable. A view of a value lent to a callback expires with that value when the callback returns. When the embedded record holds pointers, the field is read-only, because copying a whole record would alias pointers the parent already owns.
D-Bus covers calling services and exporting objects, Application Lifecycle covers ending work on unmount, termination signals and command-line apps, and Workers and Helper Processes covers moving CPU-bound work off the main thread.