state

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package state is Silk's hierarchical finite state machine — the equivalent of Qt's QStateMachine framework. Apps wire UI flow, animation sequences, and dialog modal stacks as a graph of named states + event-triggered transitions; the Machine drives the active-state cursor and fires onEntry / onExit hooks at the right moments.

Why a state machine and not a sea of bool flags? Two reasons. First, transitions become explicit — every change of mode is a named edge you can reason about, instead of a tangle of "if showing && not loading && hasUser". Second, the hierarchy lets a parent group share entry / exit logic across cousin states (e.g. "every state inside the Editor compound state shares the same status-bar setup").

Typical usage:

m := state.NewMachine()

idle := m.AddState("idle")
loading := m.AddState("loading")
ready := m.AddState("ready")

idle.OnEntry = func() { ui.SetStatus("idle") }
loading.OnEntry = func() { ui.ShowSpinner() }
loading.OnExit = func() { ui.HideSpinner() }

idle.AddTransition("startLoad", loading)
loading.AddTransition("loaded", ready)

m.SetInitialState(idle)
m.Start()

// Later, in response to user action:
m.PostEvent("startLoad")
m.PostEvent("loaded")

Hierarchical states (compound states): a parent state has children and an initial-child; entering the parent automatically descends into that child. PostEvent walks from the active leaf state up toward the root looking for a matching transition — children override their parents.

Goal lined up against QStateMachine: feature-parity for the dominant 80% (atomic + compound states, event transitions, entry/exit hooks, final states, initial state). The Qt-specific assignProperty, signal-bound transitions, and SCXML import/export are out of scope — Silk's signal-slot already covers the property-binding territory and SCXML is a niche.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Machine

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

Machine drives the active-state cursor and dispatches events. Add states + transitions, set initial state, Start. PostEvent from any goroutine; the machine serialises events through an internal mutex.

One Machine per logical flow. A widget tree may use several — each dialog or wizard could have its own. Machines do not share state with each other; PostEvent is local to the receiver.

func NewMachine

func NewMachine() *Machine

NewMachine constructs an empty machine with no states.

func (*Machine) Active

func (m *Machine) Active() *State

Active returns the current leaf state, or nil before Start.

Read without locking — the dominant call site is inside an OnEntry hook running on the dispatcher's goroutine while m.mu is already held. Locking here would deadlock. Callers from other goroutines should coordinate via PostEvent's return value or callbacks; the pointer read itself is atomic on every supported platform.

func (*Machine) AddChildState

func (m *Machine) AddChildState(parent *State, name string) *State

AddChildState adds a nested state under a compound parent. The child's Parent is set; the parent's Children list grows.

If parent.Initial is nil, the first child added becomes the initial — convenient default for the dominant single-initial pattern. Override by setting parent.Initial directly.

func (*Machine) AddState

func (m *Machine) AddState(name string) *State

AddState adds a top-level state. The returned *State can be mutated (set OnEntry, AddTransition, etc.) freely until Start.

Adding states after Start is allowed but the machine won't be notified — use only during initial wiring.

func (*Machine) IsRunning

func (m *Machine) IsRunning() bool

IsRunning reports whether the machine is currently driving events.

func (*Machine) LastEvent

func (m *Machine) LastEvent() string

LastEvent returns the most recently dispatched event name. Useful inside OnEntry / OnExit / Action hooks to dispatch on the trigger.

Same lock-free policy as Active — hooks fire while the dispatcher holds m.mu, so re-entering the lock would deadlock. The string read is single-word and atomic on all supported architectures.

func (*Machine) PostEvent

func (m *Machine) PostEvent(event string) bool

PostEvent dispatches a named event. The dispatcher walks the active state's transition list, then up the parent chain — first transition whose Event matches AND whose Guard (if any) returns true wins. Returns true when a transition fired.

Transition ordering during a fire (matches the QStateMachine spec):

  1. Compute the LCA (lowest common ancestor) of source and target.
  2. Walk from source up to the LCA's child, calling OnExit on each.
  3. Run Transition.Action (after exits, before entries).
  4. Walk from the LCA's child down to target, calling OnEntry on each.
  5. If target is a compound state, recursively descend into its Initial child, calling OnEntry on each level.

