Documentation
¶
Overview ¶
Package window is a pure-Go (CGO-free, no Xlib/XCB) X11 windowing backend for the go-widgets toolkit. It opens a real window on an X11 server, blits the toolkit's RGBA framebuffer into it via the core protocol's PutImage, and routes X input events into toolkit.Event, so a go-widgets widget tree runs on a Linux desktop exactly as it does in the browser/wasm host.
The X11 protocol itself is implemented from scratch in the internal/x11 package over a raw byte stream, mirroring the sovereign transport+codec approach of a pure-Go wire library such as github.com/godbus/dbus/v5.
Open dials the server named by $DISPLAY; it is implemented on Linux and returns ErrUnsupported elsewhere, so cross-builds stay green. The windowing logic (framebuffer, present, event translation, run loop) is platform-independent and driven through the transport-agnostic internal/x11 connection.
Index ¶
- Constants
- Variables
- func Alert(b Backend, o AlertOptions, done func(AlertResult)) error
- func Confirm(b Backend, message, detail, yes, no string, done func(yes bool, err error)) error
- func FitHeight(pref, lo, hi float64) int
- func Hide(b Backend) error
- func LogicalWidth(widthPx int, scale float64) float64
- func OpenFile(b Backend, o OpenOptions, done func(OpenResult)) error
- func Raise(b Backend) error
- func SaveFile(b Backend, o SaveOptions, done func(SaveResult)) error
- func SetContentSize(target any, width, height int) error
- func SetMenuBar(b Backend, appName string, m *tray.Menu) error
- func Show(b Backend) error
- func SystemFontTTF() ([]byte, error)
- func VisibleScreenSize() (w, h int, ok bool)
- func WholePoints(v float64) int
- type AlertOptions
- type AlertResult
- type Appearance
- type AppearanceReader
- type Backend
- type Child
- type Clipboard
- type Config
- type ContentSizer
- type DamageRenderer
- type Dialogs
- type Filter
- type MenuBar
- type Numbered
- type OpenOptions
- type OpenResult
- type Placement
- type Repainter
- type SaveOptions
- type SaveResult
- type Scaler
- type Screen
- type ScreenList
- type Visibility
- type Window
- func (w *Window) Appearance() Appearance
- func (w *Window) ClipboardText() string
- func (w *Window) Close() error
- func (w *Window) GPU() bool
- func (w *Window) GPUError() error
- func (w *Window) Hide() error
- func (w *Window) Raise() error
- func (w *Window) RenderScale() float64
- func (w *Window) Repaint()
- func (w *Window) Run(root toolkit.Widget) error
- func (w *Window) SetClipboardText(text string)
- func (w *Window) Show() error
- func (w *Window) Size() (int, int)
- func (w *Window) String() string
- func (w *Window) SystemFontTTF() ([]byte, error)
- type Windows
Constants ¶
const ( MaxFilters = 32 // file-type filters per dialog MaxExtensions = 64 // extensions per filter MaxButtons = 4 // buttons per alert MaxStringLen = 1024 // bytes: title, suggested name, filter name, extension, button MaxMessageLen = 4096 // bytes: an alert's message and detail )
Bounds on what a dialog request may carry. They exist so that a caller forwarding untrusted strings cannot make the platform allocate without limit.
const NativeScale = -1.0
NativeScale asks for a framebuffer at the display's own resolution rather than one pixel per logical point. See Config.RenderScale for when that is the right thing to ask for -- it is a narrower case than it sounds.
Variables ¶
var ErrCancelled = errors.New("window: dialog cancelled")
ErrCancelled is the Err of a result the user dismissed without choosing: Cancel on a file dialog, Escape or the close box on an alert that has no cancel button of its own.
var ErrClosed = errors.New("window: the window is closed")
ErrClosed is returned by a request made of a window that has been closed.
var ErrInvalidDialog = errors.New("window: invalid dialog options")
ErrInvalidDialog wraps every rejection of a dialog's options.
var ErrNoScreens = fmt.Errorf("window: no screens in the display list")
ErrNoScreens is what a back-end that could not read the display list reports.
It is deliberately NOT ErrScreensUnsupported: that one means this platform has no way to enumerate at all, which is a fact about the build. This one means the enumeration ran and came back with nothing, which is a fact about the moment and may be different a second later.
var ErrNotSupported = errors.New("window: not supported by this back-end")
ErrNotSupported is what a back-end answers for something its platform will not let it do. It is wrapped with the reason, so errors.Is finds it and the message still says why.
var ErrScreensUnsupported = errors.New("window: this back-end cannot enumerate screens yet")
ErrScreensUnsupported is returned by Screens on a back-end that cannot yet enumerate displays. It is not a failure to handle defensively so much as a statement of coverage: today macOS answers through Cocoa, X11 through RANDR, Wayland through wl_output and Windows through EnumDisplayMonitors, and js/wasm does not.
var ErrUnsupported = errors.New("window: no native windowing backend for this platform")
ErrUnsupported is returned by Open on platforms with no windowing backend — everything that is neither Linux (X11/Wayland) nor macOS (Cocoa/AppKit) nor Windows (Win32/GDI) nor the js/wasm wasmbox environment.
Functions ¶
func Alert ¶ added in v0.102.0
func Alert(b Backend, o AlertOptions, done func(AlertResult)) error
Alert shows the platform's message dialog on b; see Dialogs. With one button it is an alert, with two or more it is a choice -- see Confirm.
func Confirm ¶ added in v0.102.0
Confirm is Alert with two buttons, yes first (the default) and no second.
func FitHeight ¶ added in v0.113.0
FitHeight is the window height, in whole logical points, for a preferred height pref: rounded up so nothing is clipped, then held to [lo, hi]. A lo or hi that is not positive means no bound on that side. A pref that is not a number, is infinite or is not positive answers zero: "no opinion".
func Hide ¶ added in v0.86.0
Hide takes b's window off the screen without closing it; see Visibility. A back-end without the capability answers ErrNotSupported.
func LogicalWidth ¶ added in v0.113.0
LogicalWidth is a width in device pixels expressed in logical points at the display scale (device pixels per point). A scale that is not positive answers zero.
func OpenFile ¶ added in v0.102.0
func OpenFile(b Backend, o OpenOptions, done func(OpenResult)) error
OpenFile shows the platform's open-file dialog on b; see Dialogs for the threading and path rules. The options are validated first.
func Raise ¶ added in v0.86.0
Raise brings b's window to the front and asks for the focus; see Visibility. A back-end without the capability answers ErrNotSupported.
func SaveFile ¶ added in v0.102.0
func SaveFile(b Backend, o SaveOptions, done func(SaveResult)) error
SaveFile shows the platform's save-file dialog on b; see Dialogs.
func SetContentSize ¶ added in v0.112.0
SetContentSize resizes target's content area to width by height logical points; see ContentSizer. target is a Backend or a Child. Something without the capability answers ErrNotSupported.
func SetMenuBar ¶ added in v0.105.0
SetMenuBar installs m as b's menu bar; see MenuBar. A back-end without the capability answers ErrNotSupported.
func Show ¶ added in v0.86.0
Show makes b's window visible again; see Visibility. A back-end without the capability answers ErrNotSupported.
func SystemFontTTF ¶ added in v0.53.0
SystemFontTTF returns the raw sfnt bytes of the host's UI face, ready for toolkit.NewTrueTypeFont, and an error when the platform has no such file to offer.
It is the same answer as the AppearanceReader method of that name, asked WITHOUT a window — which is the whole reason it exists. An application that wants to be drawn in the system face has to install that font before it lays anything out, because the font decides how tall a line of text is and therefore how tall the window has to be. Reaching the method means opening the window first, so the size would have to be computed from the font the window is not going to use. Every one of these back-ends reads a file, which needs no window and no display server, so the question is answerable on the way in.
It is NOT cheap -- the macOS system face is tens of megabytes -- so it is asked once at startup, unlike Appearance, which is cheap enough to poll.
macOS answers from /System/Library/Fonts, Windows from the Segoe UI file, and both Linux back-ends report an error: a Linux desktop names a font family and leaves finding it to fontconfig, which is a font library's job and not a window's.
func VisibleScreenSize ¶ added in v0.27.0
VisibleScreenSize returns the usable area of the primary display in LOGICAL points — on X11 the full panel minus whatever the desktop reserved through _NET_WM_STRUT. ok is false when no display server can be reached, or when it reports no display.
See Screens, which supersedes it for anything multi-display: it reports every attached panel, not only the primary one.
func WholePoints ¶ added in v0.113.0
WholePoints rounds a logical size to the nearest whole point.
Types ¶
type AlertOptions ¶ added in v0.102.0
type AlertOptions struct {
Message string // the headline; required
Detail string // informative text under it
Buttons []string // one to MaxButtons labels, the first being the default; none means a single "OK"
}
AlertOptions configures Alert and Confirm.
func (AlertOptions) Validate ¶ added in v0.102.0
func (o AlertOptions) Validate() error
Validate checks the options against the package bounds.
type AlertResult ¶ added in v0.102.0
AlertResult is what an Alert callback receives: Button is the index into AlertOptions.Buttons of the button that was pressed (0 when none were given).
type Appearance ¶ added in v0.14.0
type Appearance struct {
// Dark is the effective dark/light mode.
Dark bool
// Accent is the user's accent colour, meaningful only when HasAccent is
// set. A system too old to have the notion, or one where the user made no
// choice, reports HasAccent false rather than a made-up colour.
Accent color.RGBA
HasAccent bool
}
Appearance is the host UI's look: what the user has told their system they want everything to look like.
A go-widgets app picks its own theme, which is right for an app with a designed identity and wrong for one that should feel native. An app that wants to belong on the desktop it is running on needs to know that the user chose dark mode and picked purple as their accent, and no amount of theming inside the toolkit can discover that: it is a platform fact.
type AppearanceReader ¶ added in v0.14.0
type AppearanceReader interface {
Appearance() Appearance
SystemFontTTF() ([]byte, error)
}
AppearanceReader is an optional Backend capability: reading the host look.
Appearance is cheap enough to poll -- a handful of platform queries, no allocation -- so a back-end need not push changes and an app can simply ask each frame and act when the answer differs. That keeps the seam a plain question instead of a callback with a lifetime.
SystemFontTTF is separate precisely because it is NOT cheap: the macOS system face is tens of megabytes on disk, so it is asked for once at startup, not on every poll. It returns the raw sfnt bytes, ready for toolkit.NewTrueTypeFont, and an error when the platform has no such file to offer.
Implemented by macOS (Cocoa), Windows (the registry's personalisation keys) and both Linux back-ends, which read the same XDG desktop portal — the desktop look is not a property of the display server carrying the pixels.
type Backend ¶
type Backend interface {
// Run binds root, performs the initial layout+present, then dispatches
// server/compositor events into the widget tree until the window closes.
Run(root toolkit.Widget) error
// Close releases the window and its connection.
Close() error
// Size returns the current client size in pixels.
Size() (int, int)
// String identifies the window for debugging.
String() string
}
Backend is an open, backend-specific window bound to a go-widgets scene. The X11 (*Window), Wayland, macOS Cocoa, Windows Win32 and wasmbox backends all satisfy it, so Open can return whichever the environment selects and a go-widgets application is backend-agnostic: it just calls Run, Size, String and Close.
func Open ¶
Open returns a live window backed by this environment's display server. It auto-selects: Wayland when $WAYLAND_DISPLAY is set, X11 otherwise.
Setting $GO_WIDGETS_GTK opts into the GTK4-hosted backend instead — GTK owns the window, the toolkit's framebuffer goes in a GtkPicture and native controls (toolkit.NativeControl) are real GTK widgets overlaid above it. It is opt-in so the default stays the dependency-free from-scratch backends; the GTK path needs the libgtk-4 runtime present.
Android is excluded here and answered by open_android.go, because a binary there may be running inside an APK, where there is no display server to dial at all.
type Child ¶ added in v0.110.0
type Child interface {
// Close closes the window. It is safe to call more than once, and after the
// user has closed it.
Close() error
// Raise brings the window to the front and asks for the keyboard focus.
Raise() error
// Size is the current client size, in the same unit as [Backend.Size].
Size() (int, int)
// String identifies the window for debugging.
String() string
}
Child is a secondary window opened by OpenChild. It has no Run: the parent's loop drives it. All methods are safe from any goroutine and return once the request is on its way to the window's own thread.
type Clipboard ¶ added in v0.13.0
type Clipboard interface {
// ClipboardText returns the pasteboard's plain-text contents, or "" when it
// holds no text (an image, a file promise, or nothing at all).
ClipboardText() string
// SetClipboardText replaces the pasteboard's contents with text.
SetClipboardText(text string)
}
Clipboard is an optional Backend capability: the host OS text clipboard.
Copy and paste inside a go-widgets app already work through the toolkit's own in-process clipboard. What that cannot do is carry text ACROSS applications — paste a URL from a browser into a text field, or copy an article's title out to somewhere else — because the OS pasteboard is a platform facility and the toolkit is deliberately platform-free.
A back-end that can reach the pasteboard implements this. Its method set is deliberately identical to toolkit.Clipboard, so an app installs it in one line and every text widget's copy/cut/paste starts going through the real OS pasteboard:
w, err := window.Open(cfg)
...
if c, ok := w.(window.Clipboard); ok {
toolkit.SetClipboard(c)
}
That line is the app's to write, not Open's: reaching into a package-level toolkit setting is a decision an app makes, not a side effect a constructor should have. A back-end that cannot reach a pasteboard simply does not implement this, the assertion fails, and the toolkit's in-process clipboard stays in place — copy/paste still works within the app.
Implemented by every back-end that has a pasteboard to reach: macOS through NSPasteboard, Windows through the Win32 clipboard, X11 through selection ownership and Wayland through wl_data_device.
type Config ¶
type Config struct {
// Title is the WM_NAME shown in the title bar.
Title string
// Instance and Class populate WM_CLASS (window-manager grouping). When
// empty they default to Title (Instance) and Title (Class).
Instance string
Class string
// Width and Height are the initial client size in LOGICAL points (the unit
// the toolkit lays out and the user reads in — not device pixels). A value ≤ 0
// asks the backend for a readable default: the macOS (Cocoa) backend derives
// it from the main screen's visible frame; the X11/Wayland backends use their
// standard 640×480. A desktop shell should pass its own point size here.
Width int
Height int
// Display overrides $DISPLAY (e.g. ":0"). Empty uses the environment.
Display string
// Theme overrides the toolkit theme used to paint the background and
// widgets. Nil uses toolkit.DefaultDark.
Theme *toolkit.Theme
// RenderScale is how many framebuffer pixels the back-end allocates per
// logical point.
//
// Zero, the default, is one pixel per point. The UI is laid out and painted
// at a readable size and the compositor up-samples it to a HiDPI display,
// which is slightly soft but correct for every widget tree: the toolkit lays
// out in the same units it paints in, so a framebuffer twice as wide would
// give a window full of widgets at half the size.
//
// [NativeScale] follows the display's backing factor, giving a framebuffer at
// the panel's true resolution. It is CORRECT ONLY FOR A ROOT THAT RENDERS ITS
// OWN PIXELS at the size it is given -- a [toolkit.Surface] over an
// application's own scene -- because such a root is told the render-pixel
// size and composes for it, so nothing is laid out in the wrong unit. Passing
// it with an ordinary widget tree is not an error the back-end can detect; it
// simply makes everything half-size on a 2x display.
//
// Any other positive value is used as-is.
//
// Honoured today by the macOS (Cocoa) back-end.
RenderScale float64
// Screen places the window on a particular display, as returned by
// [Screens]. Nil, the default, lets the platform choose -- which in practice
// means the display the desktop considers active.
//
// The value is re-resolved against the displays attached when Open runs, so a
// display unplugged in between is reported as an error rather than becoming a
// window at coordinates that no longer describe anything. That case is
// ordinary with an external panel, and routine with an XR headset.
//
// Honoured today by the macOS (Cocoa) back-end.
Screen *Screen
// Canvas is the id of the <canvas> a browser tab draws into, when the page
// is an ordinary tab rather than a wasmdesk/wasmbox client. Empty means
// "screen". Ignored by every other back-end.
Canvas string
// Fullscreen sizes the window to cover its screen entirely, with no title bar
// and no frame. With Screen nil it covers the primary display.
//
// It is NOT the platform's native full-screen mode: on macOS there is no
// Space, no animation and no menu bar at the top edge. A borderless window at
// the panel's exact bounds is what an immersive surface needs -- every pixel
// of the display, and nothing of the desktop -- and it is what allows one to
// sit on an external output while the desktop carries on elsewhere.
//
// Honoured today by the macOS (Cocoa) back-end.
Fullscreen bool
// FixedSize makes the window unresizable: no resize control, no drag on an
// edge, no zoom button.
//
// For a window sized to its own content there is nothing to gain from
// resizing it and something to lose. Room has to be found for what a smaller
// window cannot show, and the honest answers are a scrollbar in a dialogue
// that never needs to scroll, or a reflow into a layout nobody designed. A
// settings window is the case in point: it is exactly as big as what it has
// to say.
//
// Resizable stays the default, because most windows hold content whose size
// is the user's business rather than the layout's.
//
// Honoured today by the macOS (Cocoa) back-end; elsewhere it is accepted and
// ignored, so a caller need not ask what platform it is on.
FixedSize bool
// Passive makes the window a picture and nothing else: it never takes the
// keyboard, never takes a click, and the application never activates.
//
// It is for a window that SHOWS something rather than one somebody works in --
// a head-up display, a viewer on a second screen, a surface inside glasses.
// Such a window taking input is not a missing feature, it is a TRAP: it takes
// the keyboard from whatever the person was typing into, and the pointer that
// wanders onto the display it owns is invisible, because the picture is of
// somewhere else and does not show where the mouse is. That was measured on a
// pair of glasses, and the way out was unplugging them.
//
// A passive window is driven from outside instead -- a global shortcut, a
// menu-bar item, a socket -- so an application that asks for this must have
// another way in. Its own loop still runs: it repaints, resizes and closes as
// before, and nothing about drawing changes.
//
// Honoured today by the macOS (Cocoa) back-end; elsewhere it is accepted and
// ignored.
Passive bool
// HideOnClose makes the window's own close control -- the title bar's close
// button, WM_DELETE_WINDOW, the compositor's close request -- take the window
// off the screen instead of ending [Backend.Run]. The window and its widget
// tree stay alive: [Show] or [Raise] bring it back exactly as it was, and
// only [Backend.Close] ends Run. It is what a tray application needs, whose
// way out is an explicit Quit rather than the last window.
//
// It needs the [Visibility] capability to be useful, so Open answers
// [ErrNotSupported] where the back-end has none (Android, wasm) rather
// than accept the flag and quit anyway. Honoured by the macOS (Cocoa),
// Windows (Win32), GTK4, X11 and Wayland back-ends.
HideOnClose bool
// Immersive puts the window above the platform's own furniture -- on macOS
// the menu bar and the Dock -- instead of underneath it.
//
// [Config.Fullscreen] covers the desktop and nothing more: the menu bar and
// the Dock are drawn at window levels above an ordinary window, so on a
// display that carries them they appear ON TOP of the picture. For a
// surface showing captured desktops that reads as two menu bars, one of them
// belonging to a screen the viewer is not looking at.
//
// It is a window level rather than a presentation option deliberately:
// presentation options apply only while this application is active, and an
// immersive surface driven by global shortcuts is used precisely while
// another application has the keyboard.
//
// Honoured today by the macOS (Cocoa) back-end; ignored elsewhere.
Immersive bool
// GPU draws frames on the GPU. The widgets are recorded through
// go-widgets/gpupainter into a go-gfx/gpu2d list. On macOS gpu2d's Metal
// renderer draws it and the frame is presented in a CAMetalLayer, never
// returning to the CPU. On Linux (X11 and Wayland) gpu2d's Vulkan renderer
// draws it and the frame is copied from the renderer into the window's
// framebuffer, which is presented through the path the window always had
// (wl_shm, MIT-SHM or PutImage): the frame crosses the CPU once, and nothing
// is shared with the display server by dma-buf yet. The pixels are those of
// the CPU path, byte for byte (gpu2d and gpupainter hold that by test).
//
// It pays where pixels dominate: large and HiDPI windows, images,
// animation. A small window at 1x is already cheap on the CPU.
//
// A window with a translucent material (macOS) stays on the CPU path,
// because the effect views behind it show through holes punched in the CPU
// framebuffer; so does a machine where Metal or Vulkan will not start. On
// Linux a frame the device refuses (gpu2d.ErrTooLarge, a lost device) stops
// the GPU path for good and is drawn on the CPU, like every frame after it.
// None of this is an error: the window works as without the option, and its
// GPU and GPUError methods say which happened.
//
// On Windows (opt-in, like the others) gpu2d's Direct3D 11 renderer draws the
// frame and a flip-model swap chain on the window's HWND presents it, the
// frame never returning to the CPU; a device that cannot make one, or a frame
// it refuses, leaves the window on the GDI path. The Direct3D 11 back-end is
// proven on WARP (the software device) in CI and on no GPU.
//
// Honoured today by the macOS (Cocoa), X11, Wayland and Windows back-ends;
// ignored elsewhere.
GPU bool
}
Config parametrises a window.
type ContentSizer ¶ added in v0.112.0
ContentSizer is an optional capability: resize an open window's content area after it was opened, so a window can fit its content as the content changes (a message appears, a page is swapped for a taller one).
Sizes are LOGICAL points -- the same unit as Config.Width and Config.Height -- not device pixels, so the answer does not depend on the display's density. The window's top-left corner stays where it is; only the bottom and right edges move. The handler learns the new size through its usual Resize, in device pixels.
It is safe from any goroutine and returns once the request is on its way to the window's own thread. Implemented by the macOS (Cocoa) back-end, for the main window and for windows opened with Windows; the other back-ends do not implement it and SetContentSize answers ErrNotSupported for them, so a caller falls back to the size the window was opened with.
type DamageRenderer ¶ added in v0.4.0
type DamageRenderer interface {
// RenderDamaged paints this frame into p (the framebuffer painter, whose
// clip seam confines each rectangle's repaint to the damage) and returns
// the rectangles it repainted, in surface pixel coordinates. An empty
// result means nothing changed this frame, so the backend presents nothing.
// The returned slice need only stay valid until the backend has presented
// it (which it does immediately, before the next frame).
RenderDamaged(p painter.Painter, th *toolkit.Theme) []toolkit.Rect
}
DamageRenderer is the OPT-IN capability a root handed to Run may implement to drive incremental (damage-region) present instead of full-surface present.
A plain toolkit.Widget root keeps the full-surface path: every frame the whole framebuffer is repainted and blitted (correct, simple, unchanged). A root that ALSO implements DamageRenderer lets Run repaint and blit ONLY the rectangles that actually changed: Run draws the frame through RenderDamaged, takes the returned damage, and packs+presents just its (coalesced) union via the backend's small-rect present path (X11 MIT-SHM ShmPutImage over a framebuffer-mirroring segment, or a wl_shm sub-rect DamageBuffer). The very first frame, a resize and an X11 Expose still present the full surface — a resize because the framebuffer is reallocated, an Expose because the server discarded the window's contents — after which Run resumes incremental present.
github.com/go-widgets/toolkit/scene provides the reference implementation (scene.HostRoot), which is pixel-identical to a full repaint by construction; the interface is declared here, structurally, so the backend needs no import of the scene layer.
type Dialogs ¶ added in v0.102.0
type Dialogs interface {
OpenFile(OpenOptions, func(OpenResult)) error
SaveFile(SaveOptions, func(SaveResult)) error
Alert(AlertOptions, func(AlertResult)) error
}
Dialogs is an optional Backend capability: the platform's own modal dialogs -- open-file, save-file and message -- as opposed to anything drawn by the toolkit. It is implemented by the macOS (NSOpenPanel, NSSavePanel, NSAlert) back-end; OpenFile, SaveFile and Alert answer ErrNotSupported for a back-end without it (X11, Wayland, wasmbox, Android until their own implementations land).
Threading. Every request is asynchronous and safe from ANY goroutine, including the UI goroutine and a tray callback: it validates its options, hands the request to the platform's UI thread, and returns at once. The dialog is then shown there, and the callback is invoked exactly once, on a goroutine of its own, never on the UI thread -- so a callback may block, call back into the window or open the next dialog without freezing the loop. If the request cannot even be queued the error is returned and the callback is never called.
Paths are returned exactly as the platform hands them over. Nothing is resolved, cleaned, made absolute or checked for existence, and symbolic links are not followed: a caller that is about to open the path owns that decision.
type Filter ¶ added in v0.102.0
Filter is one file-type filter: a display name and the extensions it admits, without the leading dot ("png", not ".png"). An extension is not a glob; "*" and "?" are rejected.
type MenuBar ¶ added in v0.105.0
MenuBar is an optional Backend capability: the application's menu bar, built from the same tray.Menu model a tray icon's menu uses (labels, key equivalents, checkmarks, separators, submenus, handlers).
macOS: the menu bar at the top of the screen (NSApp.mainMenu). The application menu (About, Hide, Quit) is put first and appName names it.
Windows: the window's menu bar (CreateMenu and SetMenu); key equivalents are shown as accelerator text and handled by the window.
GTK (the opt-in $GO_WIDGETS_GTK back-end, linux amd64 and arm64): a GtkPopoverMenuBar above the content; key equivalents are window-wide GTK shortcuts (⌘ reads as Control) drawn beside the labels, except an editing role's (Copy, Paste...), which the focused field already handles.
SetMenuBar is safe from any goroutine, and installs the menu again only when it changed (tray.Menu.Signature); the handlers are always the latest ones.
X11, Wayland, wasmbox and Android have no menu bar this package draws (the toolkit has no painted one): SetMenuBar answers ErrNotSupported for them, and the application keeps the same commands reachable another way.
type Numbered ¶ added in v0.56.0
type Numbered interface {
Number() uint32
}
Numbered is an optional Backend capability: the window's system-wide identifier.
On macOS that is -[NSWindow windowNumber], which IS the CGWindowID that CoreGraphics and ScreenCaptureKit use. It exists so a program can tell a CAPTURE about its own window: capturing a display this window sits on otherwise feeds the window back into itself -- an overlay filming the screen it covers -- and the capture API takes a list of window ids to leave out.
Zero means the back-end has no such number, or has not got one yet.
Implemented today by the macOS (Cocoa) back-end.
type OpenOptions ¶ added in v0.102.0
type OpenOptions struct {
Title string // window title or prompt; empty means the platform's own
Filters []Filter // what may be chosen; empty means anything
Multiple bool // allow more than one choice
Directories bool // choose directories instead of files
}
OpenOptions configures OpenFile. The zero value asks for one existing file.
func (OpenOptions) Validate ¶ added in v0.102.0
func (o OpenOptions) Validate() error
Validate checks the options against the package bounds. Every error wraps ErrInvalidDialog.
type OpenResult ¶ added in v0.102.0
OpenResult is what an OpenFile callback receives. On success Paths holds at least one path and Err is nil; on cancel Err is ErrCancelled; on a platform failure Err says so.
type Placement ¶ added in v0.51.0
Placement is an optional Backend capability: where the window actually is.
Asking for a display is not the same as getting one. A back-end resolves Config.Screen against the displays attached at that moment, the platform may have its own opinion about where a window may sit, and a desktop that is rearranged while an application is starting can move the panel out from under the rectangle it was about to be placed at. Bounds is how an application that must own a particular display -- an XR headset, a kiosk, a presentation -- can check rather than assume, and it is how this package's own live tests assert placement from metadata instead of from pixels.
The rectangle is in the same global top-left coordinates Screen reports, so a caller compares it against the Screen it asked for directly. ok is false on a back-end that can open a window but cannot say where it went.
Implemented today by the macOS (Cocoa) back-end.
type Repainter ¶ added in v0.17.0
type Repainter interface {
Repaint()
}
Repainter is an optional Backend capability: ask for a repaint from ANY goroutine.
This package repaints when something happens — an event, a resize, a [scene.HostRoot] invalidation — which covers an interface that only changes because the user did something. It does not cover an application whose content arrives on its own: a feed reader with a fetch in flight, a log viewer, a clock. Such an application draws its first frame and, with the window idle, would show it for as long as it runs.
Repaint is safe to call from any goroutine and returns immediately; the back-end marshals the work to whatever thread its platform demands. Calling it more often than the display refreshes is not an error, just wasted frames.
Implemented by every back-end that has a run loop to wake: X11 (a SendEvent to its own window), Wayland, GTK, macOS (Cocoa), Windows (Win32), and the browser tab (the next animation frame).
An application whose results arrive on other goroutines posts them to an mvvm.Queue whose wake is Repaint, and drains the queue at the start of a frame -- in its root container's SetBounds, which every back-end calls before drawing. Repaint wakes the loop; the queue is what makes the change safe.
type SaveOptions ¶ added in v0.102.0
type SaveOptions struct {
Title string // window title or prompt
Name string // suggested file name, never a path
Filters []Filter // types the file may be saved as; the first is the default
}
SaveOptions configures SaveFile.
func (SaveOptions) Validate ¶ added in v0.102.0
func (o SaveOptions) Validate() error
Validate checks the options against the package bounds.
type SaveResult ¶ added in v0.102.0
SaveResult is what a SaveFile callback receives. Path is the platform's answer, which may name a file that does not exist yet.
type Scaler ¶ added in v0.16.0
type Scaler interface {
RenderScale() float64
}
Scaler is an optional Backend capability: how many framebuffer pixels the back-end is allocating per logical point.
It is the answer to Config.RenderScale, which may have been NativeScale -- "whatever the panel is" -- and so is not something the caller can compute from what it passed in. A self-rendering root needs it to tell its own renderer what a point is worth: Backend.Size reports FRAMEBUFFER pixels, and dividing by this gives the logical size the user actually sees.
A back-end that does not implement it renders one pixel per point.
type Screen ¶ added in v0.46.0
type Screen struct {
// Name is the display's human-readable name, e.g. "Color LCD" or
// "VITURE Beast". It is what to show a user choosing an output, and may be
// empty on a display that publishes none.
//
// It is the panel's OWN name wherever the platform offers one and that name
// identifies the display — on Linux the product string out of its EDID. It
// falls back to the connector ("HDMI-1", "DP-2", "HEADLESS-1") when the
// display publishes no product name, and ALSO when it publishes one that
// two attached displays share: two identical monitors say the identical
// thing about themselves, and a name that cannot tell them apart is not a
// name.
Name string
// X, Y, Width, Height are the display's full bounds.
X, Y int
Width, Height int
// Visible* is the usable area, with the menu bar and Dock (or their
// platform equivalents) excluded. On a secondary display it is normally the
// full bounds.
VisibleX, VisibleY int
VisibleWidth, VisibleHeight int
// Scale is the display's backing factor: device pixels per logical point. A
// Retina panel reports 2.
Scale float64
// Primary reports the display that owns the desktop's origin — the one
// carrying the menu bar or task bar. Exactly one screen has it set.
//
// It is deliberately not "the active screen": which display holds the
// focused window changes as the user clicks around, and a caller choosing an
// output wants the stable answer.
Primary bool
}
Screen describes one attached display, in LOGICAL points — the unit the toolkit lays out and the user reads in, not device pixels.
X and Y are a TOP-LEFT origin with Y growing downwards, so a screen sitting above the primary one has a negative Y. That is the convention the X11, Wayland and Win32 back-ends use; macOS's own space is bottom-left with Y growing up, and the Cocoa back-end converts. A caller therefore never has to know which platform it is on to reason about the layout of the desktop.
Placement does not go through these numbers. Pass the Screen value itself back through Config.Screen and the back-end re-resolves it against the displays attached at that moment, so a window lands on the panel the caller picked rather than at coordinates that may have stopped describing it.
type ScreenList ¶ added in v0.75.0
type ScreenList struct {
// contains filtered or unexported fields
}
ScreenList is the display list of a live system: NEVER EMPTY, primary first, and with exactly one primary — by construction rather than by convention.
⛔⛔ BOTH HALVES WERE CONVENTIONS, AND ONE OF THEM COST SOMEBODY THEIR DESK. Screens used to answer []Screen, so nothing stopped an empty one arriving, and the darwin back-end sent one: liveDisplays returned (nil, nil) when the window server counted zero, which is a failed read wearing the clothes of a fact. go-xrkit/desk looks its display up by name, found none, and quit -- twice on 2026-09-08, on a headset somebody was wearing:
desk: "VITURE Beast" is not attached any more; there is -- stopping
Nothing after "there is": the message names every attached display and named NONE. Three of the four back-ends already refused to say it (Windows and Wayland returned an error, and primaryBounds called it ErrDisplayList); the fourth was the one that shipped.
⭐ AND THE PRIMARY WAS A REPAIR RATHER THAN A GUARANTEE. primaryFirst walked the slice unsetting duplicate flags -- "only one may claim it" -- and every caller that wanted the main display then scanned for the flag again. It is a field of the list, not a property to go looking for.
The zero ScreenList is empty and reports itself so; there is no way to build a populated one but [newScreenList], which is where both rules live.
func Screens ¶ added in v0.46.0
func Screens() (ScreenList, error)
Screens enumerates the attached displays, primary first, in LOGICAL points. It is safe to call before Open — picking an output is something an application does on the way in.
It asks the SAME display server Open would dial, and by the same rule: Wayland when $WAYLAND_DISPLAY is set, X11 otherwise. Anything else would let a caller pick a display off one server and open a window on another.
See Screen for what the fields mean; the two back-ends fill them from very different protocols and are documented where they do it (screen_wayland.go and screen_x11.go).
func (ScreenList) All ¶ added in v0.75.0
func (l ScreenList) All() []Screen
All is every screen, primary first.
The slice is the list's own: reading it is free, and writing to it would break the guarantees this type exists for. Copy it if you mean to sort it.
func (ScreenList) ByName ¶ added in v0.75.0
func (l ScreenList) ByName(name string) (Screen, bool)
ByName is the screen called name, and whether there is one.
⭐ IT IS HERE BECAUSE EVERY CALLER WROTE IT. Looking a display up by name is what survives the desktop being rearranged — creating a virtual display moves the others, so a rectangle captured a moment ago names nothing — and three separate loops were doing it.
func (ScreenList) Len ¶ added in v0.75.0
func (l ScreenList) Len() int
Len is how many screens there are. It is at least 1 for any list a back-end returned, and 0 only for the zero value.
func (ScreenList) Primary ¶ added in v0.75.0
func (l ScreenList) Primary() Screen
Primary is the display that owns the desktop's origin.
⭐ A FIELD RATHER THAN A SEARCH. Every caller that wanted it used to loop looking for Screen.Primary, which is a scan for something the list already knew — and a scan that has to decide what to do when it finds none.
The zero value has no screens and returns the zero Screen, which Screen.IsZero reports.
type Visibility ¶ added in v0.86.0
Visibility is an optional Backend capability: take an open window off the screen without closing it, put it back, and bring it to the front.
It is what an application with a system-tray icon needs. Its "Open" item raises the window that is already there rather than opening a second one, and its window can be hidden while the application carries on in the tray. Hiding is not closing: Backend.Run keeps running, the widget tree keeps its state, and Show puts back exactly what was there.
All three are safe from any goroutine -- a tray's menu runs on its own -- and return once the request is on its way to the window's own thread, without waiting for the platform to act on it.
- Show makes a hidden window visible again. It does not ask for the focus, and does nothing to a window that is already visible.
- Hide takes the window off the screen, and out of the taskbar or Dock where the platform lists windows there.
- Raise shows the window if it is hidden, restores it if it is minimised, brings it to the front and asks for the keyboard focus. The platform may refuse the focus -- focus-stealing prevention is a desktop's prerogative -- and Raise does not report that, because nothing tells it.
Implemented by the X11, macOS (Cocoa), Windows (Win32) and GTK4 back-ends. On Wayland, Show and Hide are implemented and Raise answers ErrNotSupported: xdg-shell gives a client no request to raise or focus its own window. The wasmbox and Android back-ends do not implement it; Show, Hide and Raise answer ErrNotSupported for them.
type Window ¶
type Window struct {
// contains filtered or unexported fields
}
Window is an open X11 window bound to a go-widgets scene. It owns the backing RGBA framebuffer, presents it to the server and drives the toolkit widget tree from X input events.
func (*Window) Appearance ¶ added in v0.22.0
func (w *Window) Appearance() Appearance
Appearance reports the desktop's colour scheme and accent colour. Implements the AppearanceReader capability.
func (*Window) ClipboardText ¶ added in v0.21.0
ClipboardText asks the current owner for the selection and waits for it.
Implements the Clipboard capability.
func (*Window) Close ¶
Close closes the window's connection to the server.
Safe from any goroutine: the shared segment is detached under fbmu, so a run loop mirroring pixels into it finishes its frame first and finds the window closed on the next one.
func (*Window) GPU ¶ added in v0.91.0
GPU reports whether frames are being drawn on the GPU (Config.GPU).
func (*Window) GPUError ¶ added in v0.91.0
GPUError is why a window that asked for the GPU is not using it: nil when it is, or when it never asked. The GPU path starts when Run does.
func (*Window) Hide ¶ added in v0.86.0
Hide withdraws the window (ICCCM 4.1.4): it leaves the screen and, under a window manager, the taskbar, rather than becoming an icon there.
func (*Window) Raise ¶ added in v0.86.0
Raise maps the window, puts it on top of the stack, and asks the window manager to activate it. The stacking request is what a window manager without EWMH -- or no window manager at all -- still honours; _NET_ACTIVE_WINDOW is what brings a minimised window back and gives it the focus under one that speaks EWMH.
func (*Window) RenderScale ¶ added in v0.36.0
RenderScale reports how many framebuffer pixels this window allocates per logical point. Implements the Scaler capability.
It is 1 unless the caller asked for NativeScale and the desktop published an Xft.dpi that says otherwise.
func (*Window) Repaint ¶ added in v0.32.0
func (w *Window) Repaint()
Repaint asks the run loop for a frame. Implements the Repainter capability; safe to call from any goroutine, returns without waiting for the frame.
func (*Window) Run ¶
Run binds root to the window, performs the initial layout+draw+present, then dispatches server events into the toolkit until the window is closed (WM_DELETE_WINDOW) or the connection ends. It is the real-window analogue of the wasm compositor host loop.
func (*Window) SetClipboardText ¶ added in v0.21.0
SetClipboardText claims the CLIPBOARD selection and remembers the text, which is all copying is here. The text is handed out later, one requestor at a time, by answerSelectionRequest.
Implements the Clipboard capability.
func (*Window) SystemFontTTF ¶ added in v0.22.0
SystemFontTTF reports that there is no font file to hand over. Implements the AppearanceReader capability.
type Windows ¶ added in v0.110.0
type Windows interface {
OpenChild(cfg Config, root toolkit.Widget, onClose func()) (Child, error)
}
Windows is the optional capability of opening SECONDARY top-level windows: a second window, with its own widget tree, on the loop the first one already runs.
Open gives one window and Backend.Run blocks driving it, so an application that is already inside Run cannot open another by calling Open again -- that would be a second loop on a thread that has one. OpenChild instead creates the window ON the parent's loop: the parent presents it and feeds it input, and no second Run exists. It is what a "+" button that opens an add-an-item form in its own window needs.
OpenChild binds root and presents the first frame before it returns, and must be called from the parent's UI thread -- from a widget's event handler, a menu action, or anything else the parent's loop calls -- because the platform toolkit is touched directly. onClose, when non-nil, is called once on that thread when the child goes away, whether the user closed it or Child.Close did. Closing a child never ends the parent's Run; closing the parent closes its children.
Implemented by the macOS (Cocoa), GTK4 and Windows (Win32) back-ends. X11, Wayland, wasmbox and Android do NOT implement it, and OpenChild answers ErrNotSupported for them -- there is no stand-in that pretends.
Source Files
¶
- a11y.go
- appearance.go
- appearance_portal.go
- appearance_portal_state.go
- children.go
- clipboard.go
- clipboard_wayland.go
- clipboard_x11.go
- contentsize.go
- damage.go
- dialog.go
- dialog_gtk_linux.go
- dialog_win32.go
- display.go
- events.go
- fitsize.go
- menubar.go
- metricscale.go
- open_linux.go
- open_linux_only.go
- repaint_wayland.go
- repaint_x11.go
- scale_x11.go
- screen.go
- screen_linux.go
- screen_wayland.go
- screen_x11.go
- screenlist.go
- screennames.go
- screenwin32.go
- systemfont.go
- systemfont_other.go
- visibility.go
- visibility_wayland.go
- visibility_x11.go
- window.go
- wlscale.go
- wlwindow.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
childdemo
command
Command childdemo shows a secondary window: the main window has a "+" button, and pressing it opens a second window, holding a small form, on the loop the first one already runs.
|
Command childdemo shows a secondary window: the main window has a "+" button, and pressing it opens a second window, holding a small form, on the loop the first one already runs. |
|
gowidgetsclient
command
|
|
|
windowdemo
command
Command windowdemo opens a real native window showing a few go-widgets widgets, driven by the pure-Go github.com/go-widgets/window backend — an X11 or Wayland window on Linux, an NSWindow on macOS, a Win32 window on Windows.
|
Command windowdemo opens a real native window showing a few go-widgets widgets, driven by the pure-Go github.com/go-widgets/window backend — an X11 or Wayland window on Linux, an NSWindow on macOS, a Win32 window on Windows. |
|
internal
|
|
|
a11yrole
Package a11yrole holds the one decision the three native accessibility bridges (cocoa, win32, atspi) must agree on: which nodes of the toolkit's accessibility tree are published when they carry no accessible name.
|
Package a11yrole holds the one decision the three native accessibility bridges (cocoa, win32, atspi) must agree on: which nodes of the toolkit's accessibility tree are published when they carry no accessible name. |
|
atspi
Package atspi is the Linux accessibility bridge: it publishes the widget tree on the AT-SPI bus, where Orca and every other Linux screen reader read it.
|
Package atspi is the Linux accessibility bridge: it publishes the widget tree on the AT-SPI bus, where Orca and every other Linux screen reader read it. |
|
capture
Package capture answers one question for the live suites: where may a picture of somebody's screen be written?
|
Package capture answers one question for the live suites: where may a picture of somebody's screen be written? |
|
cocoa
Package cocoa is the pure-Go (CGO-free, via purego) macOS AppKit windowing backend for the go-widgets toolkit.
|
Package cocoa is the pure-Go (CGO-free, via purego) macOS AppKit windowing backend for the go-widgets toolkit. |
|
dnd
Package dnd is the backend-agnostic drag-and-drop state machine that every native windowing backend shares.
|
Package dnd is the backend-agnostic drag-and-drop state machine that every native windowing backend shares. |
|
gpupath
Package gpupath is the GPU frame path of the X11 and Wayland back-ends (Config.GPU): the widgets are recorded through go-widgets/gpupainter into a go-gfx/gpu2d list, gpu2d's Vulkan renderer draws it, and the renderer's Pixels are copied into the window's own RGBA framebuffer.
|
Package gpupath is the GPU frame path of the X11 and Wayland back-ends (Config.GPU): the widgets are recorded through go-widgets/gpupainter into a go-gfx/gpu2d list, gpu2d's Vulkan renderer draws it, and the renderer's Pixels are copied into the window's own RGBA framebuffer. |
|
gtk
Package gtk is the GTK4-hosted Linux back-end: instead of blitting to a from-scratch X11/Wayland surface, GTK owns the window, the toolkit's pixel framebuffer goes in a GtkPicture, and native platform controls (toolkit.NativeControl) are real GtkEntry/GtkButton/… overlaid above it in a GtkFixed.
|
Package gtk is the GTK4-hosted Linux back-end: instead of blitting to a from-scratch X11/Wayland surface, GTK owns the window, the toolkit's pixel framebuffer goes in a GtkPicture, and native platform controls (toolkit.NativeControl) are real GtkEntry/GtkButton/… overlaid above it in a GtkFixed. |
|
nativeclip
Package nativeclip works out the geometry of showing only the part of a native control that its viewport still shows.
|
Package nativeclip works out the geometry of showing only the part of a native control that its viewport still shows. |
|
nativeimg
Package nativeimg decodes the PNG an application hands a native control (toolkit.NativeControl.Image) and refuses a picture that is too large to be an icon.
|
Package nativeimg decodes the PNG an application hands a native control (toolkit.NativeControl.Image) and refuses a picture that is too large to be an icon. |
|
nativemenu
Package nativemenu holds the part of a native control's context menu that is the same on every host and has no reason to need a window to be tested.
|
Package nativemenu holds the part of a native control's context menu that is the same on every host and has no reason to need a window to be tested. |
|
tab
Package tab runs a widget tree in a plain browser tab, on a <canvas>, through go-widgets/webcanvas: no compositor, no SharedArrayBuffer, no cross-origin isolation.
|
Package tab runs a widget tree in a plain browser tab, on a <canvas>, through go-widgets/webcanvas: no compositor, no SharedArrayBuffer, no cross-origin isolation. |
|
wasmbox
Package wasmbox implements the client half of the wasmdesk/wasmbox external-client wire protocol, so a go-widgets application can run as a client of the browser compositor exactly as it runs on X11 or Wayland.
|
Package wasmbox implements the client half of the wasmdesk/wasmbox external-client wire protocol, so a go-widgets application can run as a client of the browser compositor exactly as it runs on X11 or Wayland. |
|
wayland
Package wayland is a from-scratch, pure-Go (CGO-free, zero non-stdlib dependency) implementation of the Wayland wire protocol, spoken directly over a UNIX-domain stream socket.
|
Package wayland is a from-scratch, pure-Go (CGO-free, zero non-stdlib dependency) implementation of the Wayland wire protocol, spoken directly over a UNIX-domain stream socket. |
|
win32
Package win32 is the pure-Go (CGO-free) Windows Win32/GDI windowing backend for the go-widgets toolkit.
|
Package win32 is the pure-Go (CGO-free) Windows Win32/GDI windowing backend for the go-widgets toolkit. |
|
Package webmirror feeds go-widgets/webcanvas's accessibility mirror and text layer from a toolkit widget tree.
|
Package webmirror feeds go-widgets/webcanvas's accessibility mirror and text layer from a toolkit widget tree. |