core

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 30 Imported by: 0

README

ui/core

English | 简体中文

The foundation for all interface modules:

Name Function
Widget Interface: Something that can Layout. All components and containers implement it
Func Use a Gio layout function as a component
DecodeImage(ctx, source) Read local/HTTP/data images, limit encoding size and number of pixels; must be called in the background and manage timeout. ReadImageSource / DecodeImageBytes are two steps of disassembly. The Image of the kit is used to decode SVG and GIF animations at the same time
Update(fn) Modify the interface from any goroutine: fn is executed in the next frame
Call(gtx, fn) For those who write components: execute user callbacks and let all windows redraw
Semantic(gtx, w, ops...), Role(...) For those who write components: declare the role, name, and status of the component so that the Agent can see it
Bind, BindIn, Bindings, BindingsIn Key table: action name to shortcut key, the context of BindIn can write conditional expressions (Editor && !ReadOnly, Pane > Editor), see Menu · Context Conditional Expression
CurrentScrollGesture, ReportScrollGesture Scrolling device (wheel/trackpad) and gesture stage; ui/window reads reports from macOS, Wayland, Carousel and other components
WindowControls, CurrentWindow() The component gets the activation status of the window where it is located, title area registration, minimize, maximize, close capabilities, and is used to customize the title bar. ui/window Registers the current window during layout
  • Dependencies: Only depends on Gio, and the internal ui/internal/loop.
  • Used by: el, kit, window, markdown.

Threading rules: Modify components directly in callbacks; modify components in other goroutines and package them into core.Update. See Architecture · Threading Rules for the reason.

ClipboardData, ClipboardImage, ClipboardReader define rich paste exchange data and asynchronous reading interface; core does not read the system clipboard and does not reference native. The application adaptation platform reads the results and is dispatched back to the UI thread by the input component.

Documentation

Overview

Package core is the foundation every UI module builds on: what a Widget is, how a component runs a user callback, and how other goroutines change the UI.

Threading has one rule. All windows render, and all callbacks run, under one lock, so callbacks may change any component directly. Code on other goroutines (timers, network, hotkey callbacks) must wrap changes in Update.

Index

Constants

View Source
const MaxImagePixels = 32_000_000

MaxImagePixels is the largest image, in pixels, that decoding accepts.

Variables

View Source
var ErrNoImageFetcher = errors.New(`network images are not linked in: import _ "github.com/dyike/keel/ui/netimage"`)

ErrNoImageFetcher is returned for http and https sources without a fetcher.

Functions

func Bind

func Bind(action string, chords ...string) error

Bind sets the chords that trigger action, replacing its earlier ones; no chords unbinds it. Chords use ParseShortcut's syntax, e.g. "mod+s". It returns an error, and changes nothing, if a chord is invalid. Every window redraws.

func BindIn

func BindIn(context, action string, chords ...string) error

BindIn sets action's chords where a key context predicate holds: a name such as "Editor", or an expression such as "Editor && !ReadOnly" or "Pane > Editor" (see keymap_predicate.go). No chords explicitly disables the action there, hiding outer and global bindings. An invalid chord or predicate leaves the map unchanged.

func Bindings

func Bindings(action string) []string

Bindings returns the chords bound to action, the first being the one to show in hints; nil if it has none.

func BindingsIn

func BindingsIn(action string, contexts ...string) []string

BindingsIn resolves action along a focus path of KeyContext names, inner to outer: the innermost level where some binding's predicate holds wins, and among bindings matching at that level, the one bound last. With none, the global keymap applies. The result is owned by the caller. An explicit empty binding prevents fallback.

func Call

func Call(gtx C, fn func())

Call runs a user callback from inside Layout and redraws every window, because the callback may have changed components that were already drawn. Components must route every user callback through it.

func ClearBindingIn

func ClearBindingIn(context, action string)

ClearBindingIn removes a contextual override, restoring inheritance.

func DecodeImage

func DecodeImage(ctx context.Context, source string) (image.Image, error)

DecodeImage reads PNG, JPEG, GIF (first frame) and WebP. Size limits apply to encoded input and decoded dimensions, before allocating a pixel buffer. It blocks until completion; call from a worker with a deadline, not during layout.

func DecodeImageBytes added in v0.0.4

func DecodeImageBytes(data []byte) (image.Image, error)

DecodeImageBytes decodes PNG, JPEG, GIF (first frame) or WebP bytes, refusing images larger than DecodeImage allows before allocating them.

func FetchImage added in v0.0.7

func FetchImage(ctx context.Context, url string, header map[string]string) (int, map[string]string, io.ReadCloser, error)

FetchImage downloads url with the installed fetcher.

func Keymap

func Keymap() map[string][]string