A self-transition (target == source) exits then re-enters source.

func (*Machine) SetInitialState

func (m *Machine) SetInitialState(s *State)

SetInitialState pins the top-level entry point. Required before Start; calling Start without an initial returns an error.

func (*Machine) SetOnFinished

func (m *Machine) SetOnFinished(fn func())

SetOnFinished registers a callback fired when the machine reaches a top-level final state. Mirrors QStateMachine::finished signal.

func (*Machine) Start

func (m *Machine) Start() error

Start enters the initial state (descending into compound children as needed) and marks the machine running. Returns an error when no initial state was set.

func (*Machine) Stop

func (m *Machine) Stop()

Stop halts the machine and clears the active state. Safe to call when not running.

type State

type State struct {
	// Name is a human-readable identifier. Used in error messages and
	// the dispatcher's debug logs. Two states may share a name in
	// different parts of the tree; the machine identifies states by
	// pointer, not name.
	Name string

	// Parent is the compound state this is nested inside, or nil for
	// top-level states. Set by Machine.AddState when the AddChildState
	// path is used; ignored for top-level AddState.
	Parent *State

	// Children is the list of nested states for a compound state.
	// Empty for atomic states.
	Children []*State

	// Initial is the child to auto-enter when the dispatcher reaches
	// this compound state. Required (must be in Children) when
	// Children is non-empty. Ignored for atomic states.
	Initial *State

	// IsFinal flags this as a final / terminating state. Entering a
	// top-level final state stops the machine. A final state inside a
	// compound parent fires the parent's "finished" event.
	IsFinal bool

	// Transitions is the list of outgoing edges. Order matters — the
	// dispatcher tries each in declaration order and takes the first
	// that matches both event name AND optional Guard.
	Transitions []*Transition

	// OnEntry is called when the dispatcher enters this state. May be
	// nil. Called AFTER the parent's OnEntry if walking down a
	// hierarchy and BEFORE any nested initial child's OnEntry.
	OnEntry func()

	// OnExit is called when the dispatcher leaves this state. Symmetric
	// to OnEntry — fires BEFORE the parent's OnExit when walking up.
	OnExit func()
}

State is one node in the state-machine graph. States may be atomic (no children) or compound (a parent that auto-enters its initial child on entry). A "final" state has IsFinal=true and stops the machine when entered at the top level — matching QFinalState.

onEntry / onExit are called by the dispatcher at the right moments during a transition. They receive no arguments because the typical hook closes over its own widget references; callers needing the transition event can read it from Machine.LastEvent inside the hook.

func (*State) AddTransition

func (s *State) AddTransition(event string, target *State) *Transition

AddTransition is a convenience for the common case: define an event-name transition with no guard or action. Returns the new Transition so the caller can attach a Guard / Action afterwards.

func (*State) AncestorPath

func (s *State) AncestorPath() []*State

AncestorPath returns the chain of states from root to this state, inclusive. Used by the dispatcher to compute the LCA between two states for transition ordering.

func (*State) IsAtomic

func (s *State) IsAtomic() bool

IsAtomic is the inverse — leaf states with no children.

func (*State) IsCompound

func (s *State) IsCompound() bool

IsCompound reports whether this state has children (i.e. is a hierarchical compound state).

type Transition

type Transition struct {
	// Event is the name the dispatcher matches against PostEvent's
	// argument. Empty Event means "match any event" — useful for
	// catch-all transitions on a parent state.
	Event string

	// Guard is an optional predicate. The transition fires only when
	// Guard returns true (or Guard is nil). Lets multiple transitions
	// share an event name and pick by condition.
	Guard func() bool

	// Target is the destination state. Cannot be nil — callers needing
	// a self-transition should set Target = source.
	Target *State

	// Action is fired during the transition, with the LCA-based
	// ordering described on Machine.PostEvent. May be nil.
	Action func()
}

Transition is one outgoing edge from a State. The dispatcher walks the active state's transition list (and its parents'), picking the first whose Event matches the posted event AND whose Guard (if set) returns true.

Action runs during the transition, between source.OnExit and target.OnEntry. Mirrors QAbstractTransition::onTransition.

Jump to

Keyboard shortcuts

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