Documentation
¶
Overview ¶
Package platform is the OS-facing seam: the contract the toolkit uses for windows, events, input, clipboard, dialogs, displays and cross-thread work, with the renderer/windowing backend supplied behind it.
This file holds the cross-thread task API, which is the part of the contract the toolkit depends on most: widget code runs on timer and worker goroutines and must marshal mutations onto the UI thread.
THE ONE EXCEPTION is real-time audio (meui-media/audio, MEDIA.md D4). A device callback runs on SDL's own audio thread and must not allocate, lock, or hop to the UI thread: marshalling an audio callback is how a glitch ships. So audio callbacks are the documented exception — they pull from a lock-free ring on the audio thread, and only the app-facing state changes are marshalled here. Every other callback in the tree follows the UI-thread rule above.
Index ¶
- Variables
- func CloseRecorder()
- func CurrentVideoDriver() string
- func CursorNames() []string
- func DrainTasks()
- func EncodeAccessibilityNodes(nodes []AccessibilityNode) string
- func EnterUIThread()
- func EventRecorderEnabled() bool
- func FileNameIsPath(loc string) bool
- func InvokeTask(fn func())
- func InvokeTaskAfter(fn func(), d time.Duration)
- func KnownBackendCursorNames() []string
- func OnUIThread() bool
- func OpenReader(ref FileRef) (io.ReadCloser, error)
- func OpenURL(raw string) error
- func PersistFile(ref FileRef) error
- func ReadFile(ref FileRef) ([]byte, error)
- func RecordEvent(ev *Event)
- func SetAppDataDir(fn func(app string) (FileRef, error))
- func SetBestDisplayForRect(fn func(graphics.Rect) *Display)
- func SetClipboardIO(get func() string, set func(string))
- func SetDefaultQueue(q *TaskQueue)
- func SetDialogRunner(fn DialogRunner)
- func SetFileIO(fn FileIO)
- func SetOpenURL(fn func(string) error)
- func SetOpenURLSchemes(schemes ...string)
- func SetVideoDriver(name string)
- func WriteFile(ref FileRef, write func(io.Writer) error) error
- func WriteFileQuick(ref FileRef, write func(io.Writer) error) error
- type Accessibility
- type AccessibilityAction
- type AccessibilityActionHandler
- type AccessibilityNode
- type App
- type Audio
- type BarAppearance
- type Biometrics
- type Clipboard
- type Connectivity
- type ConnectivityInfo
- type Cursor
- func ArrowCursor() *Cursor
- func CrosshairCursor() *Cursor
- func MoveCursor() *Cursor
- func NotAllowedCursor() *Cursor
- func PointingCursor() *Cursor
- func ResizeHorizontalCursor() *Cursor
- func ResizeLeftDiagonalCursor() *Cursor
- func ResizeRightDiagonalCursor() *Cursor
- func ResizeVerticalCursor() *Cursor
- func TextCursor() *Cursor
- func WaitCursor() *Cursor
- type CursorSource
- type DeepLinks
- type DeviceInfo
- type DialogRequest
- type DialogRunner
- type Dialogs
- type Display
- type Drawable
- type Event
- type EventType
- type FileIO
- type FileRef
- type FormFactor
- type Haptic
- type Haptics
- type Insets
- type JNIHandle
- type Job
- func (j *Job[T]) Cancel()
- func (j *Job[T]) Cancelled() bool
- func (j *Job[T]) Done() <-chan struct{}
- func (j *Job[T]) Elapsed() time.Duration
- func (j *Job[T]) Err() error
- func (j *Job[T]) Fraction() float32
- func (j *Job[T]) Progress() (work, total int64, note string)
- func (j *Job[T]) Result() T
- func (j *Job[T]) SetProgress(work, total int64, note string)
- func (j *Job[T]) Start(w Work[T])
- func (j *Job[T]) State() JobState
- func (j *Job[T]) Wait() (T, error)
- type JobState
- type KeyCode
- type Lifecycle
- type LifecycleEvent
- type LifecycleKind
- type LifecycleState
- type Location
- type LocationOptions
- type Media
- type Modifiers
- type Native
- type NetworkType
- type Notification
- type NotificationAction
- type NotificationImportance
- type Notifications
- type OpenDialog
- func (d *OpenDialog) Ref() FileRef
- func (d *OpenDialog) Refs() []FileRef
- func (d *OpenDialog) RunModal() bool
- func (d *OpenDialog) SetAllowedExtensions(e ...string)
- func (d *OpenDialog) SetAllowsMultipleSelection(b bool)
- func (d *OpenDialog) SetCanChooseDirectories(b bool)
- func (d *OpenDialog) SetCanChooseFiles(b bool)
- func (d *OpenDialog) SetInitialDirectory(dir string)
- func (d *OpenDialog) SetTitle(t string)
- type Options
- type Orientation
- type OrientationLock
- type OrientationService
- type PaintStateSetter
- type PanicError
- type Permission
- type PermissionStatus
- type Permissions
- type Position
- type Power
- type PowerInfo
- type PowerState
- type RecordedEvent
- type SaveDialog
- type Screen
- type SecureStorage
- type SensorKind
- type SensorRate
- type SensorSample
- type Sensors
- type SensorsWithRate
- type Share
- type Sink
- type SystemBars
- type SystemTheme
- type TaskQueue
- type TitleBar
- type Tray
- type TrayItem
- type Window
- type Work
Constants ¶
This section is empty.
Variables ¶
var BestDisplayForRect = func(r graphics.Rect) *Display { return &Display{ScaleX: 1, ScaleY: 1} }
BestDisplayForRect reports the display a rect falls on, which is how Window.Scale() learns the content scale of the monitor it is actually on.
It is a package-level variable rather than a function because the toolkit calls it from a place that holds no App (a window's draw callback), the same way InvokeTask and GlobalClipboard work: a backend installs its own with SetBestDisplayForRect at startup. The default reports scale 1.0, matching The reference toolkit's X11 path, where the window realizes a scale of 1.0 and ScaleFonts(1) bumps the theme's base font to cap-8.
var ErrSecureNotFound = errors.New("platform: secure key not found")
ErrSecureNotFound is returned by SecureStorage.Get when the key is absent.
var ErrUnsupportedRef = errors.New("platform: this build has no implementation for that file location")
ErrUnsupportedRef is what the file I/O returns for a location this build cannot open — a URI with no backend installed, most often. It is a distinct error so an app can say "this platform cannot open that here" rather than showing a raw filesystem failure.
var GlobalClipboard = &Clipboard{}
GlobalClipboard is the toolkit-wide clipboard. Text goes to the OS clipboard when the platform layer is available (SDL3 on desktop); a memory mirror always backs it so copy/paste works inside the app and in headless tests regardless of platform support.
Functions ¶
func CurrentVideoDriver ¶ added in v0.5.6
func CurrentVideoDriver() string
CurrentVideoDriver returns the installed driver name, or "" when no backend has registered one.
func CursorNames ¶
func CursorNames() []string
CursorNames returns every logical cursor name the toolkit can produce.
func EncodeAccessibilityNodes ¶ added in v0.5.40
func EncodeAccessibilityNodes(nodes []AccessibilityNode) string
EncodeAccessibilityNodes is the compact wire format consumed by the Android virtual-node provider. One node per line, tab-separated:
id label role x y w h clickable value hint disabled focused selected checked expanded actions
Strings are flattened (tabs/newlines become spaces); action names are comma-separated. Missing trailing fields are treated as zero by the reader.
func EnterUIThread ¶
func EnterUIThread()
EnterUIThread marks the calling goroutine as the default queue's UI thread.
func EventRecorderEnabled ¶
func EventRecorderEnabled() bool
func FileNameIsPath ¶
FileNameIsPath reports whether a raw location string the OS gave us should be treated as a path rather than a URI. It exists so the DIALOG backends can tag what they return without each of them re-deriving the rule: a scheme followed by "//" is a URI, anything else is a path.
func InvokeTask ¶
func InvokeTask(fn func())
InvokeTask runs fn on the UI thread (inline when already there).
func InvokeTaskAfter ¶
InvokeTaskAfter queues fn to run on the UI thread after d.
func KnownBackendCursorNames ¶
func KnownBackendCursorNames() []string
KnownBackendCursorNames returns the names the backend maps to a system cursor. It is the same list; keeping it a separate call documents the contract the two sides must satisfy (see the cursor contract test). The SDL adapter maps these names through mobilegles.
func OnUIThread ¶
func OnUIThread() bool
OnUIThread reports whether the caller is on the default queue's UI thread.
func OpenReader ¶
func OpenReader(ref FileRef) (io.ReadCloser, error)
OpenReader reads a location as a stream, for a file too large to want in memory whole.
The default implementation is whole-file; a backend that can truly stream replaces `fileIO.Read` or this outright, and the comment here is the contract it is expected to keep.
`bytes.NewReader(data)`, NOT `strings.NewReader(string(data))`: the second one copies the whole file AGAIN and makes a binary payload a string on the way, which is exactly the copy this function exists to let a caller avoid.
func OpenURL ¶
OpenURL launches the platform handler for a URL (browser, mail client, …).
It is a package-level function rather than an App method because the toolkit calls it from places that hold no App — a markdown link's default action — the same way InvokeTask and GlobalClipboard work. A backend installs its own with SetOpenURL at startup; the default shells out, which is the desktop fallback.
The URL is validated before it reaches the backend: no empty URL, no control characters, and only a scheme in the allow-list (see SetOpenURLSchemes).
func PersistFile ¶ added in v0.4.0
PersistFile asks the platform to keep a security-scoped grant for ref alive. It is a no-op success on a desktop path; a URI with no backend returns ErrUnsupportedRef. Android content resolvers need this for a recents list.
func RecordEvent ¶
func RecordEvent(ev *Event)
func SetAppDataDir ¶
SetAppDataDir installs the backend's answer for where an app may write. Nil restores the default.
func SetBestDisplayForRect ¶
SetBestDisplayForRect installs the backend's display lookup. Nil restores the scale-1.0 default.
func SetClipboardIO ¶ added in v0.5.2
SetClipboardIO installs the operating-system clipboard. A backend calls this once during initialization; nil restores the memory-only behaviour.
func SetDefaultQueue ¶
func SetDefaultQueue(q *TaskQueue)
SetDefaultQueue replaces the process-wide queue (called by a backend's startup).
func SetDialogRunner ¶
func SetDialogRunner(fn DialogRunner)
SetDialogRunner installs the backend's dialog implementation. Nil restores the no-dialog behaviour, where RunModal reports false.
func SetFileIO ¶
func SetFileIO(fn FileIO)
SetFileIO installs the backend's file I/O. Nil restores the default, which is `os` for paths and ErrUnsupportedRef for anything else.
func SetOpenURL ¶
SetOpenURL installs the backend's implementation. Nil restores the fallback.
func SetOpenURLSchemes ¶ added in v0.1.2
func SetOpenURLSchemes(schemes ...string)
SetOpenURLSchemes replaces the schemes OpenURL accepts. Called with no arguments it restores the default http/https/mailto/tel list. An app that needs a custom scheme should add only that scheme, not choose to trust everything.
func SetVideoDriver ¶ added in v0.5.6
func SetVideoDriver(name string)
SetVideoDriver is installed once by the window backend during startup.
func WriteFile ¶
WriteFile writes a location through the seam, and is ATOMIC WHERE THE PLATFORM ALLOWS: the default implementation writes a temporary file beside the target and renames it, so an interrupted save leaves the original intact rather than a half-written file that looks like the document.
The promise is deliberately worded that way. A mobile content resolver hands out a stream that cannot be renamed over, so a backend there can only write in place — and an app must not be told it got atomicity it did not get.
func WriteFileQuick ¶
WriteFileQuick writes a location atomically but WITHOUT the fsync that makes WriteFile durable across a power loss.
THE DISTINCTION IS WORTH MAKING because an fsync costs a disk round trip, and not everything an app writes deserves one: a recent-files list or a session file can be lost with no harm, while a document the user saved cannot. An app that used the durable write for its own state paid for a promise it did not need on every open — measurable on a slow disk, invisible on a fast one, which is the worst kind of performance bug to find later.
Types ¶
type Accessibility ¶ added in v0.4.1
type Accessibility interface {
// Enabled reports whether a screen reader or touch exploration is active.
Enabled() bool
// Announce speaks a short status message through the platform's screen
// reader. It is a no-op when no accessibility service is active.
Announce(message string) error
// SetNodes replaces the virtual accessibility tree. Backends without a
// virtual-node provider return ErrUnsupportedRef.
SetNodes(nodes []AccessibilityNode) error
// OnAction subscribes to activation of a node ID. The stop function is
// idempotent.
OnAction(fn func(id string)) (stop func())
}
Accessibility is the screen-reader bridge. Announce sends a live-region message; it is not a substitute for exposing a widget tree with roles and labels, which the GL toolkit still needs.
type AccessibilityAction ¶ added in v0.5.7
type AccessibilityAction string
AccessibilityAction is an action a screen reader can ask a node to perform.
const ( AccessibilityActivate AccessibilityAction = "activate" AccessibilityFocus AccessibilityAction = "focus" AccessibilityIncrement AccessibilityAction = "increment" AccessibilityDecrement AccessibilityAction = "decrement" AccessibilityScroll AccessibilityAction = "scroll" )
type AccessibilityActionHandler ¶ added in v0.5.7
type AccessibilityActionHandler interface {
OnAccessibilityAction(fn func(id string, action AccessibilityAction)) (stop func())
}
AccessibilityActionHandler is the optional richer bridge: backends that can report which action fired implement this in addition to Accessibility.
type AccessibilityNode ¶ added in v0.4.3
type AccessibilityNode struct {
ID string
Label string
Role string // heading, button, textbox, tab, static, …
Bounds graphics.Rect
Clickable bool
// State. These are additive to the original node shape; old backends can
// ignore them, new ones should expose them through the platform semantics
// API.
Value string
Hint string
Disabled bool
Focused bool
Focusable bool
TabIndex int
Selected bool
Checked int8 // -1 unchecked, 0 mixed/unknown, 1 checked
Expanded int8 // -1 collapsed, 0 unknown, 1 expanded
// Actions the node supports. An empty list means activation only when
// Clickable is true.
Actions []AccessibilityAction
}
AccessibilityNode is one virtual widget in the accessibility tree. Bounds are in window-local logical units; the backend applies the display density.
The zero value is a non-interactive static node. Backends should ignore nodes with neither a label nor a role.
type App ¶
type App interface {
// Run starts the event loop and returns when the last window closes.
Run(setup func()) error
Quit()
// CreateWindow opens an OS window. The backend owns creation so the
// toolkit's app facade never names a concrete backend.
CreateWindow(opts Options) (Window, error)
// Task queue (see TaskQueue for the threading contract).
PostTask(fn func())
InvokeTaskAfter(fn func(), d time.Duration)
OnUIThread() bool
// OS services
Displays() []*Display
Clipboard() *Clipboard
Dialogs() Dialogs
// Tray returns the system-tray service, or false when the backend has
// none (mobile, or a desktop backend without tray support yet).
Tray() (Tray, bool)
// Capabilities (see capability.go). Each accessor answers false when the
// backend — or the device — cannot provide it, so an app checks once and
// degrades, and never learns which OS call is underneath. Tray above is the
// same shape; these are the rest of the surface.
Power() (Power, bool)
Lifecycle() (Lifecycle, bool)
Orientation() (OrientationService, bool)
DeviceInfo() DeviceInfo
Screen() (Screen, bool)
SecureStorage() (SecureStorage, bool)
DeepLinks() (DeepLinks, bool)
Media() (Media, bool)
Audio() (Audio, bool)
Accessibility() (Accessibility, bool)
Sensors() (Sensors, bool)
Haptics() (Haptics, bool)
// Permissions is the gate for most hardware, so it is the one capability an
// app is most likely to need and the one most likely to be absent.
Permissions() (Permissions, bool)
// Connectivity, Share and Notifications are the OS integrations that need no
// hardware: each answers false when the platform has none.
Connectivity() (Connectivity, bool)
Notifications() (Notifications, bool)
Location() (Location, bool)
Biometrics() (Biometrics, bool)
// SystemBars controls the system bars' appearance and whether the app draws behind
// them. It reports false on a desktop, which has neither.
SystemBars() (SystemBars, bool)
// SystemTheme is the OS's light/dark preference, unknown when it has none.
SystemTheme() SystemTheme
// Native is the ONE intentional leak (see native.go): an opaque handle to the
// backend's platform object, for the surfaces the seam deliberately does not
// abstract. Opt-in, and an app that uses it is writing platform-specific code
// on purpose.
Native() (Native, bool)
}
App is the process-level platform contract: it owns the event loop, the UI-thread task queue and the OS services that are not per-window.
type Audio ¶ added in v0.4.1
type Audio interface {
// PlayPCM starts playback and returns a stop function. Playback may end
// naturally; stop is still safe and idempotent.
PlayPCM(rate, channels int, data []byte) (stop func(), err error)
// RecordPCM starts microphone capture. fn receives successive chunks until
// stop is called. The backend must have microphone permission already; this
// call never prompts.
RecordPCM(rate, channels int, fn func([]byte)) (stop func(), err error)
}
Audio is raw PCM audio. The seam deliberately does not decode files or mix streams: an app that needs an MP3 decoder or a mixer puts one above this and hands the backend PCM. Samples are signed 16-bit little-endian, interleaved.
Record callbacks run on the audio thread and must not block. They are the one documented exception to the UI-thread callback rule; copying the chunk into a queue owned by the app is the expected use.
type BarAppearance ¶
type BarAppearance uint8
BarAppearance is what the system-bar ICONS should be, which is a property of what is behind them and NOT of the app's own theme: an app drawing a white surface behind the status bar needs dark icons even while its own theme is dark.
const ( // BarAppearanceAuto follows the OS's light/dark preference, which is the right // default: it matches every other app on the device. BarAppearanceAuto BarAppearance = iota // BarAppearanceLight means DARK icons, for a light background. BarAppearanceLight // BarAppearanceDark means LIGHT icons, for a dark background. BarAppearanceDark )
func (BarAppearance) String ¶
func (b BarAppearance) String() string
type Biometrics ¶
type Biometrics interface {
// Available reports whether the device CAN authenticate: hardware present and
// at least one credential enrolled. It is a query and never prompts.
Available() bool
// Authenticate prompts and blocks until the user succeeds, fails or cancels,
// pumping the event loop meanwhile. The reason is shown to the user and is
// required by the platforms.
Authenticate(reason string) bool
}
Biometrics is the OS's "prove it is you" prompt.
type Clipboard ¶
type Clipboard struct {
// contains filtered or unexported fields
}
Clipboard stores text for cut/copy/paste. SetText mirrors to the OS clipboard; GetText prefers it and falls back to the in-memory mirror (e.g. headless tests, platforms without clipboard support).
type Connectivity ¶
type Connectivity interface {
// Online reports whether there is a usable network, and whether that network
// is METERED — the second value is the one that matters, because it is what
// tells an app not to stream video on someone's mobile data.
Online() (online bool, metered bool)
// Info reports online, metered and the transport together.
Info() ConnectivityInfo
// OnChange subscribes to network changes. The stop function is idempotent.
OnChange(fn func(ConnectivityInfo)) (stop func())
}
Connectivity reports the device's network situation and publishes changes.
Online and Info are queries; OnChange is the stream an app needs to avoid polling on a timer. The callback runs on the UI thread and receives the current snapshot immediately.
type ConnectivityInfo ¶ added in v0.4.0
type ConnectivityInfo struct {
Online bool
Metered bool
Type NetworkType
}
ConnectivityInfo is one consistent snapshot of the active network.
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor is the hover-cursor vocabulary the toolkit speaks: a logical name the backend maps to a real system cursor (mobilegles does this through SDL_CreateSystemCursor). Widgets return one from CursorAt; returning nil leaves the cursor alone, and the window falls back to the default arrow.
The names are the contract with the backend. mobilegles.SetCursorByName maps every name produced here (see TestCursorNamesAreMappable in mobilegles).
func ArrowCursor ¶
func ArrowCursor() *Cursor
Cursor constructors are functions (not variables) so meui call sites `platform.ResizeHorizontalCursor()` compile without modification.
"Default arrow" is expressed by returning nil from CursorAt; ArrowCursor exists for a widget that must *stop* the hit-test walk and force the arrow over part of itself.
func CrosshairCursor ¶
func CrosshairCursor() *Cursor
func MoveCursor ¶
func MoveCursor() *Cursor
func NotAllowedCursor ¶
func NotAllowedCursor() *Cursor
func PointingCursor ¶
func PointingCursor() *Cursor
func ResizeHorizontalCursor ¶
func ResizeHorizontalCursor() *Cursor
func ResizeLeftDiagonalCursor ¶
func ResizeLeftDiagonalCursor() *Cursor
func ResizeRightDiagonalCursor ¶
func ResizeRightDiagonalCursor() *Cursor
func ResizeVerticalCursor ¶
func ResizeVerticalCursor() *Cursor
func TextCursor ¶
func TextCursor() *Cursor
func WaitCursor ¶
func WaitCursor() *Cursor
type CursorSource ¶
CursorSource reports the cursor a window should show for a content point. The toolkit's window implements it; the backend queries it on pointer moves.
type DeepLinks ¶ added in v0.4.0
type DeepLinks interface {
// Initial returns the URI that launched the app, if any. It is empty when
// the app was opened normally.
Initial() string
// OnLink subscribes to subsequent links. The stop function is idempotent.
OnLink(fn func(string)) (stop func())
}
DeepLinks delivers app links / custom-scheme URLs from the OS. The backend only transports the URI; routing it (which page opens) belongs to the app.
type DeviceInfo ¶ added in v0.4.0
type DeviceInfo struct {
Manufacturer string
Model string
OSName string
OSVersion string
Locale string
AppID string
AppVersion string
}
DeviceInfo is the stable, app-facing description of the running device and application. OS-specific implementation names stay out of it.
type DialogRequest ¶
type DialogRequest struct {
Title string
Extensions []string // bare extensions, e.g. "png", "go"; empty means all files
InitialDirectory string
AllowMany bool // open dialogs only
ChooseDirectories bool // open dialogs only
Save bool
}
DialogRequest is everything a backend needs to show a dialog, in neutral terms: no SDL, no JNI, no Objective-C.
type DialogRunner ¶
type DialogRunner func(DialogRequest) (refs []FileRef, ok bool)
DialogRunner shows the OS dialog and returns the chosen locations as FileRefs.
ok is false both when the user cancelled and when the platform could not show a dialog at all. The two are deliberately the same answer: an app can do nothing different about either, and distinguishing them would leak the platform back into the API.
type Dialogs ¶
type Dialogs interface {
OpenDialog() *OpenDialog
SaveDialog() *SaveDialog
}
Dialogs supplies native file dialogs. Backends without native integration return the stubs, whose RunModal always reports false.
type Display ¶
type Display struct {
Name string
ScaleX float32
ScaleY float32
// contains filtered or unexported fields
}
Display is one physical screen.
It used to be a stub that always reported scale 1.0. The SDL3 adapter now enumerates real displays and reports the content scale SDL reports, which is what makes Window.Scale() — and therefore HiDPI — real on the desktop and on mobile (see MOBILE-PLAN.md P4).
func NewDisplay ¶
NewDisplay builds a Display for a backend. Name may be empty; a scale below 1 is clamped, because 1.0 is the "unknown, assume unscaled" floor.
type Drawable ¶
Drawable is anything a platform window can render: the toolkit's window and panel root implement it, and the window calls Paint once per frame after the background clear. It names only seam types, so the contract does not depend on any particular windowing backend.
type Event ¶
type Event struct {
Type EventType `json:"t"`
Pos graphics.Point `json:"pos,omitempty"`
Button int `json:"button,omitempty"`
ClickCount int `json:"clicks,omitempty"`
Mods Modifiers `json:"mods,omitempty"`
Key KeyCode `json:"key,omitempty"`
Rune rune `json:"rune,omitempty"`
// Composition (EventTextEditing): the in-progress text and the IME's selection inside it, as byte
// offsets. They are not input yet; the committed characters arrive as RuneTyped events.
Text string `json:"text,omitempty"`
CompStart int `json:"cstart,omitempty"`
CompLength int `json:"clen,omitempty"`
Repeat bool `json:"repeat,omitempty"`
DeltaX float32 `json:"dx,omitempty"`
DeltaY float32 `json:"dy,omitempty"`
W int32 `json:"w,omitempty"`
H int32 `json:"h,omitempty"`
// Action is set on EventKeyDown when the key+modifiers match a
// binding in the global keymap (meui/keymap). The WINDOW offers these
// to the app through meui.Window.SetOnAction after the focused widget
// has declined them (a shortcut must never steal a key a text field
// needed) and never on a repeat; the desktop adapter only applies the
// window-level ones (close, exit-fullscreen) when nothing took the key.
// Multiple actions may share a key — see keymap.Map.MatchAll.
Actions []string `json:"actions,omitempty"`
}
Event is one input event. Fields beyond Type are populated per type:
MouseDown/Up/Move/Drag : Pos, Button, ClickCount, Mods MouseWheel : Pos, Mods, DeltaX, DeltaY KeyDown/KeyUp : Key, Mods, Repeat RuneTyped : Rune Resize : W, H
type EventType ¶
type EventType int
EventType enumerates the input events the platform layer delivers.
const ( EventMouseDown EventType = iota EventMouseUp EventMouseMove EventMouseDrag // synthesized: mousemove while a button is held EventMouseWheel EventKeyDown EventKeyUp EventRuneTyped // EventTextEditing is the IME's IN-PROGRESS composition: show it (underlined), replace it as it // changes, and treat the EventRuneTyped that follows as the commit. A TextEditing with empty text // means the composition was cancelled. EventTextEditing EventResize // Touch input (mobile backends). Today the desktop path synthesizes // mouse events from these in internal/window; Android will deliver // them directly and a Window-level gesture recognizer will map them // to widgets (mobile assessment, "gesture recognizer" phase 1). EventTouchDown EventTouchUp EventTouchMove EventTouchCancel // EventBack is the OS asking to go back: Android's back gesture or button, and // anything a desktop maps to the same intent. It is offered to the app before the // window closes, because on Android the default is that the app is closed and can // never participate in its own navigation. EventBack )
type FileIO ¶
type FileIO struct {
Read func(FileRef) ([]byte, error)
Write func(FileRef, func(io.Writer) error) error
// WriteQuick is WriteFile without the fsync; see WriteFileQuick. A backend that cannot offer a
// cheaper write may leave it nil, and WriteFileQuick falls back to Write.
WriteQuick func(FileRef, func(io.Writer) error) error
// Persist asks the platform to keep a security-scoped grant alive across
// launches. Android's SAF needs it for a content:// URI saved in a recents
// list; a backend without persisted grants leaves it nil.
Persist func(FileRef) error
}
FileIO is the backend's file I/O. A desktop build needs none — the default is `os` — and a mobile backend installs one that understands its platform's locations.
type FileRef ¶
type FileRef struct {
// contains filtered or unexported fields
}
FileRef is an opaque reference to a file the user chose. The zero value is "no file".
Nothing outside this package should interpret Loc; DisplayPath and DisplayName exist for the two legitimate uses (a window title, a status line), and they are allowed to be empty.
func AppDataDir ¶
AppDataDir is where an app may keep files of its own — a recent list, a session, a cache. It is NOT a user document: nothing here is shown in a file manager or chosen by a picker.
The default is the user's config directory plus the app's name, which is right on the desktop. A backend replaces it with the platform's own answer (SDL_GetPrefPath on a phone), because an app's writable home is one of the things an OS decides rather than an app.
func DeserializeRef ¶
DeserializeRef reads a location written by Serialize. An unrecognised or empty string is the zero ref: a recents list with a line this build cannot read should lose that line, not fail to load at all.
func URIRef ¶
URIRef makes a ref from a platform URI — an Android `content://` document, for instance. The default I/O below cannot open one, and says so with ErrUnsupportedRef rather than failing obscurely inside os.Open: a mobile backend installs an implementation that can.
func (FileRef) DisplayName ¶
DisplayName is the file's base name, for a title bar. A URI's last path segment is the closest thing it has to one.
func (FileRef) DisplayPath ¶
DisplayPath returns the file's path, and ONLY for a ref that is a path. It is empty for a URI, which is the point: a caller that wants "the location as text" to hand to something else has to notice that there isn't one, instead of receiving a URI and passing it to a function that expects a path.
func (FileRef) Scheme ¶
Scheme names the kind of location, for logs and diagnostics. It is NOT for choosing how to open the file: that is the seam's job.
func (FileRef) Serialize ¶
Serialize encodes a location for storage. The zero ref encodes as an empty string.
func (FileRef) String ¶
String is for logs. It is deliberately NOT the location for a URI, whose contents are long and not useful in a message; use DisplayPath when a path is genuinely wanted.
type FormFactor ¶
type FormFactor uint8
FormFactor is HOW a surface should behave, as distinct from how it should look.
It is deliberately separate from the theme's Platform. The theme decides appearance — which is a property of the OS — while the form factor decides behaviour, and behaviour follows the SIZE of the surface rather than the name of the OS. Back navigation, sheet-versus-dialog, scroll physics and the touch-target floor all belong here, and none of them is something a theme should be asked about.
Deriving it from size rather than from runtime.GOOS is what makes the mobile layout testable on a desk: a 400px-wide desktop window IS a phone by these rules, so phone behaviour can be exercised without a device or an emulator.
const ( // FormFactorDesktop is a pointer-driven surface: no touch floor, hover states, // dialogs rather than sheets. FormFactorDesktop FormFactor = iota // FormFactorPhone is a compact surface (<600dp). One pane, touch, sheets. FormFactorPhone // FormFactorTablet is a medium surface (600-839dp): touch, but room for a // navigation rail and two panes. FormFactorTablet )
func FormFactorFor ¶
func FormFactorFor(width, height, scale float32) FormFactor
FormFactorFor reports the form factor for a surface of the given size at the given content scale. width and height are in the window's own units; the scale DIVIDES them to density-independent pixels, which is the direction the toolkit already uses (a widget's local coordinate is the window's divided by its scale).
func (FormFactor) String ¶
func (f FormFactor) String() string
type Haptics ¶
Haptics plays short effects. Supported is the runtime check: a device with no vibrator answers false, and Play is then a no-op rather than an error.
type Insets ¶
Insets are the safe-area / keyboard insets around a window's content. Zero on desktop; mobile backends fill them in.
type JNIHandle ¶
type JNIHandle struct {
Env unsafe.Pointer // JNIEnv*
Activity unsafe.Pointer // jobject, the current Activity
}
JNIHandle is the Android escape hatch: the JNI environment for the calling thread and the Activity, so an app can call Java APIs the seam does not cover.
Both are raw JNI pointers and the app is responsible for using them correctly: Env is a JNIEnv* valid only on the thread that asked for it, and Activity is a LOCAL reference, so an app that keeps it must make a global reference itself (NewGlobalRef) before the frame that produced it returns.
This is deliberately not wrapped in helpers. A helper layer is what the seam already is; the point of the hatch is to hand over the real thing.
type Job ¶
type Job[T any] struct { // Name is for logs and for a status line. It is not shown unless a caller asks. Name string // contains filtered or unexported fields }
Job is one unit of bounded background work.
T is whatever the work produces, so a job is not a "return nothing" abstraction: a thumbnail job yields an image, an import job yields a document, a proxy job yields a path.
func (*Job[T]) Cancel ¶
func (j *Job[T]) Cancel()
Cancel asks the job to stop. It is COOPERATIVE: the work checks its context and returns. A job whose work ignores the context will run to completion.
func (*Job[T]) Cancelled ¶
Cancelled reports whether Cancel has been called. The work uses this, or its context, to stop early.
func (*Job[T]) Done ¶
func (j *Job[T]) Done() <-chan struct{}
Done is closed when the job finishes, fails, or is cancelled. It is closed EXACTLY ONCE, so a job that fails and is then cancelled does not panic a second close.
func (*Job[T]) Elapsed ¶
Elapsed is how long the job has been running, or ran for. It is 0 before it starts.
func (*Job[T]) Err ¶
Err is the failure, or nil. It is only meaningful once the job is no longer running.
func (*Job[T]) Fraction ¶
Fraction is progress as 0..1, or -1 when the total is not known. -1 rather than 0 because "nothing done" and "we do not know how much there is" are different states, and a bar that shows 0% for a job that cannot say how long it is is lying.
func (*Job[T]) Progress ¶
Progress is the work done, the total, and a note. All three are a consistent snapshot, so a caller cannot read a work count from one step and a total from the next.
func (*Job[T]) Result ¶
func (j *Job[T]) Result() T
Result is what the work produced, or the zero T if the job has not finished or failed. Prefer Wait or OnDone: this does not block, so it is the one to call from a poll.
It returns T rather than *T for the same reason Wait does — a `Job[*Document]` should hand back a `*Document`, not a `**Document`.
func (*Job[T]) SetProgress ¶
SetProgress records how far the work has got. work is in units of total; a total of 0 means the amount is not yet known, which the progress bar shows as indeterminate rather than as a bar stuck at zero.
It is safe from the work's own goroutine and never blocks on the reader.
func (*Job[T]) Start ¶
Start runs the work on its own goroutine and returns immediately.
The result is NOT returned here: a job is asynchronous by construction, and the caller's next question is always "when is it done", which is Wait or OnDone. Returning a value from Start would invite a caller to block on it and defeat the reason for having a job.
func (*Job[T]) State ¶
State is where the job is. Safe from any thread, at any time, including after it finished.
func (*Job[T]) Wait ¶
Wait blocks until the job finishes and returns its result and error. It is for a caller that genuinely has nothing to do until the work is over, which in a UI is rarely; OnDone is usually the right choice.
It returns T, not *T, even though the zero value of T may itself be a pointer. A job that produces a document is `Job[*Document]`, and returning `*T` from that is a `**Document` — a level of indirection the caller has to see through at every call site for no benefit. The zero T is returned when the job failed, and the error says so.
type JobState ¶
type JobState int32
JobState is where a job is in its life.
const ( // JobPending is queued but not started. JobPending JobState = iota // JobRunning means the work function is executing. JobRunning // JobDone means it finished successfully. JobDone // JobFailed means it returned an error, or panicked. JobFailed // JobCancelled means it stopped because it was cancelled. JobCancelled )
type KeyCode ¶
type KeyCode int
KeyCode is the toolkit's keyboard vocabulary. The values are USB HID usages, matching the input pump; a backend converts its native codes before delivering a platform.Event.
const ( KeyUnknown KeyCode = 0 KeyA KeyCode = 4 KeyB KeyCode = 5 KeyC KeyCode = 6 KeyD KeyCode = 7 KeyE KeyCode = 8 KeyG KeyCode = 10 KeyH KeyCode = 11 KeyI KeyCode = 12 KeyJ KeyCode = 13 KeyK KeyCode = 14 KeyL KeyCode = 15 KeyM KeyCode = 16 KeyN KeyCode = 17 KeyO KeyCode = 18 KeyP KeyCode = 19 KeyQ KeyCode = 20 KeyR KeyCode = 21 KeyS KeyCode = 22 KeyT KeyCode = 23 KeyU KeyCode = 24 KeyV KeyCode = 25 KeyW KeyCode = 26 KeyX KeyCode = 27 KeyY KeyCode = 28 KeyZ KeyCode = 29 KeyUp KeyCode = 200 KeyDown KeyCode = 208 KeyLeft KeyCode = 203 KeyRight KeyCode = 205 KeySpace KeyCode = 44 KeyTab KeyCode = 43 KeyEscape KeyCode = 41 KeyBackspace KeyCode = 42 KeyEnter KeyCode = 40 Key0 KeyCode = 39 Key1 KeyCode = 30 Key2 KeyCode = 31 Key3 KeyCode = 32 Key4 KeyCode = 33 Key5 KeyCode = 34 Key6 KeyCode = 35 Key7 KeyCode = 36 Key8 KeyCode = 37 Key9 KeyCode = 38 KeyLeftShift KeyCode = 225 KeyRightShift KeyCode = 229 KeyLeftCtrl KeyCode = 224 KeyRightCtrl KeyCode = 228 KeyLeftAlt KeyCode = 226 KeyRightAlt KeyCode = 230 KeyLeftMeta KeyCode = 227 KeyRightMeta KeyCode = 231 KeyReturn KeyCode = 40 KeyNumPadEnter KeyCode = 88 KeyHome KeyCode = 199 KeyEnd KeyCode = 213 KeyInsert KeyCode = 210 KeyDelete KeyCode = 212 KeyPageUp KeyCode = 211 KeyPageDown KeyCode = 214 KeyF KeyCode = 9 KeyF1 KeyCode = 58 KeyF2 KeyCode = 59 KeyF3 KeyCode = 60 KeyF4 KeyCode = 61 KeyF5 KeyCode = 62 KeyF6 KeyCode = 63 KeyF7 KeyCode = 64 KeyF8 KeyCode = 65 KeyF9 KeyCode = 66 KeyF10 KeyCode = 67 KeyF11 KeyCode = 68 KeyF12 KeyCode = 69 KeyBackslash KeyCode = 49 KeyOpenBracket KeyCode = 47 KeyCloseBracket KeyCode = 48 KeySemicolon KeyCode = 51 KeyApostrophe KeyCode = 52 KeyGrave KeyCode = 53 KeyComma KeyCode = 54 KeyPeriod KeyCode = 55 KeySlash KeyCode = 56 KeyMinus KeyCode = 45 KeyEqual KeyCode = 46 KeypadPlus KeyCode = 87 KeypadMinus KeyCode = 78 KeypadEquals KeyCode = 103 )
type Lifecycle ¶ added in v0.4.0
type Lifecycle interface {
State() LifecycleState
OnChange(fn func(LifecycleState)) (stop func())
}
Lifecycle publishes application state changes. OnChange delivers the current state immediately and then every change; the returned stop function is idempotent. Callbacks run on the UI thread, like every other capability.
The interface is optional because a backend may not have a meaningful lifecycle (a desktop window that never backgrounds). Callers must keep working when App.Lifecycle returns false.
type LifecycleEvent ¶
type LifecycleEvent struct {
Kind LifecycleKind
}
LifecycleEvent is one lifecycle transition.
type LifecycleKind ¶
type LifecycleKind int
LifecycleKind enumerates app lifecycle transitions. Desktop delivers none of these today; mobile backends deliver them so the app can park live work (TradeUI's tick streams).
const ( LifecycleStart LifecycleKind = iota LifecycleResume LifecyclePause LifecycleStop LifecycleDestroy LifecycleLowMemory LifecycleBack )
type LifecycleState ¶ added in v0.4.0
type LifecycleState int
LifecycleState is the application's coarse foreground/background state. It is deliberately smaller than the OS enums: a screen that needs to pause work only has to distinguish "interactive", "visible but not interactive", "in the background" and "terminating".
const ( LifecycleActive LifecycleState = iota LifecycleInactive LifecycleBackground LifecycleTerminating )
func (LifecycleState) String ¶ added in v0.4.0
func (s LifecycleState) String() string
type Location ¶
type Location interface {
// Enabled reports whether location services are switched on for the DEVICE.
// It says nothing about whether this app may use them — that is
// Permissions.Status(PermissionLocation), and the two are genuinely
// independent: services can be on while the app is refused, and off while
// the app is allowed.
Enabled() bool
// Last returns the most recent fix the OS already has, if any. It never
// waits for a new one and never starts a listener, so it cannot drain the
// battery — and it returns false rather than blocking when there is none.
Last() (Position, bool)
// Start subscribes to fresh fixes. The callback runs on the UI thread. The
// stop function is idempotent and must be safe to call from a lifecycle
// pause handler.
Start(opts LocationOptions, fn func(Position)) (stop func(), err error)
}
type LocationOptions ¶ added in v0.4.1
type LocationOptions struct {
// Interval is the desired update interval. Zero means one second.
Interval time.Duration
// MinDistance is the minimum movement in metres before an update. Zero
// means the platform's default.
MinDistance float64
// Background requests updates while the app is not visible. Android needs a
// foreground service and ACCESS_BACKGROUND_LOCATION; a backend that cannot
// provide that contract returns an error instead of pretending.
Background bool
}
Location reports where the device is, as far as the OS will say.
Deliberately not a stream. A stream needs a subscription lifecycle, a power policy and a background-mode story on each platform, and the honest API for that is Start/Stop like sensors — which is a later, larger piece of work than the rest of this slice.
type Media ¶ added in v0.4.0
type Media interface {
// PickImage opens the system image picker and blocks until the user picks
// or cancels. The returned ref is readable through ReadFile; backends that
// can persist the grant do so.
PickImage() (FileRef, error)
// CaptureImage opens the system camera and blocks until the user takes a
// photo or cancels. The returned ref is readable through ReadFile. The
// backend chooses the output location; Android writes through its file
// provider into the app cache so the caller can read/share it.
CaptureImage() (FileRef, error)
}
Media picks visual media. It is intentionally a small surface: Android's photo picker and iOS's PHPicker are the right UI for "choose an image", and a camera preview/renderer belongs to the app or a separate media module.
type Modifiers ¶
type Modifiers int
Modifiers is a bit set of held modifier and lock keys.
func (Modifiers) ControlDown ¶ added in v0.5.2
func (Modifiers) OptionDown ¶ added in v0.5.2
type Native ¶
type Native interface {
// Kind names what the handle is, so an app can fail clearly on the wrong
// platform instead of mis-casting: "android/jni" or "ios/uikit".
Kind() string
// Handle returns the platform object; its concrete type depends on Kind.
// See JNIHandle for Android.
Handle() any
}
Native is an opaque handle to the backend's native platform object.
type NetworkType ¶ added in v0.4.0
type NetworkType int
NetworkType is the transport of the active network.
const ( NetworkUnknown NetworkType = iota NetworkNone NetworkWiFi NetworkCellular NetworkEthernet NetworkVPN NetworkOther )
func (NetworkType) String ¶ added in v0.4.0
func (n NetworkType) String() string
type Notification ¶
type Notification struct {
// ID identifies the notification, so posting again with the same ID replaces
// it rather than stacking a second one. Zero is a valid ID.
ID int
Title string
Body string
// Channel groups notifications by behaviour. Empty uses the app's default
// channel; changing a channel's importance after creation is an OS decision.
Channel string
// Importance is applied when the channel is first created.
Importance NotificationImportance
// Data is an optional deep-link payload. A backend that can route it puts it
// on the notification's launch intent; the app owns what the URI means.
Data string
// Actions are optional buttons. Backends that support them open the app at
// the action's Data URI; Java/Android limits visible actions by platform.
Actions []NotificationAction
}
Notification is one message to show in the OS notification area.
type NotificationAction ¶ added in v0.4.1
NotificationAction is one button on a notification. Data is the deep link the button should deliver when tapped.
type NotificationImportance ¶ added in v0.4.0
type NotificationImportance int
NotificationImportance controls how prominently a notification is shown.
const ( NotificationLow NotificationImportance = iota NotificationDefault NotificationHigh )
type Notifications ¶
type Notifications interface {
// Supported reports whether this device and OS can show notifications at all.
// It does NOT mean the app is allowed to: that is
// Permissions.Status(PermissionNotifications), and asking is the app's job —
// the seam reports, it never silently prompts.
Supported() bool
// Post shows a notification. It returns an error rather than prompting when
// permission is missing, because a permission prompt belongs to the app's
// flow, not to a side effect.
Post(Notification) error
// Cancel removes a notification previously posted with the same ID.
Cancel(id int) error
}
Notifications posts OS notifications.
type OpenDialog ¶
type OpenDialog struct {
// contains filtered or unexported fields
}
OpenDialog collects what to ask for, then holds the answer.
func NewOpenDialog ¶
func NewOpenDialog() OpenDialog
func (*OpenDialog) Ref ¶
func (d *OpenDialog) Ref() FileRef
Ref returns the first chosen location, for the single-selection case.
func (*OpenDialog) Refs ¶
func (d *OpenDialog) Refs() []FileRef
Refs returns the chosen locations; empty after a cancelled or failed dialog.
There is deliberately no Paths() accessor beside it. A path is a desktop-only idea — the platform may have handed back a `content://` URI — so the app gets the opaque ref and asks the seam to do the I/O.
func (*OpenDialog) RunModal ¶
func (d *OpenDialog) RunModal() bool
RunModal shows the dialog and blocks until it is answered. It reports false when there is no backend, when the user cancelled, or when the platform could not show a dialog.
func (*OpenDialog) SetAllowedExtensions ¶
func (d *OpenDialog) SetAllowedExtensions(e ...string)
func (*OpenDialog) SetAllowsMultipleSelection ¶
func (d *OpenDialog) SetAllowsMultipleSelection(b bool)
func (*OpenDialog) SetCanChooseDirectories ¶
func (d *OpenDialog) SetCanChooseDirectories(b bool)
func (*OpenDialog) SetCanChooseFiles ¶
func (d *OpenDialog) SetCanChooseFiles(b bool)
func (*OpenDialog) SetInitialDirectory ¶
func (d *OpenDialog) SetInitialDirectory(dir string)
func (*OpenDialog) SetTitle ¶
func (d *OpenDialog) SetTitle(t string)
type Orientation ¶
type Orientation int
Orientation is how the display is held.
const ( OrientationUnknown Orientation = iota OrientationLandscape OrientationLandscapeFlipped OrientationPortrait OrientationPortraitFlipped )
func (Orientation) String ¶
func (o Orientation) String() string
type OrientationLock ¶ added in v0.4.0
type OrientationLock int
OrientationLock asks the OS to keep the app in one orientation. It is a request, not a guarantee: multi-window and some devices may ignore it.
const ( OrientationUnlocked OrientationLock = iota OrientationLockPortrait OrientationLockLandscape OrientationLockCurrent )
func (OrientationLock) String ¶ added in v0.4.0
func (o OrientationLock) String() string
type OrientationService ¶ added in v0.4.0
type OrientationService interface {
Current() Orientation
// OnChange delivers the current orientation immediately and then every
// change. The returned stop function is idempotent.
OnChange(fn func(Orientation)) (stop func())
}
OrientationService reports and publishes display orientation. Window resize already triggers layout, but an app also needs the semantic orientation for camera previews, media, and landscape-only screens.
type PaintStateSetter ¶ added in v0.5.9
type PaintStateSetter interface {
SetPaintState(needs func() bool, painted func())
}
PaintStateSetter is an optional backend capability: the toolkit supplies a predicate that is true when a frame would change pixels, and a callback to run after a frame has been presented. Backends that do not implement it keep repainting on every loop iteration.
type PanicError ¶
PanicError is what a job reports when its work panicked, so a failure has a message and a job name rather than arriving as a dead process.
func (*PanicError) Error ¶
func (e *PanicError) Error() string
type Permission ¶
type Permission int
Permission is a capability the OS gates behind a user grant.
It is the gate for most hardware, and on Android there is no NDK permission API at all — the NDK's own answer is that most of it is Java-only — so this is where a native bridge is unavoidable and where it must be best hidden: the app asks for PermissionCamera and never learns whether the answer came from a JNI call or an Objective-C message.
const ( PermissionCamera Permission = iota PermissionMicrophone PermissionLocation PermissionLocationBackground PermissionNotifications PermissionBluetooth PermissionBluetoothScan PermissionContacts PermissionCalendar PermissionPhotos PermissionMotion // iOS: CoreMotion; Android grants it at install PermissionVibrate PermissionStorageRead )
func (Permission) String ¶
func (p Permission) String() string
type PermissionStatus ¶
type PermissionStatus int
PermissionStatus is the answer to a permission question.
The distinctions matter to an app: Denied means "ask again later with a reason", NotDetermined means "ask now", Restricted means "do not ask, the OS forbids it" (parental controls, MDM), and Unavailable means the platform has no such permission — four different behaviours behind one word.
const ( PermissionUnknown PermissionStatus = iota PermissionGranted PermissionDenied PermissionRestricted PermissionNotDetermined )
func (PermissionStatus) String ¶
func (s PermissionStatus) String() string
type Permissions ¶
type Permissions interface {
// Status reports the current state WITHOUT prompting.
Status(Permission) PermissionStatus
// Request asks the user and blocks until they answer, pumping the event
// loop meanwhile — the same nested-pump shape as a file dialog, and for the
// same reason: the OS answers on a callback.
Request(Permission) PermissionStatus
// Known reports the permissions this platform actually has, so an app can
// show an accurate list instead of guessing.
Known() []Permission
// ShouldExplain reports whether the platform recommends showing a rationale
// before Request — typically true after one refusal and false before the
// first ask or after "don't ask again". A backend that cannot distinguish
// returns false.
ShouldExplain(Permission) bool
}
Permissions asks for and reports OS permission grants.
type Position ¶
Position is one location fix. The units are the ones every platform uses, so there is nothing to convert and nothing to name: degrees, metres, and a time.
type PowerInfo ¶
type PowerInfo struct {
State PowerState
Seconds int
Percent int
}
PowerInfo is one reading. Seconds and Percent are -1 when unknown.
type PowerState ¶
type PowerState int
PowerState is the device's power situation.
const ( PowerUnknown PowerState = iota PowerOnBattery PowerNoBattery // plugged in, no battery: a desktop PowerCharging PowerCharged )
func (PowerState) String ¶
func (p PowerState) String() string
type RecordedEvent ¶
type RecordedEvent struct {
Type string `json:"type"`
At float64 `json:"at"` // seconds since recording start
Ev *Event `json:"ev"`
When time.Time `json:"-"`
}
func ParseRecordedEvents ¶
func ParseRecordedEvents(data []byte) []RecordedEvent
ParseRecordedEvents reads a JSON-lines recording.
type SaveDialog ¶
type SaveDialog struct {
// contains filtered or unexported fields
}
SaveDialog collects what to ask for, then holds the chosen path.
func NewSaveDialog ¶
func NewSaveDialog() SaveDialog
func (*SaveDialog) Ref ¶
func (d *SaveDialog) Ref() FileRef
Ref returns the chosen location; invalid after a cancelled or failed dialog.
func (*SaveDialog) RunModal ¶
func (d *SaveDialog) RunModal() bool
RunModal shows the save dialog and blocks until it is answered.
func (*SaveDialog) SetAllowedExtensions ¶
func (d *SaveDialog) SetAllowedExtensions(e ...string)
func (*SaveDialog) SetInitialDirectory ¶
func (d *SaveDialog) SetInitialDirectory(dir string)
func (*SaveDialog) SetTitle ¶
func (d *SaveDialog) SetTitle(t string)
type Screen ¶ added in v0.4.0
type Screen interface {
SetKeepAwake(on bool) error
SetOrientationLock(lock OrientationLock) error
}
Screen controls the device display for this app: keeping it awake and locking orientation. Both are best-effort and return an error when the platform cannot honour them.
type SecureStorage ¶ added in v0.4.0
type SecureStorage interface {
Get(key string) ([]byte, error)
Set(key string, value []byte) error
Delete(key string) error
}
SecureStorage stores small secrets — tokens, passwords, keys — encrypted at rest by the platform (Android Keystore / iOS Keychain). It is not a general database: values should be small, and losing them on uninstall is expected.
type SensorKind ¶
type SensorKind int
SensorKind is a sensor an app can ask for, in neutral terms.
const ( SensorAccelerometer SensorKind = iota SensorGyroscope SensorMagnetometer SensorStepCounter SensorBarometer )
func (SensorKind) String ¶
func (k SensorKind) String() string
type SensorRate ¶ added in v0.4.1
type SensorRate int
SensorRate is a requested sampling cadence. It is a hint: the OS may clamp it to save power, and a sensor that only reports on change ignores it.
const ( SensorRateLow SensorRate = iota SensorRateNormal SensorRateGame SensorRateUI SensorRateFastest )
func (SensorRate) String ¶ added in v0.4.1
func (r SensorRate) String() string
type SensorSample ¶
type SensorSample struct {
Kind SensorKind
X, Y, Z float64
At time.Time
}
SensorSample is one reading. The units are the sensor's own and are the same on every platform: g for the accelerometer, rad/s for the gyroscope, µT for the magnetometer.
type Sensors ¶
type Sensors interface {
Has(SensorKind) bool
// Start delivers samples until stop is called. Samples arrive on the UI
// thread — the backend marshals them through the task queue — so the app
// never sees an OS thread or a sensor queue. (Real-time audio is THE
// exception to this rule; see the note in task.go and MEDIA.md D4.)
Start(kind SensorKind, fn func(SensorSample)) (stop func(), err error)
}
Sensors is a device's sensor set. Has is the runtime capability check: a device without a gyroscope answers false, and that is not an error.
type SensorsWithRate ¶ added in v0.4.1
type SensorsWithRate interface {
StartWithRate(kind SensorKind, rate SensorRate, fn func(SensorSample)) (stop func(), err error)
}
SensorsWithRate is the optional extension a backend implements when it can choose a sampling cadence. Sensors.Start uses SensorRateNormal.
type Share ¶
type Share interface {
Text(text, url string) error
// backend chooses the MIME type where it can; text is an optional caption.
File(ref FileRef, text string) error
}
Share hands content to the OS share sheet.
Fire and forget: the OS owns the sheet, the user may pick anything or nothing, and no platform reports back what they chose. An app that needs to know the result has to ask the user itself.
type Sink ¶
Sink receives platform input events. HandleEvent returns true when the event was consumed.
type SystemBars ¶
type SystemBars interface {
// SetEdgeToEdge asks the platform to let the app draw behind the bars. It reports
// whether the request was accepted, not whether it took effect — the platform applies
// it asynchronously, on its own thread.
SetEdgeToEdge(on bool) bool
// SetAppearance sets the system-bar icon appearance.
SetAppearance(BarAppearance) bool
}
SystemBars is the system bars: drawing behind them, and how their content is drawn.
Two things about it are worth stating because they are the opposite of how most capabilities behave:
- Edge-to-edge is not a preference. Android 15 ENFORCES it, and below 15 asking for it is what stops the app being letterboxed between two opaque strips. An app should turn it on and then keep its content out of the insets, which the toolkit already does from Window.Insets().
- The appearance is about the ICONS, not the bars. A bar itself is transparent in both cases; what changes is whether the clock and the gesture handle are drawn light or dark, so the choice depends on the app's background at that edge.
type SystemTheme ¶
type SystemTheme int
SystemTheme is the OS's light/dark preference.
const ( ThemeUnknown SystemTheme = iota ThemeLight ThemeDark )
func (SystemTheme) String ¶
func (t SystemTheme) String() string
type TaskQueue ¶
type TaskQueue struct {
// contains filtered or unexported fields
}
TaskQueue is the UI-thread work queue.
Threading contract:
- The queue has exactly one UI thread: the goroutine that called EnterUIThread (the loop that drives frames).
- Post from that goroutine runs the callback inline, immediately.
- Post from any other goroutine enqueues it; it runs on the UI thread at the next Drain, in submission order.
- PostAfter always enqueues with a due time; it runs at the first Drain after that time.
- Drain must only be called on the UI thread (the frame loop calls it at frame start, before layout and paint).
The inline case matters: it keeps the previous synchronous behaviour for callers that are already on the UI thread, while fixing the real defect — callbacks fired from timers and worker goroutines used to run on those goroutines and mutate the widget tree concurrently with paint.
func NewTaskQueue ¶
func NewTaskQueue(wake func()) *TaskQueue
NewTaskQueue returns an empty queue. wake, when non-nil, is called after a cross-thread enqueue so a backend can poke its event loop; a continuously running frame loop needs no wake.
func (*TaskQueue) Drain ¶
func (q *TaskQueue) Drain()
Drain runs every task that is due, in submission order, on the UI thread.
func (*TaskQueue) EnterUIThread ¶
func (q *TaskQueue) EnterUIThread()
EnterUIThread marks the calling goroutine as the queue's UI thread.
func (*TaskQueue) OnUIThread ¶
OnUIThread reports whether the caller is the queue's UI thread.
func (*TaskQueue) Pending ¶
Pending reports how many tasks are waiting (including not-yet-due timers).
type TitleBar ¶
type TitleBar interface {
// BarHeight is the strip height, in window pixels; the content is laid out
// below it.
BarHeight() float32
// PaintBar draws the bar across the top of the window.
PaintBar(c *graphics.Canvas, width float32)
// Bar events receive window-relative coordinates within the strip.
BarMouseDown(x, y float32, btn int) bool
BarMouseUp(x, y float32, btn int) bool
BarMouseMove(x, y float32)
// BarDoubleClick handles a double press on the bar strip (btn 0 only). It
// returns true when consumed — conventionally a maximize/restore toggle.
BarDoubleClick(x, y float32) bool
// FrameHit returns an SDL_HITTEST_* value (0 normal, 1 draggable, 2..10
// resize zones) for a window-relative point, which is what lets the window
// manager drag and resize a borderless window natively.
FrameHit(x, y, w, h float32) uint32
}
TitleBar is the toolkit's window-chrome contract: a strip the backend paints above the content and routes bar events to.
It exists at this level because chrome is a *window* concern, not a widget one: the desktop backends create undecorated windows, so a title bar is the only thing that can move, maximize or resize them. A backend that draws no chrome (a mobile surface, the renderer-level window) simply does not implement SetTitleBar, and an app opts out with WindowOptions.NoChrome.
The widgets package provides the standard implementation and registers it as the default, so an app that uses the toolkit's widgets gets working chrome without writing any of this by hand.
type Tray ¶
type Tray interface {
SetIconPNG(data []byte) error
SetIconName(name string)
SetTooltip(text string)
SetTitle(title string)
SetMenu(items []TrayItem)
Show()
Hide()
Remove()
// SetOnActivate fires when the icon itself is clicked.
SetOnActivate(fn func())
// SetOnSecondaryActivate fires on a middle/secondary click.
SetOnSecondaryActivate(fn func())
// SetOnMenu fires with the ID of the chosen item — TrayItem.ID, which is
// the app's own identifier and is never rewritten by the backend.
SetOnMenu(fn func(id int))
// SetOnScroll fires with the wheel delta and "vertical" or "horizontal".
SetOnScroll(fn func(delta int, orientation string))
}
Tray is a system-tray icon. It is desktop-only: App.Tray reports false when the backend has no tray support, and mobile backends always report false.
The callbacks are not optional decoration — without them the interface is unusable. An app could set a menu and never learn which entry was chosen, or that the icon was clicked at all, so a tray built on the earlier version could only ever be a picture. They mirror what the widget-layer implementation this was ported from already had.
type TrayItem ¶
type TrayItem struct {
Label string
ID int
Separator bool
Checked bool
Disabled bool
Children []TrayItem
}
TrayItem is one entry in a tray menu. It is a seam-level type so the tray contract does not depend on the widget layer.
type Window ¶
type Window interface {
// SetTextInput turns the OS text input on or off for this window and says
// where the text is being edited, in window coordinates.
//
// It must be driven by FOCUS CHANGES, not called once at startup. On mobile
// the on-screen keyboard is raised by the OS only while text input is active,
// so leaving it on permanently means a keyboard that never goes away, and
// turning it on only at creation means one that never appears when a field is
// actually focused. On Android the area is also load-bearing rather than
// advisory: SDL sizes a hidden edit view from it, and with a zero rect the
// InputMethodManager refuses to serve the IME at all.
SetTextInput(active bool, area graphics.Rect)
// Identity and geometry
SetTitle(title string)
Title() string
SetContentRect(rect graphics.Rect)
ContentRect() graphics.Rect
Width() int32
Height() int32
Scale() float32
Insets() Insets
// FormFactor is how this surface should BEHAVE — touch targets, sheets rather
// than dialogs, back navigation — as distinct from how it should look, which is
// the theme's Platform. It follows the window's size, not runtime.GOOS, so a
// narrow desktop window is a phone and the mobile layout is testable without a
// device.
FormFactor() FormFactor
// Content and input
SetContent(c Drawable)
Content() Drawable
SetSink(s Sink)
ValidateLayout()
// Visibility and window state
Show()
Close()
Minimize()
Maximize()
Restore()
ToggleMaximize()
SetFullscreen(on bool)
// Raise brings the window to the front, for a caller that wants to focus an
// already-open window instead of opening a second copy of it.
Raise()
// Chrome
SetCursor(name string)
// Threading
PostTask(fn func())
// Lifecycle and platform hooks. Desktop delivers zero values / never
// calls them; they exist so mobile backends slot in without a
// signature change.
SetOnClose(fn func() bool)
SetOnResize(fn func(graphics.Size))
SetOnLifecycle(fn func(LifecycleEvent))
SetOnInsets(fn func(Insets))
}
Window is the OS window contract the toolkit drives. Every method is expressed in seam types only, so a backend can implement it without the toolkit knowing which one is in use.
type Work ¶
Work is what a job does. The context is cancelled when the job is, so the work checks it between steps of something long — a decode loop, a row scan, an encode — and returns ctx.Err() when it sees it.
The work is expected to call SetProgress. A job that never does is still correct; it is simply indeterminate, which is why the progress bar has an indeterminate mode.
Source Files
¶
- accessibility.go
- accessibility_wire.go
- audio.go
- capability.go
- clipboard.go
- cursor.go
- deeplink.go
- device.go
- dialog.go
- display.go
- drawable.go
- event.go
- file.go
- file_os.go
- formfactor.go
- job.go
- keycode.go
- lifecycle.go
- media.go
- native.go
- openurl.go
- orientation.go
- paintstate.go
- screen.go
- secure.go
- systembars.go
- task.go
- titlebar.go
- tray.go
- videodriver.go
- window.go