devhost

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 22 Imported by: 0 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 devhost implements hot reload of Tango's self-drawn UI under `tan dev` (docs/specs/ui-hotreload.md): the wire protocol between the long-lived host process (it owns the windows) and the worker processes (the user's app, replaced on every rebuild), shared-memory frame transport and state snapshots. The host itself lives in internal/devhost/host; package uihost is the worker side.

This package is a leaf (standard library plus the plain ui/input and ui/geom types) so cmd/tan can speak the control protocol without linking platform code. Nothing here is linked into an app unless it is built with -tags tango_dev (tan dev does that).

Index

Constants

View Source
const (
	EnvRole = "TANGO_DEV_ROLE" // "host" or "worker"
	EnvAddr = "TANGO_DEV_ADDR" // control channel: "unix:/path" or "tcp:127.0.0.1:port"
	EnvName = "TANGO_DEV_NAME" // app display name (host)
	EnvID   = "TANGO_DEV_ID"   // app id (host)
	EnvDir  = "TANGO_DEV_DIR"  // scratch directory for frame buffers (unix)
	// EnvToken is the secret every peer sends in Hello. tan dev makes a
	// fresh one per session; the host refuses connections without it, so
	// another local user cannot attach to a TCP control channel (Windows).
	EnvToken = "TANGO_DEV_TOKEN"
)

Environment variables set by tan dev.

View Source
const (
	RoleHost   = "host"
	RoleWorker = "worker"
	RoleCtl    = "ctl" // tan dev's control connection to the host
)

Roles.

View Source
const (
	OpGet = iota // only answer SurfaceInfo
	OpShow
	OpHide
	OpFocus
	OpSetTitle
	OpSetSize
	OpSetBounds
	OpCenter
	OpSetSizeLimits
	OpSetState
	OpSetAppearance
)

SurfaceOp kinds.

View Source
const (
	EvResized = iota + 1
	EvMoved
	EvStateChanged
	EvFocused
	EvBlurred
)

SurfaceEvent kinds.

View Source
const AttachSymbol = "github.com/tangoui/tango/uihost.AttachWith"

AttachSymbol is uihost.AttachWith's name in a binary's function table. uihost.Attach calls AttachWith, so the symbol is linked exactly when an app attaches canvases to WebView windows; tan dev restarts such apps on changes instead of hot-reloading them. A uihost test pins the name, so moving or renaming AttachWith fails there rather than silently in tan.

View Source
const Marker = "tango-devhost-protocol-v1"

Marker is a string tan dev looks for in a built binary to tell whether it links the dev host (package uihost built with tango_dev).

View Source
const ProtoVersion = 5

ProtoVersion changes whenever a message changes incompatibly. A worker with another version is refused, and tan dev restarts the host.

Variables

View Source
var ErrA11yDelta = errors.New("devhost: accessibility delta without a base tree")

ErrA11yDelta is returned by Apply for a delta without a base tree.

View Source
var ErrClosed = errors.New("devhost: connection to the host closed")

ErrClosed is returned by requests after the connection ended.

View Source
var ErrNoSlot = errors.New("devhost: no free frame slot")

ErrNoSlot is returned by Write when the host held both slots too long.

View Source
var SlotTimeout = time.Second

SlotTimeout bounds how long Write waits for the host to release a slot.

Functions

func Decode

func Decode(entries []Entry, key string, ptr any) (bool, error)

Decode fills ptr from the entry with key in entries. It reports whether there was one. On a decode error (the type changed incompatibly) ptr is left untouched.

func FrameImage

func FrameImage(seg *Segment, f FrameReady) (*image.RGBA, error)

FrameImage returns the frame f inside seg (no copy). The slot size is half the segment.

func Listen

func Listen(addr string) (net.Listener, error)

Listen listens on addr ("unix:/path" or "tcp:host:port").

func NewToken

func NewToken() (string, error)

NewToken returns a fresh random session token for EnvToken.

func Role

func Role() string

Role returns this process's dev role ("" outside tan dev).

func TokenOK

func TokenOK(got, want string) bool

TokenOK reports whether got matches the session token want, in constant time. An empty want accepts any token (hosts started without one, as in tests).

Types

type A11yAction

type A11yAction struct {
	Win int
	ID  a11y.NodeID
	Act a11y.Action
	Arg string
}

A11yAction asks the worker to perform an assistive technology's action on node ID of window Win (host → worker).

type A11yState

type A11yState struct {
	Win   int
	On    bool
	Epoch int
}

A11yState switches the semantics tree of window Win on or off (host → worker). Every On carries a new Epoch: the worker answers with a full A11yTree of that epoch and tags the deltas that follow with it, so the host can drop trees sent for an earlier request.

