application

package module
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: BSD-3-Clause Imports: 14 Imported by: ? modules, 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

application — cross-platform application lifecycle for go-widgets

CI Go Reference

The layer above go-widgets/window: where window presents a single surface, application owns the whole app lifecycle. It opens the native OS window, drives its run loop, blits the handler's own RGBA framebuffer into it, composes a system-tray / menu-bar icon alongside the window (via go-widgets/tray), threads the live system appearance (dark/light, accent, system font) into the handler, translates native input into the toolkit's event vocabulary, publishes an accessibility tree, and fires a ready callback once the first frame is on screen. No WebKit, no wasm, no HTTP — every widget is drawn by the framework and the window is just a bitmap surface plus a native event source. Everything is CGO_ENABLED=0.

Opening a real OS window and pumping its event loop is a launch-verified boundary, so the native Run path is excluded from the coverage gate (like the wasm glue elsewhere); the contract, the event translation, the present gating, the appearance pump, the launch-height seam and the ready-after-first-frame counter are all unit-tested to 100%.

platform native window (go-widgets/window) native tray (go-widgets/tray)
darwin Cocoa / NSWindow (purego + the Obj-C runtime) NSStatusItem + NSMenu
windows win32 (golang.org/x/sys/windows syscalls) Shell_NotifyIcon + TrackPopupMenu
linux X11 / Wayland (pure-Go wire protocols) StatusNotifierItem over DBus

The tray is attached to the window's own loop (Tray.Attach) once the first frame is up. A tray that cannot be attached is Run's error, not a silence: the window is closed and Run returns the attach error wrapped, so errors.Is(err, tray.ErrNoBackend) says why. That needs a tray release whose backend implements Attach on the platform: darwin always has; Linux and Windows do from the tray release carrying go-widgets/tray#36, and before it Spec.Tray there is now this error rather than no tray at all. An application that wants its window whatever happens to the tray leaves Spec.Tray nil and runs one itself.

Run closes the window when its loop returns, and puts back the toolkit clipboard it installed from it, so an application can call Run again to open a fresh window -- a tray app's "Open" after the window was closed -- without the old one staying on screen. (On X11 a closed window used to stay mapped, frozen, until a garbage collection finalised its connection.)

Usage

package main

import (
	"github.com/go-widgets/application"
	"github.com/go-widgets/tray"
)

func main() {
	spec := application.Spec{
		Name:       "News Reader",
		Identifier: "com.example.reader",
		Version:    "1.0.0",
		Icon:       iconPNG, // []byte, optional
		Tray: func() *tray.Menu { // optional
			return tray.NewMenu().Add(
				tray.Item("Refresh", func() { app.Refresh() }),
				tray.Item("Quit", func() { app.Quit() }),
			)
		},
	}

	cfg := application.Config{Title: "News Reader", Width: 1200, Height: 800}

	// handler renders the app's own framebuffer and takes its input; onReady
	// fires once, after the first frame is visible.
	err := application.Run(spec, cfg, handler, func() {
		log.Println("first frame is on screen")
	})
	if err != nil {
		log.Fatal(err)
	}
}

handler implements application.Handler (Frame / Resize / MouseDown / MouseMove / MouseUp / Scroll / Key). It may additionally implement any of the optional capability interfaces — AppearanceSink, ShortcutSink, ModifiedClicker, ModifiedKeyer, SecondaryClicker, ContextMenuHost, ClipboardController, Accessible, NativeControlProvider, HeightFitter — and the run loop, which never wraps the handler, will honour each one it finds.

Accessibility of painted widgets

A handler that paints its own go-widgets widgets is, to a screen reader, one unlabelled rectangle: its painted buttons are not in the macOS AX tree, the AT-SPI tree or the UIA tree until it says they exist. It does so by implementing Accessible, and A11yElementsOf builds the answer from the widget tree it paints:

func (v *View) A11yElements() []application.A11yElement {
	return application.A11yElementsOf(v.root) // role, label, value, bounds, disabled
}

Each element carries the role, label and value its widget reports, at the widget's bounds (device pixels). The back-end maps them to its platform (NSAccessibilityElement, AT-SPI, UIA), publishes only when the description changed, and turns a platform "press" into a click at the element's centre through the handler's own MouseDown/MouseUp. The result is capped at MaxA11yElements (1000). Widgets with no A11y method contribute nothing.

A disabled widget (A11yElement.Disabled) is published as such: macOS AXEnabled false, UI Automation IsEnabled false, AT-SPI without ENABLED/SENSITIVE, so a screen reader announces it as unavailable instead of offering to press it.

