stdui

package module
v0.0.0-...-f8f51e7 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package stdui provides a Go SDK for controlling a stdui subprocess.

stdui is a lightweight GUI framework that renders HTML content via an external binary. The controlling application communicates with the binary over stdin/stdout using newline-delimited JSON messages.

Basic usage:

client, err := stdui.Start("./build/game", stdui.Settings{
    Title:        "My App",
    WindowWidth:  ptr(800),
    WindowHeight: ptr(600),
})
if err != nil {
    log.Fatal(err)
}

client.OnReady(func() {
    client.UpdateContent("<h1>Hello</h1>")
})
client.OnInputChanged(func(id, value string) {
    fmt.Println(id, "=", value)
})

client.Wait()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnsureBinary

func EnsureBinary(binaryPath string, destDir string) error

EnsureBinary checks whether the stdui binary already exists at binaryPath and downloads it from the latest GitHub release if not. The contents of the "release/" folder inside the zip are extracted directly into destDir.

binaryPath is the path to check and write the binary to, e.g. "./stdui". Pass an empty string to use the platform default ("stdui" or "stdui.exe") inside destDir. Pass "" for destDir to use the current working directory.

On macOS and Linux the binary is made executable automatically. The function is a no-op if the binary is already present.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v. Useful for populating optional pointer fields in Settings without declaring intermediate variables.

client, _ := stdui.Start("./build/game", stdui.Settings{
    WindowWidth:  stdui.Ptr(800),
    WindowHeight: stdui.Ptr(600),
    BaseFontSize: stdui.Ptr(16.0),
})

Types

type Client

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

Client manages a stdui subprocess and exposes a typed API for sending commands and receiving events.

func Start

func Start(binaryPath string, settings Settings) (*Client, error)

Start spawns the stdui binary at the given path, sends the initial settings, and begins reading events from the subprocess stdout. Handlers may be registered before or after Start — any handler registered before the corresponding event arrives will be called.

The binary path may be absolute or relative to the working directory of the calling process.

func StartWithNamedPipe

func StartWithNamedPipe(binaryPath string, pipePath string, settings Settings) (*Client, error)

StartWithNamedPipe spawns the stdui binary with the --pipe flag, waits for it to create the named pipe, connects to it, sends the initial settings, and begins reading events.

On Unix/macOS, pipePath is the filesystem path of the Unix domain socket that stdui creates as the pipe backend, e.g. "/tmp/myapp.pipe". FIFOs are not used because they cannot carry bidirectional IPC reliably.

On Windows, pipePath must be a valid Windows named-pipe path of the form \\.\pipe\<name>, e.g. `\\.\pipe\myapp`.

The binary path may be absolute or relative to the working directory of the calling process.

func StartWithSocket

func StartWithSocket(binaryPath string, socketPath string, settings Settings) (*Client, error)

StartWithSocket spawns the stdui binary with the --socket flag, waits for it to create the Unix domain socket (or Windows AF_UNIX socket), connects to it, sends the initial settings, and begins reading events.

The socket file is created by the stdui process; the caller must not create it beforehand. The file is removed by stdui on shutdown.

socketPath is the filesystem path for the socket, e.g. "/tmp/myapp.sock". On Windows this must be a path on a local volume; the same Windows 10 1803+ AF_UNIX support that stdui relies on is used here.

The binary path may be absolute or relative to the working directory of the calling process.

func (*Client) Close

func (c *Client) Close() error

Close instructs stdui to close the window and exit cleanly. stdui will emit a window-closed event in response. It is safe to call from any goroutine.

func (*Client) Confirm

func (c *Client) Confirm(req ConfirmRequest) error

Confirm opens a modal dialog in the stdui window with the given question and two buttons. The result is delivered asynchronously via the handler registered with OnConfirmResult. It is safe to call from any goroutine.

func (*Client) GetClipboardText

func (c *Client) GetClipboardText() error

GetClipboardText requests the current system clipboard text from stdui. stdui responds asynchronously with a clipboard-text-result event, which is delivered to the handler registered via OnClipboardTextResult. It is safe to call from any goroutine.