type A11yTree

type A11yTree struct {
	Win           int
	Epoch         int
	Full          bool
	Root          a11y.NodeID
	Focus         a11y.NodeID
	RTL           bool
	Announcements []a11y.Announcement
	Nodes         []a11y.Node
	Removed       []a11y.NodeID
}

A11yTree is the semantics tree of window Win after a frame that changed it (worker → host). With Full set, Nodes holds the whole tree in depth-first order; otherwise Nodes holds the nodes added or changed since the previous A11yTree of the same epoch and Removed the IDs it no longer has. Root, Focus, RTL and Announcements always describe the new tree.

func NewA11yTree

func NewA11yTree(win, epoch int, tree *a11y.Tree, changed []a11y.NodeID, full bool) A11yTree

NewA11yTree encodes tree for window win: every node when full, else the nodes listed in changed (ui.AccessibilityHost semantics: IDs tree no longer has are removals).

func (A11yTree) Apply

func (m A11yTree) Apply(prev *a11y.Tree) (*a11y.Tree, error)

Apply returns the tree m describes: m itself when Full, else prev with m's changes. prev is not modified (trees are immutable snapshots); unchanged nodes are shared with it. Nodes are ordered depth first from the root, followed by any not reachable from it.

type Activity

type Activity struct {
	Win int
	At  time.Time
}

type Appearance

type Appearance struct {
	TitleBar    int
	Transparent bool
	Background  uint32
	Material    int
	AlwaysOnTop bool
	Opacity     float64
	NoShadow    bool
	NoClose     bool
	NoMinimize  bool
	NoMaximize  bool
	AllSpaces   bool
}

Appearance is the serializable tango.Appearance.

type Client

type Client struct {
	Gen int
	Dir string // where frame segments are created
	// contains filtered or unexported fields
}

Client is a worker's connection to the host.

func Connect

func Connect(addr, dir string, handler func(any)) (*Client, error)

Connect dials the host at addr and starts reading. handler receives every message that is not an answer to a request, on the reading goroutine; it must not block for long.

func NewClient

func NewClient(conn *Conn, dir string, handler func(any)) (*Client, error)

NewClient performs the worker handshake on conn and starts reading.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done is closed when the connection ends.

func (*Client) Request

func (c *Client) Request(build func(id int) any, timeout time.Duration) (any, error)

Request sends the message build(id) and waits for the reply with the same id.

func (*Client) Send

func (c *Client) Send(m any) error

Send sends a message.

type ClipboardText

type ClipboardText struct {
	Req  int
	Text string
}

ClipboardText answers ReadClipboard.

type CloseRequest

type CloseRequest struct{ Win int }

CloseRequest says the user tried to close the host window (host → worker). The worker asks its OnClose handlers and answers CloseWindow if the window may close.

type CloseWindow

type CloseWindow struct{ Win int }

CloseWindow closes a window from the worker side (Surface.Close).

type Conn

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

Conn is a gob message stream. Send is safe for concurrent use; Recv must be called from one goroutine.

func Dial

func Dial(addr string, timeout time.Duration) (*Conn, error)

Dial connects to addr, retrying until timeout (the host may still be starting).

func NewConn

func NewConn(c net.Conn) *Conn

NewConn wraps c.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) Recv

func (c *Conn) Recv() (any, error)

Recv reads one message.

func (*Conn) Send

func (c *Conn) Send(m any) error

Send writes one message.

type EmbedAssetRequest

type EmbedAssetRequest struct {
	Req, Win    int
	View        uint64
	Method, URL string
	Header      http.Header
	Body        []byte
}

type EmbedAssetResponse

type EmbedAssetResponse struct {
	Req, Status int
	Header      http.Header
	Body        []byte
}

type EmbedEvent

type EmbedEvent struct {
	Win             int
	View            uint64
	Event           platform.SurfaceEvent
	Origin, Message string
	NavKind         platform.WebNavigationKind
	NavToken        uint64
	NavPage         platform.WebPageState
	NavError        string
}

type EmbedOp

type EmbedOp struct {
	Win       int
	View      uint64
	Op        string
	Text      string
	Number    float64
	Req       int
	Placement platform.WebPlacement
}

type EmbedOpen

type EmbedOpen struct {
	Req, Win int
	View     uint64
	Opts     platform.SurfaceOptions
	Web      platform.WebOptions
}

type EmbedOpened

type EmbedOpened struct {
	Req         int
	Err         string
	Unsupported bool
}

type EmbedResult

type EmbedResult struct {
	Win         int
	View        uint64
	Req         int
	PNG         []byte
	Err         string
	Moved       bool
	Unsupported bool
}

type Entry

