GTK4, Adwaita and Webkit 6 for Go, without cgo (purego)
  • Go 99.6%
  • Shell 0.2%
  • Python 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Patrice Ferlet 50a6627d53
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
docs: add WebKit 6 and GTK screenshots
2026-12-02 15:32:36 +01:00
adw Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
cairo Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
cmd/girgen Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
docs docs: add WebKit 6 and GTK screenshots 2026-12-02 15:32:36 +01:00
examples Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
gdk Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
gdkpixbuf Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
gio Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
glib Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
graphene Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
gsk Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
gtk Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
internal Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
jsc Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
pango Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
pangocairo Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
scripts Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
webkit Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
.gitignore Generate the binding from GIR 2026-11-19 16:10:14 +01:00
.woodpecker.yml ci: escape GO_VERSION for Woodpecker 2026-12-02 14:48:46 +01:00
bind.go Add the async helpers the drop and the clipboard need 2026-12-01 10:48:13 +01:00
bind_test.go bind: resolve symbols tolerantly so older libraries can start 2026-11-21 14:27:24 +01:00
error.go bind: resolve symbols tolerantly so older libraries can start 2026-11-21 14:27:24 +01:00
go.mod Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
go.sum Initial import of the GTK4 binding extracted from Cellule 2026-11-18 22:48:31 +01:00
LICENSE Initial import of the GTK4 binding extracted from Cellule 2026-11-18 22:48:31 +01:00
mainloop.go bind: resolve symbols tolerantly so older libraries can start 2026-11-21 14:27:24 +01:00
Makefile Move module path to metal3d.org/purego/gtk4 and use org.metal3d app IDs 2026-12-02 14:30:23 +01:00
object.go Wrap a raw object pointer in a typed wrapper 2026-11-25 09:32:31 +01:00
object_test.go Wrap a raw object pointer in a typed wrapper 2026-11-25 09:32:31 +01:00
property.go bind: resolve symbols tolerantly so older libraries can start 2026-11-21 14:27:24 +01:00
README.md docs: add WebKit 6 and GTK screenshots 2026-12-02 15:32:36 +01:00
refdebug.go Initial import of the GTK4 binding extracted from Cellule 2026-11-18 22:48:31 +01:00
signal.go bind: resolve symbols tolerantly so older libraries can start 2026-11-21 14:27:24 +01:00
source.go bind: resolve symbols tolerantly so older libraries can start 2026-11-21 14:27:24 +01:00
THIRD_PARTY_NOTICES.md gen: keep upstream documentation out of the default output 2026-11-20 09:58:56 +01:00

gtk4-purego

Go Reference

GTK4, Adwaita, WebKit 6 and Cairo for Go, without cgo.

The shared libraries are opened at run time through purego instead of being linked. Building a program that imports this module needs:

  • no GTK development headers,
  • no pkg-config,
  • no C compiler.

CGO_ENABLED=0 go build produces a single binary. Only the shared objects have to be present on the machine that runs it: GTK4 and Adwaita on any GTK desktop, plus WebKit 6 when you use the webkit package.

CGO_ENABLED=0 go build ./cmd/my-app

Screenshots

WebKit 6 web view GTK4 and Adwaita widgets
WebKit 6 web view GTK4 and Adwaita widgets

Both are plain Go programs from examples/: the web view uses the webkit package, the widget showcase uses the gtk and adw packages.

Status

Early, but in daily use: this is the UI layer of a desktop application that ships as one self-contained binary.

The binding is generated from GIR. gtk, adw, gdk, gio, glib, pango, webkit, graphene, gdkpixbuf, pangocairo, jsc and gsk each contain a zz_generated.go with the classes, records, constructors, methods, signals, enums/flags and interface types extracted from /usr/share/gir-1.0. Small helpers.go files hold the patches GIR cannot express: arrays and callback entry points (Application.Run, file dialogs, alert dialogs, drawing callbacks), cross-package interfaces and a few typed constructors. cairo is the exception: cairo-1.0.gir only describes the types, so its drawing subset is written by hand. The root gtk4 package is the runtime (ownership, GValue, signals, sources, errors) and stays hand-written.

make generate-full regenerates the twelve generated files; make check builds, tests, vets and audits every registered symbol; make stack generates all thirteen namespaces into a temporary module, compiles it and loads every symbol.

How it compares with puregotk

puregotk is the closest relative: also generated from GIR, also cgo-free, also loaded at run time with purego. The two target different uses, and the differences below are deliberate.