func (*Client) GetValue

func (c *Client) GetValue(id string) error

GetValue requests the current value of an interactive element by id. stdui responds asynchronously with a value-result event, which is delivered to the handler registered via OnValueResult. It is safe to call from any goroutine.

func (*Client) Maximize

func (c *Client) Maximize() error

Maximize maximizes the stdui window. It is safe to call from any goroutine.

func (*Client) Minimize

func (c *Client) Minimize() error

Minimize minimizes the stdui window. It is safe to call from any goroutine.

func (*Client) OnButtonClicked

func (c *Client) OnButtonClicked(fn func(attrs map[string]string, pane string))

OnButtonClicked registers a callback invoked when the user clicks a ui-button. attrs contains all HTML attributes of the button, including "action" and "text". pane is the id of the pane the button belongs to.

func (*Client) OnClipboardTextResult

func (c *Client) OnClipboardTextResult(fn func(text string))

OnClipboardTextResult registers a callback invoked in response to a GetClipboardText call. text is the current system clipboard contents.

func (*Client) OnConfirmResult

func (c *Client) OnConfirmResult(fn func(id string, result bool))

OnConfirmResult registers a callback invoked when the user dismisses a confirm dialog. id is the identifier from the originating Confirm call; result is true if the user clicked OK and false if they clicked Cancel.

func (*Client) OnError

func (c *Client) OnError(fn func(err error))

OnError registers a callback invoked when a message from stdui cannot be parsed. If not registered, parse errors are silently dropped.

func (*Client) OnFileDropped

func (c *Client) OnFileDropped(fn func(path string))

OnFileDropped registers a callback invoked once per file when the user drags and drops files onto the stdui window. path is the absolute path to the dropped file.

func (*Client) OnInputChanged

func (c *Client) OnInputChanged(fn func(id, value, pane string))

OnInputChanged registers a callback invoked when the user commits a change to any interactive element (ui-input, ui-select, ui-slider, ui-checkbox, ui-textarea). id is the element's id attribute; value is the new value as a string (checkboxes use "true" / "false"); pane is the id of the pane the element belongs to.

func (*Client) OnKeyPressed

func (c *Client) OnKeyPressed(fn func(id string))

OnKeyPressed registers a callback invoked when a registered keyboard shortcut is activated. id is the application-defined identifier supplied when the shortcut was registered via SetKeybinds.

func (*Client) OnLog

func (c *Client) OnLog(fn func(namespace, message string))

OnLog registers a callback invoked for every internal log message emitted by stdui. namespace is the subsystem that produced the message (e.g. "Main", "Raylib"). Defaults to no-op if not registered.

func (*Client) OnReady

func (c *Client) OnReady(fn func())

OnReady registers a callback invoked once after stdui has fully initialized and is ready to receive content. This is the correct place to call UpdateContent for the first time.

func (*Client) OnURLClicked

func (c *Client) OnURLClicked(fn func(url, pane string))

OnURLClicked registers a callback invoked when the user clicks a hyperlink inside any pane. url is the href value; pane is the id of the pane the link was clicked in.

func (*Client) OnUnknown

func (c *Client) OnUnknown(fn func(action string, raw json.RawMessage))

OnUnknown registers a callback invoked for any action not recognised by the SDK. raw is the unparsed JSON data payload. Useful for forward-compatibility with newer stdui versions.

func (*Client) OnValueResult

func (c *Client) OnValueResult(fn func(id, value string))

OnValueResult registers a callback invoked in response to a GetValue call. id is the element id that was requested; value is its current value.

func (*Client) OnWindowClosed

func (c *Client) OnWindowClosed(fn func())

OnWindowClosed registers a callback invoked when the stdui window is closed, either by the user or by calling Close. The callback fires before Wait returns.

func (*Client) PlaySound

func (c *Client) PlaySound(file string) error

PlaySound plays the sound file at the given path through stdui's audio system. The path may be absolute or relative to the stdui working directory. It is safe to call from any goroutine.

func (*Client) ScrollTo

func (c *Client) ScrollTo(pane string, y float64) error

