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
- Variables
- func Alert(o AlertOptions, done func(AlertResult)) error
- func Bind(h Handler, scale float64) *toolkit.Surface
- func BindScaled(h Handler, scaleOf func() float64) *toolkit.Surface
- func Confirm(message, detail, yes, no string, done func(yes bool, err error)) error
- func Hide() error
- func MenuError() error
- func OpenFile(o OpenOptions, done func(OpenResult)) error
- func OpenURL(rawURL string) error
- func Raise() error
- func Run(s Spec, cfg Config, h Handler, onReady func()) error
- func SaveFile(o SaveOptions, done func(SaveResult)) error
- func SetMenu(m *tray.Menu) error
- func Show() error
- type A11yElement
- type Accessible
- type AlertOptions
- type AlertResult
- type AppearanceSink
- type ClipboardController
- type Config
- type ContextMenuHost
- type Filter
- type Handler
- type HeightFitter
- type ModifiedClicker
- type ModifiedKeyer
- type Modifiers
- type NativeControlProvider
- type OpenOptions
- type OpenResult
- type SaveOptions
- type SaveResult
- type SecondaryClicker
- type ShortcutSink
- type Spec
- type SystemAppearance
- type SystemClipboard
- type Window
- type WindowConfig
Constants ¶
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.
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 ¶
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 )
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") )
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.
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.
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 ¶
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 ¶
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
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 ¶ added in v0.14.0
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
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 ¶
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
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.
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 ¶
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 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
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
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
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 ¶
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 ¶
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
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
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.