type Entry struct {
	Key  string // Type + "#" + its index among values of that type
	Type string // Go type of the pointed-to value, e.g. "main.formState"
	Data []byte // gob encoding
}

Entry is one Persist value in a snapshot.

type Focus

type Focus struct {
	Win     int
	Focused bool
}

Focus reports a key-focus change.

type FrameAck

type FrameAck struct{ Win, Seg, Slot int }

FrameAck releases a slot.

type FrameReady

type FrameReady struct {
	Win, Seg, Slot int
	W, H, Stride   int
	Scale          float32
}

FrameReady says slot Slot of segment Seg holds a W×H premultiplied RGBA frame (device pixels, rows Stride bytes apart). The worker does not touch the slot again until FrameAck.

type FrameRequest

type FrameRequest struct {
	Win   int
	W, H  float32
	Scale float32
}

FrameRequest asks the worker to render one frame at this geometry.

type FrameWriter

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

FrameWriter is the worker side of one window's frame transport.

func NewFrameWriter

func NewFrameWriter(win int, dir string, send func(any) error) *FrameWriter

NewFrameWriter returns a writer for window win; segments are created in dir and announced with send.

func (*FrameWriter) Ack

func (w *FrameWriter) Ack(seg, slot int)

Ack releases a slot. Any goroutine.

func (*FrameWriter) Close

func (w *FrameWriter) Close()

Close unmaps the current segment.

func (*FrameWriter) Write

func (w *FrameWriter) Write(img *image.RGBA, scale float32) error

Write copies img (premultiplied RGBA, device pixels) into a free slot and sends FrameReady.

type Hello

type Hello struct {
	Proto  int
	Role   string
	PID    int
	Marker string
	Token  string // EnvToken of the session
}

Hello opens every connection.

type Input

type Input struct {
	Win          int
	Ev           input.Event
	SyntheticKey bool
}

Input delivers an input event.

type Invalidate

type Invalidate struct{ Win int }

Invalidate asks for a FrameRequest.

type MenuClick struct {
	Win int
	ID  uint32
}

MenuClick reports a click on item ID of a menu set with SetMenu (host → worker).

type MenuItem struct {
	ID          uint32
	Label       string
	Accelerator string
	Role        string
	Separator   bool
	Disabled    bool
	Checked     bool
	Checkable   bool
	RadioGroup  string
	Icon        []byte
	Submenu     []MenuItem
}

MenuItem is the serializable platform.MenuItem.

type OpenWindow

type OpenWindow struct {
	Req  int
	Seq  int
	Opts WindowOpts
}

OpenWindow asks for a canvas window. Seq is the call's index among this worker's OpenWindow calls: a replacement worker's Seq-th window (or one with the same title) takes over the old worker's window.

type Opened

type Opened struct {
	Req         int
	Win         int
	W, H        float32
	Scale       float32
	Err         string
	Unsupported bool
	ActivityAt  time.Time
}

Opened answers OpenWindow.

type ReadClipboard

type ReadClipboard struct{ Req int }

ReadClipboard asks for the clipboard text; the host answers ClipboardText.

type Rect

type Rect struct{ X, Y, W, H int }

Rect is a window rectangle in logical pixels (tango.Rect).

type Registry

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

Registry records the values passed to uihost.Persist.

func (*Registry) Add

func (r *Registry) Add(ptr any) (key, typ string, err error)

Add registers ptr (a non-nil pointer) and returns its key and type name.

func (*Registry) Encode

func (r *Registry) Encode() ([]Entry, error)

Encode gob-encodes every registered value. Values that fail to encode are skipped and reported in the error.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered values.

type Segment

type Segment struct {
	Name string // file path
	// contains filtered or unexported fields
}

Segment is a shared-memory region: on unix a temporary file mapped MAP_SHARED by both processes.

func CreateSegment

func CreateSegment(dir string, size int) (*Segment, error)

CreateSegment creates a segment of size bytes in dir ("" = os.TempDir).

func OpenSegment

func OpenSegment(name string, size int) (*Segment, error)

OpenSegment maps an existing segment.

func (*Segment) Bytes

func (s *Segment) Bytes() []byte

Bytes returns the mapped memory.

func (*Segment) Close

func (s *Segment) Close() error

Close unmaps the segment.

func (s *Segment) Unlink()

Unlink removes the segment's name; existing mappings stay valid.

type SetCursor

type SetCursor struct {
	Win    int
	Cursor input.Cursor
}

SetCursor mirrors ui.Window.SetCursor.

type SetMenu

type SetMenu struct {
	Win   int
	Items []MenuItem
	Clear bool
}

SetMenu shows a menu on the host (worker → host): the application menu when Win is 0, else the window menu of Win. Clear removes it (the host goes back to its default menu).

