nish/term-io

Opening a terminal, drawing frames, reading events and leaving it as it was: the one entry point that uses the other term modules and does the I/O.

import {
  Frame,
  TermInput,
  Terminal,
  TerminalOptions,
  defaultTerminalOptions,
  openTerminal,
  runTerminal,
} from "nish/term-io";
import { defaultTerminalOptions, runTerminal, TermInput, Frame } from "nish/term-io"
  • runTerminal(options, state, update, render) is the whole program loop: it opens the terminal, runs update(state, input) at options.stepsPerSecond fixed steps a second, calls render(state, frame) whenever the refresh controller (nish/term-rate) lets a frame go out, presents it and closes the terminal when update answers false or the user quits (Ctrl-C under the kitty keyboard protocol; a plain Ctrl-C is SIGINT, after which the runtime writes the restore string). It answers Err with one sentence when the terminal cannot be opened or stdin ends.
  • openTerminal(options) answers a Terminal, for a program that runs its own loop with readEvents, present, stats and close.

Opening refuses a pipe on stdin or stdout, enters raw mode and the alternate screen, hides the cursor, probes the terminal (nish/term-probe, at most TERM_PROBE_TIMEOUT_MS) and turns on what the options ask for and the terminal has: the kitty keyboard protocol (CSI > 11 u: key releases and Ctrl-C as a key), mouse reports (1000, 1002 or 1003, in SGR form 1006, with pixel coordinates 1016 when the terminal has them), bracketed paste (2004) and focus reports (1004).

Before each change reaches the terminal, the runtime's restore string (setTerminalRestore) is set to undo everything — cancel any half-written escape (CAN), end synchronized output, delete the kitty image, pop the kitty keyboard flags, turn mouse, paste and focus reports off, reset the style, show the cursor and leave the alternate screen — so a panic or a signal leaves the terminal as it was.

present() draws the Screen and the Framebuffer, if the options gave one, with the best backend the terminal has capped by the controller (min(caps.graphics, decision.backendCap)), at the controller's resolution divisor and palette, wrapped in synchronized output when the terminal has it, as one write. It follows the frame with a DSR 5 query (CSI 5 n), whose answer (CSI 0 n) acknowledges the frame to the controller and marks the input before it as delivered to KeyState.

No answer from the terminal reaches the program: one that arrives after the probe gave up (a slow link) is taken, and a cell size among them is learned. close reads the acknowledgements still in flight before it leaves raw mode, so none is echoed onto the shell's line.

A frame's cost to the controller is the program's update and render since the last frame plus encoding it, not the write: a write that blocks on a slow link is the link's time, which the acknowledgements measure.

Steady state allocates nothing per frame that outlives it: the frame's strings live in Terminal.send's scope, the pixel encoders write into one PixelBytes, and a read that holds only frame acknowledgements is counted without being decoded.

Private helpers share the importing program's flat symbol namespace (docs/wp26-stdlib.md §3e), which is why each one carries the module's name.

Functions

defaultTerminalOptions

The options a program starts from and changes what it needs in.

const defaultTerminalOptions: () => TerminalOptions
returnsTerminalOptions

A fresh TerminalOptions holding the default each field's comment gives.

openTerminal

Open the terminal: refuse a pipe, enter raw mode and the alternate screen, hide the cursor, probe what the terminal can do and turn on what options asks for and it has. The restore string undoes all of it should the program panic or be signalled before close.

const openTerminal: (
  options: TerminalOptions,
) => Result<Terminal, string>
optionsTerminalOptionsrequired

What to turn on, and how to pace frames.

returnsResult<Terminal, string>

The open terminal, or an Err saying why not: stdin or stdout is not a terminal, or raw mode was refused.

runTerminal

Open the terminal and run the program: update once per fixed step (options.stepsPerSecond) and render whenever the controller allows a frame, which is then presented. A resize is an EVENT_RESIZE (x the new columns, y the rows) with the Screen already resized. The terminal is closed however the loop ends.

const runTerminal: <G>(
  options: TerminalOptions,
  state: G,
  update: (g: G, input: TermInput) => boolean,
  render: (g: G, frame: Frame) => void,
) => Result<i32, string>
optionsTerminalOptionsrequired

What to turn on, and how to pace steps and frames.

stateGrequired

The program's state, handed to every call.

update(g: G, input: TermInput) => booleanrequired

Runs one step on the events since the last in input.events; answers false to stop.

render(g: G, frame: Frame) => voidrequired

Draws state into frame.

returnsResult<i32, string>

Ok(0) once update answers false or the user quits (EVENT_QUIT); an Err for a terminal that could not be opened, or stdin ending.

Classes

Frame

What render draws into: the cells, the pixels, how far into the next step the clock is, and the stats.

class Frame
Member
new Frame(term: Terminal) A frame drawing into term's screen and framebuffer, at alpha 0.
alpha: f64 From 0 up to 1: how far past the last update step this frame is, to interpolate with.
caps: TermCaps What the probe found the terminal can do.
framebuffer: Framebuffer The pixels, options.framebufferWidth × framebufferHeight; 0 by 0 when the options ask for none.
screen: Screen The cell grid, the terminal's size.
stats: TermStats What the controller measured: its live stats object, which the next tick updates in place, so copy a field to keep it past this frame.