ScrollTo scrolls the named pane to an absolute vertical pixel offset. It is safe to call from any goroutine.

func (*Client) ScrollToBottom

func (c *Client) ScrollToBottom(pane string) error

ScrollToBottom scrolls the named pane to the bottom. It is safe to call from any goroutine.

func (*Client) ScrollToTop

func (c *Client) ScrollToTop(pane string) error

ScrollToTop scrolls the named pane to the top. It is safe to call from any goroutine.

func (*Client) SetClipboardText

func (c *Client) SetClipboardText(text string) error

SetClipboardText writes the given text to the system clipboard. It is safe to call from any goroutine.

func (*Client) SetFPS

func (c *Client) SetFPS(fps int) error

SetFPS updates the target frame rate at runtime. Values of 0 or below are ignored by stdui. It is safe to call from any goroutine.

func (*Client) SetKeybinds

func (c *Client) SetKeybinds(keybinds []KeybindRequest) error

SetKeybinds registers a set of keyboard shortcuts with stdui. Calling this action replaces any previously registered keybinds. When a registered shortcut is activated, stdui emits a key-pressed event carrying the keybind's ID.

It is safe to call from any goroutine.

func (*Client) SetPaneLayout

func (c *Client) SetPaneLayout(root *PaneNode) error

SetPaneLayout sends a set-pane-layout action to stdui, replacing the current layout with the given tree. Use the Pane, HSplit, and VSplit constructors to build the tree. It is safe to call from any goroutine.

func (*Client) SetPosition

func (c *Client) SetPosition(x, y int) error

SetPosition moves the stdui window to the given screen coordinates. It is safe to call from any goroutine.

func (*Client) SetTitle

func (c *Client) SetTitle(title string) error

SetTitle updates the window title bar text at runtime. It is safe to call from any goroutine.

func (*Client) SetValue

func (c *Client) SetValue(id, value string) error

SetValue programmatically sets the value of an interactive element by id. It is safe to call from any goroutine.

func (*Client) SetVolume

func (c *Client) SetVolume(volume float64) error

SetVolume updates the sound effects volume at runtime. The value is clamped to the range [0.0, 1.0] by stdui. It is safe to call from any goroutine.

func (*Client) SetWindowIcon

func (c *Client) SetWindowIcon(path string) error

SetWindowIcon sets the window icon from a single image file. The file must be a format supported by raylib (PNG, BMP, TGA, JPG, …). It is safe to call from any goroutine.

func (*Client) SetWindowIcons

func (c *Client) SetWindowIcons(paths []string) error

SetWindowIcons sets the window icon from multiple image files, allowing the OS to pick the most appropriate resolution. The files must be in a format supported by raylib (PNG, BMP, TGA, JPG, …). It is safe to call from any goroutine.

func (*Client) Toast

func (c *Client) Toast(req ToastRequest) error

Toast displays a short-lived notification window anchored to the top-center of the stdui display. Toasts stack downward and disappear after their TTL expires or when the user double-clicks inside them. It is safe to call from any goroutine.

func (*Client) UpdateContent

func (c *Client) UpdateContent(html string) error

UpdateContent sets the HTML content rendered in the stdui window. It is safe to call from any goroutine.

func (*Client) UpdatePaneContent

func (c *Client) UpdatePaneContent(pane, html string) error

UpdatePaneContent sets the HTML content of a specific named pane. The pane must exist in the current layout set via SetPaneLayout. It is safe to call from any goroutine.

func (*Client) Wait

func (c *Client) Wait()

Wait blocks until the stdui window is closed (either by the user or by calling Close). It is safe to call from any goroutine.

func (*Client) WaitContext

func (c *Client) WaitContext(ctx context.Context) error

WaitContext blocks until the stdui window is closed or ctx is cancelled, whichever comes first. If ctx is cancelled before the window closes, WaitContext closes stdin (causing stdui to exit) and returns ctx.Err(). It is safe to call from any goroutine.

type ColorScheme

