gtk4

package module
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: BSD-3-Clause Imports: 8 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gtk4

Drive GTK4 from pure Go with CGO_ENABLED=0 — windows, the common controls, GObject signals and the GLib main loop — over ebitengine/purego.

It is the Linux sibling of go-macos/objc: the shared native-toolkit bridge a go-widgets host backend embeds real controls through, so a pixel-drawn app can inlay a real GtkEntry, GtkButton or secure field over its own rendering.

ok, err := gtk4.Init()
// win := gtk4.WindowNew(); win.SetTitle("…"); win.SetDefaultSize(360, 200)
// fixed := gtk4.FixedNew()          // the overlay container
// e := gtk4.EntryNew(); e.SetVisibility(false) // a password field
// b := gtk4.ButtonNewWithLabel("OK")
// b.Connect("clicked", func() { … }) // a GObject signal, as a Go closure
// fixed.Put(e, 10, 10); fixed.Put(b, 10, 44); win.SetChild(fixed); win.Present()

No cgo

libgtk-4, libgobject-2.0 and libglib-2.0 are dlopen'd by soname and every entry point is resolved with purego.RegisterLibFunc. A GObject signal reaches Go through a purego.NewCallback, retained for the process life (GTK holds the C pointer). The package links with no cgo and cross-compiles like any other Go code.

What it binds

Init · WindowNew (+ SetTitle/SetDefaultSize/SetChild/Present) · FixedNew (+ Put/Move — absolute overlay positioning) · ButtonNewWithLabel (+ SetLabel) · EntryNew (+ SetVisibility for a secure field) · CheckButtonNewWithLabel (+ Active/SetActive; grouped check buttons are GTK radios) · LabelNew · Text/SetText (GtkEditable) · SetSizeRequest · SetVisible · Unparent · Connect (signals) · MainLoop (Run/Quit) · IdleAdd (marshal onto the GTK thread).