Keymap returns a copy of every binding, e.g. for a settings page.

func LoadKeymap

func LoadKeymap(data []byte) error

LoadKeymap binds the actions in a JSON object such as {"editor.save": ["mod+s"], "app.quit": []} on top of the current keymap; an empty list unbinds. Nothing changes if any entry is invalid.

func OpenURL

func OpenURL(raw string) error

OpenURL opens an absolute HTTP, HTTPS or mailto URL using the platform handler. It reports launch errors, not whether the destination subsequently loaded.

func ParseShortcut

func ParseShortcut(s string) (key.Name, key.Modifiers, error)

ParseShortcut reads a key chord such as "mod+s", "ctrl+shift+k" or "esc" into a Gio key name and modifiers. "mod" is Cmd on macOS and Ctrl elsewhere.

func ReadImageSource added in v0.0.4

func ReadImageSource(ctx context.Context, source string) ([]byte, error)

ReadImageSource returns the encoded bytes of an image source, as DecodeImage reads it: a local path, a file URL, an HTTP(S) URL or a data URL, up to 16MiB. Use it to decode formats DecodeImage does not, such as SVG or every frame of a GIF. It blocks; call it from a worker.

func ReportScrollGesture added in v0.0.4

func ReportScrollGesture(device ScrollDevice, active, momentum, ended bool)

ReportScrollGesture records platform scroll state; window backends call it for each native scroll event; ScrollDeviceUnknown clears what earlier reports established. A finished gesture redraws every window so components waiting on it can settle. Safe from any goroutine.

func Role

func Role(role string, value ...string) semantic.DescriptionOp

Role marks a node's role for agents, optionally with a value. The internal el-inert marker hides a background subtree from Agent snapshots while a modal el layer is active; it is not exposed as a component role. Automation reads it as "role" or "role:value" from the node's description. A button may carry "button:loading" while its action is unavailable. On a semantic.Button, automation keeps only link, tab, columnheader, select, image, disclosure and toggle; any other role is reported as given.

func SetCurrentWindow

func SetCurrentWindow(w WindowControls) (restore func())

SetCurrentWindow marks w as the window being laid out and returns a func that restores the previous one. Only ui/window calls it.

func SetHighlighter added in v0.0.7

func SetHighlighter(h Highlighter)

SetHighlighter installs the syntax highlighter; ui/highlight calls it when imported. Nil removes it.

func SetImageFetcher added in v0.0.7

func SetImageFetcher(f ImageFetcher)

SetImageFetcher installs the network image fetcher; ui/netimage calls it when imported. Nil removes it.

func SetScrollGesturePoll added in v0.0.5

func SetScrollGesturePoll(fn func())

SetScrollGesturePoll installs a function that brings the state up to date from queued platform events; window backends without push notification (Wayland) use it. CurrentScrollGesture calls it first.

func ShortcutLabel

func ShortcutLabel(s, goos string) string

ShortcutLabel formats a ParseShortcut chord for goos (darwin, windows or linux). Invalid chords are returned unchanged. It does not register a shortcut.

func Update

func Update(fn func())

Update runs fn before the next frame, where it may change components safely. It is safe from any goroutine, including from callbacks, and returns at once.

Types

type C

type C = layout.Context

type ClipboardData

type ClipboardData struct {
	Text   string
	Images []ClipboardImage
	Files  []string
}

ClipboardData holds the available text, images and file paths in one paste. Paths are references only; the UI does not open the files automatically.

type ClipboardImage

type ClipboardImage struct {
	MIME string
	Data []byte
}

ClipboardImage is owned encoded image data provided to a paste handler.

type ClipboardReader

type ClipboardReader func(done func(ClipboardData, error))

ClipboardReader starts an asynchronous read. It must call done once, on any goroutine; input components marshal completion back to the UI loop. An error falls back to Gio text paste. Applications can adapt native/clipboard.Read.

type CodeToken added in v0.0.7

type CodeToken struct {
	Text         string
	Color        color.NRGBA
	Bold, Italic bool
	Kind         CodeTokenKind
}

CodeToken is a run of source text with its style. A zero Color means the default text color.

type CodeTokenKind added in v0.0.7

type CodeTokenKind uint8

CodeTokenKind is the syntax context of a token, for editing rules such as not pairing brackets inside strings.

const (
	CodeTokenCode CodeTokenKind = iota
	CodeTokenString
	CodeTokenComment
)

type D

type D = layout.Dimensions

func Semantic

func Semantic(gtx C, w func(gtx C) D, ops ...interface{ Add(*op.Ops) }) D

Semantic lays out w inside its own clip area and attaches semantic ops to it, so the component is one node in Gio's semantic tree with its real bounds. Agents (ui/window automation) and accessibility read that tree.

