- Go 99.6%
- Shell 0.2%
- Python 0.1%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
|
||
| adw | ||
| cairo | ||
| cmd/girgen | ||
| docs | ||
| examples | ||
| gdk | ||
| gdkpixbuf | ||
| gio | ||
| glib | ||
| graphene | ||
| gsk | ||
| gtk | ||
| internal | ||
| jsc | ||
| pango | ||
| pangocairo | ||
| scripts | ||
| webkit | ||
| .gitignore | ||
| .woodpecker.yml | ||
| bind.go | ||
| bind_test.go | ||
| error.go | ||
| go.mod | ||
| go.sum | ||
| LICENSE | ||
| mainloop.go | ||
| Makefile | ||
| object.go | ||
| object_test.go | ||
| property.go | ||
| README.md | ||
| refdebug.go | ||
| signal.go | ||
| source.go | ||
| THIRD_PARTY_NOTICES.md | ||
gtk4-purego
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 |
|---|---|
![]() |
![]() |
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 checkaudits every registration against GIR: arity, ABI widths, the implicitGError**, and call sites that would hand a borrowed pointer to atransfer fullparameter. 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 stackgenerates 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 andPUREGOTK_*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.4only for programs that importwebkit,libcairo.so.2forcairo,libgraphene-1.0.so.0forgraphene,libgdk_pixbuf-2.0.so.0forgdkpixbuf,libpangocairo-1.0.so.0forpangocairo, andlibjavascriptcoregtk-6.0.so.1forjsc. Thelinkchecktest imports all of them, somake checkneeds 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
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 withthrows="1"instead of a parameter; - a Go width that does not match the C ABI (
guintvsuintptr,gsizevsuint32, ...); - a call site that passes
x.Native()to atransfer fullparameter, where the callee consumes a reference and the wrapper must passx.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
ConnectXhelpers, including interface signals (GtkEditable::changedonGtkEntryandGtkPasswordEntry); - interface methods on every implementing class, including opted-in
cross-package interfaces (
-ifaces Gtk.Editablefor 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:
- find the C prototype in the upstream headers or in the GIR
(
/usr/share/gir-1.0/Gtk-4.0.gir); - declare a package-level
funcvariable with the exact C types —uintptrfor pointers,int32forgboolean/gint,uint32forguint,uint64forgsize,float64forgdouble; a function withthrows="1"also takes a finaluintptrfor itsGError**; - register it in the package
initwithgtk4.RegisterFunc(>kSomething, gtk4.GTKLib(), "gtk_something")(orRegisterFuncfrom inside the root package); a missing symbol stays a stub instead of abortinginit; - document the ownership rule if it returns or takes an object, and run
make auditbefore 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
GTypeis already invalid; - a reference is released on an object whose
GTypeis invalid.
Both print the Go stack that created or dropped the wrapper.
Known limitations
zz_generated.gois 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.
EvaluateJavascriptFinishreturns*jsc.Value, andscript-message-receiveddelivers a*jsc.Value. - Records are opt-in. A record is generated when
-recordsselects it:Gtk.TextIter,Gdk.Rectangle/RGBA,GLib.Bytes/Variant/VariantTypeand the Graphene value types. Other records stayuintptruntil 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.
signalObjectwraps the GValue payload withAdoptNone; a handler that stores it must take its own reference. - Generated code is checked against the libraries of the generating machine.
-check-symbolsdrops symbols the local sonames do not export. Use-check-symbols=falsewhen cross-checking against a different GTK version. - Downstream assumptions belong downstream. A hand-written signature is not
a reason to bend the generated one.
GtkPasswordEntryhas aplaceholder-textproperty but no C setter; the generator emitsGetPlaceholderText/SetPlaceholderTextfrom that property. Do not inheritgtk_entry_set_placeholder_textfromEntry, which GTK rejects on a non-Entry.
Related projects
- 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-puregofor 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.