TermInput

What one update step gets: the events since the last step and which keys are down.

class TermInput
Member
new TermInput(keys: KeyState) An input with no events yet.
events: TermEvent[] The events since the last step, in the order they arrived.
keys: KeyState Which keys are down, for isDown.
isDown(key: i32, code: i32): boolean Whether a key is down.

Terminal

An open terminal: what it can do, the Screen and Framebuffer a program draws into, and the state that reads its events and paces its frames. Made by openTerminal.

class Terminal
Member
new Terminal(options: TerminalOptions, caps: TermCaps, cols: i32, rows: i32, held: TermEvent[]) A terminal already in raw mode and probed, before anything is turned on; openTerminal makes one and turns on what the options ask for.
ackCount: i32 The frames sent whose acknowledgement has not come back, up to the most the ring holds.
backend: i32 The backend the last frame used.
canvas: Canvas Half-block pixels drawn on screen, two to a cell.
caps: TermCaps What the probe found the terminal can do.
cellHeightPx: i32 A cell's height in pixels as the terminal reported it, at most 256; 0 when it did not say.
cellWidthPx: i32 A cell's width in pixels as the terminal reported it, at most 256; 0 when it did not say.
decoder: KeyDecoder Turns the bytes read from stdin into events.
framebuffer: Framebuffer The pixels the program draws into, options.framebufferWidth × framebufferHeight.
graphics: i32 The best backend the terminal has, a GRAPHICS_*.
keys: KeyState Which keys are down, and the releases made up from silence without the kitty protocol.
options: TerminalOptions The options it was opened with.
palette256: boolean Whether screen was drawn in 256 colours last frame.
pixels: PixelBytes The buffer a kitty or sixel frame is encoded into before it is written.
rate: RateController Paces the frames and chooses their detail from how fast the terminal acknowledges them.
scaled: Framebuffer The framebuffer shrunk by the controller's resolution divisor.
screen: Screen The cell grid the program draws into, the terminal's size.
checkResize(): boolean Take a new terminal size, if there is one: the Screen takes it and the framebuffer is fitted again. It compares the size the terminal answers, not the Screen's, which clamps a huge one, so a huge terminal is not resized every frame.
close(): void Undo everything openTerminal did and leave raw mode. The acknowledgements still in flight are read first, for twice the round trip (the controller's or the last frame's, whichever is longer; 50 to 500 ms), so the terminal's answers are not echoed after the program. A second call does nothing.
present(): void Send a frame: the framebuffer, if any, drawn with the backend the terminal and the controller allow, the stats overlay if the options ask for it, and the screen's changes, as one write followed by the query that acknowledges it. Its cost to the controller is workNs and the encoding, and its send time is when the write began. A closed terminal is not written to.
readEvents(waitMs: i32, out: TermEvent[]): boolean Wait for input and append what it means for the program: keys, mouse, paste and focus events, the releases made up from silence, EVENT_QUIT for Ctrl-C. Frame acknowledgements are taken here and never appended.
stats(): TermStats What the controller measured, with the backend the last frame actually used.

TerminalOptions

What openTerminal and runTerminal turn on, and how the frame loop runs.

class TerminalOptions
Member
new TerminalOptions() The defaults each field's comment gives in brackets.
allow120: boolean Whether 120 frames a second may be chosen (false).
fixedFps: i32 A fixed frame rate, or 0 to let the controller choose (0).
focus: boolean Focus reports, EVENT_FOCUS (false).
framebufferHeight: i32 The framebuffer's height in pixels, or 0 for none (0).
framebufferWidth: i32 The framebuffer's width in pixels, or 0 for none (0). Either side 0 means no framebuffer.
graphics: string The backend to use, as NISH_TERM_GRAPHICS names one ("kitty", "sixel", "halfblock" or "ascii"), or "" to take the best the terminal has (""). The variable, when it is set, wins; the probe refuses a backend the terminal did not answer for, as it does the variable's.
kittyKeyboard: boolean The kitty keyboard protocol where the terminal has it: real releases, Ctrl-C as a key (true).
maxFps: i32 The most frames a second (60).
minFps: i32 The least frame rate the controller keeps before it cuts detail (10).
mouse: i32 Mouse reports: 0 (off), 1000 (clicks), 1002 (drags) or 1003 (all motion) (0).
overlay: i32 The corner (CORNER_* from nish/term-rate) to draw the stats overlay in, or -1 for none (-1).
paste: boolean Bracketed paste, so a paste is one EVENT_PASTE (true).
prefer: i32 RATE_FIRST or DETAIL_FIRST, from nish/term-rate (RATE_FIRST).
quitOnCtrlC: boolean Whether Ctrl-C, when it arrives as a key, quits (true).
releaseGapMs: f64 How long after a held key's last repeat it counts as released, without the kitty protocol (100).
stepsPerSecond: i32 Fixed update steps a second (60).