gtk4-purego puregotk
Scope the classes, records and interfaces an application uses; records and cross-package interfaces are opt-in a broad GIR surface, including GModule and Soup-3
Subclassing none: existing types are wrapped, no new GObject types custom widgets and GObject libraries written in Go
Lifetime owned wrappers install runtime.AddCleanup; object releases run on the main loop no finalizers: every object is released by an explicit Unref
Signals one Connect(object, "name", func([]*Value)) marshaller for every signal one typed ConnectX method per signal
Libraries resolved by soname through the system loader hardcoded paths, PUREGOTK_* overrides, then pkg-config
GIR source the target machine's /usr/share/gir-1.0 at generation time GIR vendored from the GNOME Flatpak SDK

What this binding optimises for

  • A verified surface. make check audits every registration against GIR: arity, ABI widths, the implicit GError**, and call sites that would hand a borrowed pointer to a transfer full parameter. Generation also drops the symbols the local sonames do not export, so what ships is what the generator and the audit both accepted.
  • Failures that name themselves. A symbol the installed libraries do not export becomes a typed stub: calling it panics with the symbol name and a "built against a newer version" hint, so a deployment problem points at its cause.
  • One signal path. Every signal goes through the same GValue-based marshaller, including the ones GIR describes imprecisely: no per-signal trampoline to generate, and one place to debug.
  • A chosen type surface. Records and cross-package interfaces are opt-in, so unused structs and foreign-namespace methods never enter the API. The price is explicit: selecting a type is one generator flag away.
  • The whole stack is exercised. make stack generates the thirteen namespaces into a throwaway module, compiles it and resolves every symbol, so a generator regression is caught before release.
  • The distribution decides where its libraries are. Nothing hardcodes a library directory: resolution goes through the loader, like any other shared library dependency. Flatpak and NixOS may need LD_LIBRARY_PATH, which puregotk's search path and PUREGOTK_* variables handle for you.

Need a custom widget, GModule or Soup? puregotk is the right tool, and gotk4 is its cgo equivalent.

Documentation

The architecture, the GIR generator, the helper policy, the records and cross-package interface limits, and every verification target are documented in docs/README.md. The contribution rules — where a fix belongs, how to change the generator, add a helper or a library, and what to run before a release — are in docs/contributing.md.

Requirements

  • Linux (libraries are opened by soname; Windows and macOS are not handled),
  • Go 1.25 or newer,
  • at run time: libgtk-4.so.1, libadwaita-1.so.0, libgio-2.0.so.0, libgobject-2.0.so.0, libglib-2.0.so.0; libwebkitgtk-6.0.so.4 only for programs that import webkit, libcairo.so.2 for cairo, libgraphene-1.0.so.0 for graphene, libgdk_pixbuf-2.0.so.0 for gdkpixbuf, libpangocairo-1.0.so.0 for pangocairo, and libjavascriptcoregtk-6.0.so.1 for jsc. The linkcheck test imports all of them, so make check needs them too.

Compatibility across library versions

Each package binds its symbols when it initializes, but a symbol the installed library does not export is not fatal: the binding installs a stub that panics with the symbol name only if the program actually calls it. A binary built on a recent distribution therefore starts on an older one, as long as it stays within the API those older libraries provide. HasSymbol tells whether a symbol exists in a loaded library, and RegisterFunc is the tolerant registration helper (unlike purego.RegisterLibFunc, which aborts init).

The generated tree is still produced against the GIR and libraries of the build machine, so newer APIs remain declared even when the target system predates them; they simply fail at the call site instead of preventing startup.

Install

go get metal3d.org/purego/gtk4

Hello world

package main

import (
	"os"

	"metal3d.org/purego/gtk4/adw"
	"metal3d.org/purego/gtk4/gio"
	"metal3d.org/purego/gtk4/gtk"
)

func main() {
	app := gtk.NewApplication("org.metal3d.Example", gio.ApplicationDefaultFlags)
	app.ConnectActivate(func() {
		win := adw.NewApplicationWindow(app)
		win.SetTitle("Hello")
		win.SetDefaultSize(360, 120)

		toolbar := adw.NewToolbarView()
		toolbar.AddTopBar(adw.NewHeaderBar())
		toolbar.SetContent(gtk.NewLabel("Built without cgo."))
		win.SetContent(toolbar)
		win.Present()
	})
	os.Exit(app.Run(os.Args))
}

A runnable copy lives in examples/hello.

