gameui

package
v0.4.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 36 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package gameui is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package gameui provides stylized in-canvas menus, spatial focus navigation, virtual-resolution scaling, and world-anchored native NSGo overlays.

Build a widget tree from containers (Panel, VBox, HBox) and widgets (Label, Button, Toggle, Slider, List, ProgressBar, ImageProgress, Spacer), wrap it in a Root, and drive layout, input, and drawing from your game's Canvas:

  • Call Root.Layout(bounds) to compute exact non-overlapping widget rectangles with padding, spacing, fixed/flex sizing, and alignment.
  • Configure Root.Viewport (or Viewport.Draw / Viewport.WindowToVirtual) for virtual-resolution Fit/Letterbox/Fill/Stretch/Integer scaling and accurate pointer/touch hit-testing.
  • Route pointer/touch events via OnPointerMove, OnPointerDown, OnPointerUp, or OnPress, and keyboard/gamepad navigation via SpatialNavigator (2D spatial lookup, explicit NavOverrides, StepActions, OnConfirm/OnBack, and customizable FocusRingStyle) or Root.OnKeyDown.
  • Call Root.Draw(d, bounds) inside Canvas.Draw; all operations run inside Save/Restore using Path fills and strokes so caller drawing state is never mutated.
  • Customize visuals with Theme (starting from DefaultTheme), NineSlice / FrameDrawer hooks, and custom TextDrawer / TextMeasurer hooks for bitmap fonts.
  • Stack modal dialogs, screen files, SettingsMenu, and non-modal overlays over a base Root with Layers (NewLayers, Push, PushScreen, PushSettings, Pop) for bottom-to-top drawing, optional dimming, input blocking, tap-outside and Back dismissal, and automatic focus save and restore.
  • Drop in SettingsMenu for a ready-to-use Audio, Video, Controls (rebinding), Language, and Accessibility screen persisted through save.DefaultSettingsStore and playable with mouse, touch, keyboard, and gamepad alone.
  • Mount ControllerReconnectPanel as a focusable alert while the game's controller-loss policy waits for input to recover.
  • Mount AnchorOverlay over your game Canvas and call Sync(proj) each frame to pin native NSGo views (name tags, speech bubbles, text inputs) to 2D world positions with automatic off-screen hiding.

Index

Examples

Constants

View Source
const (
	AgeGateKeyTitle          = "privacy.age_gate.title"
	AgeGateKeyBirthDateTitle = "privacy.age_gate.birthdate_title"
	AgeGateKeyBody           = "privacy.age_gate.body"
	AgeGateKeyUnder13        = "privacy.age_gate.under13"
	AgeGateKey13To15         = "privacy.age_gate.13to15"
	AgeGateKey16To17         = "privacy.age_gate.16to17"
	AgeGateKeyAdult          = "privacy.age_gate.adult"
	AgeGateKeyYear           = "privacy.age_gate.year"
	AgeGateKeyMonth          = "privacy.age_gate.month"
	AgeGateKeyDay            = "privacy.age_gate.day"
	AgeGateKeyConfirm        = "privacy.age_gate.confirm"
	AgeGateKeySelectPrompt   = "privacy.age_gate.select_prompt"
	AgeGateKeyInvalidDate    = "privacy.age_gate.invalid_date"
	AgeGateKeySaveError      = "privacy.age_gate.save_error"
)

Standard l10n message keys resolved by AgeGateScreen when a Catalog is provided.

View Source
const (
	// ConsentKeyTitle is the l10n key for the consent prompt title.
	ConsentKeyTitle = "privacy.consent.title"
	// ConsentKeyBody is the l10n key for the consent prompt explanation paragraph.
	ConsentKeyBody = "privacy.consent.body"
	// ConsentKeyPolicy is the l10n key for the policy version label (supports "{version}").
	ConsentKeyPolicy = "privacy.consent.policy"
	// ConsentKeyGPCNotice is the l10n key for the Global Privacy Control notice banner.
	ConsentKeyGPCNotice = "privacy.consent.gpc_notice"
	// ConsentKeyAcceptAll is the l10n key for the "Accept all" action button.
	ConsentKeyAcceptAll = "privacy.consent.accept_all"
	// ConsentKeyRejectAll is the l10n key for the "Reject all" action button.
	ConsentKeyRejectAll = "privacy.consent.reject_all"
	// ConsentKeySave is the l10n key for the "Save choices" action button.
	ConsentKeySave = "privacy.consent.save"
	// ConsentKeySaveError is the l10n key for the error banner shown when saving fails.
	ConsentKeySaveError = "privacy.consent.save_error"
	// ConsentKeySettingsTitle is the l10n key for the privacy section heading in Settings.
	ConsentKeySettingsTitle = "privacy.settings.title"
	// ConsentKeyRecorded is the l10n key for the per-purpose audit summary (supports "{time}", "{version}", "{source}").
	ConsentKeyRecorded = "privacy.settings.recorded"
	// ConsentKeyNotSet is the l10n key shown when a purpose has no stored consent record yet.
	ConsentKeyNotSet = "privacy.settings.not_set"
	// ConsentKeyStateAllowed is the l10n key for an allowed purpose toggle label.
	ConsentKeyStateAllowed = "privacy.state.allowed"
	// ConsentKeyStateDenied is the l10n key for a denied/off purpose toggle label.
	ConsentKeyStateDenied = "privacy.state.denied"
)

Standard l10n message keys resolved by ConsentScreen and ConsentSettingsSection when a Catalog is provided.

View Source
const (
	// DefaultLongPressDuration is the touch hold duration that raises OnContextMenu when LongPressDuration is zero.
	DefaultLongPressDuration = 500 * time.Millisecond
	// DefaultLongPressMoveSlop is the maximum touch drift in points before a touch hold cancels long-press detection.
	DefaultLongPressMoveSlop float32 = 12
)
View Source
const (
	// ChinaHealthAdvisoryTitle is the standard heading for the mainland China health gaming advisory splash screen.
	ChinaHealthAdvisoryTitle = "健康游戏忠告"
	// ChinaHealthAdvisoryText is the mandatory 4-line NPPA health gaming advisory text.
	ChinaHealthAdvisoryText = "" /* 174-byte string literal not displayed */
)

Standard NPPA mainland China health gaming advisory copy (健康游戏忠告).

View Source
const (
	ParentalGateKeyTitle           = "privacy.parental_gate.title"
	ParentalGateKeyBody            = "privacy.parental_gate.body"
	ParentalGateKeyChallengeMulAdd = "privacy.parental_gate.challenge_mul_add"
	ParentalGateKeyChallengeMulSub = "privacy.parental_gate.challenge_mul_sub"
	ParentalGateKeyPlaceholder     = "privacy.parental_gate.placeholder"
	ParentalGateKeyCancel          = "privacy.parental_gate.cancel"
	ParentalGateKeySubmit          = "privacy.parental_gate.submit"
	ParentalGateKeyClear           = "privacy.parental_gate.clear"
	ParentalGateKeyBackspace       = "privacy.parental_gate.backspace"
	ParentalGateKeyWrongAnswer     = "privacy.parental_gate.wrong_answer"
)

Standard l10n message keys resolved by ParentalGate when a Catalog is provided.

View Source
const (
	// MinTouchTargetSize is the minimum touch target diameter in points required on phones and tablets.
	MinTouchTargetSize float32 = 44
	// MinTextContrastRatio is the minimum WCAG 2.1 contrast ratio required for screen text against its fill.
	MinTextContrastRatio float64 = 4.5
)
View Source
const (
	// SettingsCustomResolution is the key inside save.Settings.Custom storing the selected resolution ID.
	SettingsCustomResolution = "resolution"
	// SettingsCustomReduceFlashes is the legacy key inside save.Settings.Custom that stored the flash-reduction toggle before save.AccessibilitySettings.ReduceFlashes existed.
	//
	// Deprecated: Use save.AccessibilitySettings.ReduceFlashes directly.
	SettingsCustomReduceFlashes = "reduce_flashes"
)
View Source
const (
	MinTextScale float32 = 1
	MaxTextScale float32 = 2
)

MinTextScale and MaxTextScale bound Theme.TextScale, Root.TextScale and ScreenCheckOptions.TextScale.

View Source
const (
	StyleTypeButton = "button"
	StyleTypeLabel  = "label"
	StyleTypePanel  = "panel"
)

Style type names key Theme.Styles with the look of every widget of that type; a variation's WidgetStyle.Base names one of them or another variation.

View Source
const CreditsFileVersion = 1

CreditsFileVersion is the version of the credits.yaml format.

View Source
const CreditsSchemaComment = "# yaml-language-server: $schema=" + CreditsSchemaURL

CreditsSchemaComment is the first line MarshalCreditsFile writes: a YAML comment pointing a YAML language server at CreditsSchemaURL. ParseCreditsFile ignores it like any other comment.

View Source
const CreditsSchemaURL = "https://nsgo.games/schemas/credits.v1.json"

CreditsSchemaURL is where the JSON Schema of version 1 credits files is published.

View Source
const DefaultParentalGateMaxAttempts = 3

DefaultParentalGateMaxAttempts is how many wrong answers are allowed before ParentalGate closes and reports failure (done(false)).

View Source
const (
	// DefaultPlaceholderSample is the default fixed-width sample text substituted for
	// an unsampled {placeholder} (or inline plural # count) when CheckScreen measures
	// localized text templates and ScreenCheckOptions.PlaceholderSample is empty.
	DefaultPlaceholderSample = "WWWWWW"
)
View Source
const DefaultScreenFontSize float32 = 12

DefaultScreenFontSize is the default virtual font size in points used for screen files when a node omits fontSize.

View Source
const FirstLaunchSettingsKey = "first_launch_accessibility_complete"

FirstLaunchSettingsKey is the settings custom-field used by FirstLaunchSettings to record that the first-launch accessibility prompt has been completed.

View Source
const MaxResolvedScreenNodes = 1 << 14

MaxResolvedScreenNodes is the most nodes ResolveScreen creates for one screen, counting each copy of an instanced node.

View Source
const MaxScreenNesting = 64

MaxScreenNesting is how many screen files deep ResolveScreen follows fragment instances.

View Source
const ScreenFormatVersion = 2

ScreenFormatVersion is the newest *.screen.yaml schema version this package reads and writes (2). Version 2 adds reusable screen fragment instances (ScreenNodeDoc.Screen and ScreenNodeDoc.Overrides).

View Source
const ScreenMinVersion = 1

ScreenMinVersion is the oldest *.screen.yaml schema version this package reads and writes (1).

View Source
const ScreenSchemaComment = "# yaml-language-server: $schema=" + ScreenSchemaURL

ScreenSchemaComment is the first line EncodeScreen writes for version 1 documents: a YAML comment pointing a YAML language server at ScreenSchemaURL. ParseScreen ignores it like any other comment.

View Source
const ScreenSchemaCommentV2 = "# yaml-language-server: $schema=" + ScreenSchemaURLV2

ScreenSchemaCommentV2 is the first line EncodeScreen writes for version 2 documents: a YAML comment pointing a YAML language server at ScreenSchemaURLV2. ParseScreen ignores it like any other comment.

View Source
const ScreenSchemaURL = "https://nsgo.games/schemas/screen.v1.json"

ScreenSchemaURL is where the JSON Schema of version 1 screen documents is published. EncodeScreen writes it in a yaml-language-server comment on the first line of version 1 documents so editors and AI tools validate and complete screen files as they are written.

View Source
const ScreenSchemaURLV2 = "https://nsgo.games/schemas/screen.v2.json"

ScreenSchemaURLV2 is where the JSON Schema of version 2 screen documents is published.

Variables

View Source
var ErrUnresolvedScreen = errors.New("gameui: screen contains unresolved fragment references; call ResolveScreen first")

ErrUnresolvedScreen is returned by BuildScreen when doc still contains unresolved screen fragment references.

Functions

func ApplyBindingsToActions

func ApplyBindingsToActions(a *input.Actions, bindings map[string][]string, preserveRegions bool)

ApplyBindingsToActions updates a's action bindings from save.Settings.Bindings. When preserveRegions is true, existing TouchRegion and MouseRegion inputs on each action are preserved alongside the rebound keyboard, mouse-button, and gamepad bindings.

func ApplyInputAssistsToActions

func ApplyInputAssistsToActions(a *input.Actions, s save.Settings)

ApplyInputAssistsToActions applies s.InputAssists and s.Accessibility.HoldToToggle (expanding a.ToggleableActions() when HoldToToggle is true) onto a.

func ApplySettingsResolution

func ApplySettingsResolution(v *screen.Video, s save.Settings, resolutions ...SettingsResolution)

ApplySettingsResolution reads the persisted resolution ID from s.Custom["resolution"], resolves its dimensions against resolutions (falling back to ParseSettingsResolution), and applies it to v via v.ApplyResolution. A nil v is a no-op.

func ControllerReconnectPanel

func ControllerReconnectPanel(cfg ControllerReconnectConfig) core.Node

ControllerReconnectPanel shows a focusable alert over the game view. Mount it after the game canvas and drive Visible from the game's recovery state. The game continues to sample input and decides when to hide the panel.

func DrawFocusRing

func DrawFocusRing(d *core.Drawing, bounds core.Bounds, radius float32, style *FocusRingStyle, theme *Theme)

DrawFocusRing renders a customizable focus ring around bounds using style and theme defaults.

func EncodeScreen

func EncodeScreen(doc *ScreenDoc) ([]byte, error)

EncodeScreen validates doc as an authored screen document and writes it as deterministic 2-space YAML prefixed with ScreenSchemaCommentFor(doc.Version). Fragment references (screen) and overrides are written as authored. A document EncodeScreen writes loads with ParseScreen and saves back byte-for-byte unchanged.

func FilterASCII

func FilterASCII(r rune) bool

FilterASCII accepts printable 7-bit ASCII runes (0x20 through 0x7E).

func FilterAlphanumeric

func FilterAlphanumeric(r rune) bool

FilterAlphanumeric accepts Unicode letters and decimal digits.

func FilterDigits

func FilterDigits(r rune) bool

FilterDigits accepts ASCII decimal digits '0' through '9'.

func FilterPrintable

func FilterPrintable(r rune) bool

FilterPrintable accepts any non-control Unicode rune (excluding Unicode category Cc).

func FirstLaunchComplete

func FirstLaunchComplete(settings save.Settings) bool

FirstLaunchComplete reports whether a settings value contains the completion marker.

func Float32

func Float32(v float32) *float32

Float32 returns a pointer to v for initializing optional float32 fields such as Transform.Alpha or Transform.ScaleX.

func FormatBindingLabel

func FormatBindingLabel(token string) string

FormatBindingLabel returns a concise human-readable label for a binding token using generic gamepad names and readable key-code fallbacks.

func FormatBindingLabelForDevice

func FormatBindingLabelForDevice(cx *core.Scope, token string, device input.DeviceKind) string

FormatBindingLabelForDevice returns a binding label using device's controller family. When cx is non-nil, physical key codes use the active keyboard layout; otherwise readable names such as "W" and "Left" are used.

func FormatBindingToken

func FormatBindingToken(in input.Input) string

FormatBindingToken encodes an input.Input into a portable string token suitable for save.Settings.Bindings. Returns "" for region inputs or zero inputs.

func GamepadButtonToken

func GamepadButtonToken(b gamepad.Button) string

GamepadButtonToken returns the canonical binding token stored in save.Settings.Bindings for b (such as "gamepad:south" or "gamepad:dpad_left"), or "" if b is out of range.

func GridRects

func GridRects(count, columns int, bounds core.Bounds, spacing float32) []core.Bounds

GridRects returns deterministic cell rectangles for count children in a fixed-column grid. Columns below one become one, negative spacing becomes zero, and a cell never gets a negative size when the spacing does not fit.

func GuardQuit

func GuardQuit(cx *core.Scope, opts QuitGuardOptions)

GuardQuit registers handlers for application quit and for the window that owns cx. Ordinary requests wait for confirmation when the guard asks. Forced requests proceed after any best-effort save. The handlers live as long as the scope.

func InputAssistsFromSettings

func InputAssistsFromSettings(s save.Settings, toggleable ...string) input.Assists

InputAssistsFromSettings converts s.InputAssists (and s.Accessibility.HoldToToggle, expanding toggleable actions when enabled) into an input.Assists value.

func MarshalCreditsFile

func MarshalCreditsFile(f CreditsFile) ([]byte, error)

MarshalCreditsFile validates f and writes deterministic 2-space YAML prefixed with CreditsSchemaComment that ParseCreditsFile reads back unchanged. A zero Version is written as CreditsFileVersion; Team and Entries keep their order.

func MeasureScreenText

func MeasureScreenText(text string, fontSize float32) (width, height float32)

MeasureScreenText estimates single-line text width and height in virtual points for screen layout and overflow checks. Full-width CJK and East Asian glyphs measure at 1.0× fontSize, spaces at 0.25× fontSize, and other glyphs at 0.5× fontSize. When fontSize <= 0, DefaultScreenFontSize (12) is used.

func MeasureWidget

func MeasureWidget(w Widget, theme *Theme) core.Size

MeasureWidget returns the preferred size of w under theme (or DefaultTheme when theme is nil), or zero size when w is nil or hidden.

func NormalizeTextInput

func NormalizeTextInput(text string, options TextInputOptions) string

NormalizeTextInput replaces invalid UTF-8 with U+FFFD, removes control characters when PrintableOnly is set, and truncates the text to MaxLength runes.

func ParseBindingToken

func ParseBindingToken(token string) (input.Input, bool)

ParseBindingToken decodes a binding token from save.Settings.Bindings into an input.Input. Supported forms are "key:<name>", "keycode:<code>", "gamepad:<button>", "mouse:<button>", and bare key names (such as "space" or "Escape") treated as keyboard keys.

func ParseSettingsResolution

func ParseSettingsResolution(id string) (width, height int, ok bool)

ParseSettingsResolution parses a persisted resolution ID (such as "1280x720", "1280×720", "native", or "") into target dimensions in points. "native" and "" return (0, 0, true).

func ScreenSchemaCommentFor

func ScreenSchemaCommentFor(version int) string

ScreenSchemaCommentFor returns the YAML language server schema comment EncodeScreen writes for version: ScreenSchemaComment for version 1 and ScreenSchemaCommentV2 for version 2.

func SetFirstLaunchComplete

func SetFirstLaunchComplete(settings *save.Settings, complete bool)

SetFirstLaunchComplete updates the completion marker while preserving other custom settings.

func SetSettingsReduceFlashes deprecated

func SetSettingsReduceFlashes(s *save.Settings, reduce bool)

SetSettingsReduceFlashes sets s.Accessibility.ReduceFlashes and clears any legacy s.Custom["reduce_flashes"] entry.

Deprecated: Set save.AccessibilitySettings.ReduceFlashes directly.

func SetSettingsResolution

func SetSettingsResolution(s *save.Settings, id string)

SetSettingsResolution writes id into s.Custom["resolution"].

func SetWidgetBounds

func SetWidgetBounds(w Widget, bounds core.Bounds)

SetWidgetBounds assigns bounds to w from inside a CustomContainer.Layout hook. CustomContainer completes each visible child's layout pass with the active theme after Layout returns.

func SettingsReduceFlashesFrom deprecated

func SettingsReduceFlashesFrom(s save.Settings) bool

SettingsReduceFlashesFrom reports whether flash reduction is enabled in s, reading s.Accessibility.ReduceFlashes and falling back to legacy s.Custom["reduce_flashes"].

Deprecated: Read save.AccessibilitySettings.ReduceFlashes directly.

func SettingsResolutionFrom

func SettingsResolutionFrom(s save.Settings) string

SettingsResolutionFrom reads the persisted resolution ID from s.Custom["resolution"], or "" if unset.

func StyleTypes

func StyleTypes() []string

StyleTypes returns the widget type names Theme.Styles styles, in a fixed order.

func TitleBarDragRegion

func TitleBarDragRegion(cx *core.Scope) core.Node

TitleBarDragRegion returns a reactive transparent desktop drag strip spanning the hidden title bar between the platform's window controls. It renders nothing when the system title bar is shown, in full screen, or off desktop, so game input outside the top strip is unaffected.

func ValidateBindings

func ValidateBindings(doc *ScreenDoc, bindings *Bindings) error

ValidateBindings checks every declarative screen binding against a registry. It reports the node and property so game check can point at the authored source of an invalid binding.

func ValidateScreen

func ValidateScreen(doc *ScreenDoc) error

ValidateScreen validates doc against its *.screen.yaml schema version (1 or 2) and invariants. Authored documents refuse "/" in node IDs; self-contained documents returned by ResolveScreen allow "/"-prefixed instanced IDs.

Types

type AccessibleNode

type AccessibleNode struct {
	Role                      AccessibleRole
	Name, Description, Value  string
	Checked, Selected, Hidden bool
}

AccessibleNode is the platform-neutral accessibility description for a widget. Bounds and focus state are supplied by the host when it publishes the node.

func AccessibleNodeForScreenNode

func AccessibleNodeForScreenNode(n ScreenNodeDoc, localizedText string) AccessibleNode

AccessibleNodeForScreenNode maps a screen-file node to its semantic role. localizedText is the resolved value of TextKey when available and is used as the fallback name when a11yName is omitted.

func (AccessibleNode) Accessible

func (n AccessibleNode) Accessible() bool

Accessible reports whether the node should be exposed to accessibility clients.

func (AccessibleNode) RequiresName

func (n AccessibleNode) RequiresName() bool

RequiresName reports whether the node is exposed but has no accessible name.

type AccessibleRole

type AccessibleRole uint8

AccessibleRole identifies the semantic role exposed by a game UI node.

const (
	AccessibleGroup AccessibleRole = iota
	AccessibleLabel
	AccessibleButton
	AccessibleCheckbox
	AccessibleSlider
	AccessibleListItem
)

type AgeGateMode

type AgeGateMode int

AgeGateMode chooses whether AgeGateScreen presents neutral age-band choices or a neutral date-of-birth entry form (which immediately converts to an AgeBand without saving the date).

const (
	// AgeGateModeBands presents four neutral age-band buttons (Under 13, 13–15, 16–17, 18+) with no default selection.
	AgeGateModeBands AgeGateMode = iota
	// AgeGateModeBirthDate presents empty Year, Month and Day inputs with no pre-filled values and persists only the resulting AgeBand.
	AgeGateModeBirthDate
)

type AgeGateScreen

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

AgeGateScreen renders a neutral age-band or date-of-birth prompt with no pre-filled values and no visual or textual hint toward a preferred answer. Only the derived consent.AgeBand and asked-at timestamp are ever written to storage.

func NewAgeGateScreen

func NewAgeGateScreen(cfg AgeGateScreenConfig) *AgeGateScreen

NewAgeGateScreen creates an AgeGateScreen bound to cfg.Gate with empty initial state.

func (*AgeGateScreen) Close

func (s *AgeGateScreen) Close()

Close hides the screen and clears transient birth-date inputs without modifying stored state.

func (*AgeGateScreen) Err

func (s *AgeGateScreen) Err() error

Err returns the last validation or storage error from Submit.

func (*AgeGateScreen) Open

func (s *AgeGateScreen) Open()

Open clears any transient input state (never pre-filling a band or date) and shows the screen.

func (*AgeGateScreen) Required

func (s *AgeGateScreen) Required() bool

Required reports whether the underlying AgeGate still needs an answer from the player.

func (*AgeGateScreen) Select

func (s *AgeGateScreen) Select(b consent.AgeBand)

Select highlights b in band mode without saving until Submit is called.

func (*AgeGateScreen) Selected

func (s *AgeGateScreen) Selected() (consent.AgeBand, bool)

Selected returns the currently highlighted AgeBand in band mode, or ("", false) when nothing is selected.

func (*AgeGateScreen) SetBirthDateFields

func (s *AgeGateScreen) SetBirthDateFields(year, month, day string)

SetBirthDateFields updates the neutral year, month and day text fields in birth-date mode.

func (*AgeGateScreen) Submit

func (s *AgeGateScreen) Submit() error

Submit validates the player's band or birth date, persists only the derived AgeBand to Gate, clears any birth-date input buffers, closes the overlay and invokes OnComplete.

func (*AgeGateScreen) View

func (s *AgeGateScreen) View(cx *core.Scope) core.Node

View renders the neutral age gate as a native NSGo overlay whenever Gate.NeedsPrompt() is true or Open() was called.

type AgeGateScreenConfig

type AgeGateScreenConfig struct {
	// Gate persists the derived AgeBand and determines whether the prompt is required.
	Gate *consent.AgeGate
	// Mode chooses between AgeGateModeBands (default) and AgeGateModeBirthDate.
	Mode AgeGateMode
	// Catalog optionally localizes all screen strings through l10n.
	Catalog *l10n.Catalog
	// Locale selects the active BCP-47 locale tag in Catalog.
	Locale string
	// Text optionally overrides localized or default strings.
	Text AgeGateText
	// Theme restyles the screen surface, typography and buttons. Nil uses DefaultTheme.
	Theme *Theme
	// OnComplete runs after a valid AgeBand is stored.
	OnComplete func(consent.AgeBand)
}

AgeGateScreenConfig configures an AgeGateScreen bound to a consent.AgeGate.

type AgeGateText

type AgeGateText struct {
	Title          string
	BirthDateTitle string
	Body           string
	Under13        string
	Age13To15      string
	Age16To17      string
	Adult          string
	Year           string
	Month          string
	Day            string
	Confirm        string
	SelectPrompt   string
	InvalidDate    string
	SaveError      string
}

AgeGateText holds user-visible copy for AgeGateScreen. Empty fields are resolved from Catalog before falling back to DefaultAgeGateText.

func DefaultAgeGateText

func DefaultAgeGateText() AgeGateText

DefaultAgeGateText returns neutral English copy for AgeGateScreen with no hint at a preferred answer.

type Align

type Align uint8

Align controls cross-axis placement in VBox and HBox, and child placement inside Panel.

const (
	// AlignDefault inherits the container's Align, or stretches when unset on a container.
	AlignDefault Align = iota
	// AlignStretch expands the child to fill the available cross-axis size unless it sets a fixed size.
	AlignStretch
	// AlignStart aligns the child to the start (left in VBox, top in HBox).
	AlignStart
	// AlignCenter centers the child along the cross axis.
	AlignCenter
	// AlignEnd aligns the child to the end (right in VBox, bottom in HBox).
	AlignEnd
)

type AnchorOverlay

type AnchorOverlay struct {
	// TestID optionally sets the TestID on the overlay container view.
	TestID string
	// contains filtered or unexported fields
}

AnchorOverlay renders native NSGo views anchored to 2D world positions inside a non-blocking overlay (PointerEventsNone on the overlay container, PointerEventsOn on each anchored view). Call Sync(proj) each frame to update screen coordinates in the same commit and automatically hide off-screen anchors.

func NewAnchorOverlay

func NewAnchorOverlay(cx *core.Scope) *AnchorOverlay

NewAnchorOverlay creates a signal-driven AnchorOverlay bound to cx.

func (*AnchorOverlay) Add

func (o *AnchorOverlay) Add(anchor *WorldAnchor)

Add registers or replaces anchor by its ID. If Sync has already been called, the new anchor is immediately projected with the last WorldProjection.

func (*AnchorOverlay) Get

func (o *AnchorOverlay) Get(id string) *WorldAnchor

Get returns the registered WorldAnchor with id, or nil if not found.

func (*AnchorOverlay) Remove

func (o *AnchorOverlay) Remove(id string) bool

Remove deletes the anchor with id from the overlay. Returns true if it existed.

func (*AnchorOverlay) ScreenPosition

func (o *AnchorOverlay) ScreenPosition(id string) (core.Point, bool)

ScreenPosition returns the last synced screen position (including OffsetX/OffsetY) and on-screen visibility for id.

func (*AnchorOverlay) SetVisible

func (o *AnchorOverlay) SetVisible(id string, visible bool) bool

SetVisible updates an anchor's logical visibility flag. Call Sync to apply.

func (*AnchorOverlay) SetWorldPosition

func (o *AnchorOverlay) SetWorldPosition(id string, worldX, worldY float32) bool

SetWorldPosition updates an anchor's world coordinates. Call Sync to project and commit updated screen positions.

func (*AnchorOverlay) Sync

func (o *AnchorOverlay) Sync(proj WorldProjection)

Sync projects all registered anchors through proj and atomically updates their screen positions and visibility signals in a single batch so anchored views stay aligned within the same frame and off-screen anchors are hidden immediately.

func (*AnchorOverlay) View

func (o *AnchorOverlay) View(_ *core.Scope) core.View

View returns the non-blocking absolute overlay core.View rendering all currently visible world anchors. The container uses PointerEventsNone so clicks pass through to the game canvas underneath, while each anchored wrapper re-enables interaction with PointerEventsOn.

type AnchoredItem

type AnchoredItem struct {
	ID          string
	Widget      Widget
	Anchor      ScreenAnchor
	Offset      ScreenOffsetDoc
	SafeArea    bool
	SizeMode    SizeMode
	FixedWidth  float32
	FixedHeight float32
	// PassThrough marks an unsized container whose children anchor directly against the parent's full bounds and safe area.
	PassThrough bool
}

AnchoredItem pairs a child Widget with its anchor, offset, safe-area inset preference, and sizing mode inside a ScreenCanvas.

type AspectBox