type ColorScheme struct {
	// Text is the primary foreground color.
	Text string `json:"text,omitempty"`
	// TextMuted is the secondary / muted foreground color.
	TextMuted string `json:"textMuted,omitempty"`
	// WindowBg is the background color of all pane windows.
	WindowBg string `json:"windowBg,omitempty"`
	// ElementBg is the default background color for interactive elements.
	ElementBg string `json:"elementBg,omitempty"`
	// ElementHovered is the background color when hovering an interactive element.
	ElementHovered string `json:"elementHovered,omitempty"`
	// ElementActive is the background color when pressing an interactive element.
	ElementActive string `json:"elementActive,omitempty"`
	// TitleBg is the background color of window title bars.
	TitleBg string `json:"titleBg,omitempty"`
	// Border is the color used for element and window borders.
	Border string `json:"border,omitempty"`
	// Primary is the accent / brand color used for buttons and highlights.
	Primary string `json:"primary,omitempty"`
	// Warn is the color used for warning indicators.
	Warn string `json:"warn,omitempty"`
	// Danger is the color used for destructive actions and error indicators.
	Danger string `json:"danger,omitempty"`
	// PrimaryTranslucent is a semi-transparent variant of Primary.
	PrimaryTranslucent string `json:"primaryTranslucent,omitempty"`
	// PrimarySubtle is a very lightly tinted variant of Primary for backgrounds.
	PrimarySubtle string `json:"primarySubtle,omitempty"`
	// TextSelectionBg is the background color of selected text.
	TextSelectionBg string `json:"textSelectionBg,omitempty"`
	// ModalDim is the overlay color behind modal dialogs.
	ModalDim string `json:"modalDim,omitempty"`
}

ColorScheme configures the UI color palette. All fields are hex color strings (e.g. "#1f2328" or "#0969da"). Omitted fields fall back to the built-in light theme defaults.

type ConfirmRequest

type ConfirmRequest struct {
	// ID is an opaque identifier echoed back in the confirm-result response.
	ID string
	// Question is the message shown inside the dialog.
	Question string
	// Title is the dialog heading. Defaults to "Confirm" when empty.
	Title string
	// OKText is the label for the confirmation button. Defaults to "OK" when empty.
	OKText string
	// CancelText is the label for the cancellation button. Defaults to "Cancel" when empty.
	CancelText string
}

ConfirmRequest holds the parameters for a confirm dialog. ID and Question are required; the remaining fields are optional and fall back to sensible defaults when left as empty strings.

type KeybindRequest

type KeybindRequest struct {
	// ID is an application-defined identifier echoed back in key-pressed events.
	ID string `json:"id"`
	// Key is the primary key name, case-insensitive.
	// Examples: "s", "f5", "escape", "enter", "space", "tab",
	//           "delete", "home", "end", "pageup", "pagedown",
	//           "left", "right", "up", "down",
	//           "0"–"9", "a"–"z", "f1"–"f12".
	Key string `json:"key"`
	// Ctrl requires the Ctrl key to be held.
	Ctrl bool `json:"ctrl,omitempty"`
	// Shift requires the Shift key to be held.
	Shift bool `json:"shift,omitempty"`
	// Alt requires the Alt key to be held.
	Alt bool `json:"alt,omitempty"`
	// Meta requires the Super/Cmd key to be held.
	Meta bool `json:"meta,omitempty"`
}

KeybindRequest describes a single keyboard shortcut to register. ID and Key are required. Modifier fields default to false when omitted.

type PaneNode

type PaneNode struct {
	Type      PaneNodeType       `json:"type"`
	ID        string             `json:"id,omitempty"`
	Direction PaneSplitDirection `json:"direction,omitempty"`
	Size      float64            `json:"size,omitempty"`
	Children  []*PaneNode        `json:"children,omitempty"`
}

PaneNode is one node in a pane layout tree. Set Type to PaneNodeTypePane for a leaf pane (requires ID) or PaneNodeTypeSplit for an interior split (requires Direction and Children). Size is a relative weight used by the parent split (defaults to 1 when zero).

func HSplit

func HSplit(children []*PaneNode, size ...float64) *PaneNode

HSplit is a convenience constructor that returns a horizontal split PaneNode with the given children and an optional relative size weight (defaults to 1).

func Pane

func Pane(id string, size ...float64) *PaneNode

Pane is a convenience constructor that returns a leaf PaneNode with the given id and optional relative size weight.

func VSplit

func VSplit(children []*PaneNode, size ...float64) *PaneNode

VSplit is a convenience constructor that returns a vertical split PaneNode with the given children and an optional relative size weight (defaults to 1).

type PaneNodeType

type PaneNodeType string

PaneNodeType identifies whether a PaneNode is a leaf pane or an interior split.

const (
	// PaneNodeTypePane is a leaf pane that renders HTML content.
	PaneNodeTypePane PaneNodeType = "pane"
	// PaneNodeTypeSplit is an interior node that divides its space among children.
	PaneNodeTypeSplit PaneNodeType = "split"
)

type PaneSplitDirection

type PaneSplitDirection string

PaneSplitDirection controls how a split node arranges its children.

const (
	// PaneSplitHorizontal arranges children left-to-right.
	PaneSplitHorizontal PaneSplitDirection = "horizontal"
	// PaneSplitVertical arranges children top-to-bottom.
	PaneSplitVertical PaneSplitDirection = "vertical"
)

type Settings

type Settings struct {
	// Title is the window title bar text. Defaults to "StdUI".
	Title string `json:"title,omitempty"`

	// Resizable controls whether the window can be resized. Defaults to true.
	Resizable *bool `json:"resizable,omitempty"`

	// WindowWidth is the initial window width in pixels. Defaults to 800.
	WindowWidth *int `json:"windowWidth,omitempty"`

	// WindowHeight is the initial window height in pixels. Defaults to 600.
	WindowHeight *int `json:"windowHeight,omitempty"`

	// WindowMinWidth is the minimum allowed window width in pixels. Defaults to 400.
	WindowMinWidth *int `json:"windowMinWidth,omitempty"`

	// WindowMinHeight is the minimum allowed window height in pixels. Defaults to 300.
	WindowMinHeight *int `json:"windowMinHeight,omitempty"`

	// WindowMaxWidth is the maximum allowed window width in pixels. Defaults to 3840.
	WindowMaxWidth *int `json:"windowMaxWidth,omitempty"`

	// WindowMaxHeight is the maximum allowed window height in pixels. Defaults to 2160.
	WindowMaxHeight *int `json:"windowMaxHeight,omitempty"`

	// BaseFontSize is the base UI font size in pixels. Defaults to 16.0.
	BaseFontSize *float64 `json:"baseFontSize,omitempty"`

	// AudioVolume is the audio volume level (0.0–1.0). Defaults to 1.0.
	AudioVolume *float64 `json:"audioVolume,omitempty"`

	// TargetFPS is the target frame rate in frames per second. Defaults to 60.
	TargetFPS *int `json:"targetFps,omitempty"`

	// FontRegular is the path to the regular font file.
	FontRegular string `json:"fontRegular,omitempty"`

	// FontBold is the path to the bold font file.
	FontBold string `json:"fontBold,omitempty"`

	// FontItalic is the path to the italic font file.
	FontItalic string `json:"fontItalic,omitempty"`

	// FontBoldItalic is the path to the bold-italic font file.
	FontBoldItalic string `json:"fontBoldItalic,omitempty"`

	// ColorScheme overrides the built-in light theme. Omit to use the default.
	ColorScheme *ColorScheme `json:"colorScheme,omitempty"`
}

Settings configures the stdui window and renderer. All fields are optional; omitted fields use stdui's built-in defaults.

type ToastRequest

type ToastRequest struct {
	// Content is the HTML to render inside the toast.
	Content string
	// Width is the toast window width in pixels. Defaults to 300 when zero.
	Width float64
	// Height is the toast window height in pixels. Defaults to 80 when zero.
	Height float64
	// TTL is the time-to-live in seconds. Defaults to 3 when zero.
	TTL float64
}

ToastRequest holds the parameters for a toast notification. Content is required; all other fields are optional and fall back to sensible defaults when left as zero values.

Jump to

Keyboard shortcuts

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