When libadwaita widgets are used with a plain Gtk.Application, call adw.Init() once in activate, before creating widgets: it registers libadwaita's styles and its bundled icon resources (the expander arrow, for instance, is not in the system icon theme). An adw.Application does it automatically.

A WebKit web view

WebKitGTK 6.0 is the GTK4 build of WebKit. Its bindings live in the webkit package; the window stays a GTK window.

view := webkit.NewWebView()
view.LoadURI("https://go.dev")
win.SetChild(view)

A runnable copy that opens go.dev lives in examples/webview:

go run ./examples/webview

examples/browser goes one step further and is a small browser: an Adwaita header bar with back, forward and reload buttons, a URL entry as the title widget, and the page title mirrored into the window title.

go run ./examples/browser

examples/kitchen-sink is the tour of the widget toolkit: an Adw.OverlaySplitView with a collapsible sidebar (a switch turns it into an overlay), an Adw.TabView whose pages appear as thumbnails in an Adw.TabOverview, a toast overlay, preferences rows, progress, a spinner and the Adwaita type scale. Each control is an AdwExpanderRow; expanding it shows the Go source that builds it, colored with Pango markup.

go run ./examples/kitchen-sink

JavaScript and JavaScriptCore

The jsc package evaluates scripts in a jsc.Context; values are typed (ToDouble, ToString, ToJSON, IsNumber, ...). WebKit uses the same package: EvaluateJavascriptFinish returns *jsc.Value, and script-message-received delivers a *jsc.Value.

examples/jsc is a small REPL: edit a script, press Run, and the result is printed (objects and arrays as JSON). The context is reused, so declarations persist between runs.

go run ./examples/jsc

Scene rendering with Gsk

The gsk package exposes the GTK Scene Kit: render nodes, path builders, transforms, strokes and renderers. Gtk.Snapshot methods are now typed with *gsk.Path, *gsk.RenderNode and *graphene.Rect where the GIR provides them. Gsk lives in libgtk-4.so.1; adding the package does not require another runtime library.

examples/gsk builds a GtkSnapshot with an AppendCairo node, converts it to a GskRenderNode, renders it to a GdkTexture with the window renderer and shows it in a GtkPicture. Snapshot.AppendCairo returns *cairo.Context (transfer full); the example destroys the context after drawing.

go run ./examples/gsk

examples/screenshot uses the same pieces for CI: it snapshots a window with GtkWidgetPaintable, converts the snapshot to a GskRenderNode, renders it with GskCairoRenderer and writes a PNG. No external screenshot program or compositor is involved.

# Xvfb is the simplest CI backend
xvfb-run -a go run ./examples/screenshot -out shot.png

# Broadway also works, but needs a connected browser client to drive frames
gtk4-broadwayd :5 &
GDK_BACKEND=broadway BROADWAY_DISPLAY=:5 go run ./examples/screenshot -out shot.png

-delay waits for the first frame (default 1000 ms); -out selects the file.

Drawing with Cairo

The cairo package covers what Gtk.DrawingArea callbacks and file export need: paths, strokes and fills, colours, transforms, text, and image/PDF/SVG surfaces. DrawingArea.SetDrawFunc bridges GTK's C callback and a borrowed *cairo.Context.

examples/cairo is one window with three pages: a real-time clock, a chart that can be exported to PDF or SVG with FileDialog.SaveFile, and a composition of gradients, curves and text.

go run ./examples/cairo

Packages

package Go reference wraps
gtk Go Reference GTK4: application, windows, widgets, lists, events, text
adw Go Reference libadwaita: toolbar view, header bar, clamp, preferences, alerts
gdk Go Reference GDK4: display, textures, cursors, clipboard, drag and drop
gio Go Reference GIO: actions, list models, notifications, async results
glib Go Reference GLib: strings, variants, GBytes
pango Go Reference Pango: attributes and markup enums
graphene Go Reference Graphene: points, sizes, rectangles, matrices, vectors
gdkpixbuf Go Reference GdkPixbuf: pixbufs, loaders, animations
pangocairo Go Reference PangoCairo: render Pango layouts on Cairo contexts
jsc Go Reference JavaScriptCore: contexts, values, virtual machines, classes
gsk Go Reference Gsk: render nodes, paths, transforms, strokes, renderers
webkit Go Reference WebKitGTK 6.0: WebView, settings, contexts, policies, downloads
cairo Go Reference Cairo: contexts, paths, text, image/PDF/SVG surfaces (hand-written)
gtk4 (root) Go Reference object ownership, GValue, signals, idle/timeout sources, errors
cmd/girgen — GIR parser, code generator and signature audit
internal/gir — the GIR model and XML parser used by the generator