type AspectBox struct {
	Child          Widget
	Ratio          float32
	Stretch        AspectStretch
	Align          Align
	Padding        core.Edges
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	Background     core.Color
	Border         core.Color
	CornerRadius   float32
	Transform      Transform
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

AspectBox lays out a single Child preserving a fixed width/height Ratio (<= 0 defaults to 1).

func (*AspectBox) Bounds

func (a *AspectBox) Bounds() core.Bounds

Bounds returns the aspect-ratio box's laid-out rectangle.

func (*AspectBox) ChildWidgets

func (a *AspectBox) ChildWidgets() []Widget

ChildWidgets returns the aspect-ratio box's child if non-nil.

type AspectStretch

type AspectStretch uint8

AspectStretch controls how AspectBox sizes its Child relative to its own inner bounds.

const (
	// AspectFit fits the largest rectangle matching Ratio inside the AspectBox bounds (default).
	AspectFit AspectStretch = iota
	// AspectCover scales to cover the entire AspectBox bounds while matching Ratio, clipping any overflow.
	AspectCover
	// AspectWidthControlsHeight uses the available width and derives height as width / Ratio.
	AspectWidthControlsHeight
	// AspectHeightControlsWidth uses the available height and derives width as height * Ratio.
	AspectHeightControlsWidth
)

func ParseAspectStretch

func ParseAspectStretch(s string) (AspectStretch, bool)

ParseAspectStretch maps a screen-file stretch mode name to AspectStretch.

func (AspectStretch) String

func (s AspectStretch) String() string

String returns the screen-file name of s ("fit", "cover", "width_controls_height", or "height_controls_width").

type Bindings

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

Bindings resolves named screen data paths without polling. Sources are read when a screen requests a value, and can be replaced atomically.

func NewBindings

func NewBindings() *Bindings

NewBindings creates an empty binding registry.

func (*Bindings) Bool

func (b *Bindings) Bool(path string) (bool, error)

Bool returns the boolean value registered at path.

func (*Bindings) Func

func (b *Bindings) Func(path string, fn func() any) error

Func registers a lazily evaluated function at path.

func (*Bindings) Get

func (b *Bindings) Get(path string) (any, bool)

Get returns the value registered at path, evaluating function sources lazily.

func (*Bindings) Has

func (b *Bindings) Has(path string) bool

Has reports whether a source has been registered, including a function source whose value is computed lazily.

func (*Bindings) Int

func (b *Bindings) Int(path string) (int, error)

Int returns the integer value registered at path.

func (*Bindings) Set

func (b *Bindings) Set(path string, value any) error

Set registers value at path and notifies subscribers after the value changes. When value is a function source registered through Func, subscribers receive the function's result rather than the function itself.

func (*Bindings) String

func (b *Bindings) String(path string) (string, error)

String returns the string value registered at path.

func (*Bindings) Subscribe

func (b *Bindings) Subscribe(path string, callback func(any)) (func(), error)

Subscribe registers a callback for changes to path. The callback is invoked after each Set with the new value (a function source is evaluated first). The returned function removes the subscription and is safe to call more than once.

type BoxShadow

type BoxShadow struct {
	Color  core.Color
	Size   float32
	Offset core.Point
}

BoxShadow is a flat StyleBox's drop shadow: the box's shape grown by Size on every side, moved by Offset and filled with Color under the box.

type BuiltScreen

type BuiltScreen struct {
	// Root is the interactive gameui.Root configured with the screen's Viewport and theme.
	Root *Root
	// Navigator is a SpatialNavigator attached to Root with explicit focus-order overrides wired.
	Navigator *SpatialNavigator
	// Doc is a clone of the ScreenDoc this screen was built from.
	Doc *ScreenDoc
	// Canvas is the root ScreenCanvas child of Root.
	Canvas *ScreenCanvas
	// Nodes maps canvas node IDs to their built widgets. Mount the native reconnect
	// overlay separately with Doc.ControllerReconnectPanel.
	Nodes map[string]Widget
	// FocusOrder lists focusable widgets that declared an explicit focusOrder, sorted ascending.
	FocusOrder []Widget
	// OnEvent, when set, is called with the name of each animation clip event playback crosses.
	OnEvent func(name string)
	// contains filtered or unexported fields
}

BuiltScreen is the runtime UI tree constructed from a *.screen.yaml document.

func BuildScreen

func BuildScreen(doc *ScreenDoc, opts ScreenBuildOptions) (*BuiltScreen, error)

BuildScreen constructs a runtime BuiltScreen (including a configured gameui.Root, Viewport, safe-area anchoring, localized text, device-class visibility, and focus-order navigation) from doc. Screens that instance other *.screen.yaml fragments must be resolved with ResolveScreen first.

func (*BuiltScreen) Animation

func (s *BuiltScreen) Animation(name string) ScreenClip

Animation returns the registered ScreenClip named name, or nil if none is registered.

func (*BuiltScreen) ApplyBindings

func (s *BuiltScreen) ApplyBindings(bindings *Bindings) error

ApplyBindings applies registered screen bindings and subscribes to future changes. Calling it again first removes subscriptions installed by the previous call.

func (*BuiltScreen) ApplyCatalog

func (s *BuiltScreen) ApplyCatalog(cat *l10n.Catalog, locale string)

ApplyCatalog refreshes all localized text nodes from cat for locale (or cat's fallback locale when locale is empty).

func (*BuiltScreen) AttachInput

func (s *BuiltScreen) AttachInput(cx *core.Scope) core.Node

AttachInput mounts the hidden native input layer for text_field nodes in this screen.

func (*BuiltScreen) CanvasNodes

func (s *BuiltScreen) CanvasNodes() []core.CanvasNode

CanvasNodes returns the visible, screen-reader nodes in a built screen. Nodes use the widget ID as their stable CanvasNode ID, carry bounds in the canvas coordinates from the last Layout or Draw call, and are ordered from top to bottom, then left to right. Call it after Layout or Draw and add each node to the canvas drawing with Drawing.Node.

func (*BuiltScreen) Checked

func (s *BuiltScreen) Checked(id string) (bool, bool)

Checked returns the current checked state of a toggle node with id.

func (*BuiltScreen) Dispose

func (s *BuiltScreen) Dispose()

Dispose releases subscriptions owned by the screen. It is safe to call more than once and leaves the widgets at their current values.

func (*BuiltScreen) Draw

func (s *BuiltScreen) Draw(d *core.Drawing, bounds core.Bounds)

Draw delegates to s.Root.Draw(d, bounds).

func (*BuiltScreen) HandleCanvasAccessibilityAction

func (s *BuiltScreen) HandleCanvasAccessibilityAction(ev core.CanvasActionEvent) bool

HandleCanvasAccessibilityAction dispatches an assistive-technology action received from a Canvas to the matching widget. It returns false when the node is unknown, hidden, disabled, or does not support the action.

func (*BuiltScreen) Instance

func (s *BuiltScreen) Instance(name string) Widget

Instance constructs a fresh widget tree from a resolved list item screen fragment. name may be a fragment path (such as "screens/parts/mail_item.screen.yaml"), the ID of a list node in this screen (such as "mail"), the fragment's Name field, or the fragment's base filename stem (such as "mail_item"). The returned Widget is a *ScreenCanvas whose Widget(id) method looks up any node inside the instantiated fragment. Returns nil if no matching fragment exists.

func (*BuiltScreen) Layout

func (s *BuiltScreen) Layout(bounds core.Bounds)

Layout delegates to s.Root.Layout(bounds).

func (*BuiltScreen) Play

func (s *BuiltScreen) Play(name string) bool

Play restarts and plays the named animation clip from time 0. It returns true if name is registered on s and false otherwise.

func (*BuiltScreen) SetAnimation

func (s *BuiltScreen) SetAnimation(name string, clip ScreenClip)

SetAnimation registers or replaces a named animation clip on s. If clip supports event callbacks (such as *animclip.Player), its events are routed to s.OnEvent. Passing nil removes the named animation.

func (*BuiltScreen) SetChecked

func (s *BuiltScreen) SetChecked(id string, checked bool) bool

SetChecked updates the checked state of a toggle node with id. When checked is true on a toggle belonging to a radio group, other checked toggles in the same group are turned off first (invoking their OnToggle callbacks with false). Invokes this toggle's OnToggle callback if its state changed. Returns true if id matched a toggle node.

func (*BuiltScreen) SetDeviceClass

func (s *BuiltScreen) SetDeviceClass(class DeviceClass)

SetDeviceClass updates conditional visibility for all nodes carrying deviceClasses restrictions. Passing an empty DeviceClass makes all non-disjoint nodes visible.

func (*BuiltScreen) SetHidden

func (s *BuiltScreen) SetHidden(id string, hidden bool)

SetHidden records application-controlled visibility for the node with id. Use this method for nodes restricted by deviceClasses so the setting is retained while the node is filtered out and restored when its class matches.

func (*BuiltScreen) SetSafeArea

func (s *BuiltScreen) SetSafeArea(insets core.Edges)

SetSafeArea updates the safe-area insets used by subsequent Layout and Draw calls without clearing any active title-bar inset.

func (*BuiltScreen) SetState

func (s *BuiltScreen) SetState(nodeID, set, value string) error

SetState switches the named state set on nodeID to value, applying that state's per-node overrides and reverting any overridden field not set by value back to its base screen definition. Overrides from distinct state sets combine independently. Visibility overrides never unhide a node filtered out by SetDeviceClass. If the state set names a transition clip registered on s and the value changed, SetState plays that clip via Play; otherwise the switch is immediate.

func (*BuiltScreen) SetTextLookup

func (s *BuiltScreen) SetTextLookup(fn func(key string) string)

SetTextLookup refreshes all localized text nodes using fn (or the raw textKey when fn is nil).

func (*BuiltScreen) SetTitleBar

func (s *BuiltScreen) SetTitleBar(insets core.Edges)

SetTitleBar updates the desktop hidden title-bar insets used by subsequent Layout and Draw calls. Pass desktop.TitleBar(cx) from a desktop game; passing zero edges in full screen or with a system title bar clears the title-bar inset while keeping the platform safe area.

func (*BuiltScreen) SetValue

func (s *BuiltScreen) SetValue(id string, v float32) bool

SetValue updates the value of a progress_bar, image_progress, or slider node with id, clamped to the widget's [min, max] range. Non-finite values are ignored. For slider nodes, OnChange fires when the clamped value differs from the current value. Returns true if id matched a value widget and v was finite.

func (*BuiltScreen) State

func (s *BuiltScreen) State(nodeID, set string) string

State returns the active state value for the named state set on nodeID, or "" if s is nil or no such node or state set is declared.

func (*BuiltScreen) Stop

func (s *BuiltScreen) Stop(name string)

Stop pauses the named animation clip if registered.

func (*BuiltScreen) StopAll

func (s *BuiltScreen) StopAll()

StopAll pauses every animation clip registered on s.

func (*BuiltScreen) Update

func (s *BuiltScreen) Update(dt time.Duration)

Update advances every animation clip already playing on s when Update starts, by dt in deterministic name order, and advances Root physics (ScrollList inertia/bounce and touch long-press detection). Clips started from an OnEvent callback begin advancing on the next Update; clips stopped or replaced from OnEvent stop immediately.

func (*BuiltScreen) Value

func (s *BuiltScreen) Value(id string) (float32, bool)

Value returns the current value of a progress_bar, image_progress, or slider node with id.

func (*BuiltScreen) Widget

func (s *BuiltScreen) Widget(id string) Widget

Widget returns the built Widget with id, or nil if no node has that ID.

type Button

type Button struct {
	Text     string
	OnClick  func()
	Disabled bool
	Font     core.Font
	Effects  text.TextEffects
	// Wrap selects multi-line wrapping inside the button's inner width (WrapDefault and WrapNone keep a single line).
	Wrap text.Wrap
	// Overrun selects how text exceeding the button's inner width or MaxLines is clipped or ellipsized.
	Overrun text.Overrun
	// MaxLines caps the number of visible lines when > 0 (0 means unlimited when wrapping).
	MaxLines int
	// Variation names a Theme.Styles entry that styles this button in place of the theme's button style.
	Variation      string
	TextColor      core.Color
	Background     core.Color
	CornerRadius   float32
	Padding        core.Edges
	FocusOrder     int
	TouchHitSize   float32
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Button is a clickable and focusable action trigger.

func (*Button) Bounds

func (b *Button) Bounds() core.Bounds

Bounds returns the button's laid-out rectangle.

func (*Button) HitBounds

func (b *Button) HitBounds() core.Bounds

HitBounds returns the button's interactive hit area, expanded to TouchHitSize when larger than Bounds.

type CADPAAgeRating

type CADPAAgeRating string

CADPAAgeRating is a China Audio-video and Digital Publishing Association (CADPA) age-appropriateness notice level (适龄提示).

const (
	// CADPAAge8Plus marks content suitable for players aged 8 and above (green badge).
	CADPAAge8Plus CADPAAgeRating = "8+"
	// CADPAAge12Plus marks content suitable for players aged 12 and above (blue badge).
	CADPAAge12Plus CADPAAgeRating = "12+"
	// CADPAAge16Plus marks content suitable for players aged 16 and above (amber badge).
	CADPAAge16Plus CADPAAgeRating = "16+"
	// CADPAAge18Plus marks content suitable for players aged 18 and above (red badge).
	CADPAAge18Plus CADPAAgeRating = "18+"
)

type CanvasQuitConfirmation

type CanvasQuitConfirmation struct {
	Root      *Root
	Navigator *SpatialNavigator
	Open      func() bool
	OnAnswer  func(proceed bool)
	Save      func() error
	CanSave   func() bool
	Report    func(error)
	// contains filtered or unexported fields
}

CanvasQuitConfirmation is a gameui confirmation screen for canvas games. Its Root and Navigator use the same pointer, touch, keyboard, and gamepad input-action paths as other gameui screens without enabling native focus navigation. Cancel is focused whenever the confirmation opens, and NavBack, Back, or Escape cancels.

func NewCanvasQuitConfirmation

func NewCanvasQuitConfirmation(opts CanvasQuitConfirmationOptions) *CanvasQuitConfirmation

NewCanvasQuitConfirmation builds a navigable canvas confirmation screen.

func (*CanvasQuitConfirmation) Back

func (q *CanvasQuitConfirmation) Back() bool

Back cancels the confirmation when it is open.

func (*CanvasQuitConfirmation) Draw

func (q *CanvasQuitConfirmation) Draw(d *core.Drawing, bounds core.Bounds)

Draw renders the confirmation when Open is true and focuses Cancel when it opens.

func (*CanvasQuitConfirmation) HandleAction

func (q *CanvasQuitConfirmation) HandleAction(action NavAction) bool

HandleAction dispatches a logical NavAction (from keyboard, gamepad, or virtual controls) through the confirmation when it is open. NavBack cancels.

func (*CanvasQuitConfirmation) OnKeyDown

func (q *CanvasQuitConfirmation) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown routes keyboard navigation to the confirmation's root and cancels on Escape or Back.

func (*CanvasQuitConfirmation) OnPointerDown

func (q *CanvasQuitConfirmation) OnPointerDown(p core.Point) bool

OnPointerDown routes a pointer press start to the confirmation when it is open.

func (*CanvasQuitConfirmation) OnPointerMove

func (q *CanvasQuitConfirmation) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state for the confirmation when it is open.

func (*CanvasQuitConfirmation) OnPointerUp

func (q *CanvasQuitConfirmation) OnPointerUp(p core.Point) bool

OnPointerUp finishes a pointer press on the confirmation when it is open.

func (*CanvasQuitConfirmation) OnPress

func (q *CanvasQuitConfirmation) OnPress(ev core.PressEvent) bool

OnPress routes a canvas press to the confirmation's gameui root.

func (*CanvasQuitConfirmation) StepActions

func (q *CanvasQuitConfirmation) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions (such as from input.Actions.JustPressed) and dispatches them in deterministic order while the confirmation is open.

type CanvasQuitConfirmationOptions

type CanvasQuitConfirmationOptions struct {
	Open func() bool
	// OnAnswer receives true to proceed and false to cancel. Close the confirmation
	// by making Open return false on either answer.
	OnAnswer func(proceed bool)
	// Save is optional. A failed save leaves the confirmation open for retry.
	Save func() error
	// CanSave limits when Save and quit is shown. Nil allows it whenever Save is set.
	CanSave func() bool
	// Report receives a failed save for game-specific logging or feedback.
	Report func(error)
	// Theme styles the confirmation. Nil uses DefaultTheme.
	Theme *Theme
	// The captions can be localized or adapted for Restart and Quit to title.
	// Empty captions use English quit copy.
	Title, Description, CancelText, QuitText, SaveText, SaveFailedText string
}

CanvasQuitConfirmationOptions configures a quit confirmation drawn by a game canvas.

type CaptionPreviewLine

type CaptionPreviewLine struct {
	Kind         a11y.CaptionKind
	Speaker      string
	Prefix       string
	SpeakerPart  string
	Rest         string
	FullText     string
	SpeakerColor core.Color
	TextColor    core.Color
}

CaptionPreviewLine describes one wrapped caption line rendered inside the SettingsMenu Accessibility tab's live preview swatch.

type CaptionPreviewState

type CaptionPreviewState struct {
	Enabled           bool
	HighContrast      bool
	Background        core.Color
	BackgroundOpacity float64
	TextColor         core.Color
	SpeakerColors     bool
	FontSize          core.Points
	Lines             []CaptionPreviewLine
}

CaptionPreviewState is a snapshot of the live caption preview currently rendered over the light and dark swatches in SettingsMenu's Accessibility tab.

type ColorRect

type ColorRect struct {
	Color        core.Color
	CornerRadius float32
	Width        float32
	Height       float32
	MinWidth     float32
	MinHeight    float32
	Flex         float32
	Align        Align
	Hidden       bool
	Transform    Transform
	// contains filtered or unexported fields
}

ColorRect draws a solid or translucent filled rectangle (such as a modal backdrop or HUD plate).

func (*ColorRect) Bounds

func (c *ColorRect) Bounds() core.Bounds

Bounds returns the rectangle's laid-out bounds.

type ConsentScreen

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

ConsentScreen is a restylable, localized privacy consent prompt built from the purposes declared on a liveops.Consent manager. Mount View(cx) over the game view; it displays automatically while Consent.NeedsPrompt() is true and hides itself once the player saves their choices.

func NewConsentScreen

func NewConsentScreen(cfg ConsentScreenConfig) *ConsentScreen

NewConsentScreen creates a ConsentScreen bound to cfg.Consent.

func (*ConsentScreen) AcceptAll

func (s *ConsentScreen) AcceptAll() error

AcceptAll grants every declared purpose permitted by the current age/child mode with ConsentSourcePrompt (recording DeniedChoice for child-restricted purposes when child mode is active) and closes the screen on success.

func (*ConsentScreen) Close

func (s *ConsentScreen) Close()

Close hides the consent screen without recording new choices.

func (*ConsentScreen) Draft

func (s *ConsentScreen) Draft(p liveops.Purpose) bool

Draft returns the pending toggle state for purpose p in the consent screen.

func (*ConsentScreen) Err

func (s *ConsentScreen) Err() error

Err returns the last save error encountered by AcceptAll, RejectAll, or Save.

func (*ConsentScreen) Open

func (s *ConsentScreen) Open()

Open refreshes draft toggles from the Consent manager and displays the consent screen.

func (*ConsentScreen) RejectAll

func (s *ConsentScreen) RejectAll() error

RejectAll denies every declared purpose with ConsentSourcePrompt and closes the screen on success.

func (*ConsentScreen) Required

func (s *ConsentScreen) Required() bool

Required reports whether the underlying Consent manager requires the player to answer.

func (*ConsentScreen) Save

func (s *ConsentScreen) Save() error

Save persists every declared purpose's pending draft toggle with ConsentSourcePrompt and closes the screen on success.

func (*ConsentScreen) SetDraft

func (s *ConsentScreen) SetDraft(p liveops.Purpose, allowed bool)

SetDraft sets the pending toggle state for purpose p without saving until Save is called. Child-restricted purposes stay off while Consent is in child mode.

func (*ConsentScreen) Toggle

func (s *ConsentScreen) Toggle(p liveops.Purpose) bool

Toggle flips the pending toggle state for purpose p and returns its new value. Child-restricted purposes stay off while Consent is in child mode.

func (*ConsentScreen) View

func (s *ConsentScreen) View(cx *core.Scope) core.Node

View renders the consent screen as a native NSGo overlay when required or opened.

type ConsentScreenConfig

type ConsentScreenConfig struct {
	// Consent supplies declared purposes, policy version and persistence.
	Consent *liveops.Consent
	// Catalog optionally localizes all screen labels and purpose copy through l10n.
	Catalog *l10n.Catalog
	// Locale selects the active BCP-47 locale tag in Catalog (Catalog.FallbackLocale when empty).
	Locale string
	// Text optionally overrides localized or default strings.
	Text ConsentText
	// Theme restyles the screen surface, typography, toggles and buttons. Nil uses DefaultTheme.
	Theme *Theme
	// OnComplete runs after choices are saved via AcceptAll, RejectAll, or Save.
	OnComplete func()
}

ConsentScreenConfig configures a ConsentScreen prompt built from a shared liveops.Consent manager.

type ConsentSettingsConfig

type ConsentSettingsConfig struct {
	// Consent supplies declared purposes, stored records and persistence.
	Consent *liveops.Consent
	// Catalog optionally localizes all headings, record captions and purpose descriptions through l10n.
	Catalog *l10n.Catalog
	// Locale selects the active BCP-47 locale tag in Catalog.
	Locale string
	// Text optionally overrides localized or default strings.
	Text ConsentText
	// Theme restyles the section. Nil uses DefaultTheme.
	Theme *Theme
	// OnChange runs after a purpose choice is saved with ConsentSourceSettings.
	OnChange func(liveops.Purpose, liveops.ConsentChoice)
}

ConsentSettingsConfig configures a ConsentSettingsSection built from a shared liveops.Consent manager.

type ConsentSettingsSection

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

ConsentSettingsSection renders a privacy settings section built from a liveops.Consent manager's declared purposes. Every toggle updates Consent with ConsentSourceSettings and displays the stored timestamp, policy version and source of the player's last answer.

func NewConsentSettingsSection

func NewConsentSettingsSection(cfg ConsentSettingsConfig) *ConsentSettingsSection

NewConsentSettingsSection creates a ConsentSettingsSection bound to cfg.Consent.

func (*ConsentSettingsSection) Err

func (s *ConsentSettingsSection) Err() error

Err returns the last save error encountered by SetAllowed or Toggle.

func (*ConsentSettingsSection) SetAllowed

func (s *ConsentSettingsSection) SetAllowed(p liveops.Purpose, allowed bool) error

SetAllowed records GrantedChoice or DeniedChoice for purpose p using ConsentSourceSettings.

func (*ConsentSettingsSection) Toggle

Toggle flips the current Allowed state of purpose p and saves it using ConsentSourceSettings.

func (*ConsentSettingsSection) View

func (s *ConsentSettingsSection) View(cx *core.Scope) core.Node

View renders the privacy settings section as an embeddable native NSGo node.

func (*ConsentSettingsSection) Widgets

func (s *ConsentSettingsSection) Widgets() *VBox

Widgets builds an embeddable in-canvas gameui VBox with a heading label and a Toggle switch for every declared purpose, for canvas-only settings screens.

type ConsentText

type ConsentText struct {
	Title         string
	Body          string
	Policy        string
	GPCNotice     string
	AcceptAll     string
	RejectAll     string
	Save          string
	SaveError     string
	SettingsTitle string
	Recorded      string
	NotSet        string
	StateAllowed  string
	StateDenied   string
}

ConsentText holds user-visible copy for ConsentScreen and ConsentSettingsSection. Empty fields are looked up in the configured l10n.Catalog first, falling back to DefaultConsentText.

func DefaultConsentText

func DefaultConsentText() ConsentText

DefaultConsentText returns the English default copy for ConsentScreen and ConsentSettingsSection.

type Container

type Container interface {
	Widget
	// ChildWidgets returns the container's direct children in layout order.
	ChildWidgets() []Widget
}

Container is a Widget that lays out child widgets. Panel, VBox, and HBox implement Container.

type ControllerReconnectConfig

type ControllerReconnectConfig struct {
	// Visible follows the game's controller-loss state. A nil function shows
	// the panel whenever it is mounted.
	Visible func() bool
	// Title and Message read localized strings. Nil functions use English copy
	// that asks the player to reconnect the original controller.
	Title   func() string
	Message func() string
	// Prompt supplies an optional glyph from the game's input prompt table.
	Prompt func() input.Prompt
	// Theme styles the panel. Nil uses DefaultTheme.
	Theme *Theme
}

ControllerReconnectConfig configures a native controller-reconnect panel.

type CornerRadii

type CornerRadii struct {
	TopLeft     float32
	TopRight    float32
	BottomRight float32
	BottomLeft  float32
}

CornerRadii holds a radius in points for each corner of a rectangle.

func UniformCorners

func UniformCorners(r float32) CornerRadii

UniformCorners returns CornerRadii with r on every corner.

type CreditEntry

type CreditEntry struct {
	// Name is the credited asset, library or notice, such as "Kenney Pixel Font".
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Author is the optional creator or copyright holder.
	Author string `yaml:"author,omitempty"`
	// License is the optional license name or SPDX identifier, such as "CC0-1.0" or "MIT".
	License string `yaml:"license,omitempty"`
	// URL is the optional address of the asset's source or license text.
	URL string `yaml:"url,omitempty"`
}

CreditEntry is one credited asset or third-party notice.

type CreditPerson

type CreditPerson struct {
	// Name is the person's displayed name.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Role is the optional role shown beside the name, such as "Design".
	Role string `yaml:"role,omitempty"`
}

CreditPerson identifies a member of the game's team.

type Credits

type Credits struct {
	// Title is the displayed game title.
	Title string
	// Version is the displayed app version.
	Version string
	// Build is an optional build identifier.
	Build string
	// Entries contains third-party acknowledgements.
	Entries []CreditEntry
}

Credits groups app version/build metadata and acknowledgements.

func (Credits) Sorted

func (c Credits) Sorted() []CreditEntry

Sorted returns a copy of the entries sorted by name; entries with the same name keep their order.

func (Credits) Valid

func (c Credits) Valid() bool

Valid reports whether the credits have the required title and version.

type CreditsFile

type CreditsFile struct {
	// Version is the schema version; it must equal CreditsFileVersion (1).
	Version int `yaml:"version" schema:"required"`
	// Title is the displayed game title.
	Title string `yaml:"title" schema:"required,minLength=1"`
	// AppVersion is the displayed app version, such as "1.2.3".
	AppVersion string `yaml:"appVersion" schema:"required,minLength=1"`
	// Build is an optional build identifier.
	Build string `yaml:"build,omitempty"`
	// Team lists the game's team in presentation order.
	Team []CreditPerson `yaml:"team,omitempty"`
	// Entries lists third-party assets and notices in the order they are written.
	Entries []CreditEntry `yaml:"entries,omitempty"`
}

CreditsFile is the root of a versioned credits.yaml resource a game ships beside its assets. Team and Entries keep the order they are written in, so loading and saving a file changes nothing; Credits.Sorted gives the entries in name order for display.

func ParseCreditsFile

func ParseCreditsFile(data []byte) (CreditsFile, error)

ParseCreditsFile decodes and validates a versioned credits.yaml resource. Unknown fields, trailing YAML documents, missing or unsupported versions, and missing title, appVersion, or names are refused with *loaderr.Error line info.

func (CreditsFile) Credits

func (f CreditsFile) Credits() Credits

Credits converts the file metadata and entries to the compact runtime model.

func (CreditsFile) Valid

func (f CreditsFile) Valid() bool

Valid reports whether f contains the required metadata for a credits file.

type Custom

type Custom struct {
	// Impl supplies measurement, drawing, and optional focus, pointer, navigation, and hit-test hooks.
	Impl CustomWidget
	// Width and Height override the measured size when positive.
	Width, Height float32
	// MinWidth and MinHeight constrain the measured size.
	MinWidth, MinHeight float32
	// Flex receives extra space in its parent box layout.
	Flex float32
	// Align controls cross-axis placement in its parent box layout.
	Align Align
	// Hidden excludes the widget from layout, drawing, focus, and hit testing.
	Hidden bool
	// Disabled excludes the widget from focus and pointer input and sets WidgetState.Disabled.
	Disabled bool
	// FocusOrder controls explicit keyboard/gamepad focus ordering.
	FocusOrder int
	// Nav configures explicit directional focus neighbors that override 2D spatial lookup.
	Nav NavOverrides
	// Transform holds per-node translation, scale, rotation, pivot, and opacity.
	Transform Transform
	// OnContextMenu runs on right-click or touch long-press over this widget.
	OnContextMenu func(core.Point)
	// PointerFilter controls whether a hit claims the pointer. The zero value stops propagation.
	PointerFilter PointerFilter
	// Tooltip supplies delayed hover/focus help for this widget.
	Tooltip *Tooltip
	// Drag and Drop opt this widget into the shared drag-and-drop state machine.
	Drag *DragSource
	Drop *DropTarget
	// contains filtered or unexported fields
}

Custom adapts a game-owned CustomWidget into the gameui layout, focus, and input tree.

Example

Custom adapts a game-owned CustomWidget with optional Focusable, PointerHandler, NavHandler, and HitTester hooks into layout and focus.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

type exampleDial struct{ value int }

func (d *exampleDial) Measure(gameui.MeasureContext) core.Size {
	return core.Size{Width: 64, Height: 64}
}

func (d *exampleDial) Draw(_ *core.Drawing, _ core.Bounds, _ gameui.WidgetState, _ *gameui.Theme) {}

func (d *exampleDial) OnPointer(ev gameui.PointerEvent) bool {
	if ev.Kind == gameui.PointerDown {
		fmt.Println("pointer", ev.Kind, ev.Position)
		return true
	}
	return false
}

func (d *exampleDial) OnNav(a gameui.NavAction) bool {
	switch a {
	case gameui.NavRight:
		d.value++
		return true
	case gameui.NavLeft:
		d.value--
		return true
	default:
		return false
	}
}

func main() {
	dial := &exampleDial{}
	slot := &gameui.Custom{Impl: dial, Width: 64, Height: 64}
	root := gameui.NewRoot(&gameui.VBox{Padding: core.All(10), Align: gameui.AlignStart, Children: []gameui.Widget{slot}})
	root.Layout(core.Bounds{Size: core.Size{Width: 200, Height: 120}})

	nav := gameui.NewSpatialNavigator(root)
	nav.SetFocus(slot)
	nav.HandleAction(gameui.NavRight)
	root.OnPointerDown(core.Point{X: 25, Y: 30})
	fmt.Println("value:", dial.value, "focused:", nav.Focused() == slot)
}
Output:
pointer down {15 20}
value: 1 focused: true

func (*Custom) Bounds

func (c *Custom) Bounds() core.Bounds

Bounds returns the rectangle assigned by the last layout pass.

type CustomContainer

type CustomContainer struct {
	// Children holds the direct child widgets laid out by Layout.
	Children []Widget
	// Measure optionally returns the preferred inner content size for the container's visible children (Padding is added outside it).
	// When nil, the preferred content size is the maximum width and height among visible children.
	Measure func(ctx MeasureContext, children []Widget) core.Size
	// Layout positions visible children inside b using SetWidgetBounds (or reading child preferred sizes with MeasureChild / MeasureWidget).
	// When nil, visible children fill b.
	Layout func(b core.Bounds, children []Widget)
	// Draw optionally renders custom container artwork inside Bounds() behind Children.
	Draw func(d *core.Drawing, b core.Bounds, st WidgetState, th *Theme)
	// Padding insets the bounds passed to Layout and expands the measured size.
	Padding core.Edges
	// Width and Height override the measured size when positive.
	Width, Height float32
	// MinWidth and MinHeight constrain the measured size.
	MinWidth, MinHeight float32
	// Flex receives extra space in its parent box layout.
	Flex float32
	// Align controls cross-axis placement in its parent box layout.
	Align Align
	// Hidden excludes the container and its children from layout, drawing, focus, and hit testing.
	Hidden bool
	// DrawBackground, FrameDrawer, and NineSlice optionally render framing behind Draw and Children.
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	// Transform holds per-node translation, scale, rotation, pivot, and opacity.
	Transform Transform
	// OnContextMenu runs on right-click or touch long-press over this container.
	OnContextMenu func(core.Point)
	// contains filtered or unexported fields
}

CustomContainer arranges Children using game-owned measurement and layout hooks (such as radial or hex layouts). It implements Container and Widget.

Example

CustomContainer arranges children with a custom Layout hook while keeping Root focus navigation intact.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	b0 := &gameui.Button{Text: "East", Width: 40, Height: 24}
	b1 := &gameui.Button{Text: "West", Width: 40, Height: 24}
	radial := &gameui.CustomContainer{
		Width:    200,
		Height:   100,
		Children: []gameui.Widget{b0, b1},
		Layout: func(b core.Bounds, children []gameui.Widget) {
			gameui.SetWidgetBounds(children[0], core.Bounds{Origin: core.Point{X: b.Origin.X + 140, Y: b.Origin.Y + 38}, Size: core.Size{Width: 40, Height: 24}})
			gameui.SetWidgetBounds(children[1], core.Bounds{Origin: core.Point{X: b.Origin.X + 20, Y: b.Origin.Y + 38}, Size: core.Size{Width: 40, Height: 24}})
		},
	}
	root := gameui.NewRoot(radial)
	root.Layout(core.Bounds{Size: core.Size{Width: 200, Height: 100}})

	nav := gameui.NewSpatialNavigator(root)
	nav.SetFocus(b1)
	nav.HandleAction(gameui.NavRight)
	fmt.Println(nav.Focused().(*gameui.Button).Text)
}
Output:
East

func (*CustomContainer) Bounds

func (c *CustomContainer) Bounds() core.Bounds

Bounds returns the container's laid-out rectangle.

func (*CustomContainer) ChildWidgets

func (c *CustomContainer) ChildWidgets() []Widget

ChildWidgets returns the container's direct children in layout order.

func (*CustomContainer) MeasureChild

func (c *CustomContainer) MeasureChild(child Widget) core.Size

MeasureChild measures child using the container's active layout/measure theme (or DefaultTheme outside a pass).

type CustomWidget

type CustomWidget interface {
	// Measure returns the preferred size using the current theme.
	Measure(MeasureContext) core.Size
	// Draw renders the widget inside bounds with its current interaction state.
	Draw(*core.Drawing, core.Bounds, WidgetState, *Theme)
}

CustomWidget is the drawing and measurement contract implemented by a game-owned widget.

type DeviceClass

type DeviceClass string

DeviceClass identifies a target device form factor for conditional visibility and reference layout checks.

const (
	DevicePhone     DeviceClass = "phone"
	DeviceTablet    DeviceClass = "tablet"
	DeviceDesktop   DeviceClass = "desktop"
	DeviceUltrawide DeviceClass = "ultrawide"
)

type DeviceProfile

type DeviceProfile struct {
	// ID is the machine identifier (for example "phone", "tablet", "desktop", "ultrawide").
	ID string
	// Name is the human-readable profile name (for example "Phone 19.5:9 (notch)").
	Name string
	// Class is the device class matched against ScreenNodeDoc.DeviceClasses.
	Class DeviceClass
	// Width and Height are the virtual canvas dimensions in points at this aspect ratio.
	Width  float32
	Height float32
	// SafeArea specifies the notch, rounded-corner, and home-indicator insets in virtual points.
	SafeArea core.Edges
	// TitleBar specifies the desktop hidden title-bar control area in virtual points; zero in full screen or with the system title bar.
	TitleBar core.Edges
	// Touch reports whether this device uses touch input (and enforces minimum touch target size).
	Touch bool
}

DeviceProfile describes a reference display size, safe-area insets, and device class used to preview and validate screens.

func DesktopTitleBarDevicesFor

func DesktopTitleBarDevicesFor(designW, designH float32) []DeviceProfile

DesktopTitleBarDevicesFor returns desktop 16:9 and ultrawide 21:9 reference profiles with macOS-style (top-left) and Windows-style (top-right) hidden title-bar controls scaled to a screen's design size.

func PortraitReferenceDevices

func PortraitReferenceDevices() []DeviceProfile

PortraitReferenceDevices returns the two standard portrait phone reference profiles for a 640×360 design canvas: Phone 9:19.5 (portrait) (360×780) with top notch and bottom home-indicator insets, and Phone 9:19.5 (mobile browser) (360×780) with top and bottom browser toolbar insets.

func PortraitReferenceDevicesFor

func PortraitReferenceDevicesFor(designW, designH float32) []DeviceProfile

PortraitReferenceDevicesFor returns portrait phone reference profiles scaled to match a screen's design size: Phone 9:19.5 (portrait) with top notch and bottom home-indicator insets, and Phone 9:19.5 (mobile browser) with top and bottom browser toolbar insets.

func ReferenceDevices

func ReferenceDevices() []DeviceProfile

ReferenceDevices returns the four standard reference profiles for a 640×360 design canvas: Phone 19.5:9 with a notch (780×360), Tablet 4:3 (640×480), Desktop 16:9 (640×360), and Ultrawide 21:9 (840×360).

func ReferenceDevicesFor

func ReferenceDevicesFor(designW, designH float32) []DeviceProfile

ReferenceDevicesFor returns the four standard reference profiles scaled to match a screen's design size: Phone 19.5:9 with a notch, Tablet 4:3, Desktop 16:9, and Ultrawide 21:9.

type DragSource

type DragSource struct {
	Data    any
	Slop    float32
	Preview func() Widget
}

DragSource describes data that a widget can pick up after the pointer moves beyond Slop. Preview is optional and is evaluated only when a drag starts.

type DragState

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

DragState is a small deterministic drag-and-drop state machine. Roots and custom widgets can share it for mouse, touch, or gamepad pointer emulation.

func (*DragState) Begin

func (d *DragState) Begin(source *DragSource, position core.Point)

Begin records a press. The drag remains pending until Move crosses Slop.

func (*DragState) Cancel

func (d *DragState) Cancel()

Cancel abandons a pending or active drag.

func (*DragState) End

func (d *DragState) End() bool

End drops the data on the current target when accepted and clears the state.

func (*DragState) Move

func (d *DragState) Move(position core.Point) bool

Move updates the pointer and reports whether a drag is active.

func (*DragState) Preview

func (d *DragState) Preview() Widget

Preview returns the current drag preview, if one was provided.

func (*DragState) SetTarget

func (d *DragState) SetTarget(target *DropTarget) bool

SetTarget updates the hovered drop target and returns whether it accepts the data.

type DropTarget

type DropTarget struct {
	Accept  func(data any) bool
	OnDrop  func(data any)
	Preview func() Widget
}

DropTarget describes a widget that can accept a drag. Accept is called while hovering and OnDrop is called once for an accepted release.

type Dropdown struct {
	// Label optionally displays a left-aligned field name beside the selected value (useful in options screens).
	Label string
	// Items lists the menu entries shown when the dropdown opens.
	Items []MenuItem
	// Selected is the 0-based index of the currently selected item in Items (-1 for none).
	Selected int
	// Placeholder is shown when Selected is out of range or has no display text.
	Placeholder string
	// OnSelect is invoked with the chosen item's ID when the player picks an entry.
	OnSelect func(id string)
	// Translate optionally resolves MenuItem.TextKey into display text.
	Translate func(key string) string
	// Placement chooses anchored placement (default) or bottom-edge sheet placement (MenuSheetPosition).
	Placement MenuPositionMode
	// SafeArea optionally constrains popup placement inside the layer bounds.
	SafeArea core.Bounds
	// SafeInsets optionally insets the layer bounds when SafeArea is zero.
	SafeInsets core.Edges
	// Layers optionally specifies the Layers stack to open the popup on.
	// When nil, Dropdown automatically uses the Layers stack owning its Root (or a Root-local popup fallback).
	Layers *Layers

	Disabled       bool
	Font           core.Font
	Effects        text.TextEffects
	TextColor      core.Color
	Background     core.Color
	CornerRadius   float32
	Padding        core.Edges
	FocusOrder     int
	TouchHitSize   float32
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Dropdown is a focusable picker that displays the currently selected item and opens a popup menu of MenuItem entries (with icons, separators, disabled entries, checkboxes, radios, and submenus).

func (dd *Dropdown) Bounds() core.Bounds

Bounds returns the dropdown's laid-out rectangle.

func (dd *Dropdown) Close() bool

Close closes the dropdown's popup menu if currently open.

func (dd *Dropdown) HitBounds() core.Bounds

HitBounds returns the dropdown's interactive hit area, expanded to TouchHitSize when larger than Bounds.

func (dd *Dropdown) IsOpen() bool

IsOpen reports whether the dropdown's popup menu is currently open.

func (dd *Dropdown) Open() *Layer

Open opens the dropdown's popup menu on its Layers stack (or standalone Root) and returns the Layer handle when opened on Layers.

func (dd *Dropdown) Select(index int) bool

Select sets Selected to index if it is selectable and invokes OnSelect with its ID.

func (dd *Dropdown) SelectID(id string) bool

SelectID finds the first selectable item matching id, updates Selected, and invokes OnSelect.

func (dd *Dropdown) SelectedID() string

SelectedID returns the ID of the currently selected item, or "" if Selected is out of range.

func (dd *Dropdown) SelectedText() string

SelectedText returns the display label of the currently selected item, or Placeholder if none.

type FillMode

type FillMode uint8

FillMode picks how an ImageProgress reveals its progress image as the value grows.

const (
	// FillLeftToRight reveals the progress image from the left edge to the right (the default).
	FillLeftToRight FillMode = iota
	// FillRightToLeft reveals the progress image from the right edge to the left.
	FillRightToLeft
	// FillTopToBottom reveals the progress image from the top edge to the bottom.
	FillTopToBottom
	// FillBottomToTop reveals the progress image from the bottom edge to the top.
	FillBottomToTop
	// FillCenterHorizontal reveals the progress image from the horizontal center outward to both sides.
	FillCenterHorizontal
	// FillCenterVertical reveals the progress image from the vertical center outward to both edges.
	FillCenterVertical
	// FillClockwise reveals the progress image along a clockwise pie sweep from StartAngle.
	FillClockwise
	// FillCounterClockwise reveals the progress image along a counter-clockwise pie sweep from StartAngle.
	FillCounterClockwise
)

func ParseFillMode

func ParseFillMode(s string) (FillMode, bool)

ParseFillMode maps a screen-file fill name (such as "clockwise") to its FillMode, reporting whether s was recognized.

func (FillMode) String

func (m FillMode) String() string

String returns the screen-file name of m (such as "clockwise"), or "left_to_right" for an unknown mode.

type FirstLaunchSettings

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

FirstLaunchSettings is a small, reusable first-launch gate for templates. It enables captions by default, preserves a player's existing text and motion preferences, and disappears permanently after Continue succeeds.

func NewFirstLaunchSettings

func NewFirstLaunchSettings(cfg FirstLaunchSettingsConfig) *FirstLaunchSettings

NewFirstLaunchSettings creates a prompt from persisted settings or defaults.

func (*FirstLaunchSettings) Complete

func (f *FirstLaunchSettings) Complete() error

Complete enables captions, persists the completion marker, and closes the prompt.

func (*FirstLaunchSettings) Err

func (f *FirstLaunchSettings) Err() error

Err returns the last load or save error.

func (*FirstLaunchSettings) Required

func (f *FirstLaunchSettings) Required() bool

Required reports whether the prompt should block the first game screen.

func (*FirstLaunchSettings) Settings

func (f *FirstLaunchSettings) Settings() save.Settings

Settings returns a validated copy of the settings currently held by the prompt.

func (*FirstLaunchSettings) View

func (f *FirstLaunchSettings) View(cx *core.Scope) core.Node

View renders the prompt as a native NSGo overlay. Mount it before the first sound is played; it removes itself once Complete succeeds and renders nothing when the prompt was already completed.

type FirstLaunchSettingsConfig

type FirstLaunchSettingsConfig struct {
	// Store persists the completion marker and the initial accessibility values.
	Store *save.DefaultSettingsStore
	// Initial supplies settings when Store is nil or has no saved value.
	Initial *save.Settings
	// Text localizes the prompt. Empty fields use DefaultFirstLaunchSettingsText.
	Text FirstLaunchSettingsText
	// OnMoreOptions opens the full SettingsMenu's Accessibility tab.
	OnMoreOptions func()
	// OnComplete runs after the marker and settings have been saved.
	OnComplete func(save.Settings) error
}

FirstLaunchSettingsConfig configures the first-launch accessibility prompt.

type FirstLaunchSettingsText

type FirstLaunchSettingsText struct {
	Title         string
	Body          string
	Captions      string
	TextSize      string
	ReducedMotion string
	MoreOptions   string
	Continue      string
}

FirstLaunchSettingsText contains the copy shown before a game plays its first sound. Applications can localize the prompt without replacing its layout.

func DefaultFirstLaunchSettingsText

func DefaultFirstLaunchSettingsText() FirstLaunchSettingsText

DefaultFirstLaunchSettingsText returns the English first-launch copy.

type Flow

type Flow struct {
	Children       []Widget
	Direction      ScrollDirection
	Spacing        float32
	LineSpacing    float32
	Justify        Justify
	Align          Align
	Padding        core.Edges
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	Background     core.Color
	Border         core.Color
	CornerRadius   float32
	Transform      Transform
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Flow arranges visible Children sequentially along Direction (Horizontal wraps into rows; Vertical wraps into columns), breaking onto a new line whenever the next child would exceed the available main-axis space.

func (*Flow) Bounds

func (f *Flow) Bounds() core.Bounds

Bounds returns the flow container's laid-out rectangle.

func (*Flow) ChildWidgets

func (f *Flow) ChildWidgets() []Widget

ChildWidgets returns the flow container's direct children.

type FocusManager

type FocusManager = SpatialNavigator

FocusManager is an alias for SpatialNavigator.

type FocusRingStyle

type FocusRingStyle struct {
	// Color overrides Theme.FocusedBorder when non-zero. Set core.Transparent to disable the default stroke.
	Color core.Color
	// Width overrides Theme.FocusWidth when > 0.
	Width float32
	// Outset expands the ring outward from the widget bounds by Outset points (negative insets it).
	Outset float32
	// CornerRadius overrides the corner radius (0 uses widget/theme default; < 0 uses square corners).
	CornerRadius float32
	// Dash sets an optional line dash pattern for the focus ring stroke.
	Dash []float32
	// Draw replaces the default stroke when non-nil, running inside Save/Restore.
	Draw func(d *core.Drawing, bounds core.Bounds, theme *Theme)
}

FocusRingStyle customizes the focus indicator drawn around the currently focused widget.

type Focusable

type Focusable interface {
	Focusable() bool
}

Focusable optionally controls whether a CustomWidget can receive keyboard/gamepad focus. Implementations that do not satisfy Focusable are focusable by default when Custom.Impl is non-nil and neither Hidden nor Disabled.

type FrameDrawer

type FrameDrawer func(d *core.Drawing, bounds core.Bounds, state WidgetState)

FrameDrawer draws a stylized background frame (such as a nine-slice sprite or custom skin) for a widget in its current interaction state.

func NineSliceStateFrame

func NineSliceStateFrame(normal, hover, pressed, disabled *NineSlice) FrameDrawer

NineSliceStateFrame returns a state-aware FrameDrawer that selects the matching NineSlice for Disabled, Pressed, Hovered, or Normal state, falling back to normal when a state slice is nil.

type Grid

type Grid struct {
	Children       []Widget
	Columns        int
	Spacing        float32
	HSpacing       float32
	VSpacing       float32
	Padding        core.Edges
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Background     core.Color
	Border         core.Color
	CornerRadius   float32
	Transform      Transform
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Grid arranges visible Children into a fixed-column, row-major grid. When no visible child sets Flex > 0, all cells share equal widths and heights (matching GridRects); when any visible child sets Flex > 0, columns and rows with Flex distribute remaining space proportionally.

func (*Grid) Bounds

func (g *Grid) Bounds() core.Bounds

Bounds returns the grid's laid-out rectangle.

func (*Grid) ChildWidgets

func (g *Grid) ChildWidgets() []Widget

ChildWidgets returns the grid's direct children.

type HBox

type HBox struct {
	Children       []Widget
	Spacing        float32
	Padding        core.Edges
	Align          Align
	Justify        Justify
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

HBox arranges Children horizontally from left to right with Spacing and Padding.

func (*HBox) Bounds

func (b *HBox) Bounds() core.Bounds

Bounds returns the HBox's laid-out rectangle.

func (*HBox) ChildWidgets

func (b *HBox) ChildWidgets() []Widget

ChildWidgets returns the HBox's direct children.

type HealthAdvisoryConfig

type HealthAdvisoryConfig struct {
	// Title overrides ChinaHealthAdvisoryTitle when non-empty.
	Title string
	// Body overrides ChinaHealthAdvisoryText when non-empty.
	Body string
	// AgeRating selects the built-in CADPA age badge (8+, 12+, 16+, or 18+). Empty omits the built-in badge unless AgeBadgeSlot is supplied.
	AgeRating CADPAAgeRating
	// AgeBadgeLabel overrides the default "适龄提示 <AgeRating>" label shown inside the built-in badge.
	AgeBadgeLabel string
	// AgeBadgeSlot, when non-nil, renders a custom age-appropriateness badge node instead of the default pill badge.
	AgeBadgeSlot func(*core.Scope) core.Node
	// Disclosure holds optional NPPA approval, ISBN, publisher, copyright holder, and filing numbers.
	Disclosure HealthAdvisoryDisclosure
	// ContinueLabel overrides the default "进入游戏" continue button label.
	ContinueLabel string
	// MinDuration is the optional minimum time before Dismiss via the Continue button is accepted; 0 allows immediate dismissal.
	MinDuration time.Duration
	// OnDismiss runs once when the screen is dismissed.
	OnDismiss func()
}

HealthAdvisoryConfig configures a mainland China HealthAdvisoryScreen splash overlay.

type HealthAdvisoryDisclosure

type HealthAdvisoryDisclosure struct {
	// ApprovalNumber is the NPPA publishing approval number (文号 / 版号).
	ApprovalNumber string
	// ISBN is the game's ISBN number.
	ISBN string
	// Publisher is the licensed publishing unit (出版单位).
	Publisher string
	// CopyrightHolder is the software copyright holder (著作权人).
	CopyrightHolder string
	// FilingNumber is the MIIT APP or ICP filing number (备案号).
	FilingNumber string
}

HealthAdvisoryDisclosure holds optional publishing and regulatory filing metadata shown at the bottom of the mainland China splash screen.

func (HealthAdvisoryDisclosure) Lines

func (d HealthAdvisoryDisclosure) Lines() []string

Lines returns the non-empty formatted disclosure lines in deterministic order.

type HealthAdvisoryScreen

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

HealthAdvisoryScreen is a reusable mainland China start/splash overlay that renders the NPPA "健康游戏忠告" text, an optional CADPA age-appropriateness badge (or custom AgeBadgeSlot), and publishing disclosures.

func NewHealthAdvisoryScreen

func NewHealthAdvisoryScreen(cfg HealthAdvisoryConfig) *HealthAdvisoryScreen

NewHealthAdvisoryScreen creates a HealthAdvisoryScreen using cfg and standard Chinese defaults for any empty copy fields.

func (*HealthAdvisoryScreen) Advance

func (s *HealthAdvisoryScreen) Advance(dt time.Duration)

Advance advances the screen's display timer by dt (ignored when dt <= 0).

func (*HealthAdvisoryScreen) Dismiss

func (s *HealthAdvisoryScreen) Dismiss()

Dismiss hides the health advisory screen and calls OnDismiss once. If MinDuration has not yet elapsed, Dismiss is a no-op; use Advance first or set MinDuration to 0.

func (*HealthAdvisoryScreen) Ready

func (s *HealthAdvisoryScreen) Ready() bool

Ready reports whether the optional MinDuration has elapsed so the player can dismiss the screen.

func (*HealthAdvisoryScreen) View

func (s *HealthAdvisoryScreen) View(cx *core.Scope) core.Node

View renders the health advisory splash as a full-screen native NSGo overlay. Mount it on the start screen; it unmounts once Dismiss runs.

func (*HealthAdvisoryScreen) Visible

func (s *HealthAdvisoryScreen) Visible() bool

Visible reports whether the health advisory overlay has not been dismissed yet.

type HitTester

type HitTester interface {
	HitTest(p core.Point) bool
}

HitTester optionally refines hit testing for non-rectangular custom widgets. p is in local widget coordinates relative to Custom.Bounds().Origin for points inside Custom.Bounds().

type Image

type Image struct {
	SpritePath  string
	SpriteFrame string
	Image       core.ImageSource
	Src         core.Bounds
	HasImage    bool
	Scale       ImageScale
	Insets      NineSliceInsets
	TileCenter  bool
	Color       core.Color
	Width       float32
	Height      float32
	MinWidth    float32
	MinHeight   float32
	Flex        float32
	Align       Align
	Hidden      bool
	Transform   Transform
	// contains filtered or unexported fields
}

Image displays a sprite image or atlas frame stretched (ImageScaleSimple), nine-sliced (ImageScaleNineSlice), or tiled (ImageScaleTile).

func (*Image) Bounds

func (im *Image) Bounds() core.Bounds

Bounds returns the image's laid-out bounds.

type ImageProgress

type ImageProgress struct {
	Value         float32
	Min           float32
	Max           float32
	Under         *NineSlice
	Progress      *NineSlice
	Over          *NineSlice
	Fill          FillMode
	StartAngle    float32 // degrees, 0 = right, positive clockwise; radial fills only
	Span          float32 // degrees, 0 defaults to 360; radial fills only
	FillColor     core.Color
	TrackColor    core.Color
	Width         float32
	Height        float32
	MinWidth      float32
	MinHeight     float32
	Flex          float32
	Align         Align
	Hidden        bool
	Transform     Transform
	OnContextMenu func(core.Point)
	// contains filtered or unexported fields
}

ImageProgress displays a read-only progress meter in [Min, Max] (or [0, 1] when both Min and Max are 0) built from up to three layered images: Under drawn in full first, Progress revealed by the value along Fill, and Over drawn in full last (such as an ornate frame over a boss bar).

Each layer is a NineSlice: a plain image when its insets are zero, or a nine-patch that keeps its cap sizes when the widget is wider or taller than the source. Linear fills clip the progress layer to the revealed rectangle, so a nine-slice progress image keeps its caps at any value; radial fills (FillClockwise and FillCounterClockwise) clip it to a pie from StartAngle degrees (0 points right, positive is clockwise) sweeping Span degrees (0 defaults to 360). When a layer is nil the widget falls back to a flat fill: TrackColor (or Theme.Track) for Under and FillColor (or Theme.Accent) for Progress.

func (*ImageProgress) Bounds

func (p *ImageProgress) Bounds() core.Bounds

Bounds returns the image progress's laid-out rectangle.

func (*ImageProgress) Fraction

func (p *ImageProgress) Fraction() float32

Fraction returns Value normalized into [0, 1].

type ImageScale

type ImageScale string

ImageScale selects how an image screen node fills its laid-out bounds.

const (
	// ImageScaleSimple stretches the image or frame to fill the node's bounds (the default when omitted).
	ImageScaleSimple ImageScale = "simple"
	// ImageScaleNineSlice keeps corners unscaled using the frame's nine-slice insets and stretches edges and center.
	ImageScaleNineSlice ImageScale = "nine_slice"
	// ImageScaleTile repeats the image or frame at its natural size across the node's bounds, clipping the final row and column.
	ImageScaleTile ImageScale = "tile"
)

type Justify

type Justify uint8

Justify controls main-axis distribution in VBox and HBox when extra space remains and no child has Flex > 0.

const (
	// JustifyStart packs children at the start of the main axis.
	JustifyStart Justify = iota
	// JustifyCenter centers children as a group along the main axis.
	JustifyCenter
	// JustifyEnd packs children at the end of the main axis.
	JustifyEnd
	// JustifySpaceBetween spreads remaining space evenly between adjacent children.
	JustifySpaceBetween
)

func ParseJustify

func ParseJustify(s string) (Justify, bool)

ParseJustify maps a screen-file justify name ("start", "center", "end", or "space_between") to Justify.

func (Justify) String

func (j Justify) String() string

String returns the screen-file name of j ("start", "center", "end", or "space_between").

type KeyboardKind

type KeyboardKind uint8

KeyboardKind hints at the native keyboard requested by a text field.

const (
	// KeyboardText requests the platform's default text keyboard.
	KeyboardText KeyboardKind = iota
	// KeyboardNumber requests a numeric keypad.
	KeyboardNumber
	// KeyboardEmail requests a keyboard laid out for email addresses.
	KeyboardEmail
	// KeyboardURL requests a keyboard laid out for URLs.
	KeyboardURL
	// KeyboardASCII requests a keyboard limited to ASCII characters.
	KeyboardASCII
)

func ParseKeyboardKind

func ParseKeyboardKind(s string) (KeyboardKind, bool)

ParseKeyboardKind parses a screen-file keyboard hint ("text", "number", "email", "url", or "ascii").

func (KeyboardKind) String

func (k KeyboardKind) String() string

String returns the canonical YAML and display name of k.

type Label

type Label struct {
	Text string
	// Variation names a Theme.Styles entry that styles this label in place of the theme's label style.
	Variation    string
	Color        core.Color
	Background   core.Color
	CornerRadius float32
	Padding      core.Edges
	Font         core.Font
	Effects      text.TextEffects
	TextAlign    core.TextAlign
	// Wrap selects multi-line wrapping inside the label's inner width (WrapDefault and WrapNone keep a single line).
	Wrap text.Wrap
	// Overrun selects how text exceeding the label's inner width or MaxLines is clipped or ellipsized.
	Overrun text.Overrun
	// MaxLines caps the number of visible lines when > 0 (0 means unlimited when wrapping).
	MaxLines       int
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Label displays non-interactive text. Focus navigation skips labels automatically.

func (*Label) Bounds

func (l *Label) Bounds() core.Bounds

Bounds returns the label's laid-out rectangle.

type Layer

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

Layer is a handle to a single UI layer inside a Layers stack.

func (*Layer) Close

func (layer *Layer) Close() bool

Close pops this layer from its Layers stack (or begins its CloseClip if configured). Base layers cannot be closed. Calling Close on an already closing or closed layer is a no-op.

func (*Layer) Closed

func (layer *Layer) Closed() bool

Closed reports whether this layer has been removed from its Layers stack.

func (*Layer) Closing

func (layer *Layer) Closing() bool

Closing reports whether this layer is currently playing its CloseClip before removal.

func (*Layer) IsBase

func (layer *Layer) IsBase() bool

IsBase reports whether this layer is the base layer passed to NewLayers.

func (*Layer) MenuBounds

func (layer *Layer) MenuBounds() core.Bounds

MenuBounds returns the laid-out bounds of the root popup panel when this layer was opened with Layers.OpenMenu.

func (*Layer) MenuDepth

func (layer *Layer) MenuDepth() int

MenuDepth returns the number of currently open menu panels on this layer (1 for root popup, 2+ when submenus are open, 0 if not a menu layer).

func (*Layer) MenuItemBounds

func (layer *Layer) MenuItemBounds(index int) core.Bounds

MenuItemBounds returns the laid-out rectangle of item index in the active (topmost) menu panel, or zero Bounds if out of range.

func (*Layer) MenuSelectedIndex

func (layer *Layer) MenuSelectedIndex() int

MenuSelectedIndex returns the currently highlighted item index in the active popup menu panel, or -1 if none.

func (*Layer) MenuSheet

func (layer *Layer) MenuSheet() bool

MenuSheet reports whether this popup menu layer is placed as a bottom sheet.

func (*Layer) Navigator

func (layer *Layer) Navigator() *SpatialNavigator

Navigator returns the SpatialNavigator attached to this layer.

func (*Layer) Options

func (layer *Layer) Options() LayerOptions

Options returns a copy of the LayerOptions this layer was pushed with.

func (*Layer) Root

func (layer *Layer) Root() *Root

Root returns the gameui.Root drawn and interacted with by this layer.

func (*Layer) SubmenuBounds

func (layer *Layer) SubmenuBounds() core.Bounds

SubmenuBounds returns the laid-out bounds of the active submenu panel when a submenu is open on this layer.

type LayerClip

type LayerClip interface {
	Restart()
	Update(dt time.Duration)
	Done() bool
}

LayerClip is a playable animation clip used for optional layer open and close transitions. Both *animclip.Player and *tween.Timeline implement LayerClip.

type LayerOptions

type LayerOptions struct {
	// Modal blocks pointer, touch, keyboard, gamepad, and navigation input from reaching layers below this one.
	Modal bool
	// Dim fills the full draw bounds behind this layer before drawing its Root (for example core.RGBA(0x000000, 0.5)).
	// Zero or core.Transparent disables dimming.
	Dim core.Color
	// CloseOnBack pops this layer when NavBack, Escape, Back, or gamepad East is pressed while it is active.
	CloseOnBack bool
	// CloseOnTapOutside pops this layer when a pointer or touch press lands outside its content bounds.
	CloseOnTapOutside bool
	// OnClose is invoked once after the layer finishes closing (immediately when CloseClip is nil).
	OnClose func()
	// Navigator optionally supplies an existing SpatialNavigator for this layer.
	// When nil, Push creates a new SpatialNavigator attached to the layer's Root.
	Navigator *SpatialNavigator
	// InitialFocus optionally focuses a specific widget when this layer is pushed.
	InitialFocus Widget
	// ContentBounds optionally overrides the window-coordinate rectangle treated as inside the layer
	// for CloseOnTapOutside. When nil, Layers checks the visible widgets of the layer's Root.
	ContentBounds func() core.Bounds
	// OpenClip optionally plays when the layer is pushed. Nil opens immediately.
	OpenClip LayerClip
	// CloseClip optionally plays when the layer closes; the layer stays visible until CloseClip.Done()
	// returns true during Update. Nil closes immediately.
	CloseClip LayerClip
}

LayerOptions configures a layer pushed onto a Layers stack.

type Layers

type Layers struct {
	// LongPressDuration configures how long a stationary touch must be held in OnTouch + Update
	// before raising OnContextMenu. Zero uses DefaultLongPressDuration (500ms).
	LongPressDuration time.Duration
	// contains filtered or unexported fields
}

Layers manages a stack of gameui.Root layers drawn bottom-to-top with modal input blocking, optional dimming, tap-outside and Back dismissal, per-layer SpatialNavigator instances, and automatic focus save and restore across push and pop.

Example

Layers stacks modal dialogs and non-modal overlays over a base UI root, blocking input under modals and restoring focus on pop.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	playBtn := &gameui.Button{Text: "Play", Height: 36}
	quitBtn := &gameui.Button{Text: "Quit", Height: 36}
	menuRoot := gameui.NewRoot(&gameui.VBox{Spacing: 8, Children: []gameui.Widget{playBtn, quitBtn}})

	cancelBtn := &gameui.Button{Text: "Cancel", Height: 36}
	confirmRoot := gameui.NewRoot(&gameui.Panel{
		Background: core.Transparent,
		Border:     core.Transparent,
		Align:      gameui.AlignCenter,
		Child:      &gameui.Panel{Width: 240, Height: 120, Child: cancelBtn},
	})

	layers := gameui.NewLayers(menuRoot)
	layers.Layout(core.Bounds{Size: core.Size{Width: 640, Height: 360}})
	menuRoot.SetFocus(quitBtn)

	dlg := layers.Push(confirmRoot, gameui.LayerOptions{
		Modal:       true,
		Dim:         core.RGBA(0x000000, 0.5),
		CloseOnBack: true,
		OnClose:     func() { fmt.Println("dialog closed") },
	})
	fmt.Println("depth:", layers.Len(), "menu focused:", menuRoot.Focused() == nil, "dialog focused:", dlg.Root().Focused() == cancelBtn)

	layers.HandleAction(gameui.NavBack)
	fmt.Println("depth:", layers.Len(), "restored:", menuRoot.Focused() == quitBtn)
}
Output:
depth: 2 menu focused: true dialog focused: true
dialog closed
depth: 1 restored: true

func NewLayers

func NewLayers(base *Root) *Layers

NewLayers creates a layer stack with base as its bottom non-closable base layer. Passing nil starts an empty stack.

func (*Layers) Active

func (l *Layers) Active() *Layer

Active returns the layer that currently receives keyboard, gamepad, and navigation input, or nil if the stack is empty. When a modal layer is present, Active returns the topmost modal layer unless an open popup menu sits above it.

func (*Layers) Base

func (l *Layers) Base() *Layer

Base returns the base layer passed to NewLayers, or nil if created with nil.

func (*Layers) Draw

func (l *Layers) Draw(d *core.Drawing, bounds core.Bounds)

Draw lays out and draws every layer in the stack from bottom to top, rendering each layer's optional Dim backdrop immediately before its Root. Caller drawing state is preserved.

func (*Layers) DrawFocusRing

func (l *Layers) DrawFocusRing(d *core.Drawing)

DrawFocusRing draws the active layer's SpatialNavigator focus ring into d.

func (*Layers) HandleAction

func (l *Layers) HandleAction(action NavAction) bool

HandleAction dispatches a logical NavAction to the active layer. NavBack closes the top layer when CloseOnBack is set; modal layers block navigation from reaching layers below.

func (*Layers) HasModal

func (l *Layers) HasModal() bool

HasModal reports whether any layer currently in the stack is modal.

func (*Layers) Layers

func (l *Layers) Layers() []*Layer

Layers returns a bottom-to-top snapshot of all layers currently in the stack.

func (*Layers) Layout

func (l *Layers) Layout(bounds core.Bounds)

Layout lays out every layer in the stack into bounds from bottom to top.

func (*Layers) Len

func (l *Layers) Len() int

Len returns the number of layers currently in the stack, including the base layer when present.

func (*Layers) OnContextMenu

func (l *Layers) OnContextMenu(p core.Point) bool

OnContextMenu dispatches a context menu request (such as a desktop right-click or touch long-press) at window point p top-to-bottom through the layer stack, stopping at the topmost non-menu modal layer. Right-clicking outside an open popup menu closes that popup first so the click can immediately open a new context menu on the layer underneath.

func (*Layers) OnGamepadButton

func (l *Layers) OnGamepadButton(btn gamepad.Button) bool

OnGamepadButton processes a single rising-edge gamepad button press on the active layer. When the active layer is a SettingsMenu, LB/RB switch tabs and capture mode binds any button.

func (*Layers) OnKeyDown

func (l *Layers) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown routes keyboard navigation, confirmation, and Escape/Back dismissal to the active layer. When a modal layer is present, keys never reach layers underneath and OnKeyDown returns true.

func (*Layers) OnMouseDown

func (l *Layers) OnMouseDown(ev core.MouseButtonEvent) bool

OnMouseDown routes a mouse button press: right-click to OnContextMenu and left-click to OnPointerDown.

func (*Layers) OnMouseUp

func (l *Layers) OnMouseUp(ev core.MouseButtonEvent) bool

OnMouseUp routes a primary mouse button release to OnPointerUp.

func (*Layers) OnPointerDown

func (l *Layers) OnPointerDown(p core.Point) bool

OnPointerDown routes a pointer press start from top to bottom, stopping at the topmost modal layer. If the press lands outside a layer with CloseOnTapOutside set, that layer is closed. Returns true if an interactive widget was hit or a modal layer blocked the press.

func (*Layers) OnPointerMove

func (l *Layers) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state and drags any active slider, stopping at the topmost modal layer. Returns true if the pointer hit an interactive widget, dragged a slider, or was blocked by a modal layer.

func (*Layers) OnPointerUp

func (l *Layers) OnPointerUp(p core.Point) bool

OnPointerUp finishes any active press or slider drag, stopping at the topmost modal layer. Returns true if a press/drag was handled or blocked by a modal layer.

func (*Layers) OnPress

func (l *Layers) OnPress(ev core.PressEvent) bool

OnPress routes a core.Canvas PressEvent to the active layer (for keyboard presses) or top-to-bottom (for pointer/touch presses), respecting Modal blocking and CloseOnTapOutside.

func (*Layers) OnTouch

func (l *Layers) OnTouch(ev core.TouchEvent) bool

OnTouch routes touch start, move, end, and cancel events through the layer stack and detects stationary long-presses (via Update(dt) or advancing TouchEvent.Time) to raise OnContextMenu.

func (*Layers) OnWheel

func (l *Layers) OnWheel(ev core.WheelEvent) bool

OnWheel routes a mouse wheel or touchpad scroll event from top to bottom, stopping at the topmost modal layer. Returns true if a ScrollList consumed the event or a modal layer blocked it.

func (*Layers) OpenMenu

func (l *Layers) OpenMenu(menu Menu, opts MenuOptions, onSelect func(id string)) *Layer

OpenMenu opens a popup or context menu on the layer stack, anchored or displayed as a bottom sheet according to opts. Focus moves into the menu and returns to the previously focused widget on close; Up/Down move across enabled items, Right opens submenus, Left and Back close submenus or the menu, Confirm selects, and printable keys type-ahead by first letter. Returns the pushed Layer handle.

func (*Layers) Pop

func (l *Layers) Pop() *Layer

Pop closes the topmost non-base layer and returns it, or nil if no closable layer is open. If the topmost non-base layer is already playing its CloseClip, Pop returns nil without disturbing layers underneath.

func (*Layers) PopAll

func (l *Layers) PopAll() int

PopAll closes every non-base layer from top to bottom and returns how many layers began closing or closed.

func (*Layers) Push

func (l *Layers) Push(root *Root, opts LayerOptions) *Layer

Push adds root on top of the stack configured by opts and returns its Layer handle. Pushing a modal layer saves and clears focus on the previously active layer so popping restores it. Returns nil when l or root is nil.

func (*Layers) PushScreen

func (l *Layers) PushScreen(built *BuiltScreen, opts LayerOptions) *Layer

PushScreen pushes a built *.screen.yaml screen directly onto the stack, reusing built.Navigator (and its explicit focus-order overrides) unless opts.Navigator overrides it. Returns nil when l, built, or built.Root is nil.

func (*Layers) PushSettings

func (l *Layers) PushSettings(menu *SettingsMenu, opts LayerOptions) *Layer

PushSettings pushes a SettingsMenu as a layer without modifying its API, delegating tab switching, control-rebinding capture, cycle options, and full-screen synchronization to menu while participating in modal input blocking, dimming, tap-outside dismissal, and focus save/restore. Returns nil when l, menu, or menu.Root() is nil.

func (*Layers) StepActions

func (l *Layers) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions using pressed (for example wrapping input.Actions.JustPressed) and dispatches triggered actions in deterministic order to the active layer. If an action pushes or pops a layer, remaining actions in the same tick are skipped so input does not leak into the newly active layer.

func (*Layers) StepGamepad

func (l *Layers) StepGamepad(pads []gamepad.Pad) bool

StepGamepad polls connected gamepads once per frame, driving navigation, confirmation, Back dismissal, and SettingsMenu tab switching / control capture on button and left-stick rising edges.

func (*Layers) SyncGamepad

func (l *Layers) SyncGamepad(pads []gamepad.Pad)

SyncGamepad records the currently held gamepad buttons and left-stick position as the baseline without triggering any actions, so buttons held when opening a layer do not fire immediately.

func (*Layers) Top

func (l *Layers) Top() *Layer

Top returns the topmost layer in the stack (including a layer currently playing its CloseClip), or nil when empty.

func (*Layers) Update

func (l *Layers) Update(dt time.Duration) bool

Update advances any playing OpenClip or CloseClip animations and steps one-switch scanning on the active layer's SpatialNavigator. Returns true if any animation finished or focus moved.

type LevelSelect

type LevelSelect struct {
	// Items lists the levels to display in order.
	Items []LevelSelectItem
	// Direction selects Vertical (default) or Horizontal scrolling.
	Direction ScrollDirection
	// Columns is the number of items per row (in Vertical mode) or rows per column (in Horizontal mode); <= 0 defaults to 1.
	Columns int
	// ItemWidth and ItemHeight set each tile's size in virtual points (<= 0 uses defaults).
	ItemWidth  float32
	ItemHeight float32
	// Spacing is the gap between adjacent tiles in virtual points (0 uses a 12pt default; < 0 uses 0).
	Spacing float32
	// Padding insets the scrollable viewport inside LevelSelect's bounds.
	Padding core.Edges
	// Overscan is the number of extra lines kept materialized outside the viewport.
	Overscan int
	// Selected is the currently selected item index (-1 for none).
	Selected int
	// Disabled prevents scrolling and item activation.
	Disabled bool

	// LockedText, CurrentText, and DoneText override the status badges shown on locked, current, and done tiles.
	LockedText  string
	CurrentText string
	DoneText    string

	// Optional visual overrides; zero values use built-in high-contrast defaults.
	LockedColor    core.Color
	CurrentBorder  core.Color
	DoneBorder     core.Color
	StarColor      core.Color
	EmptyStarColor core.Color

	// OnSelect is called when an unlocked (LevelCurrent or LevelDone) item is tapped or activated.
	// Locked items never invoke OnSelect.
	OnSelect func(item LevelSelectItem, index int)

	// NewItem and BindItem optionally replace the built-in tile template while keeping ScrollList virtualization.
	NewItem  func() Widget
	BindItem func(w Widget, item LevelSelectItem, index int)

	FocusOrder     int
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	Background     core.Color
	Border         core.Color
	CornerRadius   float32
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

LevelSelect is a virtualized level-select grid or scrolling map built on ScrollList. Each item displays a locked, current, or done state along with earned stars, and JumpToCurrent scrolls directly to the next unplayed unlocked level.

func (*LevelSelect) ActiveCount

func (l *LevelSelect) ActiveCount() int

ActiveCount returns the number of currently materialized tile widgets.

func (*LevelSelect) Bounds

func (l *LevelSelect) Bounds() core.Bounds

Bounds returns the widget's laid-out rectangle.

func (*LevelSelect) ChildWidgets

func (l *LevelSelect) ChildWidgets() []Widget

ChildWidgets returns the underlying virtualized ScrollList.

func (*LevelSelect) CurrentIndex

func (l *LevelSelect) CurrentIndex() int

CurrentIndex returns the index of the first LevelCurrent item, or -1 if none exists.

func (*LevelSelect) ItemBounds

func (l *LevelSelect) ItemBounds(index int) core.Bounds

ItemBounds returns the laid-out bounds of item index.

func (*LevelSelect) JumpToCurrent

func (l *LevelSelect) JumpToCurrent(align ...ScrollAlign) bool

JumpToCurrent scrolls to the first LevelCurrent item (next unplayed unlocked level) and returns whether one existed. Optional align overrides ScrollNearest.

func (*LevelSelect) PoolCount

func (l *LevelSelect) PoolCount() int

PoolCount returns the number of idle recycled tile widgets in the pool.

func (*LevelSelect) Refresh

func (l *LevelSelect) Refresh()

Refresh rebinds all materialized item tiles after Items or state changes.

func (*LevelSelect) ScrollList

func (l *LevelSelect) ScrollList() *ScrollList

ScrollList returns the underlying virtualized ScrollList widget.

func (*LevelSelect) ScrollTo

func (l *LevelSelect) ScrollTo(index int, align ScrollAlign)

ScrollTo scrolls to item index with align.

func (*LevelSelect) Select

func (l *LevelSelect) Select(index int) bool

Select activates item index if it is unlocked, returning true if OnSelect was eligible and triggered.

func (*LevelSelect) SetItems

func (l *LevelSelect) SetItems(items []LevelSelectItem)

SetItems replaces the displayed level items and refreshes the virtualized list.

func (*LevelSelect) SetPack

SetPack populates Items from packID in m using progress, ctx, and locale, returning false if packID does not exist.

func (*LevelSelect) VisibleRange

func (l *LevelSelect) VisibleRange() (first, last int)

VisibleRange returns the inclusive range of logical item indices currently overlapping the viewport.

type LevelSelectItem

type LevelSelectItem struct {
	// ID is the stable level ID.
	ID string
	// Number is the short label shown prominently on the tile (defaults to 1-based index when empty).
	Number string
	// Title is the display name shown beneath Number.
	Title string
	// State is LevelLocked, LevelCurrent, or LevelDone.
	State LevelState
	// Stars is the number of stars earned (0..MaxStars).
	Stars int
	// MaxStars is the maximum stars for the level (<= 0 defaults to 3).
	MaxStars int
	// BestText optionally displays the player's best metric result (such as "3 moves" or "4,500").
	BestText string
}

LevelSelectItem describes one entry rendered by LevelSelect.

func LevelSelectItems

func LevelSelectItems(m progression.Manifest, packID string, p progression.Progress, ctx progression.UnlockContext, locale string) []LevelSelectItem

LevelSelectItems builds LevelSelectItem entries for packID in m using progress, ctx, and locale. It marks locked levels as LevelLocked, completed levels (Stars > 0) as LevelDone, and unlocked unplayed levels as LevelCurrent.

type LevelState

type LevelState uint8

LevelState represents the player-facing progression state of an item in LevelSelect.

const (
	// LevelLocked marks a level whose unlock requirements are not yet satisfied.
	LevelLocked LevelState = iota
	// LevelCurrent marks an unlocked level that has not yet been completed (the next playable target).
	LevelCurrent
	// LevelDone marks a completed level with earned stars.
	LevelDone
)

func (LevelState) String

func (s LevelState) String() string

String returns "locked", "current", or "done".

type List

type List struct {
	Items          []string
	Selected       int
	ItemHeight     float32
	Spacing        float32
	OnSelect       func(index int, item string)
	Disabled       bool
	Font           core.Font
	Effects        text.TextEffects
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

List is a focusable vertical list of selectable string items supporting pointer and keyboard/gamepad selection. List fits all rows inside its bounds without scrolling; for long lists, grids, carousels, or custom row widgets, use ScrollList.

func (*List) Bounds

func (l *List) Bounds() core.Bounds

Bounds returns the list's laid-out rectangle.

func (*List) ItemAt

func (l *List) ItemAt(p core.Point) int

ItemAt returns the 0-based index of the item containing p, or -1 if none.

func (*List) ItemBounds

func (l *List) ItemBounds(index int) core.Bounds

ItemBounds returns the laid-out rectangle for item at index, or zero Bounds if out of range.

func (*List) Select

func (l *List) Select(index int) bool

Select updates Selected to index (clamped into [0, len(Items)-1]) and invokes OnSelect. Returns false when the list is disabled or empty.

type MeasureContext

type MeasureContext struct {
	// Theme is the active game UI theme.
	Theme *Theme
}

MeasureContext describes theme information available while measuring a custom widget.

type Menu struct {
	Items []MenuItem
	// Translate optionally resolves MenuItem.TextKey into display text.
	// When nil (or when Translate returns ""), MenuItem.Text is used, falling back to TextKey then ID.
	Translate func(key string) string
}

Menu is a deterministic ordered popup menu model.

func (m Menu) DisplayText(index int) string

DisplayText returns the resolved user-visible label for item index, or "" if out of range.

func (m Menu) IndexByID(id string) int

IndexByID returns the index of the first item matching id, or -1 if not found.

func (m Menu) NextEnabled(index, step int) int

NextEnabled returns the next item Selectable accepts, moving one item forward for a positive step and one back for a negative one, wrapping around and skipping separators, disabled items and items without an ID. It returns -1 when no item is selectable. An index outside the items, such as -1 for no selection, starts from the matching end.

func (m Menu) Selectable(index int) bool

Selectable reports whether index can be activated or opened as a submenu.

func (m Menu) TypeAhead(from int, ch rune) int

TypeAhead finds the next selectable item after from (wrapping around) whose displayed text starts with ch (case-insensitive), or -1 if no selectable item matches.

type MenuButton struct {
	Text       string
	Icon       core.ImageSource
	IconSrc    core.Bounds
	Menu       Menu
	OnSelect   func(id string)
	Placement  MenuPositionMode
	SafeArea   core.Bounds
	SafeInsets core.Edges
	// Layers optionally specifies the Layers stack to open the popup on.
	// When nil, MenuButton automatically uses the Layers stack owning its Root (or a Root-local popup fallback).
	Layers *Layers

	Disabled       bool
	Font           core.Font
	Effects        text.TextEffects
	TextColor      core.Color
	Background     core.Color
	CornerRadius   float32
	Padding        core.Edges
	FocusOrder     int
	TouchHitSize   float32
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

MenuButton is a focusable button that opens an attached popup Menu when activated.

func (mb *MenuButton) Bounds() core.Bounds

Bounds returns the menu button's laid-out rectangle.

func (mb *MenuButton) Close() bool

Close closes the menu button's popup if currently open.

func (mb *MenuButton) HitBounds() core.Bounds

HitBounds returns the menu button's interactive hit area, expanded to TouchHitSize when larger than Bounds.

func (mb *MenuButton) IsOpen() bool

IsOpen reports whether the menu button's popup is currently open.

func (mb *MenuButton) Open() *Layer

Open opens mb.Menu on its Layers stack (or standalone Root) and returns the Layer handle when opened on Layers.

type MenuCheck uint8

MenuCheck picks the check indicator drawn beside a MenuItem.

const (
	// CheckNone draws no checkbox or radio outline (a subtle checkmark is still drawn if Checked is true).
	CheckNone MenuCheck = iota
	// CheckBox draws a square checkbox indicator reflecting MenuItem.Checked.
	CheckBox
	// CheckRadio draws a circular radio indicator reflecting MenuItem.Checked.
	CheckRadio
)
type MenuItem struct {
	ID        string
	Text      string
	TextKey   string
	Icon      core.ImageSource
	IconSrc   core.Bounds
	Check     MenuCheck
	Disabled  bool
	Separator bool
	Checked   bool
	Submenu   *Menu
}

MenuItem is an actionable, checkable, submenu, or separator row in a dropdown or popup menu.

type MenuOptions struct {
	// Anchor is the owner rectangle (in window/canvas coordinates) that the popup opens next to.
	Anchor core.Bounds
	// Mode selects anchored placement (default) or bottom-edge sheet placement (MenuSheetPosition).
	Mode MenuPositionMode
	// SafeArea optionally constrains popup placement inside the layer bounds. Zero uses the full layer bounds (minus SafeInsets).
	SafeArea core.Bounds
	// SafeInsets optionally insets the layer bounds when SafeArea is zero (for example notch or title-bar margins).
	SafeInsets core.Edges
	// Modal blocks pointer, touch, keyboard, and gamepad input from reaching layers below while open.
	// MenuAt, MenuAtPoint, and MenuSheet set Modal to true; set Modal to false for a non-blocking popup layer.
	Modal bool
	// Dim optionally fills a backdrop color behind the popup (MenuSheet defaults to a translucent dim).
	Dim core.Color
	// Theme optionally overrides the popup menu theme; nil inherits from the active layer or DefaultTheme.
	Theme *Theme
	// Translate optionally resolves MenuItem.TextKey when Menu.Translate is nil.
	Translate func(key string) string
	// InitialSelected optionally pre-highlights an item index when the menu opens (negative or unselectable focuses the first selectable item).
	InitialSelected int
	// MinWidth enforces a minimum popup width in points (for example matching a Dropdown's width).
	MinWidth float32
	// OnClose is invoked once when the popup closes.
	OnClose func()
	// OpenClip and CloseClip optionally animate opening and closing the popup layer.
	OpenClip  LayerClip
	CloseClip LayerClip
}

MenuOptions configures how Layers.OpenMenu positions, styles, and dismisses a popup or context menu.

func MenuAt(owner core.Bounds) MenuOptions

MenuAt returns modal MenuOptions anchored to owner bounds (placed below, flipping above or shifting to stay inside the safe area).

func MenuAtPoint(p core.Point) MenuOptions

MenuAtPoint returns modal MenuOptions anchored at a single point (such as a mouse right-click or touch long-press position).

func MenuSheet() MenuOptions

MenuSheet returns modal MenuOptions that open from the bottom edge of the safe area, suited for phones.

type MenuPlacement struct {
	Bounds core.Bounds
	Sheet  bool
}

MenuPlacement describes a popup rectangle constrained to a safe area.

func PlaceMenu

func PlaceMenu(owner, safe core.Bounds, width, height core.Points) MenuPlacement

PlaceMenu places a popup below owner, flipping above or clamping inside safe.

func PlaceMenuSheet

func PlaceMenuSheet(safe core.Bounds, height core.Points) MenuPlacement

PlaceMenuSheet places a bottom-edge sheet popup inside safe.

func PlaceSubmenu

func PlaceSubmenu(parentItem, safe core.Bounds, width, height core.Points) MenuPlacement

PlaceSubmenu places a submenu to the right of parentItem, flipping to the left or shifting vertically to stay inside safe.

type MenuPositionMode uint8

MenuPositionMode selects how a popup menu is placed inside the safe area.

const (
	// MenuAnchorPosition places the popup below Anchor, flipping above or clamping inside SafeArea.
	MenuAnchorPosition MenuPositionMode = iota
	// MenuSheetPosition anchors the popup along the bottom edge of SafeArea (suited for phones).
	MenuSheetPosition
)
type NavAction uint8

NavAction identifies a logical UI navigation action from keyboard, gamepad, or virtual controls.

const (
	// NavNone is the zero value representing no action.
	NavNone NavAction = iota
	// NavUp moves focus upward.
	NavUp
	// NavDown moves focus downward.
	NavDown
	// NavLeft moves focus left (or decrements a focused Slider when SliderSteps is enabled).
	NavLeft
	// NavRight moves focus right (or increments a focused Slider when SliderSteps is enabled).
	NavRight
	// NavConfirm activates the currently focused widget and invokes OnConfirm.
	NavConfirm
	// NavBack invokes OnBack (e.g. closing a submenu or canceling an action).
	NavBack
	// NavPrevTab switches to the previous tab in a Tabs container (e.g. gamepad LB).
	NavPrevTab
	// NavNextTab switches to the next tab in a Tabs container (e.g. gamepad RB).
	NavNextTab
)
func (a NavAction) String() string

String returns a human-readable name for a.

type NavHandler interface {
	OnNav(a NavAction) bool
}

NavHandler optionally intercepts logical navigation actions while the custom widget holds focus. Returning true consumes the action inside the widget instead of moving focus or triggering outer handlers.

type NavOverrides struct {
	Up    Widget
	Down  Widget
	Left  Widget
	Right Widget
}

NavOverrides specifies explicit per-widget directional neighbors that take precedence over automatic 2D spatial lookup.

func (o NavOverrides) For(dir NavAction) Widget

For returns the explicit neighbor configured for dir, or nil if unset or non-directional.

type NineSlice

type NineSlice struct {
	Image      core.ImageSource
	Src        core.Bounds
	Left       float32
	Top        float32
	Right      float32
	Bottom     float32
	TileCenter bool
}

NineSlice describes a 9-patch sprite frame with fixed corner margins (Left, Top, Right, Bottom) inside Src of Image. Corners stay unstretched while edges and center scale to fill destination bounds. When TileCenter is true, the center region repeats at its natural size instead of stretching.

func (NineSlice) Draw

func (ns NineSlice) Draw(d *core.Drawing, dst core.Bounds)

Draw renders the 9-patch image stretched into dst. Corner insets clamp proportionally if dst is smaller than Left+Right or Top+Bottom.

func (NineSlice) FrameDrawer

func (ns NineSlice) FrameDrawer() FrameDrawer

FrameDrawer adapts a single NineSlice into a FrameDrawer callback.

type NineSliceInsets

type NineSliceInsets struct {
	Left   float32
	Top    float32
	Right  float32
	Bottom float32
}

NineSliceInsets holds the unscaled corner margins of a nine-slice sprite frame in points. Its fields match sprite.Insets so values from sprite.Atlas.Slices convert directly.

type OSKAction

type OSKAction uint8

OSKAction identifies a direct on-screen keyboard editing command mapped to gamepad buttons.

const (
	// OSKActionNone is the zero value.
	OSKActionNone OSKAction = iota
	// OSKActionBackspace deletes the character before the caret (Gamepad West / X / Square).
	OSKActionBackspace
	// OSKActionSpace inserts a space character (Gamepad North / Y / Triangle).
	OSKActionSpace
	// OSKActionShift toggles uppercase / shifted symbols (Gamepad LB / L1 / L3).
	OSKActionShift
	// OSKActionDone confirms entry and closes the keyboard, restoring focus (Gamepad Start / RB).
	OSKActionDone
	// OSKActionCancel closes the keyboard and restores focus (Gamepad East / B / Circle).
	OSKActionCancel
)

type OSKLayout

type OSKLayout uint8

OSKLayout selects the key arrangement displayed by OnScreenKeyboard.

const (
	// OSKLayoutAuto chooses a layout from the locale and target field's KeyboardKind.
	OSKLayoutAuto OSKLayout = iota
	// OSKLayoutQWERTY displays a standard QWERTY keyboard with a top digit row.
	OSKLayoutQWERTY
	// OSKLayoutAZERTY displays a French AZERTY keyboard with a top digit row.
	OSKLayoutAZERTY
	// OSKLayoutNumeric displays a compact numeric keypad.
	OSKLayoutNumeric
)

func OSKLayoutForLocale

func OSKLayoutForLocale(locale string, kind KeyboardKind) OSKLayout

OSKLayoutForLocale selects the default on-screen keyboard layout for locale and kind. KeyboardNumber always selects OSKLayoutNumeric; French locales ("fr", "fr-FR", "fr-BE", etc.) select OSKLayoutAZERTY; all other locales select OSKLayoutQWERTY.

func (OSKLayout) String

func (l OSKLayout) String() string

String returns the canonical name of l.

type OnScreenKeyboard

type OnScreenKeyboard struct {
	// KeyLayout overrides locale-based layout selection when not OSKLayoutAuto.
	KeyLayout OSKLayout
	// Locale optionally overrides the locale used for OSKLayoutAuto (e.g. "fr-FR").
	Locale string
	// Theme styles the keyboard overlay; nil inherits the owning Root's theme or DefaultTheme.
	Theme *Theme
	// SubmitOnDone invokes Target.Submit() in addition to restoring focus when Done is pressed.
	SubmitOnDone bool
	// OnDone is called with the target's text when the user finishes entry with Done.
	OnDone func(text string)
	// OnCancel is called when the user dismisses the keyboard with Cancel/Back.
	OnCancel func()
	// OnClose is called whenever the keyboard closes (committed == true for Done, false for Cancel).
	OnClose func(committed bool)

	// Root and Navigator drive the modal keyboard UI tree.
	Root      *Root
	Navigator *SpatialNavigator
	// contains filtered or unexported fields
}

OnScreenKeyboard is a modal gameui key grid for entering text into a TextField or TextArea with a gamepad (or pointer/touch) when no hardware keyboard is present.

func NewOnScreenKeyboard

func NewOnScreenKeyboard(layout OSKLayout, theme *Theme) *OnScreenKeyboard

NewOnScreenKeyboard constructs an OnScreenKeyboard with the given preferred layout and optional theme.

func (*OnScreenKeyboard) ActiveLayout

func (k *OnScreenKeyboard) ActiveLayout() OSKLayout

ActiveLayout returns the concrete layout currently displayed (QWERTY, AZERTY, or Numeric).

func (*OnScreenKeyboard) Close

func (k *OnScreenKeyboard) Close(done bool)

Close closes the on-screen keyboard and restores focus on the owning Root. When done is true, OnDone (and Target.Submit if SubmitOnDone is set) is invoked; otherwise OnCancel runs.

func (*OnScreenKeyboard) Draw

func (k *OnScreenKeyboard) Draw(d *core.Drawing, bounds core.Bounds)

Draw renders the modal on-screen keyboard layer when open.

func (*OnScreenKeyboard) FocusedKey

func (k *OnScreenKeyboard) FocusedKey() string

FocusedKey returns the label of the currently focused key button on the keyboard, or "".

func (*OnScreenKeyboard) HandleAction

func (k *OnScreenKeyboard) HandleAction(action NavAction) bool

HandleAction dispatches a logical NavAction through the open on-screen keyboard.

func (*OnScreenKeyboard) HandleGamepadButton

func (k *OnScreenKeyboard) HandleGamepadButton(btn gamepad.Button) bool

HandleGamepadButton maps a W3C standard gamepad button press onto the open on-screen keyboard: D-pad moves focus, South activates the focused key, West is Backspace, North is Space, LB/LeftStick toggles Shift, Start/RB confirms Done, and East cancels.

func (*OnScreenKeyboard) HandleOSKAction

func (k *OnScreenKeyboard) HandleOSKAction(act OSKAction) bool

HandleOSKAction runs a direct on-screen keyboard editing command (Backspace, Space, Shift, Done, Cancel).

func (*OnScreenKeyboard) IsOpen

func (k *OnScreenKeyboard) IsOpen() bool

IsOpen reports whether the on-screen keyboard layer is currently displayed.

func (*OnScreenKeyboard) Layout

func (k *OnScreenKeyboard) Layout(bounds core.Bounds)

Layout lays out the on-screen keyboard inside bounds when open.

func (*OnScreenKeyboard) OnKeyDown

func (k *OnScreenKeyboard) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown routes keyboard events to the open on-screen keyboard.

func (*OnScreenKeyboard) OnPointerDown

func (k *OnScreenKeyboard) OnPointerDown(p core.Point) bool

OnPointerDown routes pointer presses inside the open on-screen keyboard and blocks input below it.

func (*OnScreenKeyboard) OnPointerMove

func (k *OnScreenKeyboard) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state inside the open on-screen keyboard and blocks input below it.

func (*OnScreenKeyboard) OnPointerUp

func (k *OnScreenKeyboard) OnPointerUp(p core.Point) bool

OnPointerUp finishes pointer presses inside the open on-screen keyboard and blocks input below it.

func (*OnScreenKeyboard) OnPress

func (k *OnScreenKeyboard) OnPress(ev core.PressEvent) bool

OnPress routes canvas presses inside the open on-screen keyboard and blocks input below it.

func (*OnScreenKeyboard) Open

func (k *OnScreenKeyboard) Open(field *TextField)

Open opens the on-screen keyboard targeting field.

func (*OnScreenKeyboard) OpenTextArea

func (k *OnScreenKeyboard) OpenTextArea(area *TextArea)

OpenTextArea opens the on-screen keyboard targeting area.

func (*OnScreenKeyboard) Shifted

func (k *OnScreenKeyboard) Shifted() bool

Shifted reports whether Shift mode is currently active.

func (*OnScreenKeyboard) StepActions

func (k *OnScreenKeyboard) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions while the on-screen keyboard is open.

func (*OnScreenKeyboard) Target

func (k *OnScreenKeyboard) Target() Widget

Target returns the text widget currently being edited, or nil if closed.

func (*OnScreenKeyboard) ToggleShift

func (k *OnScreenKeyboard) ToggleShift()

ToggleShift toggles uppercase/shifted characters on the on-screen keyboard.

type Panel

type Panel struct {
	Child        Widget
	Padding      core.Edges
	Align        Align
	Width        float32
	Height       float32
	MinWidth     float32
	MinHeight    float32
	Flex         float32
	Hidden       bool
	Background   core.Color
	Border       core.Color
	CornerRadius float32 // 0 uses Theme.CornerRadius; < 0 uses square corners.
	// Variation names a Theme.Styles entry that styles this panel in place of the theme's panel style.
	Variation string
	// Theme, when set, styles the panel and its subtree in place of the theme it inherits; zero fields take DefaultTheme's values, and the text scale stays the inherited one.
	Theme          *Theme
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	Transform      Transform
	OnContextMenu  func(core.Point)
	// PointerFilter controls whether a hit claims the pointer. The zero value stops propagation.
	PointerFilter PointerFilter
	// Tooltip supplies delayed hover/focus help for this panel.
	Tooltip *Tooltip
	// Drag and Drop opt this panel into the shared drag-and-drop state machine.
	Drag *DragSource
	Drop *DropTarget
	// contains filtered or unexported fields
}

Panel frames a single optional Child with padding, background fill, and border.

func (*Panel) Bounds

func (p *Panel) Bounds() core.Bounds

Bounds returns the panel's laid-out rectangle.

func (*Panel) ChildWidgets

func (p *Panel) ChildWidgets() []Widget

ChildWidgets returns the panel's child if non-nil.

type ParentalChallenge

type ParentalChallenge struct {
	// Prompt is the human-readable text instruction or arithmetic question displayed to the parent.
	Prompt string
	// Answer is the expected trimmed, case-insensitive answer (never shown in UI or errors).
	Answer string
}

ParentalChallenge is one adult-only verification question presented by ParentalGate.

type ParentalGate

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

ParentalGate presents an adult-only verification challenge (a two-step multi-digit arithmetic instruction) before child-restricted actions such as Purchases.Buy or liveops.OpenURL proceed. Pass Ask directly as liveops.PurchasesOptions.ParentalGate or liveops.OpenURL's parentalGate argument, and mount View(cx) over the game view.

func NewParentalGate

func NewParentalGate(cfg ParentalGateConfig) *ParentalGate

NewParentalGate creates a ParentalGate modal challenge configured by cfg.

func (*ParentalGate) Answer

func (g *ParentalGate) Answer() string

Answer returns the current unsubmitted answer text.

func (*ParentalGate) AppendDigit

func (g *ParentalGate) AppendDigit(digit string)

AppendDigit appends a digit (up to 6 characters) to the current answer.

func (*ParentalGate) Ask

func (g *ParentalGate) Ask(done func(passed bool))

Ask opens the parental gate challenge and invokes done once with true if the challenge is solved or false if cancelled or attempts are exhausted. Ask matches liveops.ParentalGateFunc. If another challenge is already active, the new request fails closed by calling done(false).

func (*ParentalGate) AttemptsLeft

func (g *ParentalGate) AttemptsLeft() int

AttemptsLeft returns how many attempts remain in the active challenge.

func (*ParentalGate) Backspace

func (g *ParentalGate) Backspace()

Backspace removes the last rune from the current answer.

func (*ParentalGate) Cancel

func (g *ParentalGate) Cancel()

Cancel dismisses the active parental gate and invokes done(false).

func (*ParentalGate) Challenge

func (g *ParentalGate) Challenge() ParentalChallenge

Challenge returns the currently active ParentalChallenge (or zero when closed).

func (*ParentalGate) Clear

func (g *ParentalGate) Clear()

Clear empties the current answer input.

func (*ParentalGate) Err

func (g *ParentalGate) Err() string

Err returns the current user-visible validation error message, if any.

func (*ParentalGate) Open

func (g *ParentalGate) Open() bool

Open reports whether the parental gate is currently showing a challenge.

func (*ParentalGate) SetAnswer

func (g *ParentalGate) SetAnswer(v string)

SetAnswer updates the current answer text without submitting.

func (*ParentalGate) Submit

func (g *ParentalGate) Submit() bool

Submit checks the current answer against the active challenge. A match closes the gate and invokes done(true). A mismatch rotates to a fresh challenge and decrements remaining attempts, closing with done(false) once attempts reach zero.

func (*ParentalGate) View

func (g *ParentalGate) View(cx *core.Scope) core.Node

View renders the parental gate modal overlay when Ask has opened a challenge.

type ParentalGateConfig

type ParentalGateConfig struct {
	// Catalog optionally localizes all strings and challenge templates through l10n.
	Catalog *l10n.Catalog
	// Locale selects the active BCP-47 locale tag in Catalog.
	Locale string
	// Text optionally overrides localized or default strings.
	Text ParentalGateText
	// Theme restyles the dialog surface, typography, keypad and buttons. Nil uses DefaultTheme.
	Theme *Theme
	// MaxAttempts is the number of wrong answers allowed before failing closed (DefaultParentalGateMaxAttempts when <= 0).
	MaxAttempts int
	// Rand optionally supplies the random source for built-in challenges (crypto/rand.Reader when nil).
	Rand io.Reader
	// Generator optionally replaces the built-in multi-digit arithmetic challenge generator.
	Generator func() ParentalChallenge
}

ParentalGateConfig configures a ParentalGate modal challenge.

type ParentalGateText

type ParentalGateText struct {
	Title           string
	Body            string
	ChallengeMulAdd string
	ChallengeMulSub string
	Placeholder     string
	Cancel          string
	Submit          string
	Clear           string
	Backspace       string
	WrongAnswer     string
}

ParentalGateText holds user-visible copy for ParentalGate. Empty fields are resolved from Catalog before falling back to DefaultParentalGateText.

func DefaultParentalGateText

func DefaultParentalGateText() ParentalGateText

DefaultParentalGateText returns the English default copy for ParentalGate.

type Pivot

type Pivot struct {
	// X is the normalized horizontal pivot coordinate inside the node's bounds (0 = left, 0.5 = center, 1 = right).
	X float32 `yaml:"x,omitempty"`
	// Y is the normalized vertical pivot coordinate inside the node's bounds (0 = top, 0.5 = center, 1 = bottom).
	Y float32 `yaml:"y,omitempty"`
}

Pivot is a normalized anchor inside a widget's laid-out bounds used as the origin for Scale and Rotation. (0, 0) is the top-left corner, (0.5, 0.5) is the center, and (1, 1) is the bottom-right corner.

type PointerEvent

type PointerEvent struct {
	// Kind is the pointer phase (PointerDown, PointerMove, PointerUp, or PointerCancel).
	Kind PointerKind
	// Position is the pointer location in local widget points relative to Custom.Bounds().Origin.
	Position core.Point
}

PointerEvent describes a pointer or touch event in local widget coordinates relative to Custom.Bounds().Origin.

type PointerFilter

type PointerFilter uint8

PointerFilter controls whether a widget consumes a pointer press.

const (
	// PointerStop reports a hit and stops it from reaching the widget's parents and the world.
	PointerStop PointerFilter = iota
	// PointerPass reports a hit and lets it continue to the widget's parents and the world.
	PointerPass
	// PointerIgnore does not report a hit at all.
	PointerIgnore
)

func ParsePointerFilter

func ParsePointerFilter(value string) (PointerFilter, bool)

ParsePointerFilter parses the screen-file spelling of a pointer filter. Empty values use PointerStop for compatibility with the zero value.

func (PointerFilter) ShouldConsume

func (f PointerFilter) ShouldConsume() bool

ShouldConsume reports whether a hit should stop propagation to the world, which only PointerStop does, matching ResolvePointerFilter.

type PointerHandler

type PointerHandler interface {
	OnPointer(ev PointerEvent) bool
}

PointerHandler optionally handles mouse and touch pointer events in local widget coordinates. Returning true on PointerDown captures subsequent move, up, and cancel events even outside the widget's bounds.

type PointerKind

type PointerKind uint8

PointerKind identifies the phase of a PointerEvent delivered to a custom widget's PointerHandler.

const (
	// PointerDown indicates a pointer press started on the widget.
	PointerDown PointerKind = iota
	// PointerMove indicates the pointer moved over the widget or while captured by it.
	PointerMove
	// PointerUp indicates a pointer press ended.
	PointerUp
	// PointerCancel indicates an active pointer interaction was cancelled (such as TouchCancel or modal/popup interruption).
	PointerCancel
)

func (PointerKind) String

func (k PointerKind) String() string

String returns the lowercase name of k ("down", "move", "up", or "cancel").

type PointerResult

type PointerResult struct {
	Hit      bool
	Consumed bool
}

PointerResult describes a widget hit and whether it should continue to its parent.

func ResolvePointerFilter

func ResolvePointerFilter(filter PointerFilter, hit bool) PointerResult

ResolvePointerFilter applies a widget filter to a hit. Ignore does not claim the pointer, Pass reports the hit without consuming it, and Stop consumes it.

type ProgressBar

type ProgressBar struct {
	Value          float32
	Min            float32
	Max            float32
	Label          string
	FillColor      core.Color
	TrackColor     core.Color
	TextColor      core.Color
	Font           core.Font
	Effects        text.TextEffects
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

ProgressBar displays a read-only progress meter in [Min, Max] (or [0, 1] when both Min and Max are 0).

Example

A ProgressBar shows how far a value is between Min and Max, such as a loading screen's progress.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
)

func main() {
	bar := &gameui.ProgressBar{Min: 0, Max: 200, Value: 50}
	fmt.Println(bar.Fraction())
}
Output:
0.25

func (*ProgressBar) Bounds

func (p *ProgressBar) Bounds() core.Bounds

Bounds returns the progress bar's laid-out rectangle.

func (*ProgressBar) Fraction

func (p *ProgressBar) Fraction() float32

Fraction returns Value normalized into [0, 1].

type QuitConfirmation

type QuitConfirmation struct {
	Open func() bool
	// OnAnswer receives true to proceed and false to cancel. Close the dialog
	// by making Open return false on either answer.
	OnAnswer func(proceed bool)
	// Save is optional. A failed save leaves the dialog open for retry.
	Save func() error
	// CanSave limits when Save and quit is shown. Nil allows it whenever Save is set.
	CanSave func() bool
	// Report receives a failed save for game-specific logging or feedback.
	Report func(error)

	// The captions can be localized or adapted for Restart and Quit to title.
	// Empty captions use English quit copy.
	Title, Description, CancelText, QuitText, SaveText, SaveFailedText string
}

QuitConfirmation is an alert dialog for actions that would discard progress. It starts with Cancel focused. For controller navigation, enable gamepad.EnableFocusNavigation on the window and release gameplay input capture while the dialog is open. Canvas games that navigate menus through gameui input actions can use CanvasQuitConfirmation instead.

func (QuitConfirmation) Render

func (q QuitConfirmation) Render(cx *core.Scope) core.Node

Render implements core.Node.

type QuitGuardOptions

type QuitGuardOptions struct {
	// Guard decides which requests may proceed and when to try saving.
	Guard save.QuitGuard
	// Ask presents a confirmation and calls answer on the scope's goroutine.
	// Passing true allows the request. When Ask is nil the request is canceled.
	Ask func(answer func(quit bool))
	// Pause receives true while a confirmation is open and false when it is answered.
	Pause func(bool)
	// Report receives an error from an attempted save.
	Report func(error)
}

QuitGuardOptions connects a game's unsaved progress to desktop close and quit requests.

type RichLabel

type RichLabel struct {
	Markup        string
	OnLink        func(string)
	Links         []text.RichLink
	Color         core.Color
	Font          core.Font
	Width, Height float32
	Hidden        bool
	FocusOrder    int
	// contains filtered or unexported fields
}

RichLabel displays rich markup with [link=id]...[/link] spans. It takes focus when it has at least one link, and Root.Activate (Enter, Space or the gamepad accept button) invokes OnLink with the first link's ID; use Activate(index) to report a later link.

func (*RichLabel) Activate

func (r *RichLabel) Activate(index int)

Activate invokes OnLink for a link index.

func (*RichLabel) Bounds

func (r *RichLabel) Bounds() core.Bounds

Bounds returns the label's laid-out bounds.

func (*RichLabel) Parse

func (r *RichLabel) Parse()

Parse updates link spans from Markup.

type Root

type Root struct {
	// Child is the root widget of the UI tree (typically a Panel, VBox, or HBox).
	Child Widget
	// Theme styles all widgets under this Root; nil uses DefaultTheme.
	Theme *Theme
	// Viewport optionally maps a fixed virtual resolution onto the physical window bounds,
	// applying scaling and letterboxing in Draw and mapping window pointer/touch input into virtual coordinates.
	Viewport *Viewport
	// FocusRing optionally overrides the focus ring style drawn around the focused widget.
	FocusRing *FocusRingStyle
	// TextScale multiplies every widget font size under this Root, including explicit per-widget and screen-file sizes; it is clamped to [MinTextScale, MaxTextScale], and 0 uses Theme.TextScale.
	TextScale float32
	// DeviceTracker optionally reports the active input device; when a gamepad is active and no hardware
	// keyboard is present, activating a TextField or TextArea opens OnScreenKeyboard.
	DeviceTracker *input.DeviceTracker
	// HasHardwareKeyboard optionally reports whether a physical keyboard is available.
	// When nil, desktop environments attached via AttachInput assume a hardware keyboard is present
	// unless a Steam Deck controller is active, while non-desktop environments assume none.
	HasHardwareKeyboard func() bool
	// Locale optionally overrides the BCP-47 locale tag used to pick the OnScreenKeyboard layout (e.g. "fr-FR").
	Locale string
	// OnScreenKeyboard optionally configures the modal on-screen keyboard opened for gamepad text entry.
	// When nil, one is created on demand with OSKLayoutAuto.
	OnScreenKeyboard *OnScreenKeyboard
	// SystemKeyboard optionally opens a platform's own keyboard, such as Steam's on a Steam Deck, when gamepad text entry starts on a TextField or TextArea; OnScreenKeyboard opens instead when it is nil or returns false. OnScreenKeyboard.SubmitOnDone applies to its result too.
	SystemKeyboard SystemKeyboard
	// LongPressDuration configures how long a stationary touch must be held in OnTouch + Update
	// before raising OnContextMenu. Zero uses DefaultLongPressDuration (500ms).
	LongPressDuration time.Duration
	// contains filtered or unexported fields
}

Root manages layout, focus navigation, pointer/touch interaction, and rendering for a game UI widget tree.

Example

A Root lays out a widget tree, moves focus between the focusable widgets and activates the focused one, as a pause menu driven by a gamepad does.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	volume := &gameui.Slider{Label: "Volume", Min: 0, Max: 10, Value: 5, Step: 1, Height: 40}
	resume := &gameui.Button{Text: "Resume", Height: 40, OnClick: func() { fmt.Println("resume clicked") }}
	menu := &gameui.VBox{
		Spacing: 10,
		Padding: core.All(20),
		Children: []gameui.Widget{
			&gameui.Label{Text: "Paused", Height: 30},
			resume,
			volume,
		},
	}
	root := gameui.NewRoot(menu)
	root.Layout(core.Bounds{Size: core.Size{Width: 320, Height: 240}})
	fmt.Println(resume.Bounds().Origin, volume.Bounds().Origin)

	root.FocusNext()
	fmt.Println(root.Focused() == resume)
	root.Activate()
	root.FocusNext()
	root.Adjust(1)
	fmt.Println(volume.Value, volume.Fraction())
}
Output:
{20 60} {20 110}
true
resume clicked
6 0.6

func NewRoot

func NewRoot(child Widget) *Root

NewRoot returns a Root wrapping child with the default theme.

func (*Root) Activate

func (r *Root) Activate() bool

Activate triggers the currently focused widget (clicks a Button, flips a Toggle, opens a Dropdown/MenuButton, or begins text entry on a TextField/TextArea).

func (*Root) Adjust

func (r *Root) Adjust(delta float32) bool

Adjust steps the currently focused adjustable widget by delta steps (e.g. -1 or +1). For a Slider, Value moves by delta * step within [Min, Max]. For a Toggle, delta > 0 checks it and delta < 0 unchecks it. For a List, Selected steps by delta clamped to the available items.

func (*Root) AttachInput

func (r *Root) AttachInput(cx *core.Scope) core.Node

AttachInput mounts the hidden native NSGo input layer driven by focused TextField and TextArea widgets under r. Include the returned core.Node as a sibling after the game core.Canvas in the host view so the native input sits over the focused field's screen box for IME candidate windows, the platform virtual keyboard, clipboard shortcuts, and the touch edit menu.

func (*Root) Bounds

func (r *Root) Bounds() core.Bounds

Bounds returns the bounds from the last Layout or Draw call.

func (*Root) ClearFocus

func (r *Root) ClearFocus()

ClearFocus removes keyboard/gamepad focus from the active widget.

func (*Root) DismissKeyboard

func (r *Root) DismissKeyboard()

DismissKeyboard blurs the backing native text input, asks the platform to dismiss any open software keyboard, and closes the on-screen keyboard if it is open.

func (*Root) Draw

func (r *Root) Draw(d *core.Drawing, bounds core.Bounds)

Draw lays out the tree into bounds and draws every visible widget into d. When Viewport is set, Draw renders letterbox bars and transforms d into the virtual resolution. Caller drawing state (transform, colors, stroke settings, alpha, text align/baseline, and current path) is preserved.

func (*Root) DrawWithViewport

func (r *Root) DrawWithViewport(d *core.Drawing, vp Viewport)

DrawWithViewport renders the UI tree using vp without permanently replacing r.Viewport.

func (*Root) FieldWindowBounds

func (r *Root) FieldWindowBounds(w Widget) core.Bounds

FieldWindowBounds maps widget w's laid-out rectangle into physical window coordinates, including Viewport scaling, Root.Bounds().Origin, and active keyboard avoidance offset.

func (*Root) FocusIndex

func (r *Root) FocusIndex() int

FocusIndex returns the index of the focused widget in the current list of enabled, visible focusable widgets, or -1 if none is focused.

func (*Root) FocusNext

func (r *Root) FocusNext() bool

FocusNext moves focus to the next enabled, focusable widget, wrapping from the end to the beginning.

func (*Root) FocusPrev

func (r *Root) FocusPrev() bool

FocusPrev moves focus to the previous enabled, focusable widget, wrapping from the beginning to the end.

func (*Root) Focused

func (r *Root) Focused() Widget

Focused returns the currently focused widget, or nil if none is focused.

func (*Root) HandleGamepadButton

func (r *Root) HandleGamepadButton(btn gamepad.Button) bool

HandleGamepadButton routes a W3C standard gamepad button press to an open popup menu or OnScreenKeyboard. Returns true if the overlay consumed the button.

func (*Root) HitTest

func (r *Root) HitTest(p core.Point) Widget

HitTest returns the topmost enabled, focusable widget containing p, or nil. When Viewport is set, p is mapped from window coordinates into virtual coordinates and points inside letterbox bars return nil.

func (*Root) Hovered

func (r *Root) Hovered() Widget

Hovered returns the currently hovered interactive widget, or nil.

func (*Root) IMEBounds

func (r *Root) IMEBounds() (core.Bounds, bool)

IMEBounds returns the window-space bounds of the currently focused text field (after viewport mapping and keyboard avoidance), which is where the platform IME candidate window anchors.

func (*Root) KeyboardHeight

func (r *Root) KeyboardHeight() core.Points

KeyboardHeight returns the platform software keyboard height reported by NSGo's Env, or 0 when no input bridge is attached or no system keyboard is visible.

func (*Root) KeyboardOffset

func (r *Root) KeyboardOffset() core.Points

KeyboardOffset returns the vertical upward shift in window points currently applied to keep the focused text field above the platform software keyboard.

func (*Root) Layout

func (r *Root) Layout(bounds core.Bounds)

Layout computes exact rectangles for every widget in the tree inside bounds and refreshes the focusable widget list. When Viewport is set, bounds specifies the physical window rectangle and the widget tree is laid out in virtual coordinates.

func (*Root) MoveFocus

func (r *Root) MoveFocus(dx, dy int) bool

MoveFocus moves focus geometrically in direction (dx, dy) (for arrow keys and gamepad D-pad/stick), checking explicit per-widget NavOverrides first, wrapping along the axis when reaching an edge, and falling back to linear order if layout has not run.

func (*Root) OnContextMenu

func (r *Root) OnContextMenu(p core.Point) bool

OnContextMenu dispatches a context menu request (such as a desktop right-click or touch long-press) at window point p to the deepest visible widget under p that defines OnContextMenu or was registered with SetContextMenu. Returns true if a handler was invoked.

func (*Root) OnKeyDown

func (r *Root) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown handles keyboard navigation, activation, text entry, and slider adjustment. Returns true if the event was consumed by the UI.

func (*Root) OnMouseDown

func (r *Root) OnMouseDown(ev core.MouseButtonEvent) bool

OnMouseDown routes a mouse button press: primary button to OnPointerDown and right button to OnContextMenu.

func (*Root) OnMouseUp

func (r *Root) OnMouseUp(ev core.MouseButtonEvent) bool

OnMouseUp routes a primary mouse button release to OnPointerUp.

func (*Root) OnPointerCancel

func (r *Root) OnPointerCancel() bool

OnPointerCancel cancels any active pointer press, slider or scroll drag, or captured custom widget interaction. Returns true if an active interaction was cancelled.

func (*Root) OnPointerDown

func (r *Root) OnPointerDown(p core.Point) bool

OnPointerDown focuses and presses the interactive widget under p, beginning a drag if it is a Slider. Returns true if an interactive widget was hit.

func (*Root) OnPointerMove

func (r *Root) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state and smoothly drags any active Slider. Returns true if the pointer is over an interactive widget or dragging a Slider.

func (*Root) OnPointerUp

func (r *Root) OnPointerUp(p core.Point) bool

OnPointerUp finishes any active press or Slider drag, activating a Button, Toggle, or List item when released inside it. Returns true if a press or drag was handled.

func (*Root) OnPress

func (r *Root) OnPress(ev core.PressEvent) bool

OnPress handles a core.Canvas PressEvent directly (tapping/clicking a Button, Toggle, Slider, List, or TextField/TextArea, or activating the focused widget on keyboard press).

func (*Root) OnTouch

func (r *Root) OnTouch(ev core.TouchEvent) bool

OnTouch routes single-finger touch events to pointer interaction and detects stationary long-presses to raise OnContextMenu (cancelling any pending click so lifting the finger does not also activate the widget).

func (*Root) OnWheel

func (r *Root) OnWheel(ev core.WheelEvent) bool

OnWheel routes a mouse wheel or touchpad scroll event to the deepest visible enabled ScrollList or Scroll under ev.Position. Returns true if the event was consumed.

func (*Root) OpenOnScreenKeyboard

func (r *Root) OpenOnScreenKeyboard(field *TextField)

OpenOnScreenKeyboard opens the modal on-screen keyboard targeting field and restores focus when it closes.

func (*Root) OpenOnScreenKeyboardForArea

func (r *Root) OpenOnScreenKeyboardForArea(area *TextArea)

OpenOnScreenKeyboardForArea opens the modal on-screen keyboard targeting area and restores focus when it closes.

func (*Root) Pressed

func (r *Root) Pressed() Widget

Pressed returns the currently pressed interactive widget, or nil.

func (*Root) SetContextMenu

func (r *Root) SetContextMenu(w Widget, fn func(p core.Point))

SetContextMenu registers or clears a context menu handler for any widget in this Root, invoked on desktop right-click (OnContextMenu / OnMouseDown) or touch long-press (OnTouch + Update).

func (*Root) SetFocus

func (r *Root) SetFocus(w Widget) bool

SetFocus focuses w if it is visible and focusable in this tree.

func (*Root) SetFocusIndex

func (r *Root) SetFocusIndex(index int) bool

SetFocusIndex focuses the focusable widget at index, or clears focus when index < 0.

func (*Root) SetTextScale

func (r *Root) SetTextScale(scale float32) float32

SetTextScale sets the root text scale and returns the normalized value.

func (*Root) StateOf

func (r *Root) StateOf(w Widget) WidgetState

StateOf returns the current hover, pressed, focused, and disabled state of w.

func (*Root) SystemKeyboardOpen

func (r *Root) SystemKeyboardOpen() bool

SystemKeyboardOpen reports whether a text field is waiting for Root.SystemKeyboard to return its text.

func (*Root) Update

func (r *Root) Update(dt time.Duration) bool

Update advances touch long-press detection for context menus and inertial/edge-bounce physics on any active ScrollList widgets. Returns true if a long-press triggered or a scroll list moved.

type ScaleMode

type ScaleMode uint8

ScaleMode controls how a Viewport maps a virtual resolution into a physical window size.

const (
	// ScaleFit uniformly scales the virtual canvas to fit inside the window, adding letterbox or pillarbox bars as needed.
	ScaleFit ScaleMode = iota
	// ScaleFill uniformly scales the virtual canvas to cover the entire window, cropping any overflow symmetrically.
	ScaleFill
	// ScaleStretch scales X and Y independently to fill the window without preserving aspect ratio.
	ScaleStretch
	// ScaleInteger uniformly scales by the largest integer factor >= 1 that fits inside the window,
	// falling back to ScaleFit when the window is smaller than the virtual resolution.
	ScaleInteger

	// ScaleLetterbox is an alias for ScaleFit.
	ScaleLetterbox = ScaleFit
	// IntegerScale is an alias for ScaleInteger.
	IntegerScale = ScaleInteger
)

type ScanOptions

type ScanOptions struct {
	Enabled  bool
	Interval time.Duration
	Loops    int
	Select   NavAction
}

ScanOptions configures one-switch focus scanning. Interval is the time between focus changes. Loops limits completed passes when positive, while a zero value scans continuously. Select is the action StepActions treats as the switch that activates the highlighted widget.

type ScreenAnchor

type ScreenAnchor string

ScreenAnchor positions a node against one of nine reference points or fills its parent bounds.

const (
	AnchorTopLeft      ScreenAnchor = "top_left"
	AnchorTopCenter    ScreenAnchor = "top_center"
	AnchorTopRight     ScreenAnchor = "top_right"
	AnchorCenterLeft   ScreenAnchor = "center_left"
	AnchorCenter       ScreenAnchor = "center"
	AnchorCenterRight  ScreenAnchor = "center_right"
	AnchorBottomLeft   ScreenAnchor = "bottom_left"
	AnchorBottomCenter ScreenAnchor = "bottom_center"
	AnchorBottomRight  ScreenAnchor = "bottom_right"
	AnchorFill         ScreenAnchor = "fill"
)

type ScreenBuildOptions

type ScreenBuildOptions struct {
	// SafeArea specifies the display safe-area insets in virtual points (for notches, rounded corners, and home indicators).
	SafeArea core.Edges
	// TitleBar specifies the desktop hidden title-bar control area in virtual points from desktop.TitleBar; zero in full screen or with the system title bar.
	TitleBar core.Edges
	// DeviceClass selects which conditional nodes (ScreenNodeDoc.DeviceClasses) are visible.
	// When empty, no device-class filtering is applied and all nodes remain visible.
	DeviceClass DeviceClass
	// ViewportWidth and ViewportHeight optionally override the Viewport's virtual dimensions (for example 780×360 for a 19.5:9 phone).
	// When zero, the document's DesignWidth and DesignHeight are used.
	ViewportWidth  float32
	ViewportHeight float32
	// Text resolves localization textKey values. When nil and Catalog is set, Catalog.T(Locale, key) is used; when both are nil, the key itself is displayed.
	Text func(key string) string
	// Bindings resolves declarative node properties from screen files. When set, values are applied initially and updated from subscriptions; call BuiltScreen.Dispose to release them.
	Bindings *Bindings
	// Catalog optionally resolves textKey values when Text is nil.
	Catalog *l10n.Catalog
	// Locale optionally selects the locale in Catalog (empty uses Catalog's active locale).
	Locale string
	// Theme optionally overrides the built Root's theme; nil uses DefaultTheme tuned for DefaultScreenFontSize and screen text measurement.
	Theme *Theme
	// OnClick optionally binds click callbacks by node ID for button and touch_button nodes.
	// BuildScreen returns a *loaderr.Error if a key names no node or a node that does not accept clicks, unless IgnoreUnknownCallbacks is true.
	OnClick map[string]func()
	// OnChange optionally binds value-change callbacks by node ID for slider nodes.
	// BuildScreen returns a *loaderr.Error if a key names no node or a node that does not accept change callbacks, unless IgnoreUnknownCallbacks is true.
	OnChange map[string]func(float32)
	// OnToggle optionally binds checked-change callbacks by node ID for toggle nodes.
	// BuildScreen returns a *loaderr.Error if a key names no node or a node that does not accept toggle callbacks, unless IgnoreUnknownCallbacks is true.
	OnToggle map[string]func(bool)
	// OnSubmit optionally binds submit callbacks by callback ID (ScreenNodeDoc.OnSubmit, or node ID when OnSubmit is omitted) for text_field nodes.
	// BuildScreen returns a *loaderr.Error if a key names no text_field callback or a node of another type, unless IgnoreUnknownCallbacks is true.
	OnSubmit map[string]func(string)
	// OnLink optionally binds link callbacks by node ID for rich_label nodes; the callback receives the activated span's link ID.
	// BuildScreen returns a *loaderr.Error if a key names no node or a node that does not accept link callbacks, unless IgnoreUnknownCallbacks is true.
	OnLink map[string]func(string)
	// IgnoreUnknownCallbacks disables callback key validation in BuildScreen so one callback map can be shared across several screens.
	IgnoreUnknownCallbacks bool
	// Custom maps custom node kind strings (ScreenNodeDoc.Kind) to constructors returning a CustomWidget.
	// BuildScreen returns a *loaderr.Error if a custom node names an unregistered kind, unless IgnoreUnknownCustom is true.
	Custom map[string]func(node ScreenNodeDoc) CustomWidget
	// IgnoreUnknownCustom disables unregistered custom-kind refusal in BuildScreen (used by layout previews and schema-only checks).
	IgnoreUnknownCustom bool
	// Sprites optionally resolves a node's Sprite path (and optional SpriteFrame) into a core.ImageSource and source rectangle.
	Sprites func(path, frame string) (core.ImageSource, core.Bounds, bool)
	// SpriteInsets optionally resolves a node's Sprite path (and optional SpriteFrame) into nine-slice insets
	// (typically fed from sprite.Atlas.Slices[frame]). Used by image nodes with scale: nine_slice.
	SpriteInsets func(path, frame string) (NineSliceInsets, bool)
	// Actions supplies the current input bindings for prompt and action_bar nodes.
	Actions *input.Actions
	// DeviceTracker supplies the active input device for prompts. Nil starts on the keyboard.
	DeviceTracker *input.DeviceTracker
	// Prompts resolves bindings through the project's glyph set and explicit prompt overrides.
	Prompts *input.PromptTable
	// PromptSprites resolves a prompt's Icon key into an image and source rectangle.
	// When nil or the key is missing, the prompt displays text.
	PromptSprites func(icon string) (core.ImageSource, core.Bounds, bool)
	// Animations optionally loads and binds each animation declared in ScreenDoc.Animations
	// (called with the built screen, animation name, and project-relative animation path).
	// Pass animclip.ScreenAnimations(clips) to load *.animation.yaml files through a resource.Library or animclip.ClipMap.
	Animations func(screen *BuiltScreen, name, path string) (ScreenClip, error)
	// OnEvent optionally handles named cue events emitted by playing screen animations.
	OnEvent func(name string)
}

ScreenBuildOptions configures BuildScreen.

type ScreenCanvas

type ScreenCanvas struct {
	SafeArea     core.Edges
	Items        []AnchoredItem
	Background   core.Color
	CornerRadius float32
	Width        float32
	Height       float32
	MinWidth     float32
	MinHeight    float32
	Flex         float32
	Align        Align
	Hidden       bool
	Transform    Transform
	// PointerFilter controls whether the canvas consumes a pointer hit.
	PointerFilter PointerFilter
	// contains filtered or unexported fields
}

ScreenCanvas lays out children using nine-point anchors or fill, optional safe-area insets, and offsets. It implements Container and Widget.

func (*ScreenCanvas) Bounds

func (c *ScreenCanvas) Bounds() core.Bounds

Bounds returns the canvas's laid-out rectangle.

func (*ScreenCanvas) ChildWidgets

func (c *ScreenCanvas) ChildWidgets() []Widget

ChildWidgets returns the direct child widgets in render order.

func (*ScreenCanvas) Widget

func (c *ScreenCanvas) Widget(id string) Widget

Widget returns the descendant widget with id built into this canvas (for example, a child inside a list item fragment instance), or nil if none has that ID.

type ScreenCheckOptions

type ScreenCheckOptions struct {
	// TextScale is the largest text scale the game supports. When it is above the theme's own scale, text overflow is checked at both scales, and an overflow that only appears at the larger one names that scale in its message. It is clamped to [MinTextScale, MaxTextScale]; 0 checks the theme's scale only.
	TextScale float32
	// Locales maps normalized locale tags to their message string maps (for example from l10n.StringTable.Strings).
	Locales map[string]map[string]string
	// Plurals optionally maps normalized locale tags to their CLDR plural entries (for example from l10n.StringTable.Plurals).
	Plurals map[string]map[string]l10n.PluralForms
	// Samples optionally supplies sample values used to expand {placeholder} tokens
	// in localized templates before CheckScreen measures text width.
	//
	// Lookup precedence for a placeholder named "name" inside localization key "k":
	//  1. Samples["k.name"] (per-key placeholder override, preserving localized surrounding text);
	//  2. Samples["name"] (global placeholder sample);
	//  3. PlaceholderSample (or DefaultPlaceholderSample when PlaceholderSample is empty).
	//
	// Inline ICU plural # tokens resolve against their enclosing plural variable name using the same precedence.
	Samples map[string]string
	// PlaceholderSample overrides the fallback replacement text for any placeholder
	// not found in Samples. When empty, DefaultPlaceholderSample ("WWWWWW") is used
	// so a long placeholder identifier name alone does not cause a false text_overflow.
	PlaceholderSample string
	// Devices optionally overrides the reference device profiles; empty uses the default reference profiles for the screen's orientation (landscape ReferenceDevicesFor and/or portrait PortraitReferenceDevicesFor).
	Devices []DeviceProfile
	// Orientation optionally overrides ScreenDoc.Orientation when Devices is empty: "any" checks both landscape and portrait reference profiles, "landscape" checks landscape profiles only, and "portrait" checks portrait profiles only. Empty uses doc.EffectiveOrientation() (default "any").
	Orientation ScreenOrientation
	// Theme optionally overrides the theme used for default text/button colors and text measurement.
	Theme *Theme
	// FallbackBackdrop is the backdrop color used to composite translucent fills when no opaque ancestor fill exists (defaults to #101216).
	FallbackBackdrop core.Color
	// PromptFallback returns the readable binding prefix rendered before a prompt's localized label when no prompt icon is available. It is called with the prompt action name. A nil function checks only the localized label.
	PromptFallback func(action string) string
	// Custom optionally supplies custom widget builders so CheckScreen can verify custom node kinds and measure custom widgets during layout checks.
	// When non-nil, any custom node whose kind is missing or nil is reported as IssueUnknownCustomKind.
	Custom map[string]func(ScreenNodeDoc) CustomWidget
}

ScreenCheckOptions configures CheckScreen.

type ScreenClip

type ScreenClip interface {
	Play()
	Pause()
	Restart()
	Seek(at time.Duration)
	Update(dt time.Duration)
	Playing() bool
	Done() bool
}

ScreenClip is a playable animation clip registered on a BuiltScreen by name. *animclip.Player implements ScreenClip.

type ScreenDoc

type ScreenDoc struct {
	// Version is the schema version (ScreenMinVersion 1, or ScreenFormatVersion 2 for reusable screen fragments and overrides).
	Version int `yaml:"version" schema:"required"`
	// UID is an optional stable ID for the screen file, kept across renames by game index and game mv.
	UID string `yaml:"uid,omitempty"`
	// Name is the screen's human-readable name (for example "hud" or "pause").
	Name string `yaml:"name,omitempty"`
	// DesignWidth is the authored reference canvas width in virtual points (for example 640).
	DesignWidth float32 `yaml:"designWidth" schema:"required,exclusiveMinimum=0"`
	// DesignHeight is the authored reference canvas height in virtual points (for example 360).
	DesignHeight float32 `yaml:"designHeight" schema:"required,exclusiveMinimum=0"`
	// ScaleMode controls how the screen scales to different window sizes: fit (default), fill, stretch, or integer.
	ScaleMode ScreenScaleMode `yaml:"scaleMode,omitempty" schema:"enum=fit|fill|stretch|integer"`
	// Orientation declares which display orientations the screen supports: any (default when omitted), landscape, or portrait.
	Orientation ScreenOrientation `yaml:"orientation,omitempty" schema:"enum=any|landscape|portrait"`
	// Animations maps named screen animation clips (such as "reward_in") to project-relative *.animation.yaml paths, followed by refs and game mv.
	Animations map[string]string `yaml:"animations,omitempty"`
	// Nodes are the top-level UI nodes of the screen. Canvas widgets render in slice order.
	Nodes []ScreenNodeDoc `yaml:"nodes,omitempty"`
	// contains filtered or unexported fields
}

ScreenDoc is the root of a versioned *.screen.yaml HUD or menu screen definition.

func LoadScreenFS

func LoadScreenFS(fsys fs.FS, name string) (*ScreenDoc, error)

LoadScreenFS reads and parses a *.screen.yaml file from fsys, attaching name to any returned error.

func ParseScreen

func ParseScreen(data []byte) (*ScreenDoc, error)

ParseScreen decodes and validates a versioned *.screen.yaml document. Unknown fields, fields unsupported by a node's type, disjoint nested deviceClasses, trailing YAML documents, YAML anchors/aliases/merge keys, missing or unsupported versions, duplicate node IDs, duplicate focus orders, invalid enums or colors, and non-finite numbers are refused.

Errors are *loaderr.Error values carrying line, column, field path, and fix guidance; callers that read from a file can attach the file path with loaderr.WithFile.

func ResolveScreen

func ResolveScreen(doc *ScreenDoc, fsys fs.FS) (*ScreenDoc, error)

ResolveScreen validates doc and returns a self-contained copy with every instanced screen fragment loaded from fsys, overrides applied, and instanced node IDs prefixed with "<instanceID>/" (nested instances are prefixed recursively, such as "dialog/play/label").

ResolveScreen refuses cycles, chains deeper than MaxScreenNesting, results exceeding MaxResolvedScreenNodes, missing or invalid fragment files, controller_reconnect nodes inside instanced fragments, overrides targeting unknown node IDs, and any resolved tree that fails screen validation.

ResolveScreen never mutates doc, and fsys may be nil when doc refers to no other screen files.

func (*ScreenDoc) Clone

func (doc *ScreenDoc) Clone() *ScreenDoc

Clone returns a deep copy of doc.

func (*ScreenDoc) ControllerReconnectPanel

func (d *ScreenDoc) ControllerReconnectPanel(opts ScreenReconnectOptions) core.Node

ControllerReconnectPanel returns the native overlay declared by the screen, or nil if there is no controller_reconnect node. Mount it after the canvas in the view it should cover. A screen node without a titleKey or messageKey uses the corresponding default text.

func (*ScreenDoc) EffectiveOrientation

func (doc *ScreenDoc) EffectiveOrientation() ScreenOrientation

EffectiveOrientation returns doc.Orientation, defaulting to ScreenOrientationAny when empty.

func (*ScreenDoc) EffectiveScaleMode

func (doc *ScreenDoc) EffectiveScaleMode() ScaleMode

EffectiveScaleMode maps doc.ScaleMode to a gameui.ScaleMode, defaulting to ScaleFit.

func (*ScreenDoc) RefersToScreens

func (doc *ScreenDoc) RefersToScreens() bool

RefersToScreens reports whether doc contains any unresolved node that references another *.screen.yaml fragment (either a fragment instance via screen: or a list node's item: template not yet loaded by ResolveScreen).

func (*ScreenDoc) StateSets

func (doc *ScreenDoc) StateSets() []ScreenStateSetInfo

StateSets returns all named state sets declared across doc's node tree in document order, with state sets on the same node and values within each set sorted by name.

type ScreenIssue

type ScreenIssue struct {
	// Code classifies the issue.
	Code ScreenIssueCode
	// Severity reports whether the issue is an error (SeverityError) or a warning (SeverityWarning).
	Severity ScreenIssueSeverity
	// NodeID is the ScreenNodeDoc.ID at fault.
	NodeID string
	// NodePath holds the YAML path steps from the document root to the offending node or field (for example ["nodes", "3", "textKey"]).
	NodePath []string
	// Locale is the BCP-47 locale tag involved, when the issue is locale-specific.
	Locale string
	// State names the non-default state value where the issue was found (for example "mail_row.read=read"), or is empty for the default state.
	State string
	// Devices names the reference device profiles involved, when the issue is device-specific.
	Devices []string
	// Message describes the issue for diagnostics and UI panels.
	Message string
}

ScreenIssue is one problem CheckScreen finds in a ScreenDoc.

func CheckScreen

func CheckScreen(doc *ScreenDoc, opts ScreenCheckOptions) []ScreenIssue

CheckScreen checks doc against the HUD/menu screen quality rules in its default state and in every non-default named node state:

  • touch areas under 44 pt on phones and tablets;
  • localized text overflowing its box at any reference device size (landscape Phone 19.5:9 with notch, Tablet 4:3, Desktop 16:9, Ultrawide 21:9, and portrait Phone 9:19.5 with notch and mobile-browser toolbars, filtered by screen orientation);
  • localization keys, including prompt labels and state overrides, missing from any project locale;
  • text under 4.5:1 WCAG contrast against its own fill;
  • visible nodes whose laid-out bounds extend outside a device viewport's safe area (reported per device);
  • HUD and menu nodes overlapping desktop hidden title-bar window controls (macOS- and Windows-style).

type ScreenIssueCode

type ScreenIssueCode string

ScreenIssueCode identifies the category of a screen check diagnostic.

const (
	// IssueTouchAreaTooSmall flags a touch control whose hit area is below MinTouchTargetSize (44 pt) on phones or tablets.
	IssueTouchAreaTooSmall ScreenIssueCode = "touch_area_too_small"
	// IssueTextOverflow flags a text node whose localized string exceeds its laid-out box width at one or more reference sizes.
	IssueTextOverflow ScreenIssueCode = "text_overflow"
	// IssueTextOverrun warns that a text node's localized string is cut by its configured overrun policy (clip, ellipsis, or word_ellipsis) at one or more reference sizes.
	IssueTextOverrun ScreenIssueCode = "text_overrun"
	// IssueMissingTextKey flags a localization key absent from a project locale table.
	IssueMissingTextKey ScreenIssueCode = "missing_text_key"
	// IssueLowContrast flags text whose contrast ratio against its fill is under 4.5:1.
	IssueLowContrast ScreenIssueCode = "low_contrast"
	// IssueTitleBarOverlap flags a visible HUD or menu node whose laid-out bounds overlap the desktop window controls of a hidden title bar.
	IssueTitleBarOverlap ScreenIssueCode = "title_bar_overlap"
	// IssueOutsideSafeArea flags a visible node whose laid-out bounds extend outside a device viewport's safe area.
	IssueOutsideSafeArea ScreenIssueCode = "outside_safe_area"
	// IssueUnknownCustomKind flags a custom node whose kind is absent from ScreenCheckOptions.Custom.
	IssueUnknownCustomKind ScreenIssueCode = "unknown_custom_kind"
)

type ScreenIssueSeverity

type ScreenIssueSeverity uint8

ScreenIssueSeverity classifies whether a ScreenIssue is an error or a warning.

const (
	// SeverityError marks a check failure that should fail game check. This is the zero value.
	SeverityError ScreenIssueSeverity = iota
	// SeverityWarning marks a non-fatal diagnostic (such as localized text cut by overrun).
	SeverityWarning
)

type ScreenNodeDoc

type ScreenNodeDoc struct {
	// ID uniquely identifies this node within the screen. Authored IDs must not contain "/"; ResolveScreen prefixes instanced node IDs with "<instanceID>/".
	ID string `yaml:"id" schema:"required,minLength=1"`
	// Type selects the widget or container kind. Required unless Screen names a reusable screen fragment (version 2).
	Type ScreenNodeType `` /* 269-byte string literal not displayed */
	// Kind names the game-registered custom widget builder in ScreenBuildOptions.Custom for custom nodes.
	Kind string `yaml:"kind,omitempty" schema:"minLength=1"`
	// Screen optionally names another *.screen.yaml file to instance at this node (slash-separated project-relative path, version 2). Instanced nodes receive IDs prefixed with "<id>/". Mutually exclusive with Type.
	Screen string `yaml:"screen,omitempty"`
	// Anchor positions the node relative to the screen or safe area: one of the nine anchor points or fill.
	Anchor ScreenAnchor `` /* 143-byte string literal not displayed */
	// Offset shifts the node from its anchor in virtual points. For right and bottom anchors, positive values inset inward from that edge.
	Offset *ScreenOffsetDoc `yaml:"offset,omitempty"`
	// SafeArea keeps the node inside the display safe area (away from notches and home indicators). Nil defaults to true for non-fill anchors and false for fill.
	SafeArea *bool `yaml:"safeArea,omitempty"`
	// SizeMode selects whether width is fixed ("fixed", the default) or sizes to fit localized text ("fit_text") on label and button nodes.
	SizeMode SizeMode `yaml:"sizeMode,omitempty" schema:"enum=fixed|fit_text"`
	// Width is the node's fixed width in virtual points (0 uses intrinsic or container-determined width).
	Width float32 `yaml:"width,omitempty" schema:"minimum=0"`
	// Height is the node's fixed height in virtual points (0 uses intrinsic or container-determined height).
	Height float32 `yaml:"height,omitempty" schema:"minimum=0"`
	// Padding is the node's inner padding in virtual points (vbox, hbox, grid, flow, aspect_box, scroll, tabs, label, button, prompt, action_bar, text_field, list).
	Padding *ScreenPaddingDoc `yaml:"padding,omitempty"`
	// Spacing is the gap between children of a vbox, hbox, grid, flow, tabs, sprite_row, prompt, action_bar, or list node in virtual points.
	Spacing float32 `yaml:"spacing,omitempty" schema:"minimum=0"`
	// HSpacing overrides horizontal column spacing in virtual points on a grid node (0 uses Spacing).
	HSpacing float32 `yaml:"hSpacing,omitempty" schema:"minimum=0"`
	// VSpacing overrides vertical row spacing in virtual points on a grid node (0 uses Spacing).
	VSpacing float32 `yaml:"vSpacing,omitempty" schema:"minimum=0"`
	// LineSpacing is the cross-axis gap between wrapped lines in virtual points on a flow node.
	LineSpacing float32 `yaml:"lineSpacing,omitempty" schema:"minimum=0"`
	// Justify controls main-axis distribution of extra space on each wrapped line of a flow node: start (default), center, end, or space_between.
	Justify string `yaml:"justify,omitempty" schema:"enum=start|center|end|space_between"`
	// Ratio is the width/height aspect ratio preserved by an aspect_box node (defaults to 1 when omitted).
	Ratio float32 `yaml:"ratio,omitempty" schema:"exclusiveMinimum=0"`
	// Stretch selects how an aspect_box node fits its child: fit (default), cover, width_controls_height, or height_controls_width.
	Stretch string `yaml:"stretch,omitempty" schema:"enum=fit|cover|width_controls_height|height_controls_width"`
	// Vertical enables vertical scrolling on a scroll node (nil defaults to true unless horizontal is true).
	Vertical *bool `yaml:"vertical,omitempty"`
	// Horizontal enables horizontal scrolling on a scroll node.
	Horizontal bool `yaml:"horizontal,omitempty"`
	// Inertia enables drag and wheel coasting inertia on a scroll node (nil defaults to true).
	Inertia *bool `yaml:"inertia,omitempty"`
	// ScrollbarVisible controls scrollbar visibility on a scroll node: auto (default), always, or never.
	ScrollbarVisible string `yaml:"scrollbarVisible,omitempty" schema:"enum=auto|always|never"`
	// TabHeight sets the tab bar height in virtual points on a tabs node (0 defaults to 32).
	TabHeight float32 `yaml:"tabHeight,omitempty" schema:"minimum=0"`
	// TabSpacing sets the gap between tab buttons in virtual points on a tabs node (0 defaults to 6).
	TabSpacing float32 `yaml:"tabSpacing,omitempty" schema:"minimum=0"`
	// Selected sets the initial zero-based active tab index on a tabs node.
	Selected int `yaml:"selected,omitempty" schema:"minimum=0"`
	// TextKey names a localized string in the project's l10n tables (such as "hud.hint.lever") for label, button, touch_button, progress_bar, slider, and toggle nodes. Screen files store localization keys rather than literal text.
	TextKey string `yaml:"textKey,omitempty"`
	// Bind maps supported widget properties to registered game value paths.
	Bind map[string]string `yaml:"bind,omitempty"`
	// AccessibleName is the spoken name for this node. When empty, hosts may use the localized TextKey value.
	AccessibleName string `yaml:"a11yName,omitempty"`
	// AccessibleDescription is supplementary spoken help for this node.
	AccessibleDescription string `yaml:"a11yDescription,omitempty"`
	// AccessibleHidden omits decorative nodes from accessibility traversal.
	AccessibleHidden bool `yaml:"a11yHidden,omitempty"`
	// PlaceholderKey names a localized placeholder string in the project's l10n tables for text_field nodes.
	PlaceholderKey string `yaml:"placeholderKey,omitempty"`
	// MaxLength caps the number of runes a text_field accepts (0 means unlimited).
	MaxLength int `yaml:"maxLength,omitempty" schema:"minimum=0"`
	// Keyboard selects the keyboard hint for a text_field node: text (default), number, email, url, or ascii.
	Keyboard string `yaml:"keyboard,omitempty" schema:"enum=text|number|email|url|ascii"`
	// Secret masks entered characters on a text_field node (for passwords or codes).
	Secret bool `yaml:"secret,omitempty"`
	// OnSubmit names the callback ID in ScreenBuildOptions.OnSubmit invoked when a text_field is submitted.
	OnSubmit string `yaml:"onSubmit,omitempty" schema:"minLength=1"`
	// TitleKey names an optional localization string for the controller_reconnect title.
	TitleKey string `yaml:"titleKey,omitempty"`
	// MessageKey names an optional localization string for controller_reconnect recovery instructions.
	MessageKey string `yaml:"messageKey,omitempty"`
	// PromptAction selects an optional prompt-table action for the controller_reconnect glyph.
	PromptAction string `yaml:"promptAction,omitempty"`
	// Action names the input action displayed by a prompt node.
	Action string `yaml:"action,omitempty" schema:"minLength=1"`
	// Label names an optional localized caption displayed alongside a prompt.
	Label string `yaml:"label,omitempty" schema:"minLength=1"`
	// Actions lists the input actions displayed by an action_bar in authored order.
	Actions []string `yaml:"actions,omitempty" schema:"minItems=1"`
	// FocusOrder sets the explicit keyboard/gamepad focus traversal order (1-based; 0 means not explicitly ordered) on button, touch_button, text_field, slider, and toggle nodes.
	FocusOrder int `yaml:"focusOrder,omitempty" schema:"minimum=0"`
	// PointerFilter controls pointer propagation for pointer-aware custom and panel nodes.
	// stop (the default) consumes a hit, pass reports it without consuming it, and ignore skips the node.
	PointerFilter string `yaml:"pointerFilter,omitempty" schema:"enum=stop|pass|ignore"`
	// TooltipKey names a localized tooltip for a game's tooltip controller.
	TooltipKey string `yaml:"tooltipKey,omitempty"`
	// TouchHitSize is the touch target diameter in virtual points for touch_stick, touch_button, or touch-interactive button, slider, and toggle nodes.
	TouchHitSize float32 `yaml:"touchHitSize,omitempty" schema:"minimum=0"`
	// DeviceClasses optionally restricts the node and its subtree to the listed device classes (for example [phone, tablet]). Empty shows on all devices; nested nodes must overlap their parent's allowed classes.
	DeviceClasses []DeviceClass `yaml:"deviceClasses,omitempty"`
	// Sprite is a project-relative path to a sprite image or atlas file (for example "art/ui/heart.png") for sprite_row and image nodes, followed by refs and game mv.
	Sprite string `yaml:"sprite,omitempty"`
	// SpriteFrame optionally names a frame inside a sprite atlas when Sprite points to an atlas JSON file on a sprite_row or image node.
	SpriteFrame string `yaml:"spriteFrame,omitempty"`
	// Scale selects how an image node draws its sprite: simple (default), nine_slice, or tile.
	Scale ImageScale `yaml:"scale,omitempty" schema:"enum=simple|nine_slice|tile"`
	// SpriteCount is the number of repeated icons in a sprite_row (defaults to 1 when Sprite is set).
	SpriteCount int `yaml:"spriteCount,omitempty" schema:"minimum=0"`
	// Direction selects the primary axis of a list node (vertical default, or horizontal) or flow node (horizontal default, or vertical).
	Direction string `yaml:"direction,omitempty" schema:"enum=vertical|horizontal"`
	// Columns is the number of items per cross-axis lane in a list or grid node (defaults to 1 when omitted).
	Columns int `yaml:"columns,omitempty" schema:"minimum=1"`
	// Item is the project-relative path to the *.screen.yaml fragment instantiated for each row of a list node (required on list nodes).
	Item string `yaml:"item,omitempty"`
	// ItemHeight is the height of each item in virtual points on a list node.
	ItemHeight float32 `yaml:"itemHeight,omitempty" schema:"exclusiveMinimum=0"`
	// ItemWidth is the width of each item in virtual points on a list node.
	ItemWidth float32 `yaml:"itemWidth,omitempty" schema:"exclusiveMinimum=0"`
	// Loop repeats items seamlessly around both ends on a list node (for carousels).
	Loop bool `yaml:"loop,omitempty"`
	// Under is a project-relative path to the image_progress background layer image, drawn in full first.
	Under string `yaml:"under,omitempty"`
	// Progress is a project-relative path to the image_progress fill layer image, revealed by the value along Fill.
	Progress string `yaml:"progress,omitempty"`
	// Over is a project-relative path to the image_progress foreground layer image, drawn in full last.
	Over string `yaml:"over,omitempty"`
	// Fill picks how an image_progress reveals its progress image: left_to_right (the default), right_to_left, top_to_bottom, bottom_to_top, center_h, center_v, clockwise, or counter_clockwise.
	Fill string `` /* 137-byte string literal not displayed */
	// StartAngle is the image_progress radial fill's starting angle in degrees (0 points right, positive is clockwise).
	StartAngle float32 `yaml:"startAngle,omitempty"`
	// Span is the image_progress radial fill's full sweep in degrees (0 defaults to 360).
	Span float32 `yaml:"span,omitempty" schema:"minimum=0,maximum=360"`
	// Min is the range's lower bound (defaults to 0) on image_progress, progress_bar, and slider nodes.
	Min float32 `yaml:"min,omitempty"`
	// Max is the range's upper bound (defaults to 1 when both min and max are 0) on image_progress, progress_bar, and slider nodes.
	Max float32 `yaml:"max,omitempty"`
	// Step is the keyboard and gamepad step increment on slider nodes (0 defaults to (max - min) / 10).
	Step float32 `yaml:"step,omitempty" schema:"minimum=0"`
	// Value is the initial value within [min, max] on image_progress, progress_bar, and slider nodes; game code updates it at runtime.
	Value float32 `yaml:"value,omitempty"`
	// FillColor is an optional CSS color string parsed with core.ParseColor for the filled portion of a progress_bar node.
	FillColor string `yaml:"fillColor,omitempty"`
	// Style picks the visual presentation of a toggle node: checkbox (default) or switch.
	Style string `yaml:"style,omitempty" schema:"enum=checkbox|switch"`
	// Checked sets the initial checked state of a toggle node.
	Checked bool `yaml:"checked,omitempty"`
	// Group optionally assigns a toggle node to a named radio group where turning one toggle on turns others in the same group off.
	Group string `yaml:"group,omitempty" schema:"minLength=1"`
	// FontSize overrides the text font size in virtual points for text-bearing nodes (label, button, touch_button, progress_bar, slider, toggle, prompt, action_bar, text_field).
	FontSize float32 `yaml:"fontSize,omitempty" schema:"minimum=0"`
	// TextColor is an optional CSS color string parsed with core.ParseColor for text-bearing nodes or the thumbstick knob (touch_stick).
	TextColor string `yaml:"textColor,omitempty"`
	// Outline is the text outline width in virtual points for text-bearing nodes (label, button, touch_button, progress_bar, slider, toggle, prompt, action_bar, text_field).
	Outline float32 `yaml:"outline,omitempty" schema:"minimum=0"`
	// OutlineColor is an optional CSS color string parsed with core.ParseColor for the text outline.
	OutlineColor string `yaml:"outlineColor,omitempty"`
	// Shadow is an optional drop shadow offset (x, y) in virtual points for text-bearing nodes.
	Shadow *ScreenOffsetDoc `yaml:"shadow,omitempty"`
	// ShadowColor is an optional CSS color string parsed with core.ParseColor for the text drop shadow.
	ShadowColor string `yaml:"shadowColor,omitempty"`
	// ShadowBlur is an optional drop shadow blur radius in virtual points for platform text.
	ShadowBlur float32 `yaml:"shadowBlur,omitempty" schema:"minimum=0"`
	// Underline draws a line under the node's text when true.
	Underline bool `yaml:"underline,omitempty"`
	// Strike draws a line through the node's text when true.
	Strike bool `yaml:"strike,omitempty"`
	// Wrap controls multi-line wrapping on label and button nodes: none (default), word, word_smart, or arbitrary.
	Wrap string `yaml:"wrap,omitempty" schema:"enum=none|word|word_smart|arbitrary"`
	// Overrun controls how text exceeding its width or maxLines is handled on label and button nodes: clip, ellipsis, or word_ellipsis.
	Overrun string `yaml:"overrun,omitempty" schema:"enum=clip|ellipsis|word_ellipsis"`
	// MaxLines caps the number of visible lines on label and button nodes (0 means unlimited when wrapping, or single line when not wrapping).
	MaxLines int `yaml:"maxLines,omitempty" schema:"minimum=0"`
	// Background is an optional CSS color string parsed with core.ParseColor for canvas nodes other than image_progress. It sets the track color on progress_bar, tints fallback sprite_row icons and the touch_stick ring, and fills other nodes.
	Background string `yaml:"background,omitempty"`
	// CornerRadius is an optional corner radius in virtual points (vbox, hbox, container, label, button, color_rect, prompt, action_bar).
	CornerRadius float32 `yaml:"cornerRadius,omitempty" schema:"minimum=0"`
	// Alpha sets the node's initial opacity from 0 to 1 (nil defaults to 1).
	Alpha *float32 `yaml:"alpha,omitempty" schema:"minimum=0,maximum=1"`
	// ScaleX sets the node's initial horizontal scale about Pivot (nil defaults to 1; negative mirrors).
	ScaleX *float32 `yaml:"scaleX,omitempty"`
	// ScaleY sets the node's initial vertical scale about Pivot (nil defaults to 1; negative mirrors).
	ScaleY *float32 `yaml:"scaleY,omitempty"`
	// Rotation sets the node's initial clockwise rotation in radians about Pivot.
	Rotation float32 `yaml:"rotation,omitempty"`
	// Pivot sets the normalized origin inside the node's bounds for scale and rotation (nil defaults to center 0.5, 0.5).
	Pivot *Pivot `yaml:"pivot,omitempty"`
	// Overrides customizes nodes inside an instanced Screen fragment by their IDs in that fragment (such as "label" or nested "badge/count"). Requires Screen (version 2).
	Overrides map[string]ScreenNodeOverride `yaml:"overrides,omitempty"`
	// States declares named state sets on this node, each overriding fields of nodes in this node's subtree by ID.
	States map[string]ScreenStateSetDoc `yaml:"states,omitempty"`
	// Child is the single child node for aspect_box and scroll nodes.
	Child *ScreenNodeDoc `yaml:"child,omitempty"`
	// Tabs defines the tab pages for a tabs node.
	Tabs []ScreenTabDoc `yaml:"tabs,omitempty" schema:"minItems=1"`
	// Children are nested child nodes for container types (vbox, hbox, grid, flow, container) or extra children appended to an instanced screen fragment.
	Children []ScreenNodeDoc `yaml:"children,omitempty"`
}

ScreenNodeDoc is one node in a *.screen.yaml tree.

func (*ScreenNodeDoc) EffectiveAnchor

func (n *ScreenNodeDoc) EffectiveAnchor() ScreenAnchor

EffectiveAnchor returns n.Anchor, defaulting to AnchorTopLeft when empty.

func (*ScreenNodeDoc) KeepInSafeArea

func (n *ScreenNodeDoc) KeepInSafeArea() bool

KeepInSafeArea reports whether the node stays inside the display safe area. When SafeArea is nil, non-fill anchors default to true and AnchorFill defaults to false.

type ScreenNodeOverride

type ScreenNodeOverride struct {
	// SizeMode overrides whether width is fixed ("fixed") or sizes to fit localized text ("fit_text") on label and button nodes.
	SizeMode *SizeMode `yaml:"sizeMode,omitempty" schema:"enum=fixed|fit_text"`
	// Width overrides the node's fixed width in virtual points (0 uses intrinsic or container-determined width).
	Width *float32 `yaml:"width,omitempty" schema:"minimum=0"`
	// Height overrides the node's fixed height in virtual points (0 uses intrinsic or container-determined height).
	Height *float32 `yaml:"height,omitempty" schema:"minimum=0"`
	// Padding overrides the node's inner padding in virtual points.
	Padding *ScreenPaddingDoc `yaml:"padding,omitempty"`
	// Spacing overrides the gap between children of a vbox, hbox, sprite_row, prompt, or action_bar in virtual points.
	Spacing *float32 `yaml:"spacing,omitempty" schema:"minimum=0"`
	// TextKey overrides the localization text key for label, button, touch_button, progress_bar, slider, and toggle nodes.
	TextKey *string `yaml:"textKey,omitempty"`
	// PlaceholderKey overrides the localization placeholder key for text_field nodes.
	PlaceholderKey *string `yaml:"placeholderKey,omitempty"`
	// Label overrides the localization caption key for prompt nodes.
	Label *string `yaml:"label,omitempty"`
	// TitleKey overrides the localization title key for controller_reconnect nodes.
	TitleKey *string `yaml:"titleKey,omitempty"`
	// MessageKey overrides the localization message key for controller_reconnect nodes.
	MessageKey *string `yaml:"messageKey,omitempty"`
	// FocusOrder overrides the explicit keyboard/gamepad focus order on focusable nodes.
	FocusOrder *int `yaml:"focusOrder,omitempty" schema:"minimum=0"`
	// TouchHitSize overrides the touch target diameter in virtual points for touch-interactive nodes.
	TouchHitSize *float32 `yaml:"touchHitSize,omitempty" schema:"minimum=0"`
	// DeviceClasses overrides which device classes show the node (an empty slice shows on all devices).
	DeviceClasses *[]DeviceClass `yaml:"deviceClasses,omitempty"`
	// Sprite overrides the project-relative path to a sprite image or atlas file for sprite_row and image nodes.
	Sprite *string `yaml:"sprite,omitempty"`
	// SpriteFrame overrides the frame name inside a sprite atlas for sprite_row and image nodes.
	SpriteFrame *string `yaml:"spriteFrame,omitempty"`
	// Scale overrides how an image node draws its sprite: simple, nine_slice, or tile.
	Scale *ImageScale `yaml:"scale,omitempty" schema:"enum=simple|nine_slice|tile"`
	// SpriteCount overrides the number of repeated icons in a sprite_row node.
	SpriteCount *int `yaml:"spriteCount,omitempty" schema:"minimum=0"`
	// Under overrides the image_progress background layer image path.
	Under *string `yaml:"under,omitempty"`
	// Progress overrides the image_progress fill layer image path.
	Progress *string `yaml:"progress,omitempty"`
	// Over overrides the image_progress foreground layer image path.
	Over *string `yaml:"over,omitempty"`
	// Min overrides the range lower bound on image_progress, progress_bar, and slider nodes.
	Min *float32 `yaml:"min,omitempty"`
	// Max overrides the range upper bound on image_progress, progress_bar, and slider nodes.
	Max *float32 `yaml:"max,omitempty"`
	// Step overrides the keyboard and gamepad step increment on slider nodes.
	Step *float32 `yaml:"step,omitempty" schema:"minimum=0"`
	// Value overrides the initial value on image_progress, progress_bar, and slider nodes.
	Value *float32 `yaml:"value,omitempty"`
	// FillColor overrides the CSS fill color string on progress_bar nodes.
	FillColor *string `yaml:"fillColor,omitempty"`
	// Style overrides the visual presentation of a toggle node: checkbox or switch.
	Style *string `yaml:"style,omitempty" schema:"enum=checkbox|switch"`
	// Checked overrides the initial checked state of a toggle node.
	Checked *bool `yaml:"checked,omitempty"`
	// Group overrides the radio group name of a toggle node.
	Group *string `yaml:"group,omitempty"`
	// FontSize overrides the text font size in virtual points.
	FontSize *float32 `yaml:"fontSize,omitempty" schema:"minimum=0"`
	// TextColor overrides the CSS color string for text or a thumbstick knob.
	TextColor *string `yaml:"textColor,omitempty"`
	// Outline overrides the text outline width in virtual points.
	Outline *float32 `yaml:"outline,omitempty" schema:"minimum=0"`
	// OutlineColor overrides the CSS color string for the text outline.
	OutlineColor *string `yaml:"outlineColor,omitempty"`
	// Shadow overrides the text drop shadow offset (x, y) in virtual points.
	Shadow *ScreenOffsetDoc `yaml:"shadow,omitempty"`
	// ShadowColor overrides the CSS color string for the text drop shadow.
	ShadowColor *string `yaml:"shadowColor,omitempty"`
	// ShadowBlur overrides the text drop shadow blur radius in virtual points.
	ShadowBlur *float32 `yaml:"shadowBlur,omitempty" schema:"minimum=0"`
	// Underline overrides whether the node's text is underlined.
	Underline *bool `yaml:"underline,omitempty"`
	// Strike overrides whether the node's text has a strikethrough.
	Strike *bool `yaml:"strike,omitempty"`
	// Wrap overrides the multi-line wrapping mode on label and button nodes: none, word, word_smart, or arbitrary.
	Wrap *string `yaml:"wrap,omitempty" schema:"enum=none|word|word_smart|arbitrary"`
	// Overrun overrides how text exceeding its width or maxLines is handled on label and button nodes: clip, ellipsis, or word_ellipsis.
	Overrun *string `yaml:"overrun,omitempty" schema:"enum=clip|ellipsis|word_ellipsis"`
	// MaxLines overrides the maximum number of visible lines on label and button nodes.
	MaxLines *int `yaml:"maxLines,omitempty" schema:"minimum=0"`
	// Background overrides the CSS background fill color.
	Background *string `yaml:"background,omitempty"`
	// CornerRadius overrides the corner radius in virtual points.
	CornerRadius *float32 `yaml:"cornerRadius,omitempty" schema:"minimum=0"`
	// Alpha overrides the node's initial opacity from 0 to 1.
	Alpha *float32 `yaml:"alpha,omitempty" schema:"minimum=0,maximum=1"`
	// ScaleX overrides the node's initial horizontal scale about Pivot.
	ScaleX *float32 `yaml:"scaleX,omitempty"`
	// ScaleY overrides the node's initial vertical scale about Pivot.
	ScaleY *float32 `yaml:"scaleY,omitempty"`
	// Rotation overrides the node's initial clockwise rotation in radians about Pivot.
	Rotation *float32 `yaml:"rotation,omitempty"`
	// Pivot overrides the normalized transform origin inside the node's bounds.
	Pivot *Pivot `yaml:"pivot,omitempty"`
}

ScreenNodeOverride replaces visual, sizing, text, sprite, color, transform, and device-class fields on a node inside an instanced screen fragment (ScreenNodeDoc.Overrides). Any nil field keeps the instanced node's value; structural fields (id, type, screen, overrides, children) cannot be overridden.

func (ScreenNodeOverride) IsEmpty

func (ov ScreenNodeOverride) IsEmpty() bool

IsEmpty reports whether ov sets no override fields.

type ScreenNodeOverrideDoc

type ScreenNodeOverrideDoc struct {
	// Visible overrides whether the node is shown (true) or hidden (false).
	Visible *bool `yaml:"visible,omitempty"`
	// TextKey overrides the node's localization key (label, button, touch_button, progress_bar, slider, toggle).
	TextKey *string `yaml:"textKey,omitempty" schema:"minLength=1"`
	// TextColor overrides the node's CSS text (or thumbstick knob) color.
	TextColor *string `yaml:"textColor,omitempty" schema:"minLength=1"`
	// Background overrides the node's CSS background (or fallback sprite tint / touch_stick ring) color.
	Background *string `yaml:"background,omitempty" schema:"minLength=1"`
	// Sprite overrides the node's project-relative sprite image or atlas path (sprite_row, image).
	Sprite *string `yaml:"sprite,omitempty" schema:"minLength=1"`
	// SpriteFrame overrides the node's atlas frame name (sprite_row, image).
	SpriteFrame *string `yaml:"spriteFrame,omitempty" schema:"minLength=1"`
	// Offset overrides the node's anchor offset in virtual points (or visual translation offset for box children).
	Offset *ScreenOffsetDoc `yaml:"offset,omitempty"`
	// Width overrides the node's fixed width in virtual points (0 uses intrinsic or container-determined width).
	Width *float32 `yaml:"width,omitempty" schema:"minimum=0"`
	// Height overrides the node's fixed height in virtual points (0 uses intrinsic or container-determined height).
	Height *float32 `yaml:"height,omitempty" schema:"minimum=0"`
}

ScreenNodeOverrideDoc overrides a bounded set of visual and layout properties on a single screen node while a state value is active.

type ScreenNodeType

type ScreenNodeType string

ScreenNodeType identifies the widget or container kind of a ScreenNodeDoc.

const (
	// NodeVBox stacks children vertically.
	NodeVBox ScreenNodeType = "vbox"
	// NodeHBox arranges children horizontally.
	NodeHBox ScreenNodeType = "hbox"
	// NodeGrid arranges children into a fixed-column row-major grid.
	NodeGrid ScreenNodeType = "grid"
	// NodeFlow wraps children horizontally or vertically into lines.
	NodeFlow ScreenNodeType = "flow"
	// NodeAspectBox keeps a single child at a fixed width/height ratio.
	NodeAspectBox ScreenNodeType = "aspect_box"
	// NodeScroll clips and scrolls a single child vertically, horizontally, or both.
	NodeScroll ScreenNodeType = "scroll"
	// NodeTabs displays a focusable horizontal tab bar above the selected tab's child page.
	NodeTabs ScreenNodeType = "tabs"
	// NodeLabel displays localized non-interactive text.
	NodeLabel ScreenNodeType = "label"
	// NodeButton displays a focusable, clickable button.
	NodeButton ScreenNodeType = "button"
	// NodeRichLabel displays localized rich-text markup whose [link=id]...[/link] spans report their link ID when activated.
	NodeRichLabel ScreenNodeType = "rich_label"
	// NodeSpriteRow displays a horizontal row of repeated sprite icons (such as health hearts).
	NodeSpriteRow ScreenNodeType = "sprite_row"
	// NodeColorRect draws a filled rectangle (such as a modal dim backdrop or HUD plate).
	NodeColorRect ScreenNodeType = "color_rect"
	// NodeTouchStick displays an on-screen virtual thumbstick for touch devices.
	NodeTouchStick ScreenNodeType = "touch_stick"
	// NodeTouchButton displays an on-screen circular/rounded touch action button.
	NodeTouchButton ScreenNodeType = "touch_button"
	// NodeContainer groups child nodes with optional device-class filtering or anchored sub-bounds.
	NodeContainer ScreenNodeType = "container"
	// NodeImageProgress displays a read-only progress meter built from layered under/progress/over images with a directional or radial fill.
	NodeImageProgress ScreenNodeType = "image_progress"
	// NodeControllerReconnect declares the screen's native controller-reconnect overlay.
	NodeControllerReconnect ScreenNodeType = "controller_reconnect"
	// NodePrompt displays the current binding for an input action.
	NodePrompt ScreenNodeType = "prompt"
	// NodeActionBar displays an ordered row of prompts for this screen's actions.
	NodeActionBar ScreenNodeType = "action_bar"
	// NodeTextField displays a themed, focusable text entry field backed by native input.
	NodeTextField ScreenNodeType = "text_field"
	// NodeImage displays a sprite image or atlas frame stretched (simple), nine-sliced (nine_slice), or tiled (tile).
	NodeImage ScreenNodeType = "image"
	// NodeProgressBar displays a read-only flat progress bar in [min, max].
	NodeProgressBar ScreenNodeType = "progress_bar"
	// NodeSlider displays a focusable horizontal value slider in [min, max].
	NodeSlider ScreenNodeType = "slider"
	// NodeToggle displays a focusable checkbox or switch boolean control, optionally in a radio group.
	NodeToggle ScreenNodeType = "toggle"
	// NodeList displays a virtualized scrolling list or grid whose rows are instantiated from an item screen fragment.
	NodeList ScreenNodeType = "list"
	// NodeCustom mounts a game-registered CustomWidget built by ScreenBuildOptions.Custom[Kind].
	NodeCustom ScreenNodeType = "custom"
)

func (ScreenNodeType) IsContainer

func (t ScreenNodeType) IsContainer() bool

IsContainer reports whether t can hold child nodes.

type ScreenOffsetDoc

type ScreenOffsetDoc struct {
	// X is the horizontal offset in virtual points.
	X float32 `yaml:"x,omitempty"`
	// Y is the vertical offset in virtual points.
	Y float32 `yaml:"y,omitempty"`
}

ScreenOffsetDoc is an offset from a node's anchor point in virtual points. For right and bottom anchors, positive X and Y values move inward away from that edge.

type ScreenOrientation

type ScreenOrientation string

ScreenOrientation declares which display orientations a screen is designed for.

const (
	// ScreenOrientationAny means the screen adapts to both landscape and portrait viewports (the default when omitted).
	ScreenOrientationAny ScreenOrientation = "any"
	// ScreenOrientationLandscape marks a landscape-only screen; CheckScreen checks landscape reference profiles and skips portrait ones.
	ScreenOrientationLandscape ScreenOrientation = "landscape"
	// ScreenOrientationPortrait marks a portrait-only screen; CheckScreen checks portrait reference profiles and skips landscape ones.
	ScreenOrientationPortrait ScreenOrientation = "portrait"
)

type ScreenPaddingDoc

type ScreenPaddingDoc struct {
	// Top is the top inner padding in virtual points.
	Top float32 `yaml:"top,omitempty" schema:"minimum=0"`
	// Right is the right inner padding in virtual points.
	Right float32 `yaml:"right,omitempty" schema:"minimum=0"`
	// Bottom is the bottom inner padding in virtual points.
	Bottom float32 `yaml:"bottom,omitempty" schema:"minimum=0"`
	// Left is the left inner padding in virtual points.
	Left float32 `yaml:"left,omitempty" schema:"minimum=0"`
}

ScreenPaddingDoc holds inner padding in virtual points.

func (*ScreenPaddingDoc) Edges

func (p *ScreenPaddingDoc) Edges() core.Edges

Edges converts p into core.Edges (returning zero edges when p is nil).

type ScreenReconnectOptions

type ScreenReconnectOptions struct {
	// Visible follows the game's controller-loss state. Nil shows the panel whenever mounted.
	Visible func() bool
	// Text resolves the titleKey and messageKey. It may read a locale signal.
	// Nil shows the keys themselves.
	Text func(key string) string
	// Prompt resolves promptAction to the current device's prompt. Nil omits the glyph.
	Prompt func(action string) input.Prompt
	// Theme styles the panel. Nil uses DefaultTheme.
	Theme *Theme
}

ScreenReconnectOptions binds a screen's controller_reconnect node to the game.

type ScreenScaleMode

type ScreenScaleMode string

ScreenScaleMode selects the Viewport scaling behavior for a screen file.

const (
	// ScreenScaleFit uniformly scales the design canvas to fit inside the window (default).
	ScreenScaleFit ScreenScaleMode = "fit"
	// ScreenScaleFill uniformly scales the design canvas to cover the window.
	ScreenScaleFill ScreenScaleMode = "fill"
	// ScreenScaleStretch scales X and Y independently to fill the window.
	ScreenScaleStretch ScreenScaleMode = "stretch"
	// ScreenScaleInteger uniformly scales by the largest integer factor >= 1 that fits.
	ScreenScaleInteger ScreenScaleMode = "integer"
)

type ScreenStateSetDoc

type ScreenStateSetDoc struct {
	// Default names the initial state value applied when the screen is built; it must be a key in Values.
	Default string `yaml:"default" schema:"required,minLength=1"`
	// Transition optionally names a screen animation clip declared in ScreenDoc.Animations to play when this state changes.
	Transition string `yaml:"transition,omitempty" schema:"minLength=1"`
	// Values maps each state name to per-node field overrides keyed by node ID within the declaring node's subtree.
	Values map[string]map[string]ScreenNodeOverrideDoc `yaml:"values" schema:"required"`
}

ScreenStateSetDoc defines one named state set on a screen node (for example "read" with values "unread" and "read"). Each value maps node IDs inside the declaring node's subtree (including the declaring node itself) to per-node overrides.

type ScreenStateSetInfo

type ScreenStateSetInfo struct {
	// NodeID is the ScreenNodeDoc.ID that declares this state set.
	NodeID string
	// Set is the name of the state set (for example "read").
	Set string
	// Default is the initial state value name.
	Default string
	// Values lists the state value names in sorted order.
	Values []string
	// Transition is the optional animation clip name played when this state changes.
	Transition string
}

ScreenStateSetInfo summarizes one declared state set in a ScreenDoc, in deterministic document and set-name order.

type ScreenTabDoc

type ScreenTabDoc struct {
	// TextKey names a localized string in the project's l10n tables for the tab button label.
	TextKey string `yaml:"textKey" schema:"required,minLength=1"`
	// Child is the optional root widget node shown when this tab is selected.
	Child *ScreenNodeDoc `yaml:"child,omitempty"`
}

ScreenTabDoc defines one tab entry inside a tabs node in a *.screen.yaml document.

type Scroll

type Scroll struct {
	Child            Widget
	Vertical         bool
	Horizontal       bool
	Inertia          bool
	ScrollbarVisible ScrollbarVisibility
	Padding          core.Edges
	Disabled         bool
	FocusOrder       int
	Width            float32
	Height           float32
	MinWidth         float32
	MinHeight        float32
	Flex             float32
	Align            Align
	Hidden           bool
	Nav              NavOverrides
	Background       core.Color
	Border           core.Color
	CornerRadius     float32
	DrawBackground   func(*core.Drawing, core.Bounds)
	FrameDrawer      FrameDrawer
	NineSlice        *NineSlice
	Transform        Transform
	OnContextMenu    func(core.Point)
	// contains filtered or unexported fields
}

Scroll clips and scrolls an arbitrary single Child widget vertically, horizontally, or both, supporting pointer/touch drag with optional inertia and edge bounce, mouse wheel / touchpad events, ScrollTo(widget), and keeping focused descendants visible during SpatialNavigator traversal.

func (*Scroll) Bounds

func (s *Scroll) Bounds() core.Bounds

Bounds returns the scroll container's laid-out rectangle.

func (*Scroll) ChildWidgets

func (s *Scroll) ChildWidgets() []Widget

ChildWidgets returns the scroll container's Child if non-nil.

func (*Scroll) ContentSize

func (s *Scroll) ContentSize() core.Size

ContentSize returns the laid-out size of Child from the most recent Layout.

func (*Scroll) MaxScrollX

func (s *Scroll) MaxScrollX() float32

MaxScrollX returns the maximum horizontal scroll offset in virtual points.

func (*Scroll) MaxScrollY

func (s *Scroll) MaxScrollY() float32

MaxScrollY returns the maximum vertical scroll offset in virtual points.

func (*Scroll) OnWheel

func (s *Scroll) OnWheel(ev core.WheelEvent) bool

OnWheel applies a mouse wheel or touchpad scroll event to enabled scroll axes. Following core.WheelEvent's convention, negative Delta moves content up/left and increases offset. Returns false if no enabled scrollable axis changed or could consume the event.

func (*Scroll) ScrollBy

func (s *Scroll) ScrollBy(dx, dy float32)

ScrollBy shifts the scroll offsets by (dx, dy) virtual points. Non-finite deltas are ignored.

func (*Scroll) ScrollOffset

func (s *Scroll) ScrollOffset() float32

ScrollOffset returns the primary scroll offset (vertical when vertical scrolling is enabled, otherwise horizontal).

func (*Scroll) ScrollOffsetX

func (s *Scroll) ScrollOffsetX() float32

ScrollOffsetX returns the current horizontal scroll offset in virtual points.

func (*Scroll) ScrollOffsetY

func (s *Scroll) ScrollOffsetY() float32

ScrollOffsetY returns the current vertical scroll offset in virtual points.

func (*Scroll) ScrollTo

func (s *Scroll) ScrollTo(w Widget) bool

ScrollTo scrolls the minimum distance along enabled axes so w (Child or a descendant of Child) becomes visible inside the viewport. Calling ScrollTo before Layout queues the scroll until bounds are known. Returns false if w is nil or not inside Child.

func (*Scroll) SetScrollOffset

func (s *Scroll) SetScrollOffset(x, y float32)

SetScrollOffset jumps directly to (x, y) in virtual points, clamping each enabled axis to [0, MaxScroll] and canceling active inertia. Non-finite coordinates leave that axis unchanged.

func (*Scroll) Update

func (s *Scroll) Update(dt time.Duration) bool

Update advances drag inertia decay and edge-bounce physics by dt. Returns true if either scroll offset changed.

func (*Scroll) VelocityX

func (s *Scroll) VelocityX() float32

VelocityX returns the current horizontal inertial scroll velocity in virtual points per second.

func (*Scroll) VelocityY

func (s *Scroll) VelocityY() float32

VelocityY returns the current vertical inertial scroll velocity in virtual points per second.

func (*Scroll) ViewportBounds

func (s *Scroll) ViewportBounds() core.Bounds

ViewportBounds returns the padded inner clipping rectangle in canvas points.

type ScrollAlign

type ScrollAlign uint8

ScrollAlign controls where ScrollList.ScrollTo places the target item inside the viewport.

const (
	// ScrollNearest scrolls by the smallest distance needed to bring the item fully into view.
	ScrollNearest ScrollAlign = iota
	// ScrollStart aligns the item's leading edge with the start of the viewport.
	ScrollStart
	// ScrollCenter centers the item along the scroll axis of the viewport.
	ScrollCenter
	// ScrollEnd aligns the item's trailing edge with the end of the viewport.
	ScrollEnd
)

type ScrollDirection

type ScrollDirection uint8

ScrollDirection selects the primary scrolling axis of a ScrollList.

const (
	// Vertical scrolls items top-to-bottom (the default).
	Vertical ScrollDirection = iota
	// Horizontal scrolls items left-to-right.
	Horizontal
)

func ParseScrollDirection

func ParseScrollDirection(s string) (ScrollDirection, bool)

ParseScrollDirection maps a screen-file direction name ("vertical" or "horizontal") to its ScrollDirection.

func (ScrollDirection) String

func (d ScrollDirection) String() string

String returns the screen-file name of d ("vertical" or "horizontal").

type ScrollList

type ScrollList struct {
	// Direction selects vertical (default) or horizontal scrolling.
	Direction ScrollDirection
	// Columns is the number of items per cross-axis lane (<= 0 defaults to 1).
	// In Vertical mode, Columns is the number of columns per row; in Horizontal mode,
	// Columns is the number of rows per column.
	Columns int
	// ItemCount is the total number of logical items in the virtualized list.
	ItemCount int
	// ItemHeight is the height of each item in virtual points.
	// In Vertical mode, <= 0 defaults to 40. In Horizontal mode with Columns <= 1, <= 0 stretches to viewport height.
	ItemHeight float32
	// ItemWidth is the width of each item in virtual points.
	// In Horizontal mode, <= 0 defaults to ItemHeight (when > 0) or 120. In Vertical mode with Columns <= 1, <= 0 stretches to viewport width.
	ItemWidth float32
	// Spacing is the gap in virtual points between adjacent items along both main and cross axes.
	Spacing float32
	// Padding insets the clipped item viewport inside the list's bounds.
	Padding core.Edges
	// Overscan is the number of extra lines kept materialized before and after the visible viewport (<= 0 defaults to 1).
	Overscan int
	// Loop repeats items seamlessly around both ends for carousels.
	Loop bool
	// NewItem constructs one reusable item widget when the recycling pool needs another slot.
	NewItem func() Widget
	// BindItem populates recycled widget w with data for logical item index (0 <= index < ItemCount).
	BindItem func(w Widget, index int)
	// OnSelect is invoked when an item is clicked, tapped, or activated via keyboard/gamepad confirm.
	OnSelect func(index int)
	// Selected is the currently selected logical item index (-1 for none).
	Selected int
	// Disabled prevents pointer, wheel, and keyboard/gamepad interaction.
	Disabled bool
	// FocusOrder sets explicit focus traversal order (1-based; 0 uses document order).
	FocusOrder int
	// Width, Height, MinWidth, MinHeight, Flex, Align, and Hidden configure layout sizing and visibility.
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	Background     core.Color
	Border         core.Color
	CornerRadius   float32 // 0 uses Theme.CornerRadius; < 0 uses square corners.
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

ScrollList is a virtualized scrolling list or grid with a recycling widget pool. Only items currently inside the viewport plus a small overscan margin are constructed via NewItem and bound via BindItem; as the list scrolls, off-screen item widgets are recycled and rebound to newly visible indices.

ScrollList supports vertical and horizontal scrolling, multi-column grids (Columns), seamless looping carousels (Loop), pointer/touch dragging with inertia and edge bounce, mouse wheel / touchpad scrolling, strict viewport clipping, and keyboard/gamepad focus navigation through SpatialNavigator.

func (*ScrollList) ActiveCount

func (s *ScrollList) ActiveCount() int

ActiveCount returns the number of currently materialized item widgets (visible rows plus overscan).

func (*ScrollList) Bounds

func (s *ScrollList) Bounds() core.Bounds

Bounds returns the list's laid-out rectangle.

func (*ScrollList) ChildWidgets

func (s *ScrollList) ChildWidgets() []Widget

ChildWidgets returns the currently materialized item widgets in visual order.

func (*ScrollList) FocusedIndex

func (s *ScrollList) FocusedIndex() int

FocusedIndex returns the logical index of the currently focused item, or -1 if none is focused.

func (*ScrollList) Invalidate

func (s *ScrollList) Invalidate()

Invalidate marks the list's items dirty so visible rows are rebound and laid out again.

func (*ScrollList) ItemAt

func (s *ScrollList) ItemAt(p core.Point) int

ItemAt returns the logical index of the visible item containing p inside the clipped viewport, or -1 if none.

func (*ScrollList) ItemBounds

func (s *ScrollList) ItemBounds(index int) core.Bounds

ItemBounds returns the laid-out bounds of logical item index if currently materialized, or zero Bounds otherwise.

func (*ScrollList) MaxScroll

func (s *ScrollList) MaxScroll() float32

MaxScroll returns the maximum scroll offset in virtual points for a non-looping list (0 when content fits inside the viewport or when ItemCount <= 0).

func (*ScrollList) OnWheel

func (s *ScrollList) OnWheel(ev core.WheelEvent) bool

OnWheel applies a mouse wheel or touchpad scroll event to the list. Following core.WheelEvent's convention, Delta moves the content (negative Delta.Y moves content up and increases vertical scroll offset; negative Delta.X moves content left and increases horizontal scroll offset). In Horizontal mode, Delta.Y is used as a fallback when Delta.X is zero.

func (*ScrollList) PoolCount

func (s *ScrollList) PoolCount() int

PoolCount returns the number of recycled item widgets waiting in the pool.

func (*ScrollList) Refresh

func (s *ScrollList) Refresh()

Refresh marks all materialized item widgets dirty so BindItem is invoked again for every visible item. If the list has already been laid out, scroll bounds are reconciled and visible items are rebound immediately.

func (*ScrollList) ScrollBy

func (s *ScrollList) ScrollBy(delta float32)

ScrollBy shifts the scroll offset by delta virtual points (positive moves toward later items). Non-finite deltas are ignored.

func (*ScrollList) ScrollOffset

func (s *ScrollList) ScrollOffset() float32

ScrollOffset returns the current main-axis scroll offset in virtual points.

func (*ScrollList) ScrollTo

func (s *ScrollList) ScrollTo(index int, align ScrollAlign)

ScrollTo scrolls so that logical item index is positioned according to align. Out-of-range indices clamp to [0, ItemCount-1] for non-looping lists and wrap modulo ItemCount for looping lists. Calling ScrollTo before the first Layout queues the jump to run as soon as bounds are known.

func (*ScrollList) Select

func (s *ScrollList) Select(index int) bool

Select sets Selected to index (clamped or wrapped when Loop is enabled) and invokes OnSelect. Returns false when the list is disabled or empty.

func (*ScrollList) SetFocusedIndex

func (s *ScrollList) SetFocusedIndex(index int) bool

SetFocusedIndex sets the focused logical item index and scrolls it into view. Passing a negative index clears the focused item. Returns false when the list is disabled or empty.

func (*ScrollList) SetScrollOffset

func (s *ScrollList) SetScrollOffset(offset float32)

SetScrollOffset jumps directly to offset in virtual points, canceling any active inertia. Non-looping lists clamp to [0, MaxScroll()]; looping lists wrap modulo the total loop span. Non-finite values are ignored.

func (*ScrollList) Update

func (s *ScrollList) Update(dt time.Duration) bool

Update advances drag inertia decay and edge-bounce physics by dt. Returns true if the scroll offset changed. Non-positive or non-finite durations are ignored.

func (*ScrollList) Velocity

func (s *ScrollList) Velocity() float32

Velocity returns the current inertial scroll velocity in virtual points per second.

func (*ScrollList) VisibleRange

func (s *ScrollList) VisibleRange() (first, last int)

VisibleRange returns the first and last logical indices of items currently intersecting the viewport, or (-1, -1) when empty or not laid out.

type ScrollbarVisibility

type ScrollbarVisibility uint8

ScrollbarVisibility controls when Scroll renders its scrollbar indicators.

const (
	// ScrollbarAuto displays a scrollbar only when content overflows along that axis (default).
	ScrollbarAuto ScrollbarVisibility = iota
	// ScrollbarAlways always displays scrollbars along enabled axes when the viewport is non-empty.
	ScrollbarAlways
	// ScrollbarNever hides scrollbars even when content overflows.
	ScrollbarNever
)

func ParseScrollbarVisibility

func ParseScrollbarVisibility(s string) (ScrollbarVisibility, bool)

ParseScrollbarVisibility maps a screen-file scrollbar visibility name ("auto", "always", or "never") to ScrollbarVisibility.

func (ScrollbarVisibility) String

func (v ScrollbarVisibility) String() string

String returns the screen-file name of v ("auto", "always", or "never").

type SettingsAction

type SettingsAction struct {
	// Name is the action key stored in save.Settings.Bindings (for example "jump", "left", "pause").
	Name string
	// Label is displayed in the Controls tab; defaults to Name when empty.
	Label string
	// Group identifies actions that may not share a binding. Different groups may share bindings.
	Group string
	// Defaults lists default binding tokens (for example "key:space", "gamepad:south") restored on Reset.
	Defaults []string
	// AllowToggle reports whether the Controls tab offers a per-action Hold to Toggle assist switch for this action.
	AllowToggle bool
	// AllowMash reports whether the Controls tab offers a per-action Hold to Mash assist switch for this action.
	AllowMash bool
}

SettingsAction describes a rebindable input action shown in the Controls tab.

type SettingsAudioBus

type SettingsAudioBus struct {
	// Name is the key inside save.AudioSettings.Groups (for example "music", "sfx", "ui").
	Name string
	// Label is shown next to the slider; defaults to Name when empty.
	Label string
}

SettingsAudioBus describes an audio group slider shown in the Audio tab.

type SettingsConflictPolicy

type SettingsConflictPolicy uint8

SettingsConflictPolicy controls how CaptureBinding resolves a binding used by another action in the same group.

const (
	// ConflictSwap, the default, binds the token to the capturing action and gives the other action the binding of the same device class the capturing action had, or clears the token from the other action when it had none.
	ConflictSwap SettingsConflictPolicy = iota
	// ConflictClear binds the token to the capturing action and removes it from the other action.
	ConflictClear
	// ConflictRefuse leaves every binding unchanged, keeps capturing, and shows SettingsText.ConflictStatus.
	ConflictRefuse
)

type SettingsLocale

type SettingsLocale struct {
	// Tag is the BCP-47 locale tag stored in save.Settings.Locale ("" selects the system default).
	Tag string
	// Label is displayed in the Language tab; defaults to l10n.LanguageName(Tag) or SystemDefault when Tag is empty.
	Label string
}

SettingsLocale describes a selectable language entry in the Language tab.

type SettingsMenu

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

SettingsMenu is a ready-to-use, gameui-based settings screen covering Audio, Video, Controls (rebinding), Language, and Accessibility, persisted via save.DefaultSettingsStore and operable with mouse, touch, keyboard, and gamepad alone.

Example

A SettingsMenu provides ready-to-use Audio, Video, Controls, Language, and Accessibility tabs driven by mouse, touch, keyboard, or gamepad alone.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
	"github.com/nsgo-dev/nsgo/gamepad"
)

func main() {
	menu := gameui.NewSettingsMenu(gameui.SettingsMenuConfig{})
	menu.Layout(core.Bounds{Size: core.Size{Width: 960, Height: 540}})

	// Switch to Video tab with RB and toggle Fullscreen with D-pad Right.
	menu.OnGamepadButton(gamepad.ButtonRB)
	menu.OnGamepadButton(gamepad.ButtonDPadRight)
	fmt.Println(menu.Tab(), menu.Settings().Display.Fullscreen)
}
Output:
video true

func NewSettingsMenu

func NewSettingsMenu(cfg SettingsMenuConfig) *SettingsMenu

NewSettingsMenu constructs a SettingsMenu wired to cfg and ready to draw and receive input.

func (*SettingsMenu) Apply

func (m *SettingsMenu) Apply() error

Apply validates the working settings and dispatches them to Targets, Video (for resolution), and OnApply.

func (*SettingsMenu) Back

func (m *SettingsMenu) Back()

Back cancels capture if active; otherwise invokes OnBack.

func (*SettingsMenu) BeginCapture

func (m *SettingsMenu) BeginCapture(actionName string) bool

BeginCapture enters control-rebinding capture mode for actionName.

func (*SettingsMenu) CancelCapture

func (m *SettingsMenu) CancelCapture()

CancelCapture exits control-rebinding capture mode without modifying bindings.

func (*SettingsMenu) CaptionPreviewPanel

func (m *SettingsMenu) CaptionPreviewPanel() *Panel

CaptionPreviewPanel returns the non-focusable live caption preview panel inside the Accessibility tab.

func (*SettingsMenu) CaptionPreviewState

func (m *SettingsMenu) CaptionPreviewState() CaptionPreviewState

CaptionPreviewState computes the live preview styling and sample caption lines from the menu's current working Accessibility settings.

func (*SettingsMenu) CaptureBinding

func (m *SettingsMenu) CaptureBinding(token string) bool

CaptureBinding assigns token to the currently capturing action, replacing the existing binding of the same input device class (keyboard vs gamepad vs mouse) while keeping other classes intact.

func (*SettingsMenu) CapturingAction

func (m *SettingsMenu) CapturingAction() string

CapturingAction returns the action name currently awaiting a key or gamepad button press, or "".

func (*SettingsMenu) Dirty

func (m *SettingsMenu) Dirty() bool

Dirty reports whether the working settings have unsaved changes.

func (*SettingsMenu) Draw

func (m *SettingsMenu) Draw(d *core.Drawing, bounds core.Bounds)

Draw lays out and renders the settings menu into d within bounds.

func (*SettingsMenu) Err

func (m *SettingsMenu) Err() error

Err returns the last error produced by Load, Apply, or Save.

func (*SettingsMenu) FooterButtons

func (m *SettingsMenu) FooterButtons() (apply, saveBtn, reset, back *Button)

FooterButtons returns the Apply, Save, Reset, and Back buttons in order.

func (*SettingsMenu) HandleAction

func (m *SettingsMenu) HandleAction(action NavAction) bool

HandleAction dispatches a logical NavAction through the menu, supporting slider adjustment, toggle switching, cycle-option stepping on NavLeft/NavRight, and capture cancellation on NavBack.

func (*SettingsMenu) Layout

func (m *SettingsMenu) Layout(bounds core.Bounds)

Layout lays out the menu inside bounds.

func (*SettingsMenu) Navigator

func (m *SettingsMenu) Navigator() *SpatialNavigator

Navigator returns the menu's SpatialNavigator.

func (*SettingsMenu) NextTab

func (m *SettingsMenu) NextTab()

NextTab switches to the next settings tab, wrapping from Accessibility back to Audio.

func (*SettingsMenu) OnGamepadButton

func (m *SettingsMenu) OnGamepadButton(btn gamepad.Button) bool

OnGamepadButton processes a single gamepad button press (rising edge). While capturing a control rebind, any valid button is captured; otherwise D-pad, South (confirm), East (back), and LB/RB (previous/next tab) drive the menu.

func (*SettingsMenu) OnKeyDown

func (m *SettingsMenu) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown handles keyboard navigation, slider/option stepping, and control rebinding capture.

func (*SettingsMenu) OnPointerDown

func (m *SettingsMenu) OnPointerDown(p core.Point) bool

OnPointerDown focuses and presses the control under p.

func (*SettingsMenu) OnPointerMove

func (m *SettingsMenu) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state and drags any active slider.

func (*SettingsMenu) OnPointerUp

func (m *SettingsMenu) OnPointerUp(p core.Point) bool

OnPointerUp finishes any press or slider drag, activating controls released inside their bounds.

func (*SettingsMenu) OnPress

func (m *SettingsMenu) OnPress(ev core.PressEvent) bool

OnPress handles a completed core.PressEvent directly.

func (*SettingsMenu) OnTouch

func (m *SettingsMenu) OnTouch(ev core.TouchEvent) bool

OnTouch routes touch start, move, end, and cancel events to sliders, toggles, and buttons.

func (*SettingsMenu) PrevTab

func (m *SettingsMenu) PrevTab()

PrevTab switches to the previous settings tab, wrapping from Audio to Accessibility.

func (*SettingsMenu) Reset

func (m *SettingsMenu) Reset()

Reset restores all settings to their configured defaults and refreshes the UI.

func (*SettingsMenu) ResetControls

func (m *SettingsMenu) ResetControls()

ResetControls restores all configured actions' bindings, motor assists, and control and camera preferences to their default values.

func (*SettingsMenu) Root

func (m *SettingsMenu) Root() *Root

Root returns the menu's underlying gameui Root.

func (*SettingsMenu) Save

func (m *SettingsMenu) Save() error

Save validates the working settings, persists them through Store (when configured), applies them to Targets/Video/OnApply, and invokes OnSave.

func (*SettingsMenu) SetSettings

func (m *SettingsMenu) SetSettings(s save.Settings)

SetSettings replaces the menu's working settings and refreshes all controls.

func (*SettingsMenu) SetTab

func (m *SettingsMenu) SetTab(tab SettingsTab)

SetTab switches the active settings tab, cancelling any in-progress control capture and updating focus and directional navigation cleanly.

func (*SettingsMenu) SetText

func (m *SettingsMenu) SetText(text SettingsText)

SetText updates the menu's user-visible strings (for example after changing locale).

func (*SettingsMenu) Settings

func (m *SettingsMenu) Settings() save.Settings

Settings returns a deep copy of the menu's current working player settings.

func (*SettingsMenu) StepActions

func (m *SettingsMenu) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions (such as from input.Actions.JustPressed) and dispatches them in deterministic order.

func (*SettingsMenu) StepGamepad

func (m *SettingsMenu) StepGamepad(pads []gamepad.Pad) bool

StepGamepad polls connected gamepads once per frame, driving navigation, tab switching, value adjustment, and control-rebinding capture on button and left-stick rising edges.

func (*SettingsMenu) SyncGamepad

func (m *SettingsMenu) SyncGamepad(pads []gamepad.Pad)

SyncGamepad records the currently held buttons and left-stick position on pads as the baseline without triggering any actions. Call it when opening the menu so buttons held to open the screen do not immediately fire inside it.

func (*SettingsMenu) Tab

func (m *SettingsMenu) Tab() SettingsTab

Tab returns the currently active SettingsTab.

func (*SettingsMenu) TabButton

func (m *SettingsMenu) TabButton(tab SettingsTab) *Button

TabButton returns the tab-bar Button for tab.

func (*SettingsMenu) TabControls

func (m *SettingsMenu) TabControls(tab SettingsTab) []Widget

TabControls returns the ordered focusable widgets inside tab.

type SettingsMenuConfig

type SettingsMenuConfig struct {
	// Store optionally loads initial player settings and persists changes when Save is called.
	Store *save.DefaultSettingsStore
	// Targets optionally receives validated settings via save.Apply when Apply or Save is called.
	Targets save.SettingsTargets
	// Video optionally receives the selected windowed resolution via ApplySettingsResolution whenever Apply or Save runs.
	Video *screen.Video
	// Env optionally supplies the platform environment so the Video tab hides controls that cannot apply on the current platform (hiding Window Mode where screen.CanFullScreen is false and hiding Resolution where screen.SupportsWindowResolution is false) and keeps Window Mode synchronized with Env.FullScreen. When nil, desktop capabilities are assumed unless HideResolution is set.
	Env *core.Env
	// Scope optionally resolves physical key codes to labels in the active layout.
	Scope *core.Scope
	// Initial supplies starting settings when Store is nil (or if Store.Load fails).
	Initial *save.Settings
	// Defaults supplies baseline settings restored by Reset.
	Defaults *save.Settings

	// AudioBuses configures group volume sliders in the Audio tab (defaults to music, sfx, ui).
	AudioBuses []SettingsAudioBus
	// Resolutions configures selectable resolutions in the Video tab (defaults to Native, 960x540, 1280x720, 1920x1080).
	Resolutions []SettingsResolution
	// HideResolution omits the Resolution row from the Video tab even on desktop or when Env is nil.
	HideResolution bool
	// ShowVSync includes the VSync toggle in the Video tab. False by default because NSGo v0.3.4 does not yet expose swap-interval control; enable only when wiring save.DisplaySettings.VSync to a real backend control.
	ShowVSync bool
	// ShowCameraSettings includes the field of view, camera bob, camera sway and motion blur rows (save.CameraSettings) in the Controls tab. Enable it for games with a 3D camera that applies them through SettingsTargets.ApplyCamera.
	ShowCameraSettings bool
	// UseDropdowns uses Dropdown pickers for desktop Video option rows (Window Mode, Resolution, Scale Mode, Quality Preset, and Frame Cap) when Env is nil or Env.Desktop() is true.
	UseDropdowns bool
	// ScaleModes configures scale mode options in the Video tab (defaults to fit, fill, stretch, expand).
	ScaleModes []SettingsOptionItem
	// QualityPresets configures quality preset options in the Video tab (defaults to auto, low, medium, high).
	QualityPresets []SettingsOptionItem
	// FrameCaps configures selectable FPS caps in the Video tab; 0 means uncapped (defaults to 0, 30, 60, 120).
	FrameCaps []int
	// Actions configures rebindable input actions in the Controls tab.
	Actions []SettingsAction
	// OnConflict selects how CaptureBinding resolves a binding used by another action in the same group.
	OnConflict SettingsConflictPolicy
	// DeviceTracker optionally supplies the active controller family for labels.
	DeviceTracker *input.DeviceTracker
	// Locales configures selectable languages in the Language tab.
	Locales []SettingsLocale
	// ColorBlindModes configures color-blind palette modes in the Accessibility tab.
	ColorBlindModes []SettingsOptionItem
	// CaptionSizes configures caption size presets in the Accessibility tab (defaults to small, medium, large, xlarge).
	CaptionSizes []SettingsOptionItem
	// CaptionBackgrounds configures caption backdrop colors in the Accessibility tab (defaults to black, gray, blue, white).
	CaptionBackgrounds []SettingsOptionItem
	// CaptionTextColors configures caption text colors in the Accessibility tab (defaults to white, yellow, cyan, green, black).
	CaptionTextColors []SettingsOptionItem

	// Text customizes displayed labels; unset fields inherit DefaultSettingsText.
	Text SettingsText
	// Theme optionally overrides the Theme used by the menu's Root.
	// When nil, DefaultTheme is used and switches automatically to HighContrastTheme while Accessibility.HighContrast is true.
	Theme *Theme
	// Viewport optionally attaches virtual-resolution scaling to the menu's Root.
	Viewport *Viewport

	// AutoApply dispatches Targets and OnApply immediately whenever any control changes.
	AutoApply bool
	// AutoSave persists changes to Store immediately whenever any control changes.
	AutoSave bool

	// OnChange runs whenever any setting changes in the working copy.
	OnChange func(save.Settings)
	// OnApply runs when Apply or Save applies settings.
	OnApply func(save.Settings) error
	// OnSave runs after Save succeeds.
	OnSave func(save.Settings) error
	// OnReset runs after Reset restores defaults.
	OnReset func(save.Settings)
	// OnBack runs when Back or NavBack is triggered outside capture mode.
	OnBack func()
	// OnResolutionChange runs when the selected resolution changes.
	OnResolutionChange func(SettingsResolution)
}

SettingsMenuConfig configures a ready-to-use SettingsMenu. Every field is optional.

type SettingsOptionItem

type SettingsOptionItem struct {
	Value string
	Label string
}

SettingsOptionItem pairs a persisted setting value with a user-visible display label.

type SettingsResolution

type SettingsResolution struct {
	// ID is persisted in save.Settings.Custom["resolution"] (for example "native" or "1280x720").
	ID string
	// Label is displayed in the Video tab; defaults to ID when empty.
	Label string
	// Width and Height optionally carry the target dimensions in points/pixels (0 for native/auto).
	Width  int
	Height int
}

SettingsResolution describes a selectable resolution entry in the Video tab.

type SettingsTab

type SettingsTab uint8

SettingsTab identifies one of the five built-in sections of a SettingsMenu.

const (
	// SettingsTabAudio edits mute, master volume, audio bus volumes, mono audio, and left/right balance.
	SettingsTabAudio SettingsTab = iota
	// SettingsTabVideo edits window mode, resolution (on desktop), scale mode, integer scale, quality preset, frame cap, and (when enabled via ShowVSync) VSync.
	SettingsTabVideo
	// SettingsTabControls edits keyboard and gamepad action bindings with capture and reset.
	SettingsTabControls
	// SettingsTabLanguage selects the active locale.
	SettingsTabLanguage
	// SettingsTabAccessibility edits captions, SFX captions, text scale, high contrast, reduced motion, screen shake, flash reduction, color-blind mode, game speed, invincibility, auto-aim, and hold-to-toggle.
	SettingsTabAccessibility
)

func (SettingsTab) String

func (t SettingsTab) String() string

String returns the canonical lowercase name of tab.

type SettingsText

type SettingsText struct {
	Title string

	TabAudio         string
	TabVideo         string
	TabControls      string
	TabLanguage      string
	TabAccessibility string

	MuteAll       string
	MasterVolume  string
	MonoAudio     string
	MonoOn        string
	MonoOff       string
	Balance       string
	BalanceLeft   string
	BalanceCenter string
	BalanceRight  string

	WindowMode    string
	Windowed      string
	Fullscreen    string
	Resolution    string
	ScaleMode     string
	IntegerScale  string
	QualityPreset string
	VSync         string
	FrameCap      string
	Uncapped      string

	ControlsHint     string
	CapturePrompt    string
	ConflictStatus   string
	Unbound          string
	ResetControls    string
	ActionToggle     string
	ActionMash       string
	MinPressTime     string
	AcceptDelay      string
	AssistOff        string
	MouseSensitivity string
	StickSensitivity string
	TouchSensitivity string
	GyroSensitivity  string
	InvertX          string
	InvertY          string
	StickDeadZone    string
	TriggerThreshold string
	Vibration        string
	FieldOfView      string
	CameraBob        string
	CameraSway       string
	MotionBlur       string

	LanguageHint  string
	SystemDefault string

	CaptionsSection       string
	AssistSection         string
	Subtitles             string
	DialogueCaptions      string
	ChatterCaptions       string
	SFXCaptions           string
	CaptionSize           string
	CaptionBackground     string
	CaptionOpacity        string
	CaptionTextColor      string
	SpeakerColors         string
	CaptionsOffPreview    string
	PreviewLight          string
	PreviewDark           string
	PreviewSpeaker        string
	PreviewQualifier      string
	PreviewDialogue       string
	PreviewChatterSpeaker string
	PreviewChatter        string
	PreviewSFX            string
	TextScale             string
	HighContrast          string
	ReduceMotion          string
	ScreenShake           string
	ReduceFlashes         string
	ColorBlind            string
	ColorBlindSeverity    string
	GameSpeed             string
	Invincibility         string
	AutoAim               string
	HoldToToggle          string

	Apply string
	Save  string
	Reset string
	Back  string

	SavedStatus   string
	AppliedStatus string
	ResetStatus   string
}

SettingsText holds every user-visible string displayed by SettingsMenu, so a game can localize it. Partial structs passed via SettingsMenuConfig.Text inherit unset fields from DefaultSettingsText.

func DefaultSettingsText

func DefaultSettingsText() SettingsText

DefaultSettingsText returns the English strings used by SettingsMenu.

type SizeMode

type SizeMode string

SizeMode controls whether a node uses a fixed width or sizes horizontally to fit localized text.

const (
	// SizeFixed keeps the node's declared Width (the default when omitted).
	SizeFixed SizeMode = "fixed"
	// SizeFitText expands or contracts width to fit the node's localized text plus horizontal padding.
	SizeFitText SizeMode = "fit_text"
)

type Slider

type Slider struct {
	Label string
	// ValueText formats the current value for a right-aligned readout. The
	// slider reserves a slot wide enough for the formatted Min and Max values
	// so changing the readout never moves the track.
	ValueText      func(value float32) string
	Min            float32
	Max            float32
	Value          float32
	Step           float32
	OnChange       func(value float32)
	Disabled       bool
	Font           core.Font
	Effects        text.TextEffects
	TextColor      core.Color
	Background     core.Color
	FocusOrder     int
	TouchHitSize   float32
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Slider is a horizontal draggable and left/right steppable value control in [Min, Max]. When Min and Max are both 0, the range defaults to [0, 1]. When Step <= 0, keyboard and Adjust steps default to (Max - Min) / 10.

func (*Slider) Bounds

func (s *Slider) Bounds() core.Bounds

Bounds returns the slider's laid-out rectangle.

func (*Slider) Fraction

func (s *Slider) Fraction() float32

Fraction returns the slider's current Value normalized into [0, 1].

func (*Slider) HitBounds

func (s *Slider) HitBounds() core.Bounds

HitBounds returns the slider's interactive hit area, expanded to TouchHitSize when larger than Bounds.

func (*Slider) SetValue

func (s *Slider) SetValue(v float32) bool

SetValue clamps v into [Min, Max], updates Value, and invokes OnChange if Value changed.

func (*Slider) TrackBounds

func (s *Slider) TrackBounds() core.Bounds

TrackBounds returns the slider's interactive track rectangle from the last Layout pass.

type Spacer

type Spacer struct {
	Width     float32
	Height    float32
	MinWidth  float32
	MinHeight float32
	Flex      float32
	Hidden    bool
	Transform Transform
	// contains filtered or unexported fields
}

Spacer reserves empty space inside a VBox or HBox. A zero-value Spacer defaults to Flex: 1 so it expands to push siblings apart; setting Width or Height without Flex creates a fixed gap.

func (*Spacer) Bounds

func (s *Spacer) Bounds() core.Bounds

Bounds returns the spacer's laid-out rectangle.

type SpatialNavigator

type SpatialNavigator struct {
	// Root is the UI root whose focusable widgets are navigated.
	Root *Root
	// WrapAround enables edge wrap-around when no widget exists further in the requested direction.
	WrapAround bool
	// SliderSteps causes NavLeft and NavRight to adjust a focused Slider by -1/+1 step
	// unless an explicit Left/Right neighbor override is configured for that Slider.
	SliderSteps bool
	// OnConfirm is invoked after NavConfirm activates the focused widget (or when Confirm is called).
	OnConfirm func(focused Widget)
	// OnBack is invoked when NavBack is triggered.
	OnBack func()
	// OnFocusChange is invoked whenever navigation moves focus from prev to next.
	OnFocusChange func(prev, next Widget)
	// FocusRing customizes the focus ring drawn by DrawFocusRing (or attached to Root).
	FocusRing *FocusRingStyle
	// Scan configures optional one-switch scanning. Use SetScanOptions to reset the scan clock after changing it.
	Scan ScanOptions
	// contains filtered or unexported fields
}

SpatialNavigator drives 2D spatial focus navigation, explicit neighbor overrides, action-based keyboard/gamepad input, and customizable focus ring rendering over a Root.

Example

A SpatialNavigator moves focus to the nearest widget in the pressed direction, so a grid of buttons works with a d-pad.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	buttons := make([]*gameui.Button, 4)
	row := func(a, b int) gameui.Widget {
		return &gameui.HBox{Spacing: 10, Children: []gameui.Widget{buttons[a], buttons[b]}}
	}
	for i := range buttons {
		buttons[i] = &gameui.Button{Text: fmt.Sprint("slot ", i), Width: 100, Height: 40}
	}
	root := gameui.NewRoot(&gameui.VBox{Spacing: 10, Children: []gameui.Widget{row(0, 1), row(2, 3)}})
	root.Layout(core.Bounds{Size: core.Size{Width: 400, Height: 300}})

	nav := gameui.NewSpatialNavigator(root)
	nav.OnConfirm = func(w gameui.Widget) { fmt.Println("confirm", w.(*gameui.Button).Text) }
	nav.SetFocus(buttons[0])
	for _, a := range []gameui.NavAction{gameui.NavRight, gameui.NavDown, gameui.NavLeft, gameui.NavConfirm} {
		nav.HandleAction(a)
		fmt.Println(a, nav.Focused().(*gameui.Button).Text)
	}
}
Output:
NavRight slot 1
NavDown slot 3
NavLeft slot 2
confirm slot 2
NavConfirm slot 2

func NewSpatialNavigator

func NewSpatialNavigator(root *Root) *SpatialNavigator

NewSpatialNavigator returns a SpatialNavigator attached to root with wrap-around and slider stepping enabled.

func (*SpatialNavigator) Back

func (n *SpatialNavigator) Back() bool

Back triggers the OnBack callback if configured (or closes an open OnScreenKeyboard first).

func (*SpatialNavigator) ClearFocus

func (n *SpatialNavigator) ClearFocus()

ClearFocus clears focus on Root.

func (*SpatialNavigator) ClearOverrides

func (n *SpatialNavigator) ClearOverrides(w Widget)

ClearOverrides removes any navigator-level overrides registered for w.

func (*SpatialNavigator) Confirm

func (n *SpatialNavigator) Confirm() bool

Confirm activates the currently focused widget and calls OnConfirm if configured.

func (*SpatialNavigator) DrawFocusRing

func (n *SpatialNavigator) DrawFocusRing(d *core.Drawing)

DrawFocusRing draws a customizable focus ring around the currently focused widget in Root.

func (*SpatialNavigator) Focused

func (n *SpatialNavigator) Focused() Widget

Focused returns the currently focused widget in Root, or nil.

func (*SpatialNavigator) HandleAction

func (n *SpatialNavigator) HandleAction(action NavAction) bool

HandleAction executes a single NavAction (directional move, slider step, confirm, or back).

func (*SpatialNavigator) Move

func (n *SpatialNavigator) Move(dir NavAction) bool

Move navigates focus in the directional NavAction (NavUp, NavDown, NavLeft, NavRight). It checks explicit per-widget overrides first, then falls back to 2D spatial navigation.

func (*SpatialNavigator) Overrides

func (n *SpatialNavigator) Overrides(w Widget) NavOverrides

Overrides returns the navigator-level overrides registered for w (or zero value if none).

func (*SpatialNavigator) ScanSelect

func (n *SpatialNavigator) ScanSelect() bool

ScanSelect activates the currently highlighted widget when scanning is enabled. It is suitable for a single switch or eye-tracker action.

func (*SpatialNavigator) SetFocus

func (n *SpatialNavigator) SetFocus(w Widget) bool

SetFocus focuses w if it is visible and focusable in Root.

func (*SpatialNavigator) SetOverrides

func (n *SpatialNavigator) SetOverrides(w Widget, ov NavOverrides)

SetOverrides registers explicit directional neighbor overrides for w on this navigator. Navigator overrides take precedence over widget-level Nav fields and automatic spatial search.

func (*SpatialNavigator) SetScanOptions

func (n *SpatialNavigator) SetScanOptions(opts ScanOptions)

SetScanOptions enables or disables one-switch scanning and resets its clock.

func (*SpatialNavigator) Step

func (n *SpatialNavigator) Step(dt time.Duration) bool

Step advances the scanner by fixed simulation time, moving focus through the root's focus order (wrapping from the last widget to the first) rather than by spatial direction, so rows, grids and columns all scan every widget. It returns true when focus moved.

func (*SpatialNavigator) StepActions

func (n *SpatialNavigator) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions using pressed (for example, wrapping input.Actions.JustPressed) and dispatches any triggered actions in deterministic order. Returns true if any action was handled.

type SpriteRow

type SpriteRow struct {
	SpritePath  string
	SpriteFrame string
	Image       core.ImageSource
	Src         core.Bounds
	HasImage    bool
	Count       int
	Spacing     float32
	Color       core.Color
	Width       float32
	Height      float32
	MinWidth    float32
	MinHeight   float32
	Flex        float32
	Align       Align
	Hidden      bool
	Transform   Transform
	// contains filtered or unexported fields
}

SpriteRow displays a horizontal row of repeated sprite icons (such as health hearts or ammo pips).

func (*SpriteRow) Bounds

func (s *SpriteRow) Bounds() core.Bounds

Bounds returns the sprite row's laid-out bounds.

type StateStyle

type StateStyle struct {
	// Box draws the widget's frame in place of the theme's flat colors.
	Box *StyleBox
	// TextColor colors the widget's text.
	TextColor core.Color
	// Offset moves the widget's text, such as one point down while a button is pressed.
	Offset core.Point
}

StateStyle is a widget style's look in one state. A zero field is unset and resolves from another state or the style's base.

type StyleBox

type StyleBox struct {
	// Kind selects which of the fields below draw.
	Kind StyleBoxKind
	// Fill is a flat box's fill color; zero or core.Transparent draws no fill.
	Fill core.Color
	// BorderColor and BorderWidth are a flat box's border, drawn inside its bounds with a width per side.
	BorderColor core.Color
	BorderWidth core.Edges
	// Radius rounds a flat box's corners; the border's inner edge follows each radius less the wider of its two sides.
	Radius CornerRadii
	// Shadow is a flat box's drop shadow; a zero Color draws none.
	Shadow BoxShadow
	// Expand grows the drawn area past the widget's bounds on each side, without changing layout, for frames whose art overhangs.
	Expand core.Edges
	// Image is an image box's nine-slice frame.
	Image NineSlice
	// Color and Thickness are a line box's color and stroke width in points (0 draws 1 point); Vertical runs it top to bottom instead of left to right.
	Color     core.Color
	Thickness float32
	Vertical  bool
}

StyleBox is a widget frame a theme names once and widget styles reuse: a flat rectangle, a nine-slice image or a line.

func (*StyleBox) Draw

func (b *StyleBox) Draw(d *core.Drawing, bounds core.Bounds)

Draw draws the box into bounds grown by Expand.

type StyleBoxKind

type StyleBoxKind uint8

StyleBoxKind selects how a StyleBox draws.

const (
	// StyleBoxFlat draws a filled rectangle with per-side borders, per-corner radii and a drop shadow.
	StyleBoxFlat StyleBoxKind = iota
	// StyleBoxImage draws a nine-slice image.
	StyleBoxImage
	// StyleBoxLine draws a horizontal or vertical line through the middle of its bounds.
	StyleBoxLine
)

type SystemKeyboard

type SystemKeyboard func(req SystemKeyboardRequest, done func(text string, submitted bool)) bool

SystemKeyboard opens a platform's own text-entry overlay for req, such as Steam's gamepad keyboard on a Steam Deck, and reports whether it opened. When it opened, it calls done exactly once, on the engine goroutine, with the entered text and whether the player submitted it; when it returns false, it never calls done. steamworks.Client.ShowTextInput opens Steam's keyboard in this shape.

type SystemKeyboardRequest

type SystemKeyboardRequest struct {
	// Prompt is the field's placeholder, which Steam's keyboard shows as its description.
	Prompt string
	// Text is the field's current text.
	Text string
	// MaxLength is the field's limit in runes, or 0 for none.
	MaxLength int
	// Multiline reports a TextArea or a multiline TextField.
	Multiline bool
	// Secret reports a field that masks its text, such as a password.
	Secret bool
	// Keyboard is the field's keyboard kind.
	Keyboard KeyboardKind
}

SystemKeyboardRequest describes the text field a SystemKeyboard edits.

type Tab

type Tab struct {
	// Text is the label displayed on the tab bar button.
	Text string
	// TextKey is an optional localization key used by screen files and SetTextLookup.
	TextKey string
	// Child is the page widget displayed when this tab is selected.
	Child Widget
	// Disabled prevents activating or focusing this tab's button.
	Disabled bool
}

Tab defines a single page inside a Tabs container.

type Tabs

type Tabs struct {
	Tabs           []Tab
	Selected       int
	OnChange       func(index int)
	TabHeight      float32
	TabSpacing     float32
	Spacing        float32
	Padding        core.Edges
	ContentPadding core.Edges
	Disabled       bool
	FocusOrder     int
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Background     core.Color
	Border         core.Color
	CornerRadius   float32
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TabFrameDrawer func(index int, active bool) FrameDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Tabs displays a focusable horizontal tab bar above the currently selected tab's Child page. Players switch pages by clicking/tapping tab buttons, focusing the tab bar and pressing Confirm, or triggering NavPrevTab / NavNextTab (LB/RB on gamepads, '[' / ']' on keyboards).

func (*Tabs) Bounds

func (t *Tabs) Bounds() core.Bounds

Bounds returns the tabs container's laid-out rectangle.

func (*Tabs) ChildWidgets

func (t *Tabs) ChildWidgets() []Widget

ChildWidgets returns the tab bar followed by the currently selected tab's Child (if non-nil).

func (*Tabs) NextTab

func (t *Tabs) NextTab() bool

NextTab switches to the next enabled tab, wrapping from the last tab back to the first.

func (*Tabs) PrevTab

func (t *Tabs) PrevTab() bool

PrevTab switches to the previous enabled tab, wrapping from the first tab back to the last.

func (*Tabs) Refresh

func (t *Tabs) Refresh()

Refresh synchronizes tab button labels, disabled state, and active selection with t.Tabs and t.Selected.

func (*Tabs) Select

func (t *Tabs) Select(index int) bool

Select switches the active tab to index (clamped or ignored if out of range / disabled) and invokes OnChange when the selected index changes. Returns true if index is valid and enabled.

func (*Tabs) TabButton

func (t *Tabs) TabButton(index int) *Button

TabButton returns the tab-bar Button for index, or nil if out of range.

func (*Tabs) TabCount

func (t *Tabs) TabCount() int

TabCount returns the number of tabs configured on t.

type TextArea

type TextArea struct {
	// Text is the current committed multi-line text value.
	Text string
	// Placeholder is shown in muted color when Text and any active IME composition are empty.
	Placeholder string
	// MaxLength caps Text in runes; zero or less means unlimited.
	MaxLength int
	// Keyboard hints at the native keyboard type and on-screen keyboard layout.
	Keyboard KeyboardKind
	// Readonly prevents edits while keeping focus, selection, and copy available.
	Readonly bool
	// Disabled prevents focus and editing.
	Disabled bool
	// Filter optionally restricts accepted runes; nil accepts printable runes plus '\n' and '\t'.
	Filter TextFilter
	// Rows controls the intrinsic line count used when Height is 0 (defaults to 4).
	Rows int

	// OnChange is invoked when user input, paste, undo/redo, or the on-screen keyboard modifies Text.
	OnChange func(text string)
	// OnSubmit is invoked on Ctrl/Cmd+Enter or Submit().
	OnSubmit func(text string)
	// OnFocus is invoked when the text area gains focus.
	OnFocus func()
	// OnBlur is invoked when the text area loses focus.
	OnBlur func()

	// TestID optionally sets the TestID on the backing native core.Input when this text area is focused.
	TestID string

	Font             core.Font
	Effects          text.TextEffects
	TextColor        core.Color
	PlaceholderColor core.Color
	Background       core.Color
	Border           core.Color
	CornerRadius     float32
	Padding          core.Edges
	FocusOrder       int
	Width            float32
	Height           float32
	MinWidth         float32
	MinHeight        float32
	Flex             float32
	Align            Align
	Hidden           bool
	Nav              NavOverrides
	DrawBackground   func(*core.Drawing, core.Bounds)
	FrameDrawer      FrameDrawer
	NineSlice        *NineSlice
	TextDrawer       TextDrawer

	Transform Transform
	// contains filtered or unexported fields
}

TextArea is a themed, multi-line text entry widget (for notes, descriptions, or chat) that reuses the same native NSGo input bridge, IME composition, undo, clipboard, and on-screen keyboard as TextField.

func (*TextArea) Backspace

func (t *TextArea) Backspace() bool

Backspace deletes the active selection or the rune before the caret.

func (*TextArea) Bounds

func (t *TextArea) Bounds() core.Bounds

Bounds returns the text area's laid-out rectangle.

func (*TextArea) CanRedo

func (t *TextArea) CanRedo() bool

CanRedo reports whether a redo step is available.

func (*TextArea) CanUndo

func (t *TextArea) CanUndo() bool

CanUndo reports whether an undo step is available.

func (*TextArea) Composing

func (t *TextArea) Composing() bool

Composing reports whether an input method is currently composing text in the text area.

func (*TextArea) Composition

func (t *TextArea) Composition() core.Composition

Composition returns the active IME composition state.

func (*TextArea) Copy

func (t *TextArea) Copy(cx *core.Scope) bool

Copy writes the selected text to the system clipboard.

func (*TextArea) Cut

func (t *TextArea) Cut(cx *core.Scope) bool

Cut copies the selected text to the system clipboard and deletes it unless Readonly is true.

func (*TextArea) Delete

func (t *TextArea) Delete() bool

Delete deletes the active selection or the rune after the caret.

func (*TextArea) Insert

func (t *TextArea) Insert(text string) bool

Insert inserts filtered text at the current caret or replaces the active selection.

func (*TextArea) OpenEditMenu

func (t *TextArea) OpenEditMenu()

OpenEditMenu opens the platform touch edit menu anchored to this text area when backed by AttachInput.

func (*TextArea) Paste

func (t *TextArea) Paste(cx *core.Scope) bool

Paste reads text from the system clipboard and inserts it into the text area.

func (*TextArea) PasteText

func (t *TextArea) PasteText(text string) bool

PasteText filters and inserts pasted text at the current caret or selection.

func (*TextArea) Redo

func (t *TextArea) Redo() bool

Redo re-applies the last undone edit.

func (*TextArea) SelectAll

func (t *TextArea) SelectAll()

SelectAll selects all runes in the text area.

func (*TextArea) Selection

func (t *TextArea) Selection() (start, end int)

Selection returns the current selection or caret range in rune offsets [start, end].

func (*TextArea) SetSelection

func (t *TextArea) SetSelection(start, end int)

SetSelection sets the selection (or caret when start == end) in rune offsets and syncs the native input if focused.

func (*TextArea) SetText

func (t *TextArea) SetText(s string)

SetText sets the text area's text after applying Filter and MaxLength, without firing OnChange.

func (*TextArea) Submit

func (t *TextArea) Submit()

Submit triggers OnSubmit with the current text.

func (*TextArea) Undo

func (t *TextArea) Undo() bool

Undo restores the previous text and selection state.

func (*TextArea) Value

func (t *TextArea) Value() string

Value returns the text area's current committed text.

type TextDrawParams

type TextDrawParams struct {
	Text     string
	X, Y     float32
	Font     core.Font
	Color    core.Color
	Effects  text.TextEffects
	Align    core.TextAlign
	Baseline core.TextBaseline
	// MaxWidth is the available inner text width in points when > 0.
	MaxWidth float32
	// Wrap is the widget's wrapping mode (WrapDefault and WrapNone draw a single line).
	Wrap text.Wrap
	// Overrun is the widget's truncation policy when text exceeds MaxWidth or MaxLines.
	Overrun text.Overrun
	// MaxLines caps the number of drawn lines when > 0.
	MaxLines int
	Bounds   core.Bounds
}

TextDrawParams carries the text string, anchor position, font, color, effects, alignment, baseline, wrapping, overrun, line limit, and widget bounds passed to a custom TextDrawer hook.

type TextDrawer

type TextDrawer func(d *core.Drawing, params TextDrawParams)

TextDrawer renders widget text into d, allowing custom bitmap or stylized font renderers without circular imports.

type TextField

type TextField struct {
	// Text is the current committed text value.
	Text string
	// Placeholder is shown in muted color when Text and any active IME composition are empty.
	Placeholder string
	// MaxLength caps Text in runes; zero or less means unlimited.
	MaxLength int
	// Keyboard hints at the native keyboard type and on-screen keyboard layout.
	Keyboard KeyboardKind
	// Secret masks displayed characters (as for a password) and disables copy/cut.
	Secret bool
	// Multiline allows newline input and multi-line display; prefer TextArea for dedicated multi-line notes.
	Multiline bool
	// Readonly prevents edits while keeping focus, selection, and copy available.
	Readonly bool
	// Disabled prevents focus and editing.
	Disabled bool
	// Filter optionally restricts accepted runes; nil accepts printable runes (plus '\n' when Multiline).
	Filter TextFilter

	// OnChange is invoked when user input, paste, undo/redo, or the on-screen keyboard modifies Text.
	OnChange func(text string)
	// OnSubmit is invoked when the user submits the field (Enter in single-line, Ctrl/Cmd+Enter in multiline, or Submit()).
	OnSubmit func(text string)
	// OnFocus is invoked when the field gains focus.
	OnFocus func()
	// OnBlur is invoked when the field loses focus.
	OnBlur func()

	// TestID optionally sets the TestID on the backing native core.Input when this field is focused.
	TestID string

	Font             core.Font
	Effects          text.TextEffects
	TextColor        core.Color
	PlaceholderColor core.Color
	Background       core.Color
	Border           core.Color
	CornerRadius     float32
	Padding          core.Edges
	FocusOrder       int
	Width            float32
	Height           float32
	MinWidth         float32
	MinHeight        float32
	Flex             float32
	Align            Align
	Hidden           bool
	Nav              NavOverrides
	DrawBackground   func(*core.Drawing, core.Bounds)
	FrameDrawer      FrameDrawer
	NineSlice        *NineSlice
	TextDrawer       TextDrawer

	Transform Transform
	// contains filtered or unexported fields
}

TextField is a themed, focusable single-line (or multi-line when Multiline is true) text entry widget drawn in the gameui canvas and backed by a hidden native NSGo Input when attached via Root.AttachInput.

func (*TextField) Backspace

func (t *TextField) Backspace() bool

Backspace deletes the active selection or the rune before the caret.

func (*TextField) Bounds

func (t *TextField) Bounds() core.Bounds

Bounds returns the text field's laid-out rectangle.

func (*TextField) CanRedo

func (t *TextField) CanRedo() bool

CanRedo reports whether a redo step is available.

func (*TextField) CanUndo

func (t *TextField) CanUndo() bool

CanUndo reports whether an undo step is available.

func (*TextField) Composing

func (t *TextField) Composing() bool

Composing reports whether an input method is currently composing text in the field.

func (*TextField) Composition

func (t *TextField) Composition() core.Composition

Composition returns the active IME composition state.

func (*TextField) Copy

func (t *TextField) Copy(cx *core.Scope) bool

Copy writes the selected text to the system clipboard unless Secret is true.

func (*TextField) Cut

func (t *TextField) Cut(cx *core.Scope) bool

Cut copies the selected text to the system clipboard and deletes it unless Secret or Readonly is true.

func (*TextField) Delete

func (t *TextField) Delete() bool

Delete deletes the active selection or the rune after the caret.

func (*TextField) Insert

func (t *TextField) Insert(text string) bool

Insert inserts filtered text at the current caret or replaces the active selection.

func (*TextField) OpenEditMenu

func (t *TextField) OpenEditMenu()

OpenEditMenu opens the platform touch edit menu (Cut, Copy, Paste, Select All) anchored to this field when backed by AttachInput.

func (*TextField) Paste

func (t *TextField) Paste(cx *core.Scope) bool

Paste reads text from the system clipboard and inserts it into the field.

func (*TextField) PasteText

func (t *TextField) PasteText(text string) bool

PasteText filters and inserts pasted text at the current caret or selection.

func (*TextField) Redo

func (t *TextField) Redo() bool

Redo re-applies the last undone edit.

func (*TextField) SelectAll

func (t *TextField) SelectAll()

SelectAll selects all runes in the field.

func (*TextField) Selection

func (t *TextField) Selection() (start, end int)

Selection returns the current selection or caret range in rune offsets [start, end].

func (*TextField) SetSelection

func (t *TextField) SetSelection(start, end int)

SetSelection sets the selection (or caret when start == end) in rune offsets and syncs the native input if focused.

func (*TextField) SetText

func (t *TextField) SetText(s string)

SetText sets the field's text after applying Filter and MaxLength, without firing OnChange.

func (*TextField) Submit

func (t *TextField) Submit()

Submit triggers OnSubmit with the current text.

func (*TextField) Undo

func (t *TextField) Undo() bool

Undo restores the previous text and selection state.

func (*TextField) Value

func (t *TextField) Value() string

Value returns the field's current committed text.

type TextFilter

type TextFilter func(rune) bool

TextFilter reports whether a rune may be entered into a TextField or TextArea.

type TextInputOptions

type TextInputOptions struct {
	// MaxLength limits the text to this many runes; zero or less means no limit.
	MaxLength int
	// PrintableOnly removes control characters (Unicode category Cc, which includes C0, DEL and C1).
	PrintableOnly bool
	// Secret asks the native field to hide the text, as for a password.
	Secret bool
	// Keyboard is the native keyboard hint.
	Keyboard KeyboardKind
}

TextInputOptions describes portable validation before a native input bridge applies text.

type TextMeasurer

type TextMeasurer func(text string, font core.Font) (width, height float32)

TextMeasurer measures text width and height for layout when using a custom TextDrawer.

func BitmapFontMeasurer

func BitmapFontMeasurer(font *text.Font) TextMeasurer

BitmapFontMeasurer returns a TextMeasurer backed by font.Measure, scaling the bitmap font to each requested core.Font.Size when font.Size > 0.

func DrawingTextMeasurer

func DrawingTextMeasurer(d *core.Drawing) TextMeasurer

DrawingTextMeasurer returns a TextMeasurer backed by d.MeasureText and d.TextMetrics.

func SDFFontMeasurer

func SDFFontMeasurer(font *text.SDFFont) TextMeasurer

SDFFontMeasurer returns a TextMeasurer backed by font.Measure at the requested core.Font.Size.

type Theme

type Theme struct {
	// TextScale multiplies every widget font size, the default Font and per-widget overrides alike, during layout and draw; it is clamped to [MinTextScale, MaxTextScale], and 0 means 1. Root.TextScale, when set, replaces it.
	TextScale float32
	// PanelBackground and PanelBorder style Panel containers.
	PanelBackground core.Color
	PanelBorder     core.Color

	// Background, Hover, Active, Disabled, Border, and FocusedBorder style interactive controls.
	Background    core.Color
	Hover         core.Color
	Active        core.Color
	FocusedBorder core.Color
	Disabled      core.Color
	Border        core.Color

	// Text, DisabledText, MutedText, Accent, AccentHover, AccentActive, and Track style labels, toggles, sliders, and progress bars.
	Text         core.Color
	DisabledText core.Color
	MutedText    core.Color
	Accent       core.Color
	AccentHover  core.Color
	AccentActive core.Color
	Track        core.Color

	// Padding is the default inner padding used for widget intrinsic sizing and spacing.
	Padding float32
	// CornerRadius is the default corner radius for rounded widget surfaces.
	CornerRadius float32
	// BorderWidth is the stroke width for widget borders.
	BorderWidth float32
	// FocusWidth is the stroke width for the focused outline.
	FocusWidth float32
	// Font is the default font used by text-bearing widgets.
	Font core.Font
	// TextEffects is the default outline, drop shadow, underline, and strikethrough applied to text-bearing widgets.
	TextEffects text.TextEffects

	// PanelFrame optionally draws stylized or nine-slice frames for Panel widgets.
	PanelFrame FrameDrawer
	// ButtonFrame optionally draws stylized or nine-slice frames for Button widgets.
	ButtonFrame FrameDrawer
	// FrameDrawer optionally draws stylized or nine-slice frames when a widget has no specific frame drawer.
	FrameDrawer FrameDrawer
	// TextDrawer optionally replaces default Canvas FillText rendering (for example, with a bitmap font renderer).
	TextDrawer TextDrawer
	// TextMeasurer optionally provides text dimensions for layout when using a custom TextDrawer.
	TextMeasurer TextMeasurer
	// FocusRing optionally customizes the focus ring drawn around focused widgets.
	FocusRing *FocusRingStyle
	// Styles holds per-state looks keyed by widget type (StyleTypeButton, StyleTypeLabel, StyleTypePanel) and by variation name; a widget's Variation field picks a variation. A widget with no style keeps the flat fields above.
	Styles map[string]WidgetStyle
	// contains filtered or unexported fields
}

Theme holds the colors, spacing, corner radius, borders, and default font used to lay out and draw a game UI.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme returns a high-contrast dark theme suited for in-game overlays and menus.

func HighContrastTheme

func HighContrastTheme() Theme

HighContrastTheme returns a high-contrast dark gameui Theme suitable when Accessibility.HighContrast is enabled.

type Toggle

type Toggle struct {
	Label          string
	Checked        bool
	Style          ToggleStyle
	OnChange       func(checked bool)
	Disabled       bool
	Font           core.Font
	Effects        text.TextEffects
	TextColor      core.Color
	Background     core.Color
	FocusOrder     int
	TouchHitSize   float32
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

Toggle is a focusable boolean checkbox or switch control.

Example

A Toggle flips when activated and reports the change through OnChange.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	sound := &gameui.Toggle{Label: "Sound", Checked: true, Height: 40, OnChange: func(on bool) { fmt.Println("sound:", on) }}
	root := gameui.NewRoot(&gameui.VBox{Children: []gameui.Widget{sound}})
	root.Layout(core.Bounds{Size: core.Size{Width: 200, Height: 100}})
	root.SetFocus(sound)
	root.Activate()
	fmt.Println(sound.Checked)
}
Output:
sound: false
false

func (*Toggle) Bounds

func (t *Toggle) Bounds() core.Bounds

Bounds returns the toggle's laid-out rectangle.

func (*Toggle) HitBounds

func (t *Toggle) HitBounds() core.Bounds

HitBounds returns the toggle's interactive hit area, expanded to TouchHitSize when larger than Bounds.

type ToggleStyle

type ToggleStyle uint8

ToggleStyle picks the visual presentation of a Toggle widget.

const (
	// ToggleCheckbox draws a square checkbox with a checkmark when checked.
	ToggleCheckbox ToggleStyle = iota
	// ToggleSwitch draws a sliding pill switch.
	ToggleSwitch
)

func ParseToggleStyle

func ParseToggleStyle(s string) (ToggleStyle, bool)

ParseToggleStyle maps a screen-file toggle style ("checkbox" or "switch") to its ToggleStyle, reporting whether s was recognized.

func (ToggleStyle) String

func (s ToggleStyle) String() string

String returns the screen-file name of s ("checkbox" or "switch").

type Tooltip

type Tooltip struct {
	Content func() Widget
	Delay   time.Duration
}

Tooltip describes delayed content shown while a widget is hovered or focused.

type TooltipState

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

TooltipState tracks hover time without rendering policy. Tick returns the tooltip content once Delay has elapsed and keeps it visible until Reset.

func (*TooltipState) Reset

func (s *TooltipState) Reset()

Reset hides the tooltip and clears elapsed hover time.

func (*TooltipState) Set

func (s *TooltipState) Set(tip *Tooltip)

Set starts tracking a tooltip. A nil tooltip clears the state.

func (*TooltipState) Tick

func (s *TooltipState) Tick(dt time.Duration) Widget

Tick advances the hover timer and returns the visible content, if any.

func (*TooltipState) Visible

func (s *TooltipState) Visible() Widget

Visible reports the currently shown tooltip content.

type TouchButton

type TouchButton struct {
	Text       string
	HitSize    float32
	OnClick    func()
	Disabled   bool
	Font       core.Font
	Effects    text.TextEffects
	TextColor  core.Color
	Background core.Color
	FocusOrder int
	Nav        NavOverrides
	Width      float32
	Height     float32
	MinWidth   float32
	MinHeight  float32
	Flex       float32
	Align      Align
	Hidden     bool
	TextDrawer TextDrawer
	Transform  Transform
	// contains filtered or unexported fields
}

TouchButton is an on-screen circular touch action button with an expanded touch hit target.

func (*TouchButton) Bounds

func (b *TouchButton) Bounds() core.Bounds

Bounds returns the touch button's visual bounds.

func (*TouchButton) HitBounds

func (b *TouchButton) HitBounds() core.Bounds

HitBounds returns the touch button's interactive hit area, expanded to HitSize when larger than Bounds.

type TouchStick

type TouchStick struct {
	HitSize   float32
	BaseColor core.Color
	KnobColor core.Color
	ValueX    float32
	ValueY    float32
	OnMove    func(x, y float32)
	Disabled  bool
	Width     float32
	Height    float32
	MinWidth  float32
	MinHeight float32
	Flex      float32
	Align     Align
	Hidden    bool
	Transform Transform
	// contains filtered or unexported fields
}

TouchStick is an on-screen virtual thumbstick with an optional expanded circular touch hit area.

func (*TouchStick) Bounds

func (t *TouchStick) Bounds() core.Bounds

Bounds returns the stick's visual bounds.

func (*TouchStick) HitBounds

func (t *TouchStick) HitBounds() core.Bounds

HitBounds returns the stick's interactive touch target bounds, expanded to HitSize when larger than Bounds.

type Transform

type Transform struct {
	// X is the horizontal translation offset in virtual points.
	X float32
	// Y is the vertical translation offset in virtual points.
	Y float32
	// ScaleX scales the widget horizontally about Pivot; nil defaults to 1 and negative mirrors.
	ScaleX *float32
	// ScaleY scales the widget vertically about Pivot; nil defaults to 1 and negative mirrors.
	ScaleY *float32
	// Rotation rotates the widget clockwise in radians about Pivot.
	Rotation float32
	// Alpha multiplies the widget and its subtree's opacity in [0, 1]; nil defaults to 1.
	Alpha *float32
	// Pivot sets the normalized origin inside the widget's bounds for Scale and Rotation; nil defaults to (0.5, 0.5).
	Pivot *Pivot
}

Transform holds per-node visual and hit-test transform properties applied around Pivot on top of a widget's laid-out bounds during drawing and pointer hit testing.

The zero value is the identity transform:

  • Alpha == nil means fully opaque (1); pointing to 0 means fully transparent.
  • ScaleX == nil and ScaleY == nil mean unscaled (1); pointing to 0 collapses that axis.
  • Pivot == nil defaults to the center of the widget's bounds (0.5, 0.5).
  • X and Y translate the widget and its children in virtual points.
  • Rotation turns the widget clockwise in radians about Pivot.

func WidgetTransform

func WidgetTransform(w Widget) *Transform

WidgetTransform returns a pointer to w's per-node Transform, or nil if w does not carry one.

func (*Transform) ApplyPoint

func (t *Transform) ApplyPoint(bounds core.Bounds, local core.Point) core.Point

ApplyPoint transforms local (in the widget's untransformed layout space) into parent space.

func (*Transform) EffectiveAlpha

func (t *Transform) EffectiveAlpha() float32

EffectiveAlpha returns the transform's opacity clamped into [0, 1], defaulting to 1 when nil or NaN.

func (*Transform) EffectivePivot

func (t *Transform) EffectivePivot() Pivot

EffectivePivot returns the transform's normalized pivot, defaulting to the center (0.5, 0.5) when nil or non-finite.

func (*Transform) EffectiveScaleX

func (t *Transform) EffectiveScaleX() float32

EffectiveScaleX returns the transform's horizontal scale, defaulting to 1 when nil or non-finite.

func (*Transform) EffectiveScaleY

func (t *Transform) EffectiveScaleY() float32

EffectiveScaleY returns the transform's vertical scale, defaulting to 1 when nil or non-finite.

func (*Transform) HasSpatialTransform

func (t *Transform) HasSpatialTransform() bool

HasSpatialTransform reports whether t translates, scales, or rotates a widget away from its laid-out bounds.

func (*Transform) InvertPoint

func (t *Transform) InvertPoint(bounds core.Bounds, parent core.Point) (core.Point, bool)

InvertPoint maps parent (in parent space) back into the widget's untransformed layout space. It returns (zero, false) when ScaleX or ScaleY is zero (collapsed to zero area).

func (*Transform) IsIdentity

func (t *Transform) IsIdentity() bool

IsIdentity reports whether t leaves both spatial placement and opacity unchanged.

func (*Transform) PivotPoint

func (t *Transform) PivotPoint(bounds core.Bounds) (px, py float32)

PivotPoint returns the pivot's coordinates in parent space for a widget laid out into bounds.

func (*Transform) SetAlpha

func (t *Transform) SetAlpha(v float32)

SetAlpha sets t.Alpha clamped into [0, 1], reusing the pointer when already allocated. Non-finite NaN values default to 1.

func (*Transform) SetPivot

func (t *Transform) SetPivot(x, y float32)

SetPivot sets the normalized pivot inside the widget's bounds, reusing the pointer when already allocated.

func (*Transform) SetScale

func (t *Transform) SetScale(sx, sy float32)

SetScale sets both ScaleX and ScaleY, reusing their pointers when already allocated.

func (*Transform) SetScaleX

func (t *Transform) SetScaleX(v float32)

SetScaleX sets t.ScaleX, reusing the pointer when already allocated.

func (*Transform) SetScaleY

func (t *Transform) SetScaleY(v float32)

SetScaleY sets t.ScaleY, reusing the pointer when already allocated.

type VBox

type VBox struct {
	Children       []Widget
	Spacing        float32
	Padding        core.Edges
	Align          Align
	Justify        Justify
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	Transform      Transform
	OnContextMenu  func(core.Point)
	// contains filtered or unexported fields
}

VBox arranges Children vertically from top to bottom with Spacing and Padding.

func (*VBox) Bounds

func (b *VBox) Bounds() core.Bounds

Bounds returns the VBox's laid-out rectangle.

func (*VBox) ChildWidgets

func (b *VBox) ChildWidgets() []Widget

ChildWidgets returns the VBox's direct children.

type Viewport

type Viewport struct {
	VirtualWidth  float32
	VirtualHeight float32
	WindowWidth   float32
	WindowHeight  float32
	ScaleMode     ScaleMode
	// LetterboxColor fills letterbox/pillarbox bars in Draw and DrawLetterbox.
	// Zero defaults to opaque black; set core.Transparent to skip drawing bars.
	LetterboxColor core.Color
}

Viewport maps a fixed virtual UI resolution onto a physical window size with scaling, letterboxing, drawing transform setup, and window-to-virtual coordinate conversion.

Example

A Viewport fits a fixed virtual resolution into the window, adding bars on the sides that do not fit, and maps window points back to virtual ones.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	vp := gameui.NewViewport(320, 180, gameui.ScaleFit).WithWindowSize(1280, 1024)
	fmt.Println(vp.Scale(), vp.Rect())
	fmt.Println(len(vp.LetterboxBars()))
	p, inside := vp.WindowToVirtual(core.Point{X: 640, Y: 512})
	fmt.Println(p, inside)
}
Output:
4 {{0 152} {1280 720}}
2
{160 90} true

func NewViewport

func NewViewport(virtualW, virtualH float32, mode ScaleMode) Viewport

NewViewport returns a Viewport configured for virtualW x virtualH using mode.

func (Viewport) Apply

func (v Viewport) Apply(d *core.Drawing)

Apply clips d to VisibleBounds and applies the viewport's translation and scale transform. Callers should wrap Apply in d.Save() / d.Restore().

func (Viewport) Draw

func (v Viewport) Draw(d *core.Drawing, drawFn func(d *core.Drawing, virtualBounds core.Bounds))

Draw renders letterbox bars, sets up the viewport clip and transform inside Save/Restore, and invokes drawFn with the virtual canvas bounds.

func (Viewport) DrawLetterbox

func (v Viewport) DrawLetterbox(d *core.Drawing)

DrawLetterbox fills any active letterbox/pillarbox bars into d unless LetterboxColor is core.Transparent.

func (Viewport) LetterboxBars

func (v Viewport) LetterboxBars() []core.Bounds

LetterboxBars returns the non-empty, non-overlapping bar rectangles inside the window outside Rect().

func (Viewport) Rect

func (v Viewport) Rect() core.Bounds

Rect returns the projected virtual canvas rectangle in physical window coordinates. For ScaleFill, Rect may extend outside [0, WindowWidth] x [0, WindowHeight].

func (Viewport) Scale

func (v Viewport) Scale() float32

Scale returns the uniform scale factor (or min(sx, sy) for ScaleStretch).

func (Viewport) ScaleXY

func (v Viewport) ScaleXY() (sx, sy float32)

ScaleXY returns the horizontal and vertical scale factors from virtual coordinates to window coordinates.

func (*Viewport) SetWindowSize

func (v *Viewport) SetWindowSize(size core.Size)

SetWindowSize updates the viewport's physical window dimensions.

func (Viewport) VirtualBounds

func (v Viewport) VirtualBounds() core.Bounds

VirtualBounds returns the layout rectangle in virtual coordinates: (0, 0, VirtualWidth, VirtualHeight).

func (Viewport) VirtualToWindow

func (v Viewport) VirtualToWindow(p core.Point) core.Point

VirtualToWindow maps a point in virtual coordinates into physical window coordinates.

func (Viewport) VisibleBounds

func (v Viewport) VisibleBounds() core.Bounds

VisibleBounds returns the intersection of Rect() with the window bounds [0, WindowWidth] x [0, WindowHeight]. For ScaleFit and ScaleInteger this equals Rect(); for ScaleFill it equals the full window bounds.

func (Viewport) WindowToVirtual

func (v Viewport) WindowToVirtual(p core.Point) (core.Point, bool)

WindowToVirtual maps a physical window point into virtual coordinates. ok is false when p falls outside the active viewport (for example, inside letterbox/pillarbox bars or outside the window).

func (Viewport) WithWindowSize

func (v Viewport) WithWindowSize(w, h float32) Viewport

WithWindowSize returns a copy of v with WindowWidth and WindowHeight set to w and h.

type VirtualViewport

type VirtualViewport = Viewport

VirtualViewport is an alias for Viewport.

type Widget

type Widget interface {
	// Bounds returns the widget's rectangle from the last Layout pass.
	Bounds() core.Bounds
	// contains filtered or unexported methods
}

Widget is a node in a game UI layout and focus tree.

type WidgetState

type WidgetState struct {
	Hovered  bool
	Pressed  bool
	Focused  bool
	Disabled bool
}

WidgetState describes the current interaction state of a widget during Draw or StateOf queries.

type WidgetStyle

type WidgetStyle struct {
	// Base names the style type (such as StyleTypeButton) or the variation this one extends; a widget type's own style leaves it empty.
	Base string
	// Normal, Hover, Pressed, Disabled and Focus are the looks of each state.
	Normal   StateStyle
	Hover    StateStyle
	Pressed  StateStyle
	Disabled StateStyle
	Focus    StateStyle
	// Font overrides the theme's Font field by field, the variation's over its base's; a widget's own Font overrides the result.
	Font core.Font
}

WidgetStyle is the look of a widget type, or of a named variation of one, in each state.

A property resolves state by state: a pressed widget looks for it in Pressed, then Hover, then Normal; a hovered one in Hover, then Normal; a disabled one in Disabled, then Normal. Within each state the variation is searched before its Base, so a variation that sets only Normal still takes its base type's Hover and Pressed. Focus takes only a Box, drawn over the focused widget in place of the focus ring.

type WorldAnchor

type WorldAnchor struct {
	// ID uniquely identifies this anchor inside an AnchorOverlay.
	ID string
	// WorldX and WorldY are the anchor's coordinates in 2D game world space.
	WorldX, WorldY float32
	// OffsetX and OffsetY shift the anchored view in screen points after world projection.
	OffsetX, OffsetY float32
	// AnchorX and AnchorY position the view relative to the projected point as fractions of the view's own size:
	// (0, 0) = top-left at point, (0.5, 0.5) = centered on point, (0.5, 1.0) = centered directly above point.
	AnchorX, AnchorY float32
	// Visible toggles whether this anchor is shown when on-screen.
	Visible bool
	// View builds the native NSGo view mounted at this anchor's screen position.
	View func(*core.Scope) core.View
	// TestID optionally assigns a TestID to the positioned anchor wrapper view.
	TestID string
}

WorldAnchor binds a native NSGo View (such as a name tag, speech bubble, or text input) to a 2D world position with optional screen-space pixel offset and normalized anchor pivot.

func NewWorldAnchor

func NewWorldAnchor(id string, worldX, worldY float32, view func(*core.Scope) core.View) *WorldAnchor

NewWorldAnchor returns a visible WorldAnchor at (worldX, worldY) rendering view.

type WorldProjection

type WorldProjection struct {
	// WorldToScreen converts a world position (worldX, worldY) to screen/window coordinates (screenX, screenY).
	WorldToScreen func(worldX, worldY float32) (screenX, screenY float32)
	// ScreenBounds is the visible screen rectangle in window coordinates.
	// When non-zero, projected positions outside ScreenBounds are treated as off-screen and hidden.
	ScreenBounds core.Bounds
}

WorldProjection maps 2D game world coordinates into screen/window coordinates and defines the visible screen bounds used to automatically hide off-screen world anchors.

func NewCameraViewportProjection

func NewCameraViewportProjection(camX, camY, zoom, viewW, viewH float32, vp Viewport) WorldProjection

NewCameraViewportProjection creates a WorldProjection combining a 2D camera centered at (camX, camY) with zoom and view dimensions (viewW, viewH) with a virtual-resolution Viewport (including scaling and letterboxing). Points projecting into letterbox bars or outside the window fall outside ScreenBounds.

func NewWorldProjection

func NewWorldProjection(worldToScreen func(worldX, worldY float32) (screenX, screenY float32), screenBounds core.Bounds) WorldProjection

NewWorldProjection constructs a WorldProjection from a custom projection function and visible screen bounds.

func (WorldProjection) Project

func (p WorldProjection) Project(worldX, worldY float32) (pt core.Point, onScreen bool)

Project maps (worldX, worldY) to screen coordinates and reports whether the projected point is on-screen.

Jump to

Keyboard shortcuts

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