io.worxbend.tui.runtime
Members list
Type members
Classlikes
How to lint a running A for accessibility, given the frame it last painted and where it parked the cursor.
How to lint a running A for accessibility, given the frame it last painted and where it parked the cursor.
The seam between tui-test's Pilot.a11yReport, which knows how to read a frame and a cursor off a headless run, and the layer that knows what the frame is made of — tui-dsl provides the instance for its TuiApp, found on the app type's companion. Implementations are called on the render thread of the run that painted frame.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
One accessibility problem on a frame: which rule, a sentence saying what and where, and the cells it concerns when it has a place on screen.
One accessibility problem on a frame: which rule, a sentence saying what and where, and the cells it concerns when it has a place on screen.
Attributes
- Supertypes
-
trait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
What an accessibility lint can flag on one painted frame.
What an accessibility lint can flag on one painted frame.
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
Attributes
- Companion
- class
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
AsciicastRecorder.type
Writes the frames of one run as an asciicast v2 recording: a JSON header line, then one [time, "o", data] event per frame that changed something on screen.
Writes the frames of one run as an asciicast v2 recording: a JSON header line, then one [time, "o", data] event per frame that changed something on screen.
data is the ANSI a real terminal would have received — FrameEncoder's diff against the previous frame, and a clear-screen plus full repaint for the first frame and after a resize — so asciinema play and the web player show exactly what the terminal showed, and a frame that changed nothing writes no event at all. Timestamps are seconds since the first frame, read from nanoTime when the frame is handed in; epochSeconds stamps the header the way the format expects.
Ownership and threading: apply is called by one thread — in a run configured with RunnerConfig.withRecording that is the render thread, inside onFrame — and does no I/O there: it stamps the frame and hands it to a bounded queue drained by a daemon writer thread this recorder owns, which encodes the diff and writes it. A full queue makes apply wait for room, so a disk slower than the frame rate slows the app down rather than growing memory or dropping frames. flush waits until every frame handed in so far is written and flushed (the runner calls it before suspend hands the terminal over); close does the same, closes the writer and stops the thread, and the runner calls it on every exit path. An I/O failure on the writer thread is kept and rethrown on the caller at the next apply, flush or close — on the render thread it ends the run as RunnerError.Handler rather than silently producing a truncated recording. Frames handed in must not be mutated afterwards — the runner's snapshots never are.
Attributes
- Companion
- object
- Supertypes
Structured background work for a signals-driven app — glyphora's answer to bubbletea's Cmd/Msg.
Structured background work for a signals-driven app — glyphora's answer to bubbletea's Cmd/Msg.
The problem it solves: Signals may only be mutated on the render thread (RenderThread), so a naive new Thread { data.set(fetch()) } throws. Async runs the work off-thread, then marshals the continuation back onto the render thread (via RenderThread.runLater), where it may safely update signals. The runner drains that queue at the top of each loop iteration and repaints if a signal changed — so the result appears as an ordinary reactive update, no Msg plumbing.
All executor threads are daemons, so pending work never keeps the JVM alive after the app quits. Callbacks scheduled while no runner is active simply wait on the queue until one drains it (or are dropped when the process exits).
Lifetime. Every entry point here captures its target runner at the moment it is called, and that runner's queue stops accepting work once the runner exits. Concretely:
- A bounded final batch of queued work runs before the runner retires; any remaining callbacks are discarded.
- Work queued after that is silently dropped — there is no longer a render thread to run it on, and keeping it would only grow memory.
- A Cancelable from after or every is not cancelled by the app quitting. The scheduler is a process-lifetime daemon singleton; an uncancelled
everykeeps its scheduler entry until its first firing after the owner has closed, at which point it retires itself — the body never runs again and the entry is removed. Cancel it anyway when the app quits — fromTuiApp.onStop, which runs on every exit path including Ctrl+C, or wherever a bare Runner app finishes: the timer's body may hold resources of its own, cancellation releases the entry at once rather than one interval later, and both matter most in the embedded and multiple-runner cases this module is built for.
The mirror-image rule applies to starting repeating work. Every entry point here captures the render loop of the thread that calls it, and a thread that belongs to no runner — a constructor running before any runner is registered — captures the shared unattributed queue instead. Those bodies wait for a runner, but repeating ticks coalesce to one pending delivery per timer. Detached admission throws at 256 outstanding callbacks/reservations; an active owner allows 1024. Start repeating work from TuiApp.onStart (or a bare runner's onStart).
Admission. Submission never waits for capacity and never runs background work on the submitting thread. RejectedExecutionException escapes synchronously if either the worker backlog or captured owner is full; it is not a work failure delivered to an error handler or Left. Accepted work reserves its continuation slot before starting, including the default error report, so completion cannot recursively overload the owner's queue. Timers reserve one slot until one-shot delivery or cancellation (repeating timers retain it until cancellation). These are per-owner bounds, not a global limit on owners or scheduler registrations. An unscoped timer retires itself on its first firing after its owner exits; explicit cancellation is still what releases it at once. Cancelled scheduler entries are removed immediately.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
Async.type
How Async.run reports a failure of its background work. Provided as a using value so apps can install their own (log, toast, set an error signal) without changing call sites.
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
AsyncErrorHandler.type
What a run does with System.out and System.err while it owns the terminal.
What a run does with System.out and System.err while it owns the terminal.
Ordinary println writes straight into the screen the runner is repainting: the line lands wherever the cursor happens to be, the next diff paints over part of it, and the user is left with a corrupted frame and no log. While the app runs under PrintAbove or Console, both streams are swapped for line-buffered streams and the two Scala Console dynamic variables are bound throughout the render-thread lifecycle, including onStop. Toolkit worker/timer threads forward Scala output to the current process streams across sequential runs. Root JUL ConsoleHandlers are temporarily rebound to captured stderr (or suppressed when a root JulBridge already records the event), then the original handler instances are restored. A library writing to System.err is captured from any thread. Existing third-party threads may retain an older Scala Console binding: wrap their task bodies with scala.Console.withOut(System.out)(scala.Console.withErr(System.err)(...)) to opt in. The originals are restored on every exit path, after the terminal itself has been restored, and whatever was still buffered without a trailing newline is flushed to the real streams at that point — so the output of a run that printed "done" and quit appears under the restored shell prompt rather than vanishing with the alternate screen.
RunnerHandle.suspend passes the streams straight through to the originals for the duration of its body: the terminal has been handed back, so writing to it is the right thing again, and the buffered partial line is flushed first, after any queued complete lines, and terminated so it is not glued to the first line the body prints. Captured carriage-return progress keeps the last update of each completed line; CRLF is one line ending.
The swap is process-wide — System.setOut has no narrower scope — so a second runner in the same JVM sees the first one's streams; each run restores exactly the stream it replaced, and a stream a run left installed keeps passing writes through to its original once that run is over.
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
One frame after it reached the terminal: the exact cells that were flushed, the area they covered, and which frame of the run this was.
One frame after it reached the terminal: the exact cells that were flushed, the area they covered, and which frame of the run this was.
buffer is a snapshot, not the composer's live buffer. The composer reuses one buffer for as long as the terminal keeps its size, so handing out the live one would give an observer a value that quietly changes underneath it on the next frame. Retaining this snapshot is safe, and is the point. The snapshot isolates later rendering, not caller mutation: Buffer is publicly mutable. Treat it as read-only when sharing a frame with another thread. lines and text intentionally recompute rather than caching a result that mutation could make stale.
count is the same number the Frame carried: the first frame of a run is 0. It counts composed frames, so a frame the backend's diff turned into no output at all is still counted here.
Handed to RunnerConfig.onFrame on the render thread, inside the frame it describes. Keep the body short and do not block in it: the loop is not reading input while it runs.
Attributes
- Supertypes
-
trait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
A value derived from other reactive values.
A value derived from other reactive values.
Lazily cached: set on a dependency only marks this stale (cascading to dependents); the thunk re-runs on the next read. Each recomputation first unsubscribes from the previous dependency set, then re-subscribes to exactly what the thunk reads this time — the mechanism that makes conditional dependencies correct.
The dependency graph must be acyclic. A thunk that reads the value it is itself computing — directly, or around a cycle through other computeds — throws IllegalStateException on the read that closes the loop, rather than recursing until the stack runs out.
Render-thread-confined in both directions, unlike Signal. Reading is not the safe half here: peek (and therefore get) recomputes when the cache is stale, and recomputing rewrites the cached value, the stale flag, the dirty epoch and both the dependency and subscriber sets — none of which is volatile or guarded by a lock. markStale and dispose mutate those same sets. All four enforce the graph's specific render owner, using the same initial-binding and post-retirement rebinding rules as Signal. In particular Signal.peek is explicitly safe off the render thread and Computed.peek is not; foreign-owner access throws before touching cached state. Read the signals a background thread needs directly, or marshal the read back with RenderThread.runLater.
Attributes
- Companion
- object
- Supertypes
A transparent view of another reactive value: read re-runs on every access and nothing is cached.
A transparent view of another reactive value: read re-runs on every access and nothing is cached.
Unlike Computed this holds no subscription of its own — a tracked read passes the caller's scope straight through to the underlying values, so the caller subscribes to the source rather than to an intermediate. There is consequently no lifecycle and nothing to dispose: an instance created inside a view body and abandoned after one frame leaves no edge behind. The trade is that read is evaluated per access; use Computed when the derivation is expensive enough to be worth caching, and give that computed an owner that disposes it.
Holds no mutable state, so an instance may be read from any thread its source allows.
Attributes
- Companion
- object
- Supertypes
An event handler's answer to one question: does this event change what is on screen?
An event handler's answer to one question: does this event change what is on screen?
Redraw asks the loop to compose and flush a frame once the handler returns; Ignored says the handler left the UI exactly as it was, so the loop goes straight back to waiting for input. Answering Ignored after changing state the render function reads is what leaves a stale frame on screen; answering Redraw when nothing changed costs one composed frame that the backend's diff then flushes as nothing.
One event reads more into the answer than "repaint or not". Event.Interrupt (Ctrl+C) is offered to the handler first, and a handler that answers Ignored is taken to have declined it: the loop then quits through its normal teardown, which is what makes Ctrl+C work in an app that never wrote a handler for it. A handler that wants to stay running through an interrupt — to ask "really quit?", say — answers Redraw, which it was going to have to do anyway to put that question on screen.
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
One frame being rendered: the drawable area plus the buffer widgets write into.
One frame being rendered: the drawable area plus the buffer widgets write into.
The buffer itself stays module-private — application render code goes through the widget contract, which keeps every write attributable to a widget and an area.
count is how many frames this runner composed before this one: the first frame of a run is 0 and the number goes up by one per composed frame, wrapping back to 0 after Long.MaxValue (about 300 million years at a thousand frames a second — the wrap is stated so the type is total, not because anyone will see it). It counts composed frames, not cells that reached the terminal: a frame the backend's diff turned into no output at all still consumed its number. Use it to do expensive work only every Nth frame, or to label a frame in a debug overlay. Do not drive animation from it — a frame rate is not a clock, and the same animation would then run at a different speed on a fast terminal than on a slow one. core.Progress with a real elapsed duration is the one owner of time-to-position arithmetic.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
Elapsed (wall-clock, not CPU-only) nanoseconds for one successfully completed frame.
Elapsed (wall-clock, not CPU-only) nanoseconds for one successfully completed frame.
compositionNanos includes the backend size query, buffer preparation and the application's render callback. drawNanos covers the synchronous io.worxbend.tui.terminal.Backend.draw call, including diffing, encoding and writes performed by that backend. observerNanos includes snapshot creation and the synchronous onFrame callback; it is zero when no frame observer is configured. With LatestFrameObserver it measures snapshot and admission, not the off-thread callback. These phases exclude input, queued work, cursor placement and the timing callback itself; their sum is not the whole loop iteration. Waiting, scheduling and GC can contribute to every phase.
count is the same composed-frame number as Frame.count. Delivered only when composition, draw, observation and cursor placement all succeed. Installing timing alone does not capture any frame snapshots.
The same frame is also a Flight Recorder io.worxbend.tui.FrameDrawn event whose duration spans composition and draw, with the number of cells that changed — see JfrEvents. That one needs no callback, only a recording.
Attributes
- Supertypes
-
trait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
A tracking scope for a repeatedly re-evaluated computation (an app's view): reads subscribe onInvalidate, and beginGeneration — called before each re-evaluation — unsubscribes from values that stopped being read, so signals owned by closed screens or discarded branches do not accumulate stale subscriptions. Tracking, generation changes, invalidation and disposal enforce the connected graph's specific render owner (see Signal).
A tracking scope for a repeatedly re-evaluated computation (an app's view): reads subscribe onInvalidate, and beginGeneration — called before each re-evaluation — unsubscribes from values that stopped being read, so signals owned by closed screens or discarded branches do not accumulate stale subscriptions. Tracking, generation changes, invalidation and disposal enforce the connected graph's specific render owner (see Signal).
Attributes
- Supertypes
JDK Flight Recorder events for the loop's four moments worth profiling: a frame drawn, an event routed, focus changed, async work admitted or rejected. They pair with FrameTiming: timing is a callback the app installs, these are free until a recording asks for them.
JDK Flight Recorder events for the loop's four moments worth profiling: a frame drawn, an event routed, focus changed, async work admitted or rejected. They pair with FrameTiming: timing is a callback the app installs, these are free until a recording asks for them.
java -XX:StartFlightRecording=filename=run.jfr,settings=profile -jar app.jar
jfr print --categories glyphora run.jfr
Every event is a plain jdk.jfr.Event subclass with primitive and string fields and is committed through its own instance — no reflection in this code, so a native image needs no reflect configuration for it. When no recording enables an event, isEnabled is false and the emit sites below skip all field work, including the dirty-cell count.
'''Threads.''' FrameDrawn and EventRouted are committed on the render thread, FocusChanged on the render thread of the DSL host whose focus moved, and the two async events on the submitting thread. JFR events are thread-safe to commit; nothing here is shared.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
JfrEvents.type
Feeds java.util.logging into a LogRing through a plain Handler on a logger — the root logger by default.
Feeds java.util.logging into a LogRing through a plain Handler on a logger — the root logger by default.
A Handler rather than a System.LoggerFinder: the finder is discovered through ServiceLoader, which needs reflection configuration under native-image, while adding a handler to a logger is an ordinary method call that works the same in a JVM and in a --no-fallback binary. SLF4J users route through jul-to-slf4j or slf4j-jdk14 as they already do; there is no SLF4J artifact here.
The handler publishes from whatever thread logged, and the ring is thread-safe, so nothing is marshalled. It does not change the logger's own level: a fine on a logger left at INFO is dropped before it ever reaches the handler, exactly as it would be for a ConsoleHandler. Lower the logger's level to see it.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
JulBridge.type
A caller-owned, serial off-thread frame observer with one replaceable pending frame.
A caller-owned, serial off-thread frame observer with one replaceable pending frame.
Use RunnerConfig(onFrame = Some(observer)). Construction starts one daemon worker, not a task per frame. Admission does not run user code: at most one frame is admitted to the callback and one is pending. A newer pending frame replaces the previous one (explicit latest-frame coalescing), so this is sampling, not a lossless recording API. Delivered frames follow admission order, with gaps for replaced frames. The callback and error handler run serially on that worker, never on the render thread; they must not mutate render-confined state or perform terminal I/O.
onError is required. A non-fatal callback failure is passed to it on the worker; if it returns, delivery continues. A throwing error handler, or a fatal callback failure, escapes to the thread's uncaught-exception handler and retires the observer, dropping pending delivery. It is not swallowed by an executor Future and does not become a runner error. Choose reporting explicitly (and marshal any UI reaction through a previously captured owner dispatcher).
The caller must close this observer, for example from TerminalRunner's onStop hook or a finally block. Close rejects future admission, drops pending delivery and wakes the worker without waiting or interrupting user code. A callback admitted before close may still start or finish afterward, together with its error reporting. An indefinitely blocked callback can therefore retain its worker and frame; close cannot forcibly end user code.
Frames supplied by the runner already contain independent buffer snapshots. No second copy is made here: treat the frame's publicly mutable buffer as read-only after admission, including from other threads holding that frame.
Attributes
- Supertypes
Severity of a LogRecord, in ascending order so level.ordinal >= LogLevel.Warning.ordinal is "warning or worse". Five steps rather than java.util.logging's seven, because a console filter needs a coarse ladder a user can read, not FINER versus FINEST; JulBridge folds the JUL levels onto these.
Severity of a LogRecord, in ascending order so level.ordinal >= LogLevel.Warning.ordinal is "warning or worse". Five steps rather than java.util.logging's seven, because a console filter needs a coarse ladder a user can read, not FINER versus FINEST; JulBridge folds the JUL levels onto these.
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
One captured log line: when it was recorded, how severe it is, which logger (or stream) it came from, the message, and the throwable attached to it, when there was one. An immutable value; the thread that produced it is gone by the time anything reads it.
One captured log line: when it was recorded, how severe it is, which logger (or stream) it came from, the message, and the throwable attached to it, when there was one. An immutable value; the thread that produced it is gone by the time anything reads it.
Attributes
- Supertypes
-
trait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
A thread-safe bounded ring of LogRecords: appending past capacity drops the oldest record.
A thread-safe bounded ring of LogRecords: appending past capacity drops the oldest record.
Owned by the application, which creates it once and hands it to whatever produces records — JulBridge.attach, a CaptureStdio.Console, its own log calls — and to the logConsole element that displays them. Every method is safe from any thread; readers get an immutable snapshot and never observe a half-written record. Appending is a mutation the reactive layer cannot see: a console that must repaint the moment a record arrives pairs the append with a requestRedraw() on the render thread, or lets the next tick or event pick it up.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
What a run does when the process has no terminal to be interactive on.
What a run does when the process has no terminal to be interactive on.
"No terminal" is decided by the host of the run — in the DSL, TuiApp.printTarget: standard output is not a TTY (redirected into a file, piped into another program, an IDE's output panel), or the CI environment variable is set. Every policy but Fail drives the app without a terminal: onStart runs, the first frame is composed at the detected size (COLUMNS×LINES, else 80×24), and the run ends the first time the loop would wait for input — no keystroke is ever going to arrive — so an app that only exits on q still exits, and exits 0. Background work and ticks are not waited for: the frame printed is the one the app composes from its initial state and whatever onStart set synchronously.
- Fail — the behaviour every release before 0.20.0 had: the backend reports
terminal not supportedand the app exits non-zero. The default, because it is what a user who piped a full-screen app by mistake needs to see, and what the CI smoke test of every example asserts. - PrintFinalFrame — the last frame the run composed is written to standard output as styled text (colour per the detected depth,
NO_COLOR/FORCE_COLORhonoured, no escape sequence at all when colour is off), one row per line. - PrintEveryFrame — every frame the run composed, in order, each in the same encoding.
- Plain — the text rows of every frame with no styling whatsoever, consecutive identical frames written once: the form for a screen reader, a log file, or a
grep. - AwaitingIdle — any of the three above, made to wait for the app to settle: built with
PrintFinalFrame.awaitIdle(5.seconds). Instead of ending at the first wait for input, the run goes on — ticks fire,Asyncresults land and repaint — until the loop is idle (no queued render-thread work, no outstandingAsyncwork or timer, and no frame composed since it last waited) ortimeouthas passed since the run started, whichever comes first. An app with a repeatingAsync.everyor an animation that repaints on every tick is never idle, so it prints the frame it had reached at the timeout.
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
A Signal whose value survives a restart: loaded from a file when the signal is created, written back whenever the signal changes.
A Signal whose value survives a restart: loaded from a file when the signal is created, written back whenever the signal changes.
private val layout = Persisted.signal(configDir.resolve("layout.txt"), Layout.Default)(codec.encode, codec.decode)
The result is an ordinary Signal — read it, write it and subscribe to it like any other. What is added is a subscriber that, on every change, hands the encoded current value to Async and writes it on a worker thread, so the render thread never blocks on disk. Writes coalesce: a burst of changes produces at most one write in flight and one pending, and the pending one always carries the newest value, so the file ends holding the last state and never an intermediate one. Each write goes to a sibling temporary file and is moved into place atomically, so a crash mid-write leaves the previous file intact rather than a truncated one. Missing parent directories are created.
Loading is synchronous, on the thread creating the signal — a constructor or onStart, before the first frame. A missing file, an unreadable one or text decode rejects all yield initial: a persisted value is a convenience the app must be able to run without, so the file is never a reason not to start. A write failure is reported the way a failing Async.run is — to the render loop that owns the signal, which surfaces it as RunnerError.QueuedTask when the app exits — and the signal keeps its in-memory value regardless. A drain reports its first write failure, attempts newer pending values, and releases its gate so later changes can recover; it does not retain an unbounded list of failures during a burst.
Ownership and threads: the render-thread rules of Signal are unchanged; set is a render-thread call. The encoded text is produced on the render thread at change time, so encode sees a consistent value, and only the finished String crosses to the worker. The file is this signal's: two signals on one path would overwrite each other.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
Persisted.type
Every queued-body failure one run absorbed, collapsed into a single report.
Every queued-body failure one run absorbed, collapsed into a single report.
first is the throwable that started it and count how many failures there were in total; the later throwables are attached to first as suppressed exceptions, up to a cap — so a continuation that fails on every tick for a week neither reports as one incident nor accumulates a week of stack traces.
Attributes
- Supertypes
-
trait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
A readable reactive value: a mutable Signal, a cached Computed, or a transparent Derived view.
Reads come in two flavors: get requires a ReactiveScope capability and subscribes the enclosing computation to future changes (automatic dependency tracking — no manual dependency arrays); peek reads untracked. Dependency edges are re-established on every recomputation, so conditional reads (if cond.get then a.get else b.get) subscribe exactly the branch that actually ran.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
The capability that makes a reactive read tracked: Reactive.get requires one and reports the read to it, so whoever owns the scope learns what was read and can subscribe to changes. Reads that should not subscribe anything use peek instead — or ReactiveScope.untracked when an API demands a scope.
The capability that makes a reactive read tracked: Reactive.get requires one and reports the read to it, so whoever owns the scope learns what was read and can subscribe to changes. Reads that should not subscribe anything use peek instead — or ReactiveScope.untracked when an API demands a scope.
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
-
class GenerationalScope
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
ReactiveScope.type
How a render loop reports a NonFatal throwable escaping a body queued with RenderThread.runLater — typically the continuation of some background work (see Async).
How a render loop reports a NonFatal throwable escaping a body queued with RenderThread.runLater — typically the continuation of some background work (see Async).
Installed per loop rather than passed at the call site the way AsyncErrorHandler is: each runner owns its own queue, and the queue is drained long after the caller that filled it is gone. It runs on the render thread, inside the drain; anything it throws propagates and stops that drain, which is exactly how RenderTaskErrorHandler.rethrow surfaces a failure on a loop no runner owns.
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
The single-render-thread model.
The single-render-thread model.
All UI state mutation must happen on a render thread — the thread running a Runner loop. The guard is deliberately a no-op while no render thread is registered, so unit tests of widgets and signals need no running runtime.
Each runner owns its own work queue rather than sharing one process-wide, so two runners in the same JVM (parallel test suites, an embedded app) never execute each other's queued work on the wrong thread.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
RenderThread.type
The mid-level API tier: owns the event/render loop over a Backend.
The mid-level API tier: owns the event/render loop over a Backend.
onStart runs once, on the render thread, after the terminal has been prepared and before the first frame is composed. It is the earliest moment at which the app is certainly on the render thread, which makes it the correct place to start background work: Async captures its target loop from the calling thread, so a repeating task armed from a constructor attaches to no loop at all. Calling RunnerHandle.quit from onStart exits without ever rendering a frame. onStart has no default: an app that needs nothing there passes _ => (), which costs one lambda and keeps the hook visible at every call site.
handleEvent answers, per event, whether the UI must be repainted — see EventOutcome. render fills the frame on each redraw. run blocks until the app quits (via RunnerHandle.quit) or the backend fails, and always restores the terminal on the way out — including when handleEvent throws, which ends the loop as RunnerError.Handler rather than unwinding out of run past the terminal restore. The calling thread becomes the render thread for the duration of run.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
-
class TerminalRunner
Attributes
- Companion
- class
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
RunnerConfig.type
Runner configuration: an optional tick rate (synthetic Event.Ticks for animation) and whether to capture mouse events.
Runner configuration: an optional tick rate (synthetic Event.Ticks for animation) and whether to capture mouse events.
tickRate is a FiniteDuration rather than a Duration on purpose: "no ticks" is spelled None, and every infinite Duration is a runtime failure waiting to happen — Duration.Inf.toNanos throws, so RunnerConfig(tickRate = Some(Duration.Inf)), a plausible spelling of "never tick", used to type-check and then kill the render loop on its first iteration.
onTaskError decides what happens when a body queued onto the render thread (an Async continuation, a timer body) throws. None — the default — accumulates them and returns them from Runner.run as RunnerError.QueuedTask once the app exits: the first throwable, the total count, and the later throwables attached to the first as suppressed exceptions. Installing a handler takes reporting over instead: it is called as each failure happens, and run then returns Right unless the backend itself failed. Either way the loop survives the failing body and the bodies queued behind it still run — but only as long as the reporting itself does not throw. A handler that throws is not isolated: it unwinds out of the drain, abandoning the bodies queued behind it, and out of Runner.run. Keep a handler total.
onFrame, when set, is called on the render thread immediately after each frame has been flushed, with a snapshot of what was flushed — see CompletedFrame. It is what gives a production app the frame capture that until now only tests could get through HeadlessBackend.lastDrawn: an "export the screen" command, a frame attached to a bug report, a periodic sample. None, the default, costs nothing at all — no snapshot is taken. A body that throws is not absorbed: like the render function it ends the loop as RunnerError.Handler, because a second isolation policy for frame observers would be one policy too many to reason about. For bounded off-thread sampling, pass a caller-owned LatestFrameObserver; snapshot creation and admission still happen synchronously.
onFrameTiming opts into elapsed phase measurements — see FrameTiming. It runs synchronously after successful composition, draw, observation and cursor placement, on the render thread. Keep it short: it is not itself timed, and a throwable ends the loop as RunnerError.Handler. None adds no profiling clock reads or timing records. Timing alone takes no snapshots; only onFrame enables those.
keyEventTypes asks the terminal to report key releases as well as presses, which reaches the app as Event.KeyRelease. It is off by default because it doubles the input volume for every keystroke and an app that ignores releases gains nothing for the traffic, and it is best-effort even when on: only a terminal speaking the kitty keyboard protocol can report a release at all, so an app must treat releases as an enrichment rather than as the event a feature depends on.
viewport decides how much of the terminal the run owns — the whole alternate screen (the default), or a strip of rows at the bottom of the primary screen that leaves the shell's own output visible above it. See Viewport.
captureStdio decides what happens to System.out/System.err while the run owns the terminal — see CaptureStdio. None, the default, leaves the decision to whoever owns the runner: a bare TerminalRunner captures nothing, while TuiApp captures into printAbove. Set it explicitly — withCaptureStdio(CaptureStdio.Off) — to overrule that host default.
recording, when set, writes every flushed frame of the run to that file as an asciicast v2 recording — see AsciicastRecorder. The runner opens the file before it touches the terminal (a path that cannot be opened ends run with RunnerError.Handler and the terminal untouched), records synchronously after each flush alongside any onFrame observer, and closes it during teardown. None, the default, records nothing — unless the JVM was started with -Dglyphora.record=, which names the file for a run whose configuration did not; the configuration wins when both are set.
nonInteractive says what a run does when the process has no terminal to be interactive on — standard output is not a TTY, or CI is set. See NonInteractivePolicy; the default, NonInteractivePolicy.Fail, is the behaviour every release before 0.20.0 had, and the one the CI smoke test of every example relies on.
An immutable value with a private constructor: build one from RunnerConfig.Default (or the companion apply) and the with* methods, each of which returns a new configuration. The two Booleans and every Option come as a pair — withMouseCapture/withoutMouseCapture, withTickRate(d)/withoutTickRate — so a call site reads as a sentence rather than a true. Equality and hashCode are structural over every field, with one caveat the type system forces: onTaskError, onFrame and onFrameTiming hold functions, which compare by reference — two configurations built from the same handler instance are equal, two built from separately written lambdas with the same body are not — exactly as they did when this was a case class. toString lists only the fields that differ from the default, so the common configuration prints as one short line.
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
Handed to onStart and to event handlers: request loop exit, ask for a frame, marshal work onto the render thread, or reach the backend for out-of-band terminal operations like clipboard access.
Handed to onStart and to event handlers: request loop exit, ask for a frame, marshal work onto the render thread, or reach the backend for out-of-band terminal operations like clipboard access.
Every method is called on the render thread. Core operations are abstract: a handle that silently did nothing for suspend or printAbove would hide a missing implementation behind an editor that never opens.
Adding an abstract method is source-breaking for hosts and test doubles implementing this trait. insertBefore was added on those terms in 0.13.0, and setPointerShape, notifyDesktop and setTaskbarProgress in 0.20.0. Two optional 0.20.0 additions deliberately preserve source compatibility: setTaskbarState degrades to fractional progress, and setMouseCaptureMode is a no-op for handles without dynamic mouse-mode support. Custom handles must override the latter to support hover/all-motion tracking; the production terminal handle implements both fully.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
A mutable reactive variable.
A mutable reactive variable.
set/update mark dependents stale and (via the root scope) schedule a redraw; nothing recomputes eagerly. Setting an equal value notifies nobody — change detection is delegated to the SignalEquality given in scope at creation (by default ==, with Double/Float comparing by IEEE-754 total order). A value mutated in place is equal to itself, so set(sameInstance) never notifies: hold immutable values in a signal, or set a new instance.
Tracked reads and writes belong to one render owner, not just any registered render thread. Construction on an owner binds immediately; runnerless construction binds its connected graph at first owner access. A live foreign owner (including a nested runner) is rejected. After retirement, the graph may bind to a subsequent run. With no running runtime, ordinary sequential unit-test reads and writes remain permitted.
Writing is render-thread-only, but peek may be called from any thread: the value is @volatile, so a reader outside the render thread is guaranteed to see the most recently set value rather than an arbitrarily stale one. That guarantee is what makes a test harness sound — Pilot drives the app from the test thread while the runner mutates signals on its own, and asserting on peek from there would otherwise be reading a field with no happens-before edge to the write. The subscriber set is deliberately not published that way; it is touched only on the render thread.
Attributes
- Companion
- object
- Supertypes
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
SignalEquality.type
The change-detection strategy a Signal consults on every set/update: when unchanged(next, current) is true the write is dropped — the signal keeps current and notifies nobody.
The change-detection strategy a Signal consults on every set/update: when unchanged(next, current) is true the write is dropped — the signal keeps current and notifies nobody.
The strategy is selected statically, by the type the signal is created with, not by the runtime class of the values it happens to hold: Signal(0.0) gets SignalEquality.doubleTotalOrder because the expression is typed Double. Instances are expected to be stateless and pure — the check runs on the render thread, inline with set, on every write, so an implementation that allocates, blocks, or observes mutable state outside its two arguments breaks the signal's contract, not just its performance.
Provide a local given SignalEquality[A] to override change detection for a type (for example, to compare case classes by a subset of their fields). A given in lexical or imported scope outranks the defaults in the companion, which sit in implicit scope.
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
-
object doubleTotalOrderobject floatTotalOrder
A count-up timer advanced from the app's tick loop.
A count-up timer advanced from the app's tick loop.
Caller-owned mutable state, like the widget states: call tick each frame with the elapsed real time (e.g. the runner's tickRate), and read elapsed / formatted in view. Time only accrues while running; the start/stop/toggle controls and the tick guard come from TickDriven.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
One application state value with pure transitions, cached projections and an optional undo/redo history — sugar over a Signal and Computeds, not a second reactive system.
One application state value with pure transitions, cached projections and an optional undo/redo history — sugar over a Signal and Computeds, not a second reactive system.
final case class Todo(items: Vector[String], filter: String)
private val store = Store(Todo(Vector.empty, ""), history = 50)
private val shown = store.select(s => s.items.filter(_.contains(s.filter)))
def view(using ReactiveScope, Theme): Element =
column(list(shown.get, state), button("undo")(store.undo()))
store.dispatch(s => s.copy(items = s.items :+ "write docs"))
dispatch applies action to the current state and publishes the result; an action that produces a state the signal's SignalEquality calls unchanged notifies nobody and records no history entry. select is a long-lived Computed: create it once beside the store, not inside view, and dispose it with the store's owner — the contract is the one on Computed. With history > 0 the store keeps up to that many previous states; undo steps back through them and redo forward again until the next dispatch, which discards the redo branch.
Ownership and threads: the render-thread rules of Signal and Computed apply unchanged. dispatch, undo, redo, select and get are render-thread calls (or runner-less unit-test calls); peek may be read from any thread. The history is plain mutable state touched only on that same thread.
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Optional runner-owned task group using Async's shared daemon executors, never a pool per screen.
Optional runner-owned task group using Async's shared daemon executors, never a pool per screen.
Create through Async.scope on the owner. Submission, cancellation and close are thread-safe; callbacks always return to that captured owner. Closing is idempotent and rejects subsequent submissions. Owner retirement closes the group automatically; close it earlier when a screen leaves. A new app run needs a new scope.
Cancellation suppresses callbacks not yet admitted by their delivery guard and skips worker work not yet started. It does NOT interrupt or join blocking work, undo side effects, or stop an already admitted callback. Supply IO timeouts/cooperative cancellation yourself. This is best-effort cancellation, not structured blocking concurrency.
Each task reserves one owner callback slot before worker/timer submission. Overload of that owner or the shared worker backlog throws RejectedExecutionException synchronously (not a Left); rejected tasks are unregistered and reserve no capacity. Timers coalesce to one pending/running delivery and hold their slot until cancellation or one-shot completion. Cancellation removes queued deliveries and releases the reservation, but a cancelled worker entry still waits in the bounded worker queue until dequeued, where its work is skipped.
Attributes
- Supertypes
-
trait AutoCloseableclass Objecttrait Matchableclass Any
Attributes
- Companion
- class
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
TerminalRunner.type
The production Runner: raw mode + alternate screen setup, diff-driven redraws, tick emission, resize handling, and render-thread registration around a Backend.
The production Runner: raw mode + alternate screen setup, diff-driven redraws, tick emission, resize handling, and render-thread registration around a Backend.
nanoTime is injectable so tick scheduling and opt-in frame phase timing are testable; production code uses the system's monotonic elapsed-time clock, not a CPU-time clock.
redrawRequested is the host's own "is a frame owed?" question, asked once per iteration — a TuiApp answers it from its signal-invalidation flag. It is read alongside, not instead of, RunnerHandle.requestRedraw: the handle serves code that has no reactive state to invalidate.
onStop is the registered-loop teardown seam: it runs once on the owner thread after a bounded final queued-work drain (at most 256 callbacks per queue), before the queue is closed, the owner is unregistered and the backend is closed. Remaining owned callbacks are discarded; running callbacks are never interrupted. It also runs after partial setup failure. Use it to dispose thread-confined subscriptions and services. Every release is attempted even if an earlier one throws; a prior run failure stays primary, with secondary failures exposed by RunnerError.cleanupFailures (and suppressed on its throwable when it has one). A first non-fatal teardown throwable is returned as RunnerError.Handler; fatal throwables escape only after cleanup completes.
Attributes
- Companion
- object
- Supertypes
A count-down timer advanced from the app's tick loop; fires (via justExpired) once when it reaches zero.
A count-down timer advanced from the app's tick loop; fires (via justExpired) once when it reaches zero.
Caller-owned mutable state: call tick each frame with the elapsed real time, and read remaining / isExpired / formatted in view. The start/stop/toggle controls and the tick guard come from TickDriven; what this class adds is the direction of travel, the clamp at zero and the one-shot expiry latch.
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
How much of the terminal one run owns.
How much of the terminal one run owns.
Fullscreen is the takeover every glyphora app has had until now. The terminal has two screen buffers: the primary one, which holds the shell's output and scrolls into scrollback, and the alternate one, a single screenful with no history. A full-screen app switches to the alternate screen, paints over the whole of it, and switches back on exit — so the user's shell output is hidden for the app's lifetime and comes back untouched afterwards, and the app leaves no trace behind.
Inline stays on the primary screen and owns only the bottom height rows of it. The shell's earlier output stays visible above the app, and the app's last frame is still there after it exits, the way git's output is. That is the shape a progress panel, an installer, or a one-question prompt wants.
These are terminal-space decisions, not widget-space ones: this picks the Rect a frame is composed into. Scrolling inside a widget is a separate thing entirely and is unaffected.
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all