Each binding package contains a zz_generated.go (the GIR output) and a helpers.go (the hand-written patches).

Ownership: the one thing to read

GTK counts references. A wrapper that releases a reference it never owned frees an object GTK is still using, and the crash happens later, somewhere else. The binding makes the rule explicit, straight from the GIR annotations:

helper when
AdoptOwned the call returns transfer full: we own one reference
AdoptFloating a widget constructor returns a floating reference: sink it
AdoptBorrowed the call returns transfer none: take our own reference (safe if the wrapper outlives its owner)
AdoptNone the wrapper must not release anything (rare, documented case by case)
RefNative an argument is transfer full: the callee consumes a reference, so hand it one of ours

Getting RefNative wrong is the classic bug: gtk_list_view_new and gtk_no_selection_new take transfer full arguments, and passing a bare pointer means GTK and the wrapper both release it.

Owned wrappers also register runtime.AddCleanup: the reference is released when the wrapper becomes garbage, and object releases are replayed from an idle callback because dispose and finalize must run on the main loop. Object.Unref cancels that automatic release for a deterministic teardown.

girgen audit is the authoritative checker. It reads every registration (RegisterFunc, generated or hand-written), compares the Go signature with the GIR and reports:

  • a symbol the GIR does not know;
  • a wrong parameter or result count — including the implicit GError** that GIR describes with throws="1" instead of a parameter;
  • a Go width that does not match the C ABI (guint vs uintptr, gsize vs uint32, ...);
  • a call site that passes x.Native() to a transfer full parameter, where the callee consumes a reference and the wrapper must pass x.RefNative().
make audit
# or
go run ./cmd/girgen audit -dir .

scripts/audit-gir.py remains a quick Python listing of transfer full parameters; the Go audit supersedes it for correctness checks.

Generating the binding

make generate-full builds the generator and rewrites the twelve zz_generated.go files. It uses :all cross-namespace imports, so a GtkWidget* becomes gtk.Widgetter, a GdkPaintable* becomes gdk.Paintabler, and a GtkWidget* parameter accepts every widget wrapper. The helpers.go files are hand-written and are not touched.

The generator extracts:

  • classes and their GIR parent chain, so inherited methods are real methods;
  • constructors, methods and namespace functions;
  • records selected with -records (value structs, ref-counted handles and opaque buffers);
  • signals as typed ConnectX helpers, including interface signals (GtkEditable::changed on GtkEntry and GtkPasswordEntry);
  • interface methods on every implementing class, including opted-in cross-package interfaces (-ifaces Gtk.Editable for the Adw rows);
  • enums, flags and numeric constants;
  • base-class and interface Go interfaces (Widgetter, EventControllerer, ListModeller, ...);
  • ownership (AdoptFloating, AdoptOwned, AdoptBorrowed, RefNative, throws);
  • the upstream documentation from the GIR <doc> elements, cleaned up and emitted as Go doc comments only with -docs (make generate-docs). It is off by default because that prose keeps its upstream license.

The few semantic gaps in GIR are expressed in defaultSignalOverrides: for example GtkSignalListItemFactory::setup declares a GObject* in GIR, but GTK always passes a GtkListItem, so the generated handler takes *ListItem. That table is the manifest seed; it is deliberately small.

Generate one package or a subset while exploring:

go run ./cmd/girgen gen \
  -ns Gtk-4.0 -pkg gtk -path metal3d.org/purego/gtk4/gtk \
  -root metal3d.org/purego/gtk4 \
  -classes Button,Label,Box -out /tmp/gtk_gen.go

To extend a package that is still partly hand-written, -existing DIR reuses the package's registered func variables and skips its types and wrappers. The repository itself no longer needs it: the generated files are the API.

flag meaning
-classes A,B classes to generate; their ancestors in the same namespace are added automatically
-symbols a,b extra C symbols to declare
-existing DIR extend an existing package: reuse registered variables, skip existing types and wrappers
-import NS=alias=path[:all|Class1,Class2] cross-namespace types; :all names every type of a generated package
-check-symbols (default) drop GIR entries the installed library does not export
-constants also emit the namespace's numeric constants (Gdk has thousands of keysyms)