Pixels: PictureNew with SetRGBA/UpdateRGBA (the frame is copied) or NewSharedFrame with SetFrame/UpdateFrame (GTK 4.16+ for the update; no copy: the texture is built over the frame's own GLib memory, which GdkMemoryTextureBuilder needs whole anyway, gdk/gdkmemorytexturebuilder.c:726). OverlayNew (+ SetOverlayChild/ AddOverlay) and AllocatedSize let a picture fill a resizable window and report its size.

Input method: IMContextNew (the user's session input method, falling back to GTK's built-in compose/dead-key handling) and IMContextSimpleNew (that built-in handling only), with SetClientWidget, FocusIn/FocusOut, Reset, SetCursorLocation (anchors the candidate window), Preedit (the text being composed and the caret, in characters), OnPreeditChanged and OnCommit. Widget.OnKeyIM is OnKey with the context in front: GTK offers each key to the input method first, and the callback sees only what it did not consume. A host that paints its own text fields uses these to take dead keys, compose sequences and CJK input. Pango's underline attributes of the preedit are not read.

Context menus and window close: ContextMenuNew(widget) attaches a GtkPopoverMenu over a GMenu that a secondary click opens (capture phase, so it wins over a child's own menu); SetItems([]MenuItem) swaps its entries in place (an empty Label is a separator, a nil OnPick an inert greyed entry), and Popup, Popdown, IsOpen, Activate and Destroy drive it. MenuSections is the pure layout of a flat list into GMenu sections. Widget.OnCloseRequest stops or lets through the window's close control, Widget.Close and Widget.Mapped complete it. SetButtonChild, SetTooltip, Picture.SetCanShrink and Picture.SetAlternativeText put a picture in a button with a caption a screen reader still has.

Dialogs (GTK 4.10+): ShowFileDialog(parent, FileDialogRequest, done) drives GtkFileDialog (open, open several, choose a folder, save; suffix filters, the first the default) and ShowAlert(parent, AlertRequest, done) drives GtkAlertDialog (message, detail, up to any number of buttons; the first is the default). Both may be called from any goroutine, show the dialog on the main loop thread and call done there exactly once, with the paths as g_file_get_path gives them or the index of the button pressed; a dismissal is Cancelled, not an error. On a GTK older than 4.10, and off Linux, they return ErrDialogUnsupported and never call done; DialogsSupported asks first.

Collections: ColumnViewNew(columns) is a table (a GtkColumnView in a scroller over a GtkStringList): SetRows([][]string) replaces every row with one splice, so 100 000 rows are 100 000 small GObjects and only the rows on screen get widgets; Selected/SetSelected, OnSelect (called for the person's change only, never for the host's own; Select, SelectPath and Switch change the selection as the person would, handler included), Len, Rebuilds. TreeViewNew() is a tree (a GtkListView over a GtkTreeListModel with expander rows): SetNodes([]TreeNode) (children are made lazily as a row expands; Expanded nodes start open), SetSelectedPath (opens the ancestors), SelectedPath, OnSelect. NotebookNew() is a tab strip (a GtkNotebook with empty pages, the host lays the content out): SetTabs, Current/SetCurrent, Remove, Len, OnSwitch. Each has Widget() to place and Destroy(); a cell may not hold NUL or the ASCII unit separator (dropped).

Platform

Linux only — this is the GTK path; a go-widgets host uses AppKit/Win32 on macOS/Windows. Off Linux the package still compiles (a consumer cross-compiles without a build tag) and every constructor's Init returns ErrUnsupported, so nothing is a build-time surprise. It needs only the runtime libgtk-4 (libgtk-4-1 on Debian/Ubuntu) — no -dev package.

The Linux binding is built for amd64 and arm64 only. purego.Dlopen links a Go binary dynamically (it needs the loader, ld-linux), and on the other Linux architectures a test binary run under qemu user emulation (loong64, ppc64le, riscv64, s390x) fails with "Could not open ld-linux". Those architectures get the same stub as every other platform: it compiles, Init reports ErrUnsupported, and the collection constructors return nil.

Testing

CI builds it on every platform and runs a live test against real GTK4 under a headless X server (Xvfb) — creating a window, entry, secure field, button and check button, round-tripping their values, and proving a changed signal reaches Go through the main loop.

License

BSD-3-Clause. See LICENSE.

Documentation

Overview

Package gtk4 binds the parts of GTK4 a windowing toolkit needs — windows, the common controls, GObject signals and the GLib main loop — from pure Go with CGO_ENABLED=0, over github.com/ebitengine/purego. It is the Linux sibling of github.com/go-macos/objc: the shared native-toolkit bridge a go-widgets host backend embeds real controls through.

It links no cgo: libgtk-4, libgobject-2.0 and libglib-2.0 are dlopen'd by soname and every entry point is resolved with purego.RegisterLibFunc, exactly as the feasibility spike proved on a stock Linux GTK4. A GObject signal reaches Go through a purego.NewCallback, so a control's clicks and edits are ordinary Go closures.

Index

Constants

View Source
const (
	ModShift   uint = 1 << 0  // GDK_SHIFT_MASK
	ModControl uint = 1 << 2  // GDK_CONTROL_MASK
	ModAlt     uint = 1 << 3  // GDK_ALT_MASK (Mod1)
	ModSuper   uint = 1 << 26 // GDK_SUPER_MASK
)

GDK modifier-state bits, as they arrive in a controller's current event state and in a key event's state argument. A host decodes the four the toolkit cares about; the lock and button-mask bits are left alone.

View Source
const MemoryR8G8B8A8 = 5

MemoryR8G8B8A8 is GdkMemoryFormat GDK_MEMORY_R8G8B8A8: four bytes per pixel in R, G, B, A order, not premultiplied — the layout a go-widgets pixel buffer uses, so a frame maps to a GdkTexture with no conversion.

Variables

View Source
var ErrDialogUnsupported = errors.New("gtk4: GtkFileDialog and GtkAlertDialog need GTK 4.10")

ErrDialogUnsupported is returned by the dialog functions when the GTK in use is older than 4.10, the release that added GtkFileDialog and GtkAlertDialog ("Available since: 4.10"), and on every platform but Linux.

View Source
var ErrUnsupported = errors.New("gtk4: only available on Linux")

ErrUnsupported is returned by Init on any platform without GTK4 (everything but Linux). It is defined on every platform so a portable consumer can test for it with errors.Is.

Functions

func DialogsSupported added in v0.14.0

func DialogsSupported() bool

DialogsSupported reports whether this process can show GtkFileDialog and GtkAlertDialog: libgtk-4 loads and is 4.10 or newer.

func IdleAdd

func IdleAdd(fn func())

IdleAdd schedules fn to run once on the main loop and be removed. A host uses it to marshal work onto the GTK thread. fn runs on the main loop thread.

func Init

func Init() (ok bool, err error)

Init loads GTK4 and initialises it, reporting whether a display could be opened. It is safe to call more than once. An error means the libraries could not be loaded at all (not merely that there is no display).

func IsCancel added in v0.14.0

func IsCancel(dialogDomain bool, code int) bool

IsCancel reports whether a GError of the given domain kind and code is the person declining rather than a failure. dialogDomain is true for the GtkDialogError domain and false for the GIO one.

func KeyvalToUnicode added in v0.3.0

func KeyvalToUnicode(keyval uint) rune

KeyvalToUnicode returns the Unicode rune a GDK keyval produces, or 0 for a non-printable (named) key such as Return or an arrow. It is gdk_keyval_to_unicode, so a host maps named keys itself and takes the rune for the rest.

func MenuBarSupported() bool

MenuBarSupported reports whether this GTK has what a MenuBar needs.

func MenuSections(items []MenuItem) [][]MenuEntry

MenuSections lays a flat item list out the way a GMenu wants it: runs of entries, one run per section, a separator being the boundary between two runs. A leading, trailing or doubled separator makes no empty run, because GTK draws a rule for each section and an empty one is a rule beside nothing.

The labels come back ready for GTK, which reads a leading-underscore pair as a mnemonic: "Save _as" would underline the "a" and drop the underscore, so every underscore is doubled and the person sees the word the application wrote.

func MinorVersion added in v0.10.0

func MinorVersion() int

MinorVersion is the minor version of the libgtk-4 loaded at run time (gtk_get_minor_version), or 0 if it cannot be loaded.

func ShowAlert added in v0.14.0

func ShowAlert(parent Widget, req AlertRequest, done func(AlertResult)) error

ShowAlert shows a GtkAlertDialog over parent and calls done, on the GTK main loop thread, exactly once -- unless it returns an error. Buttons may be empty (GTK then shows its own "Close"). The first button is the default.

func ShowFileDialog added in v0.14.0

func ShowFileDialog(parent Widget, req FileDialogRequest, done func(FileDialogResult)) error

ShowFileDialog shows a GtkFileDialog over parent (which may be the null widget) and calls done, on the GTK main loop thread, exactly once -- unless it returns an error, in which case done is never called. It may be called from any goroutine: the dialog is created on the main loop thread, so the loop must be running for it to appear.

func TextureFromRGBA added in v0.2.0

func TextureFromRGBA(data []byte, width, height int) uintptr

TextureFromRGBA builds a GdkTexture from width*height*4 bytes of R8G8B8A8. The bytes are copied (g_bytes_new copies), so the caller may reuse its buffer at once. The returned handle is a GdkTexture with one reference the caller owns.

func TextureUpdateSupported added in v0.10.0

func TextureUpdateSupported() bool

TextureUpdateSupported reports whether the loaded libgtk-4 has GdkMemoryTextureBuilder (GTK 4.16 or newer), the API Picture.UpdateRGBA needs. When false, callers keep to Picture.SetRGBA.

Types

type AlertRequest added in v0.14.0

type AlertRequest struct {
	Message string
	Detail  string
	Buttons []string
}

AlertRequest configures a GtkAlertDialog. Buttons are shown in order; with no cancel button, Escape and the close control dismiss the alert.

type AlertResult added in v0.14.0

type AlertResult struct {
	Button    int
	Cancelled bool
	Err       error
}

AlertResult is what an alert answered: Button is the index of the button pressed. Cancelled is true when it was dismissed without one.

type BarItem added in v0.16.0

type BarItem struct {
	Label     string
	Separator bool
	Disabled  bool
	// Check makes the row a stateful boolean action, drawn with a tick while
	// Checked. A pick calls OnActivate and then puts the state back to Checked,
	// so the row shows what the host says, not what GTK toggled it to: the host
	// changes Checked and calls [MenuBar.SetItems] again.
	Check   bool
	Checked bool
	// Accel is a GTK accelerator string such as "<Control>s" or "<Shift>F5". It
	// is bound on the bar's window and drawn beside the label by GTK.
	Accel string
	// OnActivate runs on the GTK main thread when the row is chosen or its
	// accelerator pressed. Rows with a nil OnActivate are shown greyed out.
	OnActivate func()
	// Sub, when non-nil, makes the row a menu holding these rows.
	Sub []BarItem
}

A BarItem is one row of a MenuBar. The bar's own items are menus (Sub set); inside a menu a row is a command, a check, a submenu (Sub set) or a Separator.

type ColumnView added in v0.15.0

type ColumnView struct {
	// contains filtered or unexported fields
}

A ColumnView is a table: a GtkColumnView in a scroller, one string cell per column, one row selectable. The rows live in a GtkStringList and the view binds only those on screen, so ColumnView.SetRows on 100 000 rows is one splice, not 100 000 widgets.

func ColumnViewNew added in v0.15.0

func ColumnViewNew(columns []string) *ColumnView

ColumnViewNew builds a table with one column per title (resizable, expanding). It returns nil when GTK4 cannot be bound.

func (*ColumnView) Class added in v0.15.0

func (v *ColumnView) Class() string

Class is the GTK class name of the widget that does the work ("GtkColumnView").

func (*ColumnView) Destroy added in v0.15.0

func (v *ColumnView) Destroy()

Destroy releases the view's callbacks registry entries. The widget itself is owned by its parent, as for every other widget in this package.

func (*ColumnView) Len added in v0.15.0

func (v *ColumnView) Len() int

Len is the number of rows.

func (*ColumnView) OnSelect added in v0.15.0

func (v *ColumnView) OnSelect(fn func(int))

OnSelect sets the handler called with the new selected row (-1 when cleared) when the user (or ColumnView.Select) changes the selection.

func (*ColumnView) Rebuilds added in v0.15.0

func (v *ColumnView) Rebuilds() int

Rebuilds counts how many times SetRows replaced the data; a host that skips an unchanged table (and a test that proves it) reads it.

func (*ColumnView) Select added in v0.15.0

func (v *ColumnView) Select(i int)

Select is ColumnView.SetSelected as the person would do it: the ColumnView.OnSelect handler is called when the selection changes.

func (*ColumnView) Selected added in v0.15.0

func (v *ColumnView) Selected() int

Selected is the selected row, or -1.

func (*ColumnView) SetRows added in v0.15.0

func (v *ColumnView) SetRows(rows [][]string)

SetRows replaces every row with one splice (a single items-changed); the selection is cleared by GTK when the rows it pointed at go. A cell may not hold NUL or the ASCII unit separator: both are dropped.

func (*ColumnView) SetSelected added in v0.15.0

func (v *ColumnView) SetSelected(i int)

SetSelected selects row i, or clears the selection for i < 0 or out of range. It does not call the ColumnView.OnSelect handler: only the user does.

func (*ColumnView) Widget added in v0.15.0

func (v *ColumnView) Widget() Widget

Widget is the widget to place: the scroller around the view.

type ContextMenu added in v0.13.0

type ContextMenu struct {
	// contains filtered or unexported fields
}

A ContextMenu is a GtkPopoverMenu over a GMenu, parented to a widget and opened by a secondary click on it (or by ContextMenu.Popup).

It is built so a host that reconciles its controls every frame can keep one per control: ContextMenu.SetItems swaps the entries in place, and a menu that is open when it is called stays open under the pointer.

func ContextMenuNew added in v0.13.0

func ContextMenuNew(parent Widget) *ContextMenu

ContextMenuNew attaches an (initially empty) context menu to parent: a secondary press on parent or anything inside it opens the menu at the pointer while it has entries, and is left to the widget's own handling while it has none. It returns nil when the menu machinery cannot be loaded.

Destroy it before the widget is unparented: GTK warns about, and leaks, a popover still attached to a widget that is finalized.

func (*ContextMenu) Activate added in v0.13.0

func (m *ContextMenu) Activate(i int) bool

Activate chooses the item at position i of the list given to SetItems, as a click on it would, and reports whether it was an entry that could be chosen.

func (*ContextMenu) Destroy added in v0.13.0

func (m *ContextMenu) Destroy()

Destroy closes the menu and detaches it from its widget. The ContextMenu must not be used afterwards.

func (*ContextMenu) IsOpen added in v0.13.0

func (m *ContextMenu) IsOpen() bool

IsOpen reports whether the menu is on screen.

func (*ContextMenu) Len added in v0.13.0

func (m *ContextMenu) Len() int

Len is the number of entries the menu offers, separators not counted.

func (*ContextMenu) Popdown added in v0.13.0

func (m *ContextMenu) Popdown()

Popdown closes the menu if it is open.

func (*ContextMenu) Popup added in v0.13.0

func (m *ContextMenu) Popup(x, y float64)

Popup opens the menu with its corner at the widget-local point (x, y).

func (*ContextMenu) SetItems added in v0.13.0

func (m *ContextMenu) SetItems(items []MenuItem)

SetItems replaces the menu's entries. It does the whole swap and nothing else, so call it only when the words changed -- see the host's change test.

type FileDialogKind added in v0.14.0

type FileDialogKind int

FileDialogKind says which GtkFileDialog entry point a request uses.

const (
	FileOpen         FileDialogKind = iota // gtk_file_dialog_open: one existing file
	FileOpenMultiple                       // gtk_file_dialog_open_multiple
	FileSelectFolder                       // gtk_file_dialog_select_folder
	FileSave                               // gtk_file_dialog_save
)

type FileDialogRequest added in v0.14.0

type FileDialogRequest struct {
	Kind        FileDialogKind
	Title       string
	InitialName string       // a suggested file name for FileSave
	Filters     []FileFilter // the first is the default
}

FileDialogRequest configures a GtkFileDialog.

type FileDialogResult added in v0.14.0

type FileDialogResult struct {
	Paths     []string
	Cancelled bool
	Err       error
}

FileDialogResult is what a file dialog answered. Paths are g_file_get_path's answer, untouched. Cancelled is true when the person dismissed the dialog.

type FileFilter added in v0.14.0

type FileFilter struct {
	Name     string
	Suffixes []string
}

A FileFilter is a named set of file-name suffixes, without the dot. Matching is case-insensitive (gtk_file_filter_add_suffix).

type IMContext added in v0.12.0

type IMContext uintptr

An IMContext is a GtkIMContext: the object GTK routes key events through so that dead keys, the compose key and an input method (ibus, fcitx, ...) can turn several key presses into one character. A host that paints its own text fields needs one, because GTK only feeds it to its own entry widgets.

The shape of the protocol, as GTK defines it: the host forwards key events (see Widget.OnKeyIM, which does it), the context emits "preedit-changed" while a composition is under way — IMContext.Preedit then reads the uncommitted text — and "commit" with the finished text. The host tells the context where the caret is (IMContext.SetCursorLocation) so the input method can put its candidate window next to it.

func IMContextNew added in v0.12.0

func IMContextNew() IMContext

IMContextNew returns a GtkIMMulticontext, the context GTK's own entries use: it picks the input method the user's session selects (GTK_IM_MODULE, the desktop's setting) and falls back to the built-in simple one, which handles dead keys and compose sequences with no daemon. It returns 0 when GTK cannot be loaded.

func IMContextSimpleNew added in v0.12.0

func IMContextSimpleNew() IMContext

IMContextSimpleNew returns a GtkIMContextSimple: dead keys and compose sequences only, never an input-method daemon. A host that wants the same behaviour on every machine, and a test that must not depend on whether ibus runs, use it instead of IMContextNew.

func (IMContext) FocusIn added in v0.12.0

func (c IMContext) FocusIn()

FocusIn tells the context its client has the keyboard focus. A context that is not focused ignores key events.

func (IMContext) FocusOut added in v0.12.0

func (c IMContext) FocusOut()

FocusOut tells the context its client lost the keyboard focus.

func (IMContext) Free added in v0.12.0

func (c IMContext) Free()

Free drops the host's reference.

func (IMContext) OnCommit added in v0.12.0

func (c IMContext) OnCommit(fn func(text string))

OnCommit fires with the finished text of a composition (or an ordinary character the context passes through).

func (IMContext) OnPreeditChanged added in v0.12.0

func (c IMContext) OnPreeditChanged(fn func())

OnPreeditChanged fires each time the composition changes: a character is added, a candidate is chosen, or the preedit ends. Read it with IMContext.Preedit.

func (IMContext) Preedit added in v0.12.0

func (c IMContext) Preedit() (text string, cursor int)

Preedit returns the text being composed and the caret's position in it, in characters (not bytes). Text is empty when nothing is being composed. The Pango attributes — GTK's underline styling of the preedit — are not read: a host draws its own.

func (IMContext) Reset added in v0.12.0

func (c IMContext) Reset()

Reset abandons the composition in progress; the context emits "preedit-changed" once more, with an empty preedit.

func (IMContext) SetClientWidget added in v0.12.0

func (c IMContext) SetClientWidget(w Widget)

SetClientWidget names the widget the context composes for; GTK uses it to find the display and the surface an input method pops its candidate window on.

func (IMContext) SetCursorLocation added in v0.12.0

func (c IMContext) SetCursorLocation(x, y, w, h int)

SetCursorLocation tells the input method where the caret is, as a rectangle in the client widget's coordinates (points). It anchors the candidate window.

type MainLoop

type MainLoop uintptr

A MainLoop is a GLib main loop.

func MainLoopNew

func MainLoopNew() MainLoop

MainLoopNew creates a GLib main loop.

func (MainLoop) Quit

func (l MainLoop) Quit()

func (MainLoop) Run

func (l MainLoop) Run()
type MenuBar struct {
	// contains filtered or unexported fields
}

A MenuBar is a GtkPopoverMenuBar over a GMenu, the application menu bar of a plain GtkWindow (no GtkApplication needed). Its actions live in the "bar" group inserted on the window, and its accelerators are a GtkShortcutController on the window, so a chord works wherever the keyboard focus is.

Build it with MenuBarNew, put MenuBar.Widget where the bar should sit (typically prepended to a vertical box) and call MenuBar.SetItems on the main thread whenever the rows change.

func MenuBarNew(window Widget) *MenuBar

MenuBarNew makes an empty bar for window. It returns nil when the menu machinery cannot be loaded.

func (m *MenuBar) Activate(i int) bool

Activate chooses leaf i (depth-first order) through its action name, as a click or its accelerator would, and reports whether it was a row that can be chosen.

func (m *MenuBar) Destroy()

Destroy drops the bar's actions and shortcuts from the window. The bar widget itself is the caller's to unparent.

func (m *MenuBar) Len() int

Len is the number of pickable rows (commands and checks, not menus).

func (m *MenuBar) SetItems(items []BarItem)

SetItems replaces the bar's menus. It does the whole swap, so call it only when something changed.

func (m *MenuBar) Widget() Widget

Widget is the GtkPopoverMenuBar to place in the window.

type MenuEntry struct {
	Index   int
	Label   string
	Enabled bool
}

A MenuEntry is one chosen-able line of a menu model: the position of its item in the caller's list (what an activation reports), the label GTK shows, and whether it can be chosen.

type MenuItem struct {
	Label  string
	OnPick func()
}

A MenuItem is one entry of a ContextMenu. An empty Label is a separator. A nil OnPick is an inert entry: shown, greyed out, and never called.

type Notebook added in v0.15.0

type Notebook struct {
	// contains filtered or unexported fields
}

A Notebook is a GtkNotebook whose pages are empty boxes: the tab strip only.

func NotebookNew added in v0.15.0

func NotebookNew() *Notebook

NotebookNew builds an empty tab strip. It returns nil when GTK4 cannot be bound.

func (*Notebook) Class added in v0.15.0

func (n *Notebook) Class() string

Class is the GTK class name ("GtkNotebook").

func (*Notebook) Current added in v0.15.0

func (n *Notebook) Current() int

Current is the current page, or -1 when there is none.

func (*Notebook) Destroy added in v0.15.0

func (n *Notebook) Destroy()

Destroy releases the notebook's registry entry. The widget itself is owned by its parent.

func (*Notebook) Len added in v0.15.0

func (n *Notebook) Len() int

Len is the number of pages.

func (*Notebook) OnSwitch added in v0.15.0

func (n *Notebook) OnSwitch(fn func(int))

OnSwitch sets the handler called with the new page when the user (or Notebook.Switch) switches.

func (*Notebook) Remove added in v0.15.0

func (n *Notebook) Remove(i int)

Remove removes page i; an index out of range is ignored.

func (*Notebook) SetCurrent added in v0.15.0

func (n *Notebook) SetCurrent(i int)

SetCurrent shows page i; an index out of range is ignored. It does not call the Notebook.OnSwitch handler.

func (*Notebook) SetTabs added in v0.15.0

func (n *Notebook) SetTabs(titles []string)

SetTabs replaces every page with one empty page per title. The current page is whatever GTK leaves; call Notebook.SetCurrent after.

func (*Notebook) Switch added in v0.15.0

func (n *Notebook) Switch(i int)

Switch is Notebook.SetCurrent as the person would do it: the Notebook.OnSwitch handler is called when the page changes.

func (*Notebook) Widget added in v0.15.0

func (n *Notebook) Widget() Widget

Widget is the notebook itself.

type Picture added in v0.2.0

type Picture Widget

A Picture is a GtkPicture that shows an RGBA image a host refreshes each frame with Picture.SetRGBA — the widget the GTK4-hosted go-widgets backend puts the toolkit's pixel framebuffer into, with native controls overlaid above it.

func PictureNew added in v0.2.0

func PictureNew() Picture

PictureNew creates a picture widget. It returns the null Picture if the pixel entry points cannot be loaded.

func (Picture) ReadRGBA added in v0.10.0

func (p Picture) ReadRGBA(dst []byte, width, height int) bool

ReadRGBA copies the pixels the picture shows now into dst (width*height*4, R8G8B8A8), for tests that compare what is on screen with what was drawn. GDK downloads Cairo ARGB32 (BGRA, premultiplied); the R and B channels are swapped back, exact for opaque pixels. It returns false when the picture shows no texture of that size.

func (Picture) SetAlternativeText added in v0.13.0

func (p Picture) SetAlternativeText(text string)

SetAlternativeText is the text a screen reader speaks for the picture.

func (Picture) SetCanShrink added in v0.13.0

func (p Picture) SetCanShrink(v bool)

SetCanShrink lets the picture be drawn smaller than the image, which is what makes a size request on it take effect.

func (Picture) SetFrame added in v0.11.0

func (p Picture) SetFrame(f *SharedFrame)

SetFrame shows the whole frame in the picture without copying it.

func (Picture) SetRGBA added in v0.2.0

func (p Picture) SetRGBA(data []byte, width, height int)

SetRGBA shows width*height*4 bytes of R8G8B8A8 in the picture. It is safe to call every frame: a fresh texture is set and the previous one released (the picture took a reference, so unref-ing the caller's is correct).

func (Picture) UpdateFrame added in v0.11.0

func (p Picture) UpdateFrame(f *SharedFrame, rects []Rect) bool

UpdateFrame shows the frame after only rects changed, copying nothing: the counterpart of Picture.UpdateRGBA over a SharedFrame. It returns false, having changed nothing, in the cases UpdateRGBA does (GTK older than 4.16, no texture of exactly the frame's size shown yet, empty or off-frame rects).

func (Picture) UpdateRGBA added in v0.10.0

func (p Picture) UpdateRGBA(data []byte, width, height int, rects []Rect) bool

UpdateRGBA replaces the picture's texture with the width*height*4 bytes of R8G8B8A8 in data, telling GTK that only rects differ from the texture the picture shows now (GdkMemoryTextureBuilder:update-texture and :update-region), so the renderer can avoid re-rendering the rest. data is still the WHOLE frame and is copied whole: only GTK's own re-render and texture update is narrowed.

It returns false, having changed nothing, when the update API is missing (GTK older than 4.16), when the picture shows no texture of exactly width×height yet (the first frame, a resize), or when rects is empty or lies outside the frame; the caller then calls Picture.SetRGBA.

func (Picture) Widget added in v0.2.0

func (p Picture) Widget() Widget

Widget is the picture as a plain widget, for putting into a container.

type Rect added in v0.10.0

type Rect struct{ X, Y, W, H int }

Rect is a pixel rectangle: the damaged part of a frame.

type SharedFrame added in v0.11.0

type SharedFrame struct {
	// contains filtered or unexported fields
}

A SharedFrame is a width*height R8G8B8A8 framebuffer that lives in GLib memory and is handed to GTK WITHOUT a copy: the texture Picture.SetFrame and Picture.UpdateFrame build refers to the very bytes SharedFrame.Pix returns, so a host that paints into Pix and reports the damaged rectangles pays no per-frame copy at all (SetRGBA and UpdateRGBA copy the whole frame, g_bytes_new).

GdkMemoryTextureBuilder cannot take a partial buffer: gdk_memory_texture_builder_build refuses (g_return_val_if_fail, gdk/gdkmemorytexturebuilder.c:726 at 4.16.0) any GBytes smaller than gdk_memory_format_min_buffer_size(format, stride, width, height), so the new texture's bytes must span the whole frame even though update-region only tells GTK what it may skip re-rendering. Sharing the host's one buffer is how that requirement costs nothing.

The texture sees later writes to Pix. That is exact for the partial path (a frame differs from the last only inside the reported region, which is what update-region promises) and shows the newest pixels if GTK re-reads an older texture. Pix is only valid until SharedFrame.Release; GTK keeps the memory alive for as long as a texture still refers to it.

func NewSharedFrame added in v0.11.0

func NewSharedFrame(width, height int) *SharedFrame

NewSharedFrame allocates a zeroed width×height frame, or returns nil if the GTK libraries cannot be loaded or the size is not positive or overflows.

func (*SharedFrame) Pix added in v0.11.0

func (f *SharedFrame) Pix() []byte

Pix is the frame's pixels, width*height*4 bytes of R8G8B8A8.

func (*SharedFrame) Release added in v0.11.0

func (f *SharedFrame) Release()

Release drops the host's reference. Pix must not be used afterwards; textures still showing the frame keep the memory alive until GTK is done with them.

func (*SharedFrame) Size added in v0.11.0

func (f *SharedFrame) Size() (int, int)

Size is the frame's width and height in pixels.

type TreeNode added in v0.15.0

type TreeNode struct {
	Title    string
	Children []TreeNode
	Expanded bool
}

TreeNode is one node of a TreeView: a title, its children, and whether it starts expanded.

type TreeView added in v0.15.0

type TreeView struct {
	// contains filtered or unexported fields
}

A TreeView is a tree: a GtkListView over a GtkTreeListModel with a GtkTreeExpander per row. Children are made lazily, when a row expands.

func TreeViewNew added in v0.15.0

func TreeViewNew() *TreeView

TreeViewNew builds an empty tree. It returns nil when GTK4 cannot be bound.

func (*TreeView) Class added in v0.15.0

func (t *TreeView) Class() string

Class is the GTK class name of the widget that does the work ("GtkListView").

func (*TreeView) Destroy added in v0.15.0

func (t *TreeView) Destroy()

Destroy releases the view's registry entry. The widget itself is owned by its parent.

func (*TreeView) OnSelect added in v0.15.0

func (t *TreeView) OnSelect(fn func([]int))

OnSelect sets the handler called with the new selected path (nil when cleared) when the user changes the selection.

func (*TreeView) Rebuilds added in v0.15.0

func (t *TreeView) Rebuilds() int

Rebuilds counts how many times SetNodes replaced the tree.

func (*TreeView) SelectPath added in v0.15.0

func (t *TreeView) SelectPath(path []int)

SelectPath is TreeView.SetSelectedPath as the person would do it: the TreeView.OnSelect handler is called when the selection changes (once, with the final path: opening the ancestors is not reported).

func (*TreeView) SelectedPath added in v0.15.0

func (t *TreeView) SelectedPath() []int

SelectedPath is the path of the selected node, or nil.

func (*TreeView) SetNodes added in v0.15.0

func (t *TreeView) SetNodes(nodes []TreeNode)

SetNodes replaces the tree and re-expands the nodes marked Expanded. Children are made as each row expands, so a large collapsed tree costs its top level.

func (*TreeView) SetSelectedPath added in v0.15.0

func (t *TreeView) SetSelectedPath(path []int)

SetSelectedPath selects the node at a path (child indexes from the top level), expanding its ancestors so the row exists; an empty path or one that names no node clears the selection. It does not call the TreeView.OnSelect handler.

func (*TreeView) Widget added in v0.15.0

func (t *TreeView) Widget() Widget

Widget is the widget to place: the scroller around the view.

type Widget

type Widget uintptr

A Widget is a GTK widget — a GObject pointer. The zero value is the null widget. Methods on it are thin wrappers over the C API.

func BoxNew added in v0.5.0

func BoxNew(horizontal bool) Widget

BoxNew creates a GtkBox with zero spacing, horizontal (0) or vertical (1). It is the container a host composes a segmented control from, appending linked toggle buttons; visual linking (the .linked style class) is the host's job.

func ButtonNewWithLabel

func ButtonNewWithLabel(label string) Widget

ButtonNewWithLabel creates a push button.

func CheckButtonNewWithLabel

func CheckButtonNewWithLabel(label string) Widget

CheckButtonNewWithLabel creates a labelled check button. GTK check buttons that share a group act as radios; a host groups them for a NativeRadio.

func ColorNew added in v0.5.0

func ColorNew() Widget

ColorNew creates a GtkColorButton. Read and write the colour as "#RRGGBB" with ColorHex/SetColorHex; connect "color-set" for changes.

func ComboNew added in v0.5.0

func ComboNew(items []string) Widget

ComboNew creates an editable GtkComboBoxText prefilled with items (one append per string). Read and write the shown text with ComboText/SetComboText; connect "changed" for edits.

func DateNew added in v0.5.0

func DateNew() Widget

DateNew creates a GtkCalendar. Read and write the selected day as "YYYY-MM-DD" with DateISO/SetDateISO; connect "day-selected" for changes.

func DrawingAreaNew added in v0.2.0

func DrawingAreaNew() Widget

DrawingAreaNew creates a GtkDrawingArea. QueueDraw asks a widget to repaint.

func EntryNew

func EntryNew() Widget

EntryNew creates a single-line text entry. Call SetVisibility(false) for a secure (password) entry.

func FixedNew

func FixedNew() Widget

FixedNew creates a GtkFixed — the container a host overlays native controls in at absolute positions, over the pixel drawing area.

func LabelNew

func LabelNew(text string) Widget

LabelNew creates a static text label.

func LinkNew added in v0.5.0

func LinkNew(label string) Widget

LinkNew creates a GtkLinkButton showing label with an empty URI, so GTK opens nothing on its own. Wire OnActivateLink for a plain activation.

func ListBoxNew added in v0.6.0

func ListBoxNew() Widget

ListBoxNew creates a GtkListBox — a single-column selectable list. Append rows with ListBoxAppendText, read/write the selection with SelectedRow/SelectRow, and connect "row-selected" for changes.

func OverlayNew added in v0.11.0

func OverlayNew() Widget

OverlayNew creates a GtkOverlay: one child fills it, and overlays sit above.

func PopUpNew added in v0.4.0

func PopUpNew(items []string) Widget

PopUpNew creates a GtkDropDown listing items. The items are copied into a GtkStringList (one append per string, so no C string-array marshalling is needed). Read and write the selection index with Selected/SetSelected; connect "notify::selected" for changes.

func ProgressNew added in v0.5.0

func ProgressNew() Widget

ProgressNew creates a GtkProgressBar. It is read-only: set its position with SetFraction (0..1); there is no change signal (a host drives it).

func SearchNew added in v0.5.0

func SearchNew() Widget

SearchNew creates a GtkSearchEntry. It implements GtkEditable, so Text/SetText work on it directly; connect "search-changed" for edits.

func SliderNew added in v0.4.0

func SliderNew(min, max, step float64) Widget

SliderNew creates a horizontal GtkScale over [min,max] with the given step. Read and write its value with Value/SetValue; connect "value-changed" for edits.

func SpinnerNew added in v0.5.0

func SpinnerNew() Widget

SpinnerNew creates a GtkSpinner — an indeterminate activity indicator. Start and Stop animate it; it has no value.

func StepperNew added in v0.5.0

func StepperNew(min, max, step float64) Widget

StepperNew creates a GtkSpinButton over [min,max] with the given step. Read and write its value with SpinValue/SetSpinValue; connect "value-changed" for edits.

func TextViewNew added in v0.5.0

func TextViewNew() Widget

TextViewNew creates a multi-line GtkTextView. Read and write its whole contents with TextViewText/SetTextViewText. The change signal lives on the underlying GtkTextBuffer, not the view: connect it with ConnectBufferChanged, or reach the buffer with Buffer and connect "changed" yourself.

func ToggleButtonNewWithLabel added in v0.5.0

func ToggleButtonNewWithLabel(label string) Widget

ToggleButtonNewWithLabel creates a labelled GtkToggleButton. Group several with SetGroup for a mutually-exclusive (segmented) set; read and write pressed state with the shared Active/SetActive, and connect "toggled" for changes.

func WindowNew

func WindowNew() Widget

WindowNew creates a top-level window.

func (Widget) Active

func (w Widget) Active() bool

Active and SetActive read and write the pressed state of a check button OR a toggle button — GtkCheckButton and GtkToggleButton are distinct types in GTK4 with separate accessors, so the method dispatches on the widget's runtime type (GTK_IS_TOGGLE_BUTTON). This lets both the check/radio controls and the segmented toggles share one Active/SetActive pair.

func (Widget) AddOverlay added in v0.11.0

func (w Widget) AddOverlay(child Widget)

AddOverlay puts child above the overlay's main child.

func (Widget) AddTickCallback added in v0.2.4

func (w Widget) AddTickCallback(fn func() bool) uint64

AddTickCallback registers fn to run once per frame, driven by this widget's GdkFrameClock, for as long as fn returns true. It is the GTK-native animation tick: aligned to the display's refresh, and quiescent while the widget is unmapped (the frame clock does not run then), so an idle hidden window costs nothing. A host that renders its own pixels into a Picture uses it to present a fresh frame each vsync — unlike a one-shot IdleAdd, which the frame clock would fire before the window is even mapped. fn runs on the main-loop thread; returning false removes the callback. The callback is retained for the process life, like Widget.Connect's.

func (Widget) AllocatedSize added in v0.11.0

func (w Widget) AllocatedSize() (int, int)

AllocatedSize is the size GTK last gave the widget, in logical points, or 0, 0 before the first layout (or if the library cannot be loaded).

func (Widget) Append added in v0.5.0

func (w Widget) Append(child Widget)

Append adds child to the end of a GtkBox.

func (Widget) Buffer added in v0.5.0

func (w Widget) Buffer() Widget

Buffer returns the view's GtkTextBuffer (as a Widget handle — it is a GObject a host connects signals on, not a displayable widget).

func (Widget) Close added in v0.13.0

func (w Widget) Close()

Close asks a window to close, as its close control does: the "close-request" signal runs, and the window is destroyed unless a handler stopped it.

func (Widget) ColorHex added in v0.5.0

func (w Widget) ColorHex() string

ColorHex returns the chosen colour as "#RRGGBB". GdkRGBA is four C floats (red,green,blue,alpha), 16 bytes; alpha is dropped.

func (Widget) ComboText added in v0.5.0

func (w Widget) ComboText() string

ComboText returns the combo's active text — for an editable combo, the text in its entry. gtk_combo_box_text_get_active_text returns a freshly g_malloc'd string that purego copies into Go; the C copy is not freed, a small acceptable per-call leak (no free plumbing, as agreed).

func (Widget) Connect

func (w Widget) Connect(signal string, fn func()) uint64

Connect wires a GObject signal (e.g. "clicked", "changed") to a Go func. The callback keeps the widget's value reachable through its own accessors, so the zero-argument closure is enough for the control signals a host cares about. The returned handler id is GObject's; a host rarely needs it.

The callback is retained for the process life (like the go-macos target classes): GTK holds a C pointer to it, and letting Go collect it would leave a dangling call.

func (Widget) ConnectBufferChanged added in v0.5.0

func (w Widget) ConnectBufferChanged(fn func()) uint64

ConnectBufferChanged connects fn to the view's buffer "changed" signal — fired on every edit. It resolves the buffer for the host.

func (Widget) DateISO added in v0.5.0

func (w Widget) DateISO() string

DateISO returns the selected day as "YYYY-MM-DD". gtk_calendar_get_date hands back a GDateTime we own and unref.

func (Widget) ListBoxAppendText added in v0.6.0

func (w Widget) ListBoxAppendText(text string)

ListBoxAppendText appends a row holding a left-aligned label with text.

func (Widget) Mapped added in v0.13.0

func (w Widget) Mapped() bool

Mapped reports whether the widget is on screen.

func (Widget) Move

func (f Widget) Move(child Widget, x, y float64)
func (w Widget) OnActivateLink(fn func()) uint64

OnActivateLink connects fn to "activate-link", whose handler returns gboolean. The bound callback returns TRUE, which suppresses GTK's own URI-open so the link behaves as a plain clickable activation.

func (Widget) OnCloseRequest added in v0.13.0

func (w Widget) OnCloseRequest(fn func() (stop bool))

OnCloseRequest runs fn when the window's own close control is used, and lets the window close only if fn returns false. Returning true handles the request: the window stays, and is the caller's to hide.

func (Widget) OnKey added in v0.3.0

func (w Widget) OnKey(fn func(keyval, keycode, state uint, press bool))

OnKey fires on a key press and release that reaches w — that is, one no focused child (a native entry) consumed first. It gives the GDK keyval and keycode, the modifier state, and whether this is a press. Use KeyvalToUnicode for the rune and a keyval table for named keys.

func (Widget) OnKeyIM added in v0.12.0

func (w Widget) OnKeyIM(im IMContext, fn func(keyval, keycode, state uint, press bool))

OnKeyIM is Widget.OnKey with an input method in front: GTK offers each key event to im first, and fn sees only the events im did not consume — so a dead key or a compose sequence reaches im, and the character it makes reaches the host through IMContext.OnCommit, while an ordinary letter the context passes through also arrives that way and is NOT delivered to fn. Named keys, shortcuts and releases still reach fn.

func (Widget) OnMotion added in v0.3.0

func (w Widget) OnMotion(fn func(state uint, x, y float64))

OnMotion fires when the pointer moves over w, with the modifier state (a button mask distinguishes a drag) and the widget-local point.

func (Widget) OnMouseDown added in v0.3.0

func (w Widget) OnMouseDown(fn func(button int, state uint, x, y float64))

OnMouseDown fires on a press of any mouse button over w, with the button (1 left, 2 middle, 3 right), the GDK modifier state, and the widget-local point.

func (Widget) OnMouseUp added in v0.3.0

func (w Widget) OnMouseUp(fn func(button int, state uint, x, y float64))

OnMouseUp fires on the matching release.

func (Widget) OnScroll added in v0.3.0

func (w Widget) OnScroll(fn func(dx, dy float64, state uint))

OnScroll fires on a wheel or trackpad scroll over w, with the delta in both axes (units are wheel notches / trackpad steps) and the modifier state.

func (Widget) Parent added in v0.8.0

func (w Widget) Parent() Widget

Parent is the widget currently holding this one, or 0 when nothing does.

A host that moves a control between containers -- into a clipping box as it scrolls out of view, back out as it scrolls in -- has no other way to see that the move happened: Unparent and Put report nothing, so its own record of where a widget went is the only thing it can otherwise check, and that record is exactly what would be wrong.

func (Widget) Prepend added in v0.16.0

func (w Widget) Prepend(child Widget)

Prepend adds child to the start of a GtkBox, which is where a menu bar goes.

func (Widget) Present

func (w Widget) Present()

func (Widget) Put

func (f Widget) Put(child Widget, x, y float64)

func (Widget) QueueDraw added in v0.2.0

func (w Widget) QueueDraw()

func (Widget) SelectRow added in v0.6.0

func (w Widget) SelectRow(i int)

SelectRow selects the row at index i (a no-op if i is out of range).

func (Widget) Selected added in v0.4.0

func (w Widget) Selected() int

Selected returns the selected index, or -1 when nothing is selected (GTK_INVALID_LIST_POSITION). SetSelected selects by index.

func (Widget) SelectedRow added in v0.6.0

func (w Widget) SelectedRow() int

SelectedRow returns the selected row's index, or -1 when nothing is selected.

func (Widget) SetActive

func (w Widget) SetActive(on bool)

func (Widget) SetButtonChild added in v0.13.0

func (w Widget) SetButtonChild(child Widget)

SetButtonChild replaces a button's content with child (the null widget gives the button back its label). A button given a child no longer draws its label.

func (Widget) SetChild

func (w Widget) SetChild(child Widget)

func (Widget) SetColorHex added in v0.5.0

func (w Widget) SetColorHex(s string)

SetColorHex sets the colour from an "#RRGGBB" string (alpha forced opaque). A malformed string is ignored.

func (Widget) SetComboText added in v0.5.0

func (w Widget) SetComboText(s string)

SetComboText sets the editable combo's text by writing into its child entry (gtk_combo_box_get_child → gtk_editable_set_text).

func (Widget) SetDateISO added in v0.5.0

func (w Widget) SetDateISO(s string)

SetDateISO selects the day named by an "YYYY-MM-DD" string. A malformed string or an impossible date is ignored.

func (Widget) SetDefaultSize

func (w Widget) SetDefaultSize(width, height int)

func (Widget) SetExpand added in v0.16.0

func (w Widget) SetExpand(h, v bool)

SetExpand makes the widget take the space its parent has left over, across (h) and down (v): what keeps a box's main child filling the window under a bar.

func (Widget) SetFraction added in v0.5.0

func (w Widget) SetFraction(f float64)

SetFraction sets a progress bar's fill, clamped by GTK to [0,1].

func (Widget) SetGroup added in v0.5.0

func (w Widget) SetGroup(group Widget)

SetGroup joins this toggle button to group's exclusive set. Pass the zero Widget to start a fresh group (become the group's first member).

func (Widget) SetLabel

func (w Widget) SetLabel(label string)

func (Widget) SetOverflowHidden added in v0.7.0

func (w Widget) SetOverflowHidden(hide bool)

SetOverflowHidden decides whether a widget clips what its children draw to its own allocation. A host that scrolls native controls puts one that is only partly in view inside a box sized to the visible part, with this set: without it GTK draws the child whole, past the viewport it belongs to.

func (Widget) SetOverlayChild added in v0.11.0

func (w Widget) SetOverlayChild(child Widget)

SetOverlayChild sets the widget the overlay is sized and allocated around.

func (Widget) SetSelected added in v0.4.0

func (w Widget) SetSelected(i int)

func (Widget) SetSizeRequest

func (w Widget) SetSizeRequest(width, height int)

SetSizeRequest fixes a widget's size (a host sizes controls to the region it laid out).

func (Widget) SetSpinValue added in v0.5.0

func (w Widget) SetSpinValue(v float64)

func (Widget) SetText

func (w Widget) SetText(s string)

func (Widget) SetTextViewText added in v0.5.0

func (w Widget) SetTextViewText(s string)

SetTextViewText replaces the whole buffer contents.

func (Widget) SetTitle

func (w Widget) SetTitle(title string)

func (Widget) SetTooltip added in v0.13.0

func (w Widget) SetTooltip(text string)

SetTooltip sets the text shown on hover, which assistive technology also reads for a widget with no text of its own.

func (Widget) SetValue added in v0.4.0

func (w Widget) SetValue(v float64)

func (Widget) SetVisibility

func (w Widget) SetVisibility(vis bool)

func (Widget) SetVisible

func (w Widget) SetVisible(vis bool)

SetVisible shows or hides a widget in place.

func (Widget) SpinValue added in v0.5.0

func (w Widget) SpinValue() float64

func (Widget) Start added in v0.5.0

func (w Widget) Start()

func (Widget) Stop added in v0.5.0

func (w Widget) Stop()

func (Widget) Text

func (w Widget) Text() string

Text and SetText read and write an editable's text (entry, label via editable where applicable), through the GtkEditable interface.

func (Widget) TextViewText added in v0.5.0

func (w Widget) TextViewText() string

TextViewText returns the whole buffer contents. A GtkTextIter is an opaque fixed-size struct filled in place; a 128-byte buffer is comfortably larger than its ~80 bytes. gtk_text_buffer_get_text returns a freshly g_malloc'd string that purego copies into Go; the C copy is not freed, a small acceptable per-call leak.

func (Widget) Unparent

func (w Widget) Unparent()

Unparent removes a widget from its parent (a host reconciling controls away).

func (Widget) Value added in v0.4.0

func (w Widget) Value() float64

Value and SetValue read and write a slider's (GtkRange's) current value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址