type SetShortcutCapture

type SetShortcutCapture struct {
	Win     int
	Enabled bool
}

SetShortcutCapture mirrors ui.ShortcutCaptureWindow without enabling IME.

type SetTextInput

type SetTextInput struct {
	Win     int
	Enabled bool
	Caret   geom.Rect
}

SetTextInput mirrors ui.Window.SetTextInput.

type ShmAttach

type ShmAttach struct {
	Win  int
	Seg  int
	Name string
	Size int
}

ShmAttach announces a new frame segment for a window. Frames that follow name it by Seg. The host maps it and, on unix, unlinks the file.

type SnapshotData

type SnapshotData struct {
	Req     int
	Entries []Entry
}

SnapshotData answers SnapshotGet.

type SnapshotGet

type SnapshotGet struct{ Req int }

SnapshotGet asks the host for the previous worker's state (Persist). The host answers SnapshotData.

type SnapshotReply

type SnapshotReply struct {
	Req     int
	Entries []Entry
}

SnapshotReply answers SnapshotReq.

type SnapshotReq

type SnapshotReq struct{ Req int }

SnapshotReq asks a worker for its Persist state.

type Status

type Status struct {
	Kind string
	Text string
}

Status tells the host what to overlay: Kind "" clears the banner, anything else ("build", "crash", "start") shows Text in a red banner.

type SurfaceEvent

type SurfaceEvent struct {
	Win   int
	Kind  int
	X, Y  int // EvMoved
	W, H  int // EvResized
	State int // EvStateChanged
}

SurfaceEvent reports a change of the host window (host → worker).

type SurfaceInfo

type SurfaceInfo struct {
	Req     int
	Err     string
	Title   string
	Bounds  Rect // tango.Surface.Bounds
	W, H    int  // tango.Surface.Size
	State   int
	Visible bool
	Focused bool
}

SurfaceInfo answers SurfaceOp: the host window's current state.

type SurfaceOp

type SurfaceOp struct {
	Req        int
	Win        int
	Op         int
	Title      string     // OpSetTitle
	Rect       Rect       // OpSetSize (W, H), OpSetBounds
	Limits     [4]int     // OpSetSizeLimits: minW, minH, maxW, maxH
	State      int        // OpSetState
	Appearance Appearance // OpSetAppearance
}

SurfaceOp is a tango.Surface call on the window Win (worker → host). With Req != 0 the host answers SurfaceInfo after applying it. Calls from a worker that is not on screen yet are applied when it takes over.

type Swapped

type Swapped struct {
	Old, New int
	Took     time.Duration
}

Swapped tells tan dev that worker New replaced worker Old (pids; Old is 0 for the first worker) and is now on screen. Took is the time from the new worker's connection to its first frame being shown.

type Welcome

type Welcome struct {
	Err string
	Gen int // worker generation assigned by the host
}

Welcome answers Hello. Err is set when the host refuses the peer.

func Handshake

func Handshake(c *Conn, role string) (Welcome, error)

Handshake sends Hello as role with the session token from EnvToken and waits for Welcome.

func HandshakeToken

func HandshakeToken(c *Conn, role, token string) (Welcome, error)

HandshakeToken is Handshake with an explicit session token.

type WindowClosed

type WindowClosed struct{ Win int }

WindowClosed reports that the user closed the window.

type WindowOpts

type WindowOpts struct {
	Title               string
	Width, Height       int
	MinWidth, MinHeight int
	MaxWidth, MaxHeight int
	Resizable, Hidden   bool
	X, Y                int
	Centered            bool
	State               int
	Kind                int
	TitleBar            int
	Transparent         bool
	Background          uint32
	Material            int
	AlwaysOnTop         bool
	Opacity             float64
	NoShadow            bool
	NoClose             bool
	NoMinimize          bool
	NoMaximize          bool
	AllSpaces           bool
}

WindowOpts is the serializable part of tango.SurfaceOptions.

type WorkerLeft

type WorkerLeft struct {
	PID    int
	Active bool
}

WorkerLeft tells tan dev that a worker disconnected.

type WriteClipboard

type WriteClipboard struct{ Text string }

WriteClipboard sets the clipboard text.

Directories

Path Synopsis
Package host is the hot-reload host process: it owns the canvas windows of an app run by `tan dev` and shows frames rendered by worker processes (each rebuild of the app), forwarding input to the current worker and swapping workers without closing windows.
Package host is the hot-reload host process: it owns the canvas windows of an app run by `tan dev` and shows frames rendered by worker processes (each rebuild of the app), forwarding input to the current worker and swapping workers without closing windows.

Jump to

Keyboard shortcuts

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