make stack is the end-to-end check: it generates all thirteen namespaces into a temporary module, builds it and runs a program that imports every package, so a single missing symbol fails immediately.

Checks

make check   # build, tests, vet, GIR audit
make stack   # generate all thirteen namespaces, build them, load every symbol

make check does not need a display. internal/linkcheck imports every package in one test binary, so its init functions resolve the whole declared symbol surface; gdk's test decodes a 1x1 PNG through the throws path. The audit reports 7731 registered symbols with zero errors and zero warnings.

girgen diff is still useful when migrating a hand-written package: it generates the package from scratch in memory and compares it with the current one, reporting embedding and signature drift. On the generated tree it reports the helpers.go additions as extensions, which is expected.

A real window can be smoke-tested over Broadway without touching the desktop:

gtk4-broadwayd -p 8095 :5 &
GDK_BACKEND=broadway BROADWAY_DISPLAY=:5 ./hello
# open http://127.0.0.1:8095/

Manual helpers: the helpers.go files

A symbol that GIR describes and the generator understands needs no manual code: run make generate-full. Add a manual helper only for what GIR cannot express (records, arrays, callbacks, async, cross-package interfaces). The generated GetText/GetBuffer/GetFirstChild names are the API; do not add aliases.

Rules for a manual helper:

  1. find the C prototype in the upstream headers or in the GIR (/usr/share/gir-1.0/Gtk-4.0.gir);
  2. declare a package-level func variable with the exact C types — uintptr for pointers, int32 for gboolean/gint, uint32 for guint, uint64 for gsize, float64 for gdouble; a function with throws="1" also takes a final uintptr for its GError**;
  3. register it in the package init with gtk4.RegisterFunc(&gtkSomething, gtk4.GTKLib(), "gtk_something") (or RegisterFunc from inside the root package); a missing symbol stays a stub instead of aborting init;
  4. document the ownership rule if it returns or takes an object, and run make audit before committing.

Do not edit a zz_generated.go by hand: change the generator or add a helpers.go wrapper.

Debugging

Reference problems corrupt the heap and surface as a segfault far from the cause. With GTK4_PUREGO_DEBUG=1, the binding reports the two states that mean a wrapper is holding a dead pointer:

GTK4_PUREGO_DEBUG=1 ./my-app
  • an object is adopted while its GType is already invalid;
  • a reference is released on an object whose GType is invalid.

Both print the Go stack that created or dropped the wrapper.

Known limitations

  • zz_generated.go is the API. The generator covers the introspectable classes, methods, signals, enums, flags and interfaces. Non-introspectable symbols get a low-level declaration but no typed wrapper.
  • WebKit and JavaScriptCore are typed together. EvaluateJavascriptFinish returns *jsc.Value, and script-message-received delivers a *jsc.Value.
  • Records are opt-in. A record is generated when -records selects it: Gtk.TextIter, Gdk.Rectangle/RGBA, GLib.Bytes/Variant/VariantType and the Graphene value types. Other records stay uintptr until selected.
  • Arrays, callbacks and async entry points are patches. They live in helpers.go (Application.Run, file dialogs, alert dialogs, launchers, drawing callbacks) because GIR cannot express them as plain functions.
  • No GObject subclassing. The binding wraps the existing types; it does not register new GObject types or custom widgets. puregotk and gotk4 cover that use case.
  • Signal object parameters are transient. signalObject wraps the GValue payload with AdoptNone; a handler that stores it must take its own reference.
  • Generated code is checked against the libraries of the generating machine. -check-symbols drops symbols the local sonames do not export. Use -check-symbols=false when cross-checking against a different GTK version.
  • Downstream assumptions belong downstream. A hand-written signature is not a reason to bend the generated one. GtkPasswordEntry has a placeholder-text property but no C setter; the generator emits GetPlaceholderText/SetPlaceholderText from that property. Do not inherit gtk_entry_set_placeholder_text from Entry, which GTK rejects on a non-Entry.
  • gst-purego — the same cgo-free, runtime-loaded approach for GStreamer. This module deliberately stops at GTK: a program that needs media playback or capture uses gst-purego for the pipeline and draws the frames in its own widgets.

License

MIT. See LICENSE.

The default generated files contain the API and the generator's one-line summaries, not the upstream GIR documentation. make generate-docs adds that documentation for a local go doc; it remains under the upstream licenses and must not be committed or redistributed as MIT. See THIRD_PARTY_NOTICES.md for purego and the runtime libraries.