Gio's classes cover buttons, checkboxes, editors, radios and switches. Other roles go in a Role description, e.g. Role("row") or Role("select", value).

type EditAction added in v0.1.6

type EditAction string

EditAction is a standard application-menu operation. Custom editors may consume these with NextEditAction while they retain keyboard focus.

const (
	EditCopy      EditAction = "copy"
	EditCut       EditAction = "cut"
	EditPaste     EditAction = "paste"
	EditSelectAll EditAction = "select-all"
	EditUndo      EditAction = "undo"
	EditRedo      EditAction = "redo"
)

func NextEditAction added in v0.1.6

func NextEditAction(gtx C, tag event.Tag) (EditAction, bool)

NextEditAction returns a queued menu action only for the focused, enabled editor. Call during Layout; menu clicks preserve the editor's focus.

type Func

type Func func(gtx C) D

Func adapts a plain Gio layout function to Widget.

func (Func) Layout

func (f Func) Layout(gtx C) D

type HighlightOptions added in v0.0.7

type HighlightOptions struct {
	// Language is a name, alias or file extension ("go", "Go", "golang").
	Language string
	// Guess detects the language from the code when Language is empty or
	// unknown.
	Guess bool
	// Style names a color scheme; empty picks one for Dark.
	Style string
	// Dark is true on a dark code background.
	Dark bool
}

HighlightOptions say how to highlight.

type Highlighter added in v0.0.7

type Highlighter interface {
	// Highlight splits code into tokens whose texts concatenate to code.
	// ok is false when the language is unknown (and not guessed): the code
	// then stays plain.
	Highlight(code string, opts HighlightOptions) (tokens []CodeToken, ok bool)
	// Language is the canonical name of a language, "" when unknown.
	Language(name string) string
}

Highlighter tokenizes source code. It is called off the UI goroutine.

func CurrentHighlighter added in v0.0.7

func CurrentHighlighter() Highlighter

CurrentHighlighter is the installed highlighter, or nil.

type ImageFetcher added in v0.0.7

type ImageFetcher func(ctx context.Context, url string, header map[string]string) (status int, respHeader map[string]string, body io.ReadCloser, err error)

ImageFetcher downloads a network image source. header holds request headers; it returns the status code, the response headers with canonical names ("Etag", "Last-Modified", "Cache-Control") and the body, which the caller closes.

type ScrollDevice added in v0.0.4

type ScrollDevice uint8

ScrollDevice is the kind of device behind scroll input.

const (
	// ScrollDeviceUnknown: the platform does not say.
	ScrollDeviceUnknown ScrollDevice = iota
	// ScrollDeviceWheel scrolls in notches.
	ScrollDeviceWheel
	// ScrollDeviceTrackpad scrolls continuously, with gesture phases.
	ScrollDeviceTrackpad
)

type ScrollGesture added in v0.0.4

type ScrollGesture struct {
	Device ScrollDevice
	// Phases is true once the platform has reported gesture phases, so
	// Active and Ended can be trusted.
	Phases bool
	// Active is true while fingers are on the trackpad.
	Active bool
	// Momentum is true while inertial scrolling continues after a lift.
	Momentum bool
	// Ended counts finished gestures; a change means the fingers lifted.
	Ended uint64
}

ScrollGesture is what the platform reports about scroll input beyond the deltas Gio delivers. macOS and Wayland report it; elsewhere Phases is false and components fall back to timing.

func CurrentScrollGesture added in v0.0.4

func CurrentScrollGesture() ScrollGesture

CurrentScrollGesture returns the latest platform scroll state. Components waiting on a gesture's end should re-check it every frame or so: on some platforms the end is only seen when polled.

type Widget

type Widget interface {
	Layout(gtx C) D
}

Widget is anything that can lay itself out. Every component and container is one.

type WindowControls

type WindowControls interface {
	// Frameless reports whether the window draws its own title bar.
	Frameless() bool
	// Focused reports native window activation, not an individual control focus.
	Focused() bool
	// TitleBarArea registers the current draggable title region in window dp.
	// The window clears it each frame; controls must be outside this rectangle.
	TitleBarArea(x, y, width, height float32)
	Minimize()
	// ToggleMaximize maximizes the window, or restores it when maximized.
	ToggleMaximize()
	Maximized() bool
	Close()
}

WindowControls is what UI code may ask of the window it is drawn in: a custom title bar uses it for its buttons. ui/window implements it.

func CurrentWindow

func CurrentWindow() WindowControls

CurrentWindow returns the window being laid out, or nil outside one (a screenshot, a test harness). Read it in Render or Layout, under the frame lock, and keep it for callbacks; callbacks run within the same window.

Jump to

Keyboard shortcuts

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