Handler has nowhere to put a modifier key: MouseDown(x, y int) carries no Shift, and Key's own contract says it has "no room to say which modifiers were held". ModifiedClicker and ModifiedKeyer are how a handler receives them, and without one a Shift-click or a Shift-arrow cannot reach the widget underneath whatever that widget supports.

That list is checked against the code by TestEveryCapabilityIsNamedInThePackageDoc, which walks the package for type assertions off a Handler and insists both this file and the package doc name each one. It had drifted three capabilities behind before the check existed.

For a non-window host (a desktop shell, wasmdesk, a tab in something larger), Bind(handler, scale) and BindScaled(handler, scaleOf) return a *toolkit.Surface wired to the same handler without opening a window.

A tray application: Raise, Show, Hide and Config.HideOnClose

A tray app's "Open" item must bring back the window that is already there, and closing the window must not quit the app. Both are in the package:

application.Run(spec, application.Config{Title: "App", Width: 480, Height: 640, HideOnClose: true}, h, nil)

// in the tray's "Open" callback, on any goroutine:
if err := application.Raise(); err != nil { /* ErrNoWindow, ErrNotSupported */ }
  • Raise() shows the window if hidden, restores it if minimised, brings it to the front and asks for the focus. Show() only makes it visible; Hide() takes it off the screen without closing it (Run keeps running, the handler keeps its state).
  • Config.HideOnClose makes the window's own close control hide it instead of ending Run; the app then quits through its tray's Quit. On macOS a click on the app's Dock icon while the window is hidden shows and raises it again, as standard apps do (window v0.111.0, applicationShouldHandleReopen:); Windows and Linux have no equivalent event for a hidden window.
  • Never a silent no-op: ErrNoWindow (before Run opened a window or after it returned; wraps window.ErrClosed) and ErrNotSupported (the window package's own error) say what could not be done.
back-end Raise / Show / Hide HideOnClose
macOS (Cocoa) yes yes
Windows (Win32) yes yes
X11 yes yes
Wayland Show, Hide; Raise is ErrNotSupported (no xdg request) yes
GTK, Android, wasm ErrNotSupported Run returns ErrNotSupported

A second window: OpenWindow

// In a handler callback (the "+" button's), on the UI thread:
w, err := application.OpenWindow(application.WindowConfig{Title: "Add server", Width: 420, Height: 260}, formHandler)
if err != nil { /* ErrNoWindow, ErrNotSupported */ }
w.OnClose(func() { /* the user closed it, or w.Close() did */ })
// later, from any goroutine:
w.Raise()
w.Close()

OpenWindow opens a second top-level window on the loop Run already drives. formHandler is a Handler of its own and gets what the main window's handler gets: frames at the panel's resolution, input, native controls, accessibility, damage, the system appearance and the clipboard. Closing the second window leaves Run running; closing the main window closes it. ErrNoWindow before Run has opened the main window or after it returned; ErrNotSupported on a back-end without the capability: macOS, Windows and GTK4 (GO_WIDGETS_GTK=1) have it; X11, Wayland, wasm and Android answer ErrNotSupported. Parent/modality is not offered.

A window that fits its content: FitHeight, HeightFitter
application.OpenWindow(application.WindowConfig{
    Title: "Server", Width: 480, FitHeight: true, // MinHeight / MaxHeight optional
}, formHandler) // formHandler also implements HeightFitter

func (v *form) PreferredHeight(width float64) float64 { /* logical points */ }

With FitHeight, the window is exactly as tall as the handler's PreferredHeight(width) says (rounded up, held to MinHeight/MaxHeight; the default cap is the usable screen height), so there is no empty band under the last control. The measure is in logical points, so a 1x and a 2x display get the same window, and it is taken again after every frame: a message that appears or a page that is swapped makes the window follow. The user cannot resize such a window. Resizing an open window needs go-widgets/window's ContentSizer (macOS today); elsewhere the window keeps its opening height. Apple's guidance is to "choose an initial window size that minimizes empty areas within it" (Windows, HIG).

Native dialogs: OpenFile, SaveFile, Alert, Confirm

err := application.OpenFile(application.OpenOptions{
    Title: "Open", Multiple: true,
    Filters: []application.Filter{{Name: "Images", Extensions: []string{"png", "jpg"}}},
}, func(r application.OpenResult) { /* r.Paths, or r.Err == ErrCancelled */ })
// SaveFile(SaveOptions{Name: "report.txt"}, func(SaveResult)), Alert(AlertOptions{...}, func(AlertResult)),
// Confirm(message, detail, yes, no, func(yes bool, err error))
  • Asynchronous and safe from any goroutine: the call returns at once, and the callback runs exactly once on its own goroutine (never the UI thread). When the call itself returns an error, the callback is never called.
  • Errors: ErrNoWindow before Run has opened the window, ErrNotSupported on a back-end without native dialogs (X11, Wayland, wasm), ErrInvalidDialog for an input that is out of bounds, holds a NUL byte or is not UTF-8 (limits: MaxFilters, MaxExtensions, MaxButtons, MaxStringLen, MaxMessageLen), and ErrCancelled in a result when the user dismissed the dialog.
  • Paths come back as the platform gives them, never resolved or followed.
  • Native on macOS (NSOpenPanel, NSSavePanel, NSAlert), GTK 4.10+ (GtkFileDialog, GtkAlertDialog) and Windows (IFileDialog, TaskDialog).

The menu bar: Config.Menu and SetMenu

cfg := application.Config{
	Title: "Notes",
	Menu: tray.NewMenu().Add(
		tray.SubMenu("File", tray.NewMenu().Add(
			tray.KeyItem("Save", nil, "s", tray.ModCommand, save),
		)),
		tray.EditMenu(), // Undo, Redo, Cut, Copy, Paste, Select All
	),
}
err := application.Run(spec, cfg, handler, nil)

The menu is the go-widgets/tray model (labels, key equivalents, checkmarks, separators, submenus, handlers), the same one a tray icon uses. application.SetMenu(m) changes it at any time, from any goroutine, before or while the application runs; the platform menu is rebuilt only when Menu.Signature() changed.

  • macOS: the menu bar at the top of the screen, with the standard application menu (About, Hide, Quit) first, named after Config.Title. Without tray.EditMenu() copy and paste do not work in native text fields.
  • Windows: the window's menu bar; key equivalents are shown as Ctrl+S.
  • GTK 4: a GtkPopoverMenuBar above the window's content; key equivalents are window-wide shortcuts that take precedence over the content.
  • X11, Wayland, wasm, Android: no menu bar. SetMenu answers ErrNotSupported and Run carries on without one.

Opening a URL in the browser: OpenURL

if err := application.OpenURL("https://example.com/oauth/authorize?..."); err != nil {
	// errors.Is(err, application.ErrURLScheme / ErrURLInvalid / ErrOpenURLUnsupported)
}

OpenURL(rawURL string) error opens the URL in the user's default browser and returns once the OS has accepted the request (it does not wait for the browser). It is what an OAuth sign-in needs.

Only absolute http and https URLs with a host (and a port within 1-65535, if any) are accepted, up to 8 KiB. Anything else is refused before the OS sees it: ErrURLScheme for a file:, smb:, UNC, javascript: or custom-scheme URL (the URLs an app opens often come from a server's document, and those would launch a local file or a registered handler), ErrURLInvalid for a malformed one. The URL is re-serialised from its parse, so what was checked is what is opened.

OS Mechanism
macOS NSWorkspace openURL: through the objc bridge (no open process)
Windows ShellExecuteW, verb open
Linux the org.freedesktop.portal.OpenURI portal over D-Bus (works from a sandbox), falling back to xdg-open
other ErrOpenURLUnsupported

The URL check and the Linux chain are covered by tests (the portal call against a fake portal on a real session bus); the real OS calls need a desktop and are the launch-verified boundary, like the window loop. OPENURL_LIVE=<url> go test -run TestOpenURLLive . opens one real browser tab to prove it on the machine at hand.

License

BSD-3-Clause. See LICENSE.

Documentation

Overview

Package application owns a go-widgets app's whole lifecycle: it opens the native OS window, runs its event loop, blits the handler's own RGBA framebuffer into it, composes a system-tray / menu-bar icon alongside it, and fires a "ready" callback once the first frame is on screen. It is the sibling of go-widgets/window: window presents a single surface, application is the layer above it that turns a handler plus an identity (name, icon, tray) into a running application. There is no WebKit, no wasm, no HTTP — every widget is drawn by the framework (toolkit.Surface) and the window is just a bitmap surface plus a native event source. Everything is CGO_ENABLED=0.

Opening a real OS window and pumping its event loop is inherently a launch-verified boundary, so the Run path through go-widgets/window is excluded from the coverage gate (like the wasm glue elsewhere); this contract, the event translation, the present gating, the appearance pump, the launch-height seam and the ready-after-first-frame counter are all unit-tested.

The optional capability interfaces (AppearanceSink, ShortcutSink, ModifiedClicker, ModifiedKeyer, SecondaryClicker, ContextMenuHost, ClipboardController, Accessible, NativeControlProvider, HeightFitter) are the reason the run loop must never WRAP a Handler: a wrapper would satisfy the bare Handler interface and silently drop every capability the concrete handler also implements.

⛔ That list is checked against the code, by TestEveryCapabilityIsNamedInThePackageDoc: it walks the package for type assertions off a Handler and insists the doc names each exported interface it finds. It had drifted three capabilities behind before the check existed, and a list that is wrong is worse than no list -- a reader counting six does not go looking for a seventh. Everything here threads the ORIGINAL handler through, and type-asserts for a capability at the point of use.

Index

Constants

View Source
const (
	MaxFilters    = gw.MaxFilters
	MaxExtensions = gw.MaxExtensions
	MaxButtons    = gw.MaxButtons
	MaxStringLen  = gw.MaxStringLen
	MaxMessageLen = gw.MaxMessageLen
)

The bounds and errors of the dialog options, from the window package.

View Source
const MaxA11yElements = 1000

MaxA11yElements bounds the tree A11yElementsOf reports. A screen reader cannot use thousands of stops, and each element costs the platform bridge several round-trips to the accessibility server, so a runaway tree (a log with a row per line, say) is cut rather than allowed to stall the window. Elements beyond the bound are dropped from the END of the reading order.

Variables

View Source
var (
	// ErrCancelled is the Err of a dialog the user dismissed without choosing.
	ErrCancelled = gw.ErrCancelled
	// ErrInvalidDialog wraps every rejection of a dialog's options.
	ErrInvalidDialog = gw.ErrInvalidDialog
)
View Source
var (
	// ErrURLScheme is returned (wrapped, so test with errors.Is) when the URL's
	// scheme is not http or https. It is a security boundary: the URLs an app
	// opens often come from a server's document, and a file:, smb:, UNC or
	// custom-scheme URL would make the OS launch a local file or a registered
	// handler.
	ErrURLScheme = errors.New("application: only http and https URLs are opened")
	// ErrURLInvalid is returned (wrapped) for a URL that does not parse, has no
	// host, or is empty or longer than the bound.
	ErrURLInvalid = errors.New("application: not a valid absolute URL")
	// ErrOpenURLUnsupported is returned when the platform has no way to open a
	// URL (a target with neither macOS, Windows nor Linux).
	ErrOpenURLUnsupported = errors.New("application: this platform cannot open a URL")
)
View Source
var ErrNoWindow = gw.ErrClosed

ErrNoWindow is what Raise, Show and Hide answer when no window is open: before Run has opened one, or after it has returned. It wraps github.com/go-widgets/window.ErrClosed, so errors.Is finds either.

View Source
var ErrNotSupported = gw.ErrNotSupported

ErrNotSupported is what Raise, Show, Hide and Run (with Config.HideOnClose) answer when the platform's window back-end cannot do it: never a silent no-op. It is the window package's own error, so errors.Is finds it through either name. Wayland, for one, has no request to raise a window; see github.com/go-widgets/window.Visibility for the per-back-end table.

View Source
var ErrUnsupported = errors.New("application: no native window back-end on this platform")

ErrUnsupported is returned by Run on a platform without a native back-end.

Functions

func Alert added in v0.13.0

func Alert(o AlertOptions, done func(AlertResult)) error

Alert shows the platform's message dialog with o.Buttons, the first being the default, and reports the index of the one pressed.

func Bind

func Bind(h Handler, scale float64) *toolkit.Surface

Bind returns a toolkit.Surface showing h: the frame it presents, the input it takes, and the tree it publishes for a screen reader.

Run uses it to fill a native window, but it is exported because a window is not the only place this can go. Any go-widgets host that can lay out a widget can host this application — a desktop shell, a tab in something larger, wasmdesk — and none of them should have to reimplement the translation.

scale is the framebuffer pixels per logical point the host is rendering at; pass 1 if it does not scale. A host whose scale CHANGES while running — a window dragged between displays of different density — should use Run, which re-reads it every frame.

It is also what makes the wiring testable. Everything specific to the app lives here — the resize units, the event translation, the element mapping — and none of it needs a window to be wrong, so a test can drive a real app scene through a real surface and assert the scene moved.

func BindScaled

func BindScaled(h Handler, scaleOf func() float64) *toolkit.Surface

BindScaled is Bind for a host whose scale CHANGES while it runs: a window dragged between displays of different density. The function is called every frame, and the handler is told about a change the moment it happens.

func Confirm added in v0.13.0

func Confirm(message, detail, yes, no string, done func(yes bool, err error)) error

Confirm is Alert with two buttons: done receives true when yes, the first and default, was pressed.

func Hide added in v0.11.0

func Hide() error

Hide takes the window off the screen without closing it: Run keeps running and the handler keeps its state, so Show or Raise puts back exactly what was there. See Raise for the errors.

func MenuError() error

MenuError is the error the last attempt to install the menu bar at Run failed with, or nil. ErrNotSupported is not recorded: it is the normal answer on a platform without a menu bar.

func OpenFile added in v0.13.0

func OpenFile(o OpenOptions, done func(OpenResult)) error

OpenFile shows the platform's open-file dialog: one file, or with o.Multiple several, or with o.Directories a directory. done receives the chosen paths, or ErrCancelled.

func OpenURL added in v0.9.0

func OpenURL(rawURL string) error

OpenURL opens rawURL in the user's default web browser and returns once the OS has accepted the request (it does not wait for the browser).

Only absolute http and https URLs with a host are accepted; any other scheme is ErrURLScheme, a malformed one ErrURLInvalid. The URL is re-serialised from its parse before it reaches the OS, so what was checked is what is opened.

  • macOS: NSWorkspace openURL: through the objc bridge (no `open` process).
  • Windows: ShellExecuteW with the "open" verb.
  • Linux: the org.freedesktop.portal.OpenURI portal over D-Bus (which also works from a sandbox), falling back to xdg-open when there is no portal.

func Raise added in v0.11.0

func Raise() error

Raise brings the application's window to the front, showing it first when it is hidden and restoring it when it is minimised, and asks for the keyboard focus. It is what a tray's "Open" item calls, and it is safe from any goroutine -- the tray's callback runs on its own.

It answers ErrNoWindow when no window is open, and ErrNotSupported when the back-end cannot raise (Wayland). The platform may still refuse the focus.

func Run

func Run(s Spec, cfg Config, h Handler, onReady func()) error

Run opens the application's window and runs it to completion, putting up a menu-bar tray (when Spec.Tray is set) attached to the window's run loop, and invoking onReady once after the first frame is shown. It mirrors window.Run but owns the whole app lifecycle. (The .app bundle + Dock icon are a build-time concern handled by the packager, not here.) The window is closed when Run returns, whichever way its loop ended.

The tray is ATTACHED, not Run: attaching joins the platform's already-running main loop (the one win.Run drives for the window) rather than starting a second one, which is the only way a window and a tray can coexist in one process. It is attached from onReady, on its own goroutine, and stopped with Quit when the window returns -- whichever way the window loop ends (a clean quit, or an error), the deferred Quit tears the tray down so no menu-bar icon is orphaned.

⛔ A tray that cannot be attached is an ERROR, not a shrug (go-widgets/application#28). Run used to swallow it so that "a missing tray must not stop the window", and on Linux, where the tray backend did not implement Attach, that meant Spec.Tray put no tray up and nothing said so -- in an application whose only way back to a hidden window was that tray. Now the window is closed and Run returns the attach error, wrapped (errors.Is finds tray.ErrNoBackend). A caller that wants a window whatever happens to the tray leaves Spec.Tray nil and runs one itself.

func SaveFile added in v0.13.0

func SaveFile(o SaveOptions, done func(SaveResult)) error

SaveFile shows the platform's save-file dialog with o.Name suggested. done receives the path chosen, which may not exist yet, or ErrCancelled.

func SetMenu added in v0.14.0

func SetMenu(m *tray.Menu) error

SetMenu installs m as the application's menu bar, or removes it when m is nil. Called before Run it is applied when the window opens. It answers ErrNotSupported where the back-end has no menu bar.

func Show added in v0.11.0

func Show() error

Show makes a hidden window visible again, without asking for the focus. See Raise for the errors.

Types

type A11yElement

type A11yElement struct {
	Role       string
	Name       string
	Value      string
	X, Y, W, H int
	// Disabled marks an element that is shown but cannot be operated. Each
	// back-end publishes it in its platform's own terms (macOS AXEnabled, UI
	// Automation IsEnabled, AT-SPI ENABLED/SENSITIVE), so a screen reader
	// announces it as unavailable instead of offering to press it.
	Disabled bool
}

A11yElement is one element the handler wants the platform's accessibility layer to expose: what it is, what it says, and where it sits.

Rect is in DEVICE PIXELS with a top-left origin — the same space Frame's buffer and the MouseDown coordinates use — because that is the only space this package and its handler already agree on. Each back-end converts it to whatever its own accessibility API wants (macOS: screen points, y-up).

Role is a neutral name, not a platform constant: this package presents pixels and must not drag a platform's vocabulary into the handler. The back-end maps it (see axRole).

func A11yElementsOf added in v0.10.0

func A11yElementsOf(root toolkit.Widget) []A11yElement

A11yElementsOf describes a toolkit widget tree for Accessible.

A Handler that paints with go-widgets widgets of its own, rather than handing the framework a tree to host, is a single opaque rectangle to the platform's accessibility layer: its painted buttons and labels are not in the macOS AX tree, the AT-SPI tree or the UIA tree, because nothing told the bridge they exist. The handler implements Accessible by returning the elements of the root it paints:

func (v *View) A11yElements() []application.A11yElement {
	return application.A11yElementsOf(v.root)
}

The walk is toolkit.WalkA11y, so each element carries the role, label and value its widget reports, at the widget's bounds, which are already in the handler's device-pixel space. Widgets that report nothing (no A11y method, or RolePresentation) contribute no element. Pressing an element is replayed by the back-end as a click at its centre through the handler's own MouseDown and MouseUp, so every action a click has, a press has.

Whether an unnamed or zero-area element is worth publishing is the back-end's decision, as it is for a hosted tree. The result is capped at MaxA11yElements; a nil root gives nil. Change-driven publishing is the back-end's too: it compares the description with the one it last published and republishes only what changed, so calling this every frame costs one walk and no platform calls.

Like every Accessible implementation it must be called between frames, on the goroutine that mutates the widget tree.

type Accessible

type Accessible interface {
	// A11yElements returns the current elements in reading order. It is called
	// from the platform's accessibility client, which on macOS is the main
	// thread, at unpredictable times — the implementation must be safe to call
	// between frames.
	A11yElements() []A11yElement
}

Accessible is implemented by a Handler that can describe what it is showing. A back-end that supports an accessibility API asks for the description when the platform requests it; a handler that does not implement this simply presents pixels, as before.

It is a separate, optional interface rather than a Handler method so that adding it breaks no existing back-end or handler.

type AlertOptions added in v0.13.0

type AlertOptions = gw.AlertOptions

AlertOptions configures Alert.

type AlertResult added in v0.13.0

type AlertResult = gw.AlertResult

AlertResult is what an Alert callback receives.

type AppearanceSink

type AppearanceSink interface {
	SystemAppearance(SystemAppearance)
}

AppearanceSink is an optional Handler capability. A back-end that can read the host appearance (currently the macOS Cocoa back-end) pushes it so the UI adopts the native dark/light mode, accent colour, and system font.

type ClipboardController

type ClipboardController interface {
	SetSystemClipboard(SystemClipboard)
}

ClipboardController is an optional Handler capability. A back-end that can reach the platform pasteboard installs its SystemClipboard here at startup (the mirror of AppearanceSink: this one flows a capability OUT to the handler). A back-end without clipboard support installs nothing, leaving the toolkit's default in-process clipboard in place (copy/paste still work within the app, just not across the OS).

type Config

type Config struct {
	Title string

	// Width and Height are the content size in logical points. A Height of zero
	// opens the window as tall as the visible screen; any other Height is honoured.
	Width, Height float64

	// HideOnClose makes the window's own close control hide the window instead of
	// ending [Run]: the application keeps running (in its tray) and quits only
	// through an explicit quit -- the tray's Quit item, or the process being told
	// to. [Raise] or [Show] brings the window back. A back-end that cannot hide
	// on close (GTK, Android, wasm) makes Run return [ErrNotSupported] rather than
	// open a window that quits when the user was promised it would not.
	HideOnClose bool

	// Menu is the application's menu bar, in the same model a tray icon's menu
	// uses; see [SetMenu] for the platforms and for changing it later. Nil leaves
	// the platform's default (on macOS, the bare application menu).
	Menu *tray.Menu
}

Config controls the window.

type ContextMenuHost

type ContextMenuHost interface {
	ContextMenuActive() bool
	ContextMenuEvent(ev toolkit.Event)
}

ContextMenuHost is an optional Handler capability: while it reports a context menu open, the window feeds every input event to ContextMenuEvent instead of the usual MouseDown/Move/Scroll/Key path, so the menu is modal. The handler closes the menu itself (an item fired, a click landed outside, Escape) and then reports it inactive again.

type Filter added in v0.13.0

type Filter = gw.Filter

Filter is a named set of extensions, without the dot.

type Handler

type Handler interface {
	// Frame returns the current RGBA framebuffer (w*h*4 bytes) and whether it
	// changed since the last call (damage gate).
	Frame() (buf []byte, w, h int, changed bool)
	// Resize maps the new logical size to device pixels; scale is the backing
	// scale factor (device pixels per point).
	Resize(w, h int, scale float64)
	// MouseDown reports a left button press at device-pixel coordinates.
	MouseDown(x, y int)
	// MouseMove reports pointer motion at device-pixel coordinates. It fires
	// continuously during a left-button drag (back-ends need not emit idle
	// hovers) so the handler can drive interactions like a divider resize.
	MouseMove(x, y int)
	// MouseUp reports a left button release at device-pixel coordinates.
	MouseUp(x, y int)
	// Scroll reports a wheel delta in device pixels.
	Scroll(dy int)
	// Key reports a key press: name is a symbolic label for editing keys
	// ("Backspace"/"Escape"/"Enter"), r the rune for a printable character.
	Key(name string, r rune)
}

Handler is the presenter's data source and input sink. The window calls Frame each tick (and after each event) and blits the returned buffer only when it reports changed. Input coordinates are device pixels (points × backing scale) with a top-left origin, matching the framebuffer.

type HeightFitter added in v0.18.0

type HeightFitter interface {
	PreferredHeight(width float64) float64
}

HeightFitter is an optional Handler capability: report the height the content needs at a given width, so a secondary window opened with WindowConfig.FitHeight is exactly that tall and has no empty band under its last control. Apple's guidance is "choose an initial window size that minimizes empty areas within it".

Both numbers are logical points -- the unit of WindowConfig -- so the answer does not depend on the display's density, and a window looks the same on a 1x and a 2x panel. The window asks again whenever it is drawn, so a handler whose content changes height (a message appears, a page is swapped) is followed; it must therefore be cheap and must not change the handler's state.

type ModifiedClicker added in v0.4.0

type ModifiedClicker interface {
	ModifiedClick(x, y int, m Modifiers)
}

ModifiedClicker is an optional Handler capability: a press arrives here WITH the modifier keys that were held, instead of through Handler.MouseDown, which has no room to carry them.

⛔ Without it a handler cannot express a Shift-click or a ⌘-click to the widget underneath, whatever that widget supports. Measured: go-widgets toolkit's ListBox and Table both build a multi-row selection from Ctrl/⌘ and Shift clicks, and an app on this contract could reach NONE of it -- it had nothing to put in the event's Ctrl and Shift fields, so every click arrived as a plain one and a multi-selection was unreachable with a mouse.

A handler implementing it receives presses here and NOT through MouseDown; Handler still requires MouseDown, so leave it as the plain-press path or have one call the other.

type ModifiedKeyer added in v0.4.0

type ModifiedKeyer interface {
	ModifiedKey(name string, m Modifiers)
}

ModifiedKeyer is an optional Handler capability: a key press arrives here with the modifiers that were held, instead of through Handler.Key, whose contract says it has "no room to say which modifiers were held".

⛔ Shift is the one that matters and the one nothing else carried. A command chord (Ctrl/⌘) already had a route -- ShortcutSink, which keeps precedence over this -- but a Shift-Arrow is not a command chord, so a handler could not tell it from a plain Arrow. That is every "extend the selection with the keyboard" gesture, unreachable.

name is the same symbolic label Key receives, and a handler implementing this receives key presses here and not through Key.

type Modifiers added in v0.4.0

type Modifiers struct {
	Ctrl, Shift, Alt, Meta bool
}

Modifiers says which modifier keys were held when an input event happened. Alt is the Option (⌥) / Alt key; Meta is Command (⌘) on macOS and the Super / Windows key elsewhere.

type NativeControlProvider added in v0.2.0

type NativeControlProvider interface {
	// NativeControls returns the native controls to embed this frame, keyed for
	// identity across frames, in the framebuffer's device-pixel, top-left space
	// (like A11yElements and MouseDown). It is called once per frame from the
	// back-end's main thread; a control the app is not showing this frame is
	// simply omitted.
	NativeControls() []toolkit.NativeControl
}

NativeControlProvider is implemented by a Handler that wants some of what it draws backed by real OS controls — a secure text field, a button, a slider — embedded over its framebuffer. A back-end that can host native controls asks for the descriptors each frame and reconciles the live controls to them; a handler that does not implement this simply presents pixels, as before.

It is a separate, optional interface, the exact parallel to Accessible: where Accessible describes the surface for the platform's accessibility layer, this describes the parts of it that should be real controls. The descriptor is the toolkit's own toolkit.NativeControl — kind, key, geometry, value, and the callbacks that carry the person's input back — because the back-end's seam (toolkit.Surface.Controls) speaks exactly that.

type OpenOptions added in v0.13.0

type OpenOptions = gw.OpenOptions

OpenOptions configures OpenFile.

type OpenResult added in v0.13.0

type OpenResult = gw.OpenResult

OpenResult is what an OpenFile callback receives.

type SaveOptions added in v0.13.0

type SaveOptions = gw.SaveOptions

SaveOptions configures SaveFile.

type SaveResult added in v0.13.0

type SaveResult = gw.SaveResult

SaveResult is what a SaveFile callback receives.

type SecondaryClicker

type SecondaryClicker interface {
	SecondaryClick(x, y int)
}

SecondaryClicker is an optional Handler capability: a secondary (right / two-finger / Control-click) press arrives here as the context-menu gesture, with the same device-pixel coordinates as a MouseDown. A handler that has no context menu simply does not implement it, and the press is ignored.

type ShortcutSink

type ShortcutSink interface {
	Shortcut(r rune, ctrl, meta bool)
}

ShortcutSink is an optional Handler capability: a key pressed with a command-style modifier (Ctrl/Cmd) arrives here as a shortcut, r is the base rune (modifiers stripped), ctrl/meta report which modifier was held. Back-ends route a modifier chord here instead of through Key (which drops the modified rune) so the app can act on real-browser-style shortcuts like Cmd+=.

type Spec

type Spec struct {
	Name       string            // e.g. "News Reader" — tray tooltip
	Identifier string            // reverse-DNS, e.g. "com.example.app"
	Version    string            // e.g. "1.2.0"
	Icon       []byte            // PNG icon bytes for the tray (optional)
	Tray       func() *tray.Menu // optional: builds the menu-bar menu
}

Spec is the application's identity and its optional tray. It is the piece that separates an application from a bare window: a name and identifier the OS and the tray tooltip can show, a version, and — when the app wants a menu-bar / system-tray presence — an icon and a builder for its menu.

type SystemAppearance

type SystemAppearance struct {
	// Dark is the effective dark/light mode (macOS effectiveAppearance).
	Dark bool
	// Accent is the user's accent colour (macOS controlAccentColor); only
	// meaningful when HasAccent is set.
	Accent    color.RGBA
	HasAccent bool
	// FontTTF is the raw system font (e.g. macOS SFNS.ttf). Empty on a poll that
	// only refreshes colours, so the already-installed font is kept.
	FontTTF []byte
}

SystemAppearance carries look-and-feel harvested from the host UI so the renderer can match the live system look rather than a fixed palette.

type SystemClipboard

type SystemClipboard interface {
	ClipboardText() string
	SetClipboardText(text string)
}

SystemClipboard is a host OS text clipboard (read + write). Its method set is deliberately identical to the toolkit's back-end-neutral Clipboard interface, so the app can install a back-end's SystemClipboard as the toolkit-wide clipboard directly — making every text widget's copy/cut/paste, and the app's copy actions, go through the real OS pasteboard.

type Window added in v0.16.0

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

Window is a secondary window opened by OpenWindow. Its methods are safe from any goroutine.

func OpenWindow added in v0.16.0

func OpenWindow(cfg WindowConfig, h Handler) (*Window, error)

OpenWindow opens a second top-level window showing h, on the loop Run is already driving. It is what a "+" button that opens an add-an-item form in its own window calls.

h gets everything the main window's handler gets: frames at the panel's own resolution, input, native controls, accessibility, damage, the system appearance and the clipboard. h is a handler of its own, not the main one.

It must be called on the UI thread -- from the handler's input callbacks, a menu action, or anything else the loop calls -- because the platform toolkit is touched directly.

It answers ErrNoWindow when Run has not opened the main window or has returned, and ErrNotSupported when the platform's window back-end cannot open a second window (X11, Wayland, wasm and Android today; macOS, Windows and GTK4 can). Closing the second window leaves Run running; closing the main window closes it.

func (*Window) Close added in v0.16.0

func (w *Window) Close() error

Close closes the window. It is safe to call more than once and after the user closed it.

func (*Window) OnClose added in v0.16.0

func (w *Window) OnClose(f func())

OnClose sets f to be called once, on the UI thread, when the window goes away -- the user's close control or Window.Close. It replaces any earlier callback. When the window is already closed f is called at once.

func (*Window) Raise added in v0.16.0

func (w *Window) Raise() error

Raise brings the window to the front and asks for the keyboard focus. It answers ErrNoWindow once the window is closed.

type WindowConfig added in v0.16.0

type WindowConfig struct {
	Title         string
	Width, Height float64 // logical points; zero lets the platform choose

	// FitHeight makes the window exactly as tall as its content needs, with no
	// empty band under the last control: the height comes from the handler's
	// [HeightFitter] (Height is then only the fallback for a handler that is
	// not one), is set before the window opens and follows the content as it
	// changes. The user cannot resize such a window, since its height is the
	// content's. On a back-end that cannot resize an open window (see
	// go-widgets/window's ContentSizer: macOS today) the window keeps the
	// height it opened at.
	FitHeight bool
	// MinHeight and MaxHeight bound a fitted height, in logical points. Zero
	// means no lower bound, and for the upper bound the usable screen height.
	MinHeight, MaxHeight float64
}

WindowConfig describes a secondary window opened by OpenWindow.

Jump to

Keyboard shortcuts

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