SyncTERM embeds Wren in three isolated scripting hosts. A persistent trusted VM owns the main menu, a second persistent VM owns the file picker, and every connection gets a fresh restricted VM which is torn down at disconnect. Connected scripts hook into keyboard, mouse, inbound bytes, outbound bytes, status text, and a periodic timer; menu scripts implement the dialing directory and settings UI; and picker scripts implement the local-file consent interface. Each host exposes a different set of capabilities.
This document is the reference for that scripting layer: how scripts are discovered, how the embedded scripts can be overridden, and the complete add-on object model.
Why Wren
Wren is a small, class-based, dynamically typed scripting language. Three properties make it a good fit for SyncTERM:
-
It compiles to bytecode in-process; no separate toolchain or external interpreter is required.
-
The VM is a few thousand lines of plain C with no external dependencies, vendored under
wren_vm/. -
The host program controls every binding the script can reach. No filesystem, networking, or process primitives leak in by default.
The full upstream language reference lives at https://wren.io/. This manual covers only the SyncTERM additions.
Quick Start
The minimal "hello world" hook prints a message to the SyncTERM Wren console the first time you press F1 while connected:
import "syncterm" for Hook, Key
Hook.onKey { |k|
if (k == Key.f1) {
System.print("hello from wren!")
return true // consume the keystroke
}
return false // pass through to SyncTERM
}
Save this as hello.wren in the SyncTERM scripts directory (see
Script Loading), connect to any BBS, and press F1. In a graphical
or native-console backend, open the console with Ctrl+`. In ANSI or
ncurses mode, press Ctrl+S and choose Wren Console from the Online Menu.
Wren Language Reference
A compact reference for the Wren syntax SyncTERM scripts use. Full
upstream documentation at https://wren.io/. Key facts up front:
Wren is single-threaded and cooperative (concurrency via fibers, no
threads); whitespace-significant (newline terminates statements; no
; token); class-based with single inheritance; dynamically typed.
Comments
// Line comment.
/* Block comment, /* nested */ blocks ok. */
Literals
|
Booleans. |
|
The single null value. |
|
Numbers. All numeric values are 64-bit floats; |
|
String literal. Escapes: |
|
String interpolation: |
|
List literal. |
|
Map literal. |
|
Closed Range (1, 2, 3, 4, 5 — includes 5). |
|
Half-open Range (1, 2, 3, 4 — excludes 5). |
Statement Termination
Newlines separate statements. There is no ; token at all. Two
statements on one line is a compile error. This trips up developers
coming from C / JS / Python regularly.
var x = 1 // ok
var x = 1 ; var y = 2 // ERROR: Invalid character ';'
Two consequences of the same rule:
-
Ternaries can’t span lines.
cond ? a : bmust be on one line — the then-branch terminates at a newline before the:. -
elseafter a newline-endedifbody is a syntax error.if (c) bodywhose body sits on the same line as theifends at the newline; anelseon the next line is orphaned. Either brace each branch (soelsefollows}) or put the whole chain on one line.
if (a == "x") foo() else bar() // single-line, ok
if (a == "x") { // braced, ok
foo()
} else {
bar()
}
if (a == "x") foo() // ERROR: 'else' is orphaned
else bar()
Strings and %
The Wren lexer treats % inside a "…" string as the start of an
interpolation %(expr). A % not followed by ( is a lex error —
not a literal %. To put a literal percent sign in a string, escape
it as \%:
"100%" // ERROR: Expect '(' after '%'.
"100\%" // ok — four bytes: 1, 0, 0, %
"got %(x)" // ok — interpolation, inserts x.toString
Every literal % needs a leading \. The pair \% is its own
escape — \\% does not work, because \\ consumes the slash on
its own and leaves a bare %; spell that as \\\%.
Variables
var x = 1 // declare and initialize
x = 2 // reassign
Block-scoped (everything between { and }). Shadowing in inner
scopes is allowed. Top-level var at module scope is a module-level
binding (importable from other modules). Declaration is required
before use; there is no auto-vivification.
Operators
Arithmetic: + - * / % (modulo follows the dividend’s sign), unary
- and +. Comparison: < ⇐ > >= == !=. Logical: && || ! —
short-circuit, return one of their operands (not coerced to Bool).
Bitwise: & | ^ << >> ~ — operate on integers (Wren truncates to
32-bit for the bitwise op). Range: .. and .... Conditional:
cond ? a : b (one line). Type test: obj is Class.
The .. / ... operators bind tighter than method calls, so write
(0...list.count) not 0...list.count when chaining.
Control Flow
if (cond) {
...
} else if (cond2) {
...
} else {
...
}
while (cond) {
...
}
for (item in iterable) {
...
}
break // exit innermost loop
continue // next iteration
return v // return from method/function
for (x in seq) {} works on anything implementing iterate(prev)
and iteratorValue(iter) — Lists, Maps (yields MapEntry objects), Strings
(yields codepoint substrings), Ranges, and your own classes.
Functions and Closures
Wren has no top-level function keyword. Functions are closures
created with Fn.new:
var add = Fn.new {|a, b| a + b }
var n = add.call(3, 4) // 7
var greet = Fn.new {
System.print("hi")
}
greet.call()
Block syntax { … } after a method name passes a closure as the
last argument:
list.map {|x| x * 2 } // map(_) takes a Fn
Single-line { expr } returns expr implicitly; multi-line bodies
return null unless an explicit return is hit. This applies
uniformly to Fn.new, Fiber.new, getters, methods, and operator
overloads. The inverse is also true: { return expr } on a single
line is a compile error — single-line bodies are expression-mode,
and return is a statement.
foo() { 42 } // ok — implicit return
foo() { // multi-line — last expression NOT returned
var x = 1
x + 1 // discarded; foo() returns null
}
foo() { // ok — explicit return
var x = 1
return x + 1
}
foo() { return 42 } // ERROR: single-line, return not allowed
Classes
Single inheritance, no abstract classes, no interfaces. All fields are private to the declaring class (see "Field scope" below).
class Animal {
construct new(name) {
_name = name
}
name { _name } // getter
name=(s) { _name = s } // setter
speak() { // method
System.print("%(_name) makes a sound")
}
static kingdom { "Animalia" } // static getter
static spawn(n) { Animal.new(n) } // static method
// Operators: + - * / % - (prefix) ! < > <= >= == [_] [_]=(_)
+(other) { _name + other.name }
}
class Dog is Animal {
construct new(name, breed) {
super(name) // call super constructor
_breed = breed
}
speak() { // override
System.print("%(name) barks")
}
describe() {
super.speak() // call super method
System.print("It's a %(_breed)")
}
}
Field scope
Field references (_name, __static) resolve against the class
currently being compiled, not the inheritance chain. A subclass'
_x is a brand-new slot, not the parent’s _x. Cross class
boundaries via getters/setters:
class Widget {
construct new() { _surface = null }
surface { _surface } // expose to subclasses
}
class Pane is Widget {
paint() {
var s = surface // ok — uses getter
var t = _surface // BUG: brand-new field, null
}
}
Symptom of getting it wrong: Null does not implement 'X(,)'
errors from subclass methods reading "the parent’s" field.
Naming
-
_name— instance field. Only legal inside a class body; the parser rejects it elsewhere. -
__name— static field. Same scoping rule. -
name_(trailing underscore) — convention for "class-private" methods. Not enforced by the language; a strong project hint.
Foreign methods and classes
foreign declarations bind to host C code:
class Codepage {
foreign static encodes_(s) // host-implemented static
foreign instance_method(arg) // host-implemented instance
}
foreign class Cell { // host owns instance allocation
foreign ch
foreign ch=(s)
}
A class needs foreign class only when the host allocates instance
data; a plain class with foreign static methods is fine for
namespace-style bindings (see Codepage, Hook).
Type checks
obj is Class returns true if Class is in the object’s class
chain. Compiles to obj.is(Class). You can override is, but
you cannot delegate to the default via super.is(c) — is is a
reserved keyword and super. requires an identifier after it.
Override only if the foreign genuinely implements every method of
the claimed class.
Fibers
Fibers are first-class coroutines. Wren is single-threaded and
cooperative; concurrency comes from yielding fibers, not threads.
There is no await, no Promise, no scheduler — the fiber handle IS
the resumption token.
var f = Fiber.new {
System.print("a")
Fiber.yield() // suspend; control returns to .call() caller
System.print("b")
}
f.call() // prints "a", returns when fiber yields
f.call() // prints "b", fiber finishes
// .yield(v) returns v from the .call() that resumed the fiber:
var g = Fiber.new {
while (true) {
var x = Fiber.yield(42) // yield 42, get next call's arg as x
System.print(x)
}
}
g.call() // returns 42
g.call("hi") // prints "hi", returns 42
g.call("yo") // prints "yo", returns 42
// .try() catches abort:
var h = Fiber.new { Fiber.abort("boom") }
var err = h.try() // err == "boom"; h.error == "boom"
Fiber.yield(v) transfers to the immediate .call() caller — a
child fiber yielding inside a hook body returns control to the hook
body, NOT up to the dispatcher. This is what makes
Fiber.new { … }.call() from inside a hook safe.
For host-driven async: a foreign method captures Fiber.current
from a slot and returns; the host arranges to call .call(_) on
the captured handle later. See Modal Input for the
canonical example.
Modules and Imports
import "module" // load module, no symbols imported
import "module" for Name // import a single symbol
import "module" for A, B, C // multiple
import "module" for Name as Alias // rename on import
Module names are strings; the host resolves them. In SyncTERM, modules are
looked up first in the root user script directory, then in the active event’s
user script directory, and finally in the matching embedded scripts. A user
file myhelper.wren in the script directory is importable as
import "myhelper" and overrides an embedded module with the same name.
Common Pitfalls
A checklist of mistakes that catch every new Wren author at least once. Most are consequences of rules above; this section gives them a single place to look up.
-
Semicolons. Wren has no
;. Every separator is a newline. -
Multi-line bodies don’t auto-return. Use explicit
return. -
Single-line
{ return x }is a syntax error. Dropreturn. -
Ternaries on one line only. Split via
if/elseor pre-compute. -
elsemust follow}on the same line, or chain on one line. -
Every literal
%in a string needs\%. Bare%starts interpolation. See Strings and%. -
Subclass
_fieldis NOT the parent’s. Use getters/setters. -
String.countis codepoints;s[i]ands[a...b]are bytes. Mixing them silently truncates UTF-8 strings. For byte iteration uses.bytes.count. -
String
<>⇐>=are not defined.list.sort()on strings aborts; pass an explicit byte-wise comparator. -
Wren modulo follows the dividend’s sign.
-1 % 5is-1, not4. For positive-modulo, write((x % n) + n) % n. -
foreign classis for instance allocation only. Use plainclasswithforeign staticfor namespace bindings. -
No
async/await/ scheduler. Use fibers andFiber.yield.
Wren Standard Library
The built-in classes Wren provides without any host bindings. These
are always available, no import needed. Many are mixin-aware via
the Sequence protocol, so iteration and transformation methods
work on Lists, Maps, Ranges, Strings, and your own classes that
implement iterate / iteratorValue.
System
Static-only namespace for I/O and timing.
|
Print a blank line. |
|
Print |
|
Print each item in |
|
Print |
|
Like |
|
Process CPU time reported by C |
|
Note
|
In SyncTERM, System.print / System.write are routed to the
Wren console log buffer (visible via the Wren Console pane), not to
the process’s stdout. Use Host.print(s) when you need
output to reach the launching shell. Compile errors, reported runtime errors and
stack traces go to both the Wren console and the process’s stderr.
|
Object
Root of every class hierarchy. Every value responds to:
|
Identity by default; classes can override. |
|
Negation of |
|
Hash code, integer. |
|
Type check; same as |
|
Default returns |
|
Returns the object’s class. |
|
Boolean negation. Falsy values are |
Class
The class of all classes. Useful properties:
|
String name of the class. |
|
Parent class, or |
|
The class name. |
Bool
true and false. Has toString (returns "true" / "false")
and the standard ! && || operators (the latter two short-
circuit and return one of the operands, not a coerced Bool).
Null
The single value null. !null is true; everything else
(null.toString, null == null) does what you’d expect.
Num
All numeric values are 64-bit floats. No separate integer type; the language calls something an "integer" when it has no fractional part. Mathematical method-style helpers:
|
π. |
|
+∞. |
|
Max / min finite double. |
|
Range of exact-integer doubles (±2⁵³−1). |
|
Absolute value. |
|
Round-modes. |
|
Square root. |
|
Trig (radians). |
|
Inverse trig. |
|
atan2(self, x). |
|
Natural log, log base 2, eˣ. |
|
nᵖ. |
|
Pairwise min / max. |
|
Clamp into |
|
Fractional part. |
|
-1 / 0 / +1. |
|
Predicates. |
|
Decimal string. |
|
Bitwise (truncated to 32-bit). |
|
Bit shifts (also 32-bit). |
Native integer limits
Native integer quantities exposed as Numbers use the inclusive exact range
Num.minSafeInteger through Num.maxSafeInteger
(−9,007,199,254,740,991 through 9,007,199,254,740,991). Unsigned quantities,
including file sizes, byte counts and offsets, start at zero. Fractions,
NaN, infinity and values outside the range abort before native work starts;
representable values above this range, including 2^53 itself, are rejected.
Counts must also fit the host’s size_t, and narrower protocol or API limits
still apply. SFTP v3 read counts and set-mtime values are bounded by
4,294,967,295. An offset may exceed 32 bits even on a 32-bit host.
Formatting helpers such as Format.bytes deliberately accept estimates and
retain their documented rounding/saturation rules.
Native results are checked before conversion. File.size, File.offset
and File.mtime return FileError with IOErr.outOfRange and errno zero
when the native result cannot be represented. SFTP stat/directory operations
complete with a non-transient SFTPError (IO_ERROR_OUT_OF_RANGE) if any
size or timestamp is outside the range; they never return rounded or partial
metadata. Other integer getters, including profile timestamps, picker
metadata, transfer byte counts and log sequence numbers, abort on overflow.
Continuous measurements such as elapsed fractional seconds remain Numbers.
The persistent transfer queue applies the same bounds to saved sizes, resume offsets, timestamps and IDs. It preserves an invalid queue for inspection and refuses to run it. Job IDs reserve the largest safe integer as the exhausted next-ID value, preventing rounded or reused IDs.
String
Immutable byte string with UTF-8-aware operations. Strings can contain
malformed UTF-8 and embedded NULs. For well-formed UTF-8, s.count counts
Unicode scalars, while s[i], ranges, and s.codePoints[i] use byte offsets.
Use s.bytes for bytes and s.codePoints.toList or s.toList for scalar-ordinal
indexing. Unicode scalars are not grapheme clusters; Text.graphemes supplies
that separate operation.
|
Scalar count for valid UTF-8; does not validate the string. |
|
True iff |
|
A |
|
A |
|
Codepoint substring starting at byte index |
|
Visit byte offsets in the range, expanding complete scalars at lead bytes. Negative indices count from the end. |
|
Concatenation. |
|
Byte index of first match, or |
|
Byte index of match at-or-after |
|
Substring presence. |
|
Prefix check. |
|
Suffix check. |
|
All non-overlapping occurrences. |
|
List of substrings, separator removed. |
|
Strip whitespace. |
|
Strip any chars in the supplied string. |
|
|
|
The string itself. |
|
Single-byte string. |
|
Encode a codepoint as UTF-8 string. |
The codePoints view’s subscript still takes a byte offset; only materializing
it into a List changes the index unit. A subscript into a continuation byte
returns a raw byte String, while codePoints[i] returns -1 there. Ranges are
neither raw byte slices nor scalar-ordinal slices: "é"[0…1] returns the
whole two-byte character, while "é"[1…2] returns "".
No implicit NFC normalization occurs. "é" and "e\u0301" are different
Strings, with scalar counts 1 and 2. A one-byte invalid String can also have
count == 1, so text-taking native bindings must validate UTF-8 using the
explicit byte length rather than a String count or C strlen.
List
Mutable, ordered, dynamic-length, heterogeneous.
|
Empty list. |
|
Pre-fill |
|
Literal. |
|
Length. |
|
True iff empty. |
|
Access / replace; negatives count from the end. |
|
Slice (returns a new List). |
|
Append. |
|
Append every item of |
|
Insert |
|
Remove and return the first occurrence; returns |
|
Remove and return element at |
|
Empty the list. |
|
Index of first match, or |
|
Membership. |
|
In-place sort with |
|
In-place sort with a custom comparator. |
|
In-place swap. |
|
Sequence protocol. |
|
|
Map
Mutable hash map. Keys may be any hashable value (Num, String,
Bool, Null, Range, or Class — not List, Map, or arbitrary
instance). Iteration yields MapEntry objects with key and value
properties; use m.keys when only keys are wanted.
|
Empty map. |
|
Literal. |
|
Number of pairs. |
|
Empty? |
|
Access / set. Missing key returns |
|
Distinguishes "missing" from "value is null". |
|
Remove and return the old value (or |
|
Empty the map. |
|
|
|
Sequence protocol; iterating yields |
|
|
Range
Created via the .. (inclusive) and ... (exclusive-end) operators on
Nums. Lazy — values are produced on iteration.
|
Lower bound. |
|
Upper bound. |
|
Bounds normalised regardless of direction. |
|
True for |
|
Number of values. |
|
Iterate. |
Reverse ranges are valid: 5..0 walks 5, 4, 3, 2, 1, 0, while 5...0
excludes the ending zero.
Sequence (mixin)
The base "iterable" protocol. Sequence itself isn’t usually
instantiated; List, Map, Range, String, and your own classes that
implement iterate(prev) and iteratorValue(iter) inherit its
methods. Most are lazy where it makes sense.
|
True iff |
|
True iff any item passes. |
|
Membership via |
|
Eager count. |
|
Items where |
|
Apply |
|
True iff |
|
Concatenate all items' |
|
…with |
|
Lazy mapped sequence. |
|
Lazy filtered sequence. |
|
Lazy. |
|
Fold from first item. |
|
Fold from |
|
Materialise into a List. |
Fiber
First-class coroutines.
|
Create a paused fiber whose body is the closure. |
|
The fiber currently running. |
|
Resume |
|
Like call, but does not record this fiber as the resumer; cannot be returned to via |
|
Resume |
|
Like |
|
True after the body returns or aborts. |
|
The abort message if |
|
Suspend; control returns to the most recent |
|
…passing |
|
Raise |
A yield ends the current call/try boundary. To catch an error after a later
resume, use try() for that resume too. Fiber.suspend() returns to the host
while retaining the ordinary caller chain; transfer and transferError
retain their standard Wren behavior.
Host UI/resource wrappers drive their own callback fibers with ordinary
try() calls on each resume. Native completions are delivered to those
registered drivers; direct Fiber calls are not redirected. This is a host
callback policy, not an extension to Wren’s Fiber primitives.
Fn
A callable closure. Fn.new { … } is the only constructor.
|
Build from a closure literal. |
|
Invoke with no args. |
|
Invoke with args (up to 16). |
|
Declared parameter count. |
Script Loading
Script Directory
User scripts live in a per-platform directory. SyncTERM creates the directory on first launch if it doesn’t already exist.
| Platform | Scripts directory |
|---|---|
Linux / *BSD |
|
macOS |
|
Windows |
|
Haiku |
|
The directory has two roles, distinguished by where files live within it:
| Path | Role |
|---|---|
|
Importable module. Loaded when something imports it via
|
|
Auto-loaded entry script. Runs at the moment the framework fires
|
Files anywhere else under scripts/ (e.g. user-organised
subdirectories of pure library code) are reached only via import —
the framework owns scripts/auto/ and ignores everything else for
auto-load and per-connection selection purposes.
Module Names
Each script becomes its own Wren module, named after the file
basename without the .wren extension and without any directory
prefix. myscript.wren becomes module myscript, whether it’s at
scripts/myscript.wren or scripts/auto/connected/myscript.wren.
Module names are how scripts cross-reference each other:
import "myscript" for SomeClass
Module names are also how the embedded-script override mechanism works (see below).
Embedded Scripts
SyncTERM ships with a small set of scripts compiled into the binary.
They are not stored as files; the build system runs wren_embed_gen
at compile time, infers each script’s role from its source path
(library vs auto-load, and which event for auto-load), and folds the
sources into a C string table linked alongside wren_host.c.
The currently embedded scripts are:
| Module | Role | Purpose |
|---|---|---|
|
library |
Foundational module: foreign-class declarations and Wren-side
helpers ( |
|
library / menu only |
Trusted main-menu data model: transactional BBS-list loading and editable DirectoryEntry records, program settings, web lists, and custom-font configuration. The connected loader rejects this module. |
|
library / picker only |
Request-scoped file-picker interface. It exposes directory listings, path resolution, metadata, and completion methods, but no file-open capability. Menu and connected scripts cannot import it. |
|
reserved library / picker only |
Host-controlled picker entry and recovery surface. SyncTERM always interprets its embedded copy before loading picker overrides. |
|
auto / picker |
Split-pane file and directory browser. It implements single-file,
directory, save, and cross-directory multi-file selection and exports
|
|
auto / connected |
Connected-session Ctrl+` hook for graphical and native-console
backends. ANSI and ncurses sessions reach the shared |
|
library |
Wren REPL UI shared by the connected and menu VMs. Each invocation reads the log belonging to its current VM. |
|
auto / connected |
Alt+L send-login handler. Sends username, password, and sysop password from the directory entry, with the right send-order rules per connection type. |
|
auto / connected |
Default |
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
Default |
|
auto / menu |
The persistent Wren main-menu controller. It loads the menu BBS
model, prompts for an encrypted-directory password when necessary,
and presents the classic dialing directory: the directory and
SyncTERM Settings lists remain visible together, the active list uses
the configured Classic Theme palette, and the selected entry’s comment and
list commands occupy the bottom two rows. The host calls
|
|
auto / menu |
Internal controller used by C connection and startup code for trusted
alerts, confirmations, prompts, choices, and progress overlays. An
override must preserve the |
The syncterm module is loaded on demand the first time something
imports it. Its top level obtains host-created Cache and Download
objects where that VM has them. The auto-load embeds run when their
owning VM is created: once per application for menu and picker, and
once per BBS session for connected.
Built-in main interfaces
Main Interface selects Classic or Retro: in Classic it is under Program
Settings, and in Retro it is on Settings → Program. Classic remains
the default when MainUI is absent or unrecognized. The accepted choice is
stored as MainUI=Classic or MainUI=Retro under [SyncTERM] and takes effect
when Settings closes, without restarting or reconnecting. It selects
both the offline directory and the existing edit-only connected directory.
Custom main_menu script overrides retain precedence over this built-in choice.
The legacy MainUI=DOS spelling remains readable; saves use MainUI=Retro.
The layout and selected colour theme are independent.
Retro opens on a full-width calling table. Its fixed 45-cell Name column fits
the longest legal name under the 30-scalar / 60-byte UTF-8 limits, including
wide characters. Address uses the remaining space; Port, Type, Term/Graphics,
Encoding, Calls, and Last Call appear as space permits. At 80 columns the table
shows Name, Address, Port, and Type. Narrow screens pan the table with Left/Right
instead of shrinking or truncating the Name column. Term/Graphics describes the
saved emulation and enabled graphics, such as ANSI/RIP1, ANSI/RIP3,
ANSI/Sky1.3, ANSI/Sky3.1, VT52/IGS, or ANSI/BIG; it does not report
live protocol negotiation or use the advertised TERM string as an emulator name.
The last-call date uses local time. Long text is clipped on grapheme boundaries.
Up/Down and paging keys select entries; type-to-search and Ctrl-F/Ctrl-G retain
the usual list behavior, with Retro Find also matching connection columns. Enter
connects offline and edits while connected. F2 edits, Insert adds, Delete
removes, F5/F6 copy/paste, Ctrl-S manages sorting, and </> cycle sort profiles.
A single mouse click selects a directory row; double-click activates it.
The selected entry’s comment is centred below the table, above the clickable
bottom command bar, with the same full-line styling and long-text clipping as
Classic. Entries without comments leave that line blank. F4 opens
the separate Settings screen. Tab moves between the directory and command bar;
Left/Right choose a focused command and Enter runs it. Escape exits the directory
or returns to the existing session.
Opening, resizing, or switching the directory does not resize the remote terminal.
Retro Settings opens one tabbed book with five categories on one row at 80 columns: Program (general behavior and audio/MIDI), Connections (new-entry defaults, modem, security, shell and TLS), Appearance (colours, themes, fonts and display), Files (list path, web lists and file locations), and About (read-only build capabilities and licenses). Regular settings edit directly in the book. Resource editors return to the tab that opened them; Escape from a child returns one level. Pending book edits survive child editors, including theme selection. Build information stays inside About instead of opening another menu. Resource managers and the defaults editor retain their own acceptance rules; the book’s Save/Cancel controls apply to its program-settings draft.
Resource list selectors, sorting and Wren scripts use full-page framed lists with bottom command hints. At 80 columns or wider, a separate scrollable information panel shows help or preview details. Narrow screens retain F1 help. Tab moves between the list and Back. Escape or Back returns to the owning tab or screen. Classic retains its compact menus.
Retro entry settings and New Connection Defaults use separate full-page forms.
They share the Settings book’s tab and field controls. Entry settings have three tabs on one row at 80 columns:
Connection (including login and security), Terminal (including scripts and
palette), and Files & Notes (paths, logging, and comment). New Connection
Defaults uses the same grouping without the per-entry comment, naming its last
tab Files. The active category stays highlighted and bracketed in the
top tab row while keyboard focus moves through its fields. Click a tab or use
Ctrl-PageUp/PageDown to change categories.
Tab/Shift-Tab move between three control groups: the tab bar, form fields, and
Save/Cancel. Entering the tab bar focuses the current page. Home/End jump to
the first/last tab. Arrow keys move within each group; Left/Right stay on the
same row, and Up/Down stay in the same field column. Text editors retain cursor
movement; at either end, Left/Right can cross to an adjacent field column.
tab.selected styles the current page independently of tab.focused for
keyboard focus; tab.selected.focused styles the combined state. Brackets
mark the current tab and > marks keyboard focus, including when colours match.
Labels sit beside their controls; text and number editors retain shaded,
bracketed rectangles when unfocused. Text boxes fit their field limits, numeric
boxes fit their minimum/maximum representation, and enum boxes fit their longest
choice, all capped by the available column width. Manage actions are compact
buttons sized to their labels; read-only facts are not editable boxes.
Enum fields have a down-arrow marker and open an attached dropdown with Enter,
Space, Alt-Down, or a click. The list opens below the field, or above when space
is limited. It expands to show all choices or fill the available height on that
side; a scrollbar appears only when the choices still do not fit.
Arrows, paging keys, Home/End, and typing navigate
choices. Enter or a click accepts; Tab accepts and moves to the next control group.
Escape or an outside click cancels without changing the draft. Resizing keeps
the list attached, or closes it if the field moves out of view. Opening a
dropdown retains the form’s active colours.
Wide screens balance fields across two columns. PageUp/PageDown and the
Previous/Next controls beside the tabs reach overflow fields within the current
category on small screens. F1 opens
contextual help. Specialized palette, script, font,
and file selectors remain available. Edits stay in a private draft across page
changes and resizing. Save/F10 accepts the complete draft; Cancel/Escape asks
before discarding changed drafts. A failed save retains the form and its draft
for retry. In safe mode, allowed program changes use Apply without persistence;
existing directory write restrictions still apply. Existing native partial-effect
errors, such as a saved configuration followed by a runtime-application failure,
are reported without claiming that completed effects were rolled back.
Classic retains its two-pane layout, field-list editors, immediate application of accepted program fields, and existing Escape/save conventions.
Overriding Embedded Scripts
A user script whose basename and role match an embedded module
overrides the embedded one. The shared REPL implementation can be
replaced with
~/.local/share/syncterm/scripts/wren_console.wren; all three VMs import
that library when their built-in menu, connected, or picker entry point opens
the console. Replacing
scripts/auto/connected/console.wren changes only the connected
graphical/native-console Ctrl+` hook. Replacing
scripts/auto/menu/main_menu.wren changes
the menu key binding along with the rest of the main-menu controller.
Replacing scripts/auto/picker/file_picker.wren changes the picker
implementation but not its reserved recovery surface.
The check is an exact match on the bare module name within the same
script role. A root console.wren is a library module distinct from
the connected auto-load module, while a root wren_console.wren
replaces the shared library. Case matters: Wren_Console.wren is a
different module from wren_console.wren.
To opt out of an embedded auto-load script entirely, drop a stub override into the matching directory:
// ~/.local/share/syncterm/scripts/auto/connected/connected.wren
// Disable the default Alt+L handler.
The override is loaded but registers no hook, so Alt+L silently does nothing.
Load Order
-
scripts/auto/<event>/is enumerated for files with the exact lowercase.wrensuffix. -
Each embedded script tagged with the firing event runs, unless its module name appears in the user-script set.
-
Each user script in
scripts/auto/<event>/runs as its own filename-derived module in case-sensitive byte order. This phase runs the user override omitted from the preceding embedded phase. A module already loaded through an earlier import is skipped. -
For
connected, root modules selected by the active personal directory entry run in their stored order. A module already loaded by an earlier script or import is skipped because Wren modules execute only once per VM. -
A command-line
-Wscript runs last in the connected VM.
import statements (whether from a script’s top-level or inside its
body) resolve through the lookup chain for the current VM:
-
scripts/<name>.wren— importable root module. -
scripts/auto/<event>/<name>.wren— where<event>ismenu,connected, orpicker; this catches imports of auto-load modules which have not run yet. -
The embedded table — built-in fallback by module name.
The foundational syncterm module lazily loads the first time
anything imports it; subsequent imports hit Wren’s module cache.
The menu host attempts every menu auto-load module and refuses to start a
partly initialized menu if any of them cannot be read or interpreted. Picker
implementation modules are optional: their errors are logged while the
embedded picker bootstrap and recovery surface remain available. A missing
FilePicker class enters recovery when the picker is invoked.
Per-Connection Scripts
A personal directory entry may contain an ordered WrenScripts INI value:
[Example BBS]
WrenScripts = session_logger,custom_keys
Each value names scripts/<name>.wren; do not include a path or extension.
Names contain only ASCII letters, digits, and underscore, are at most 255
bytes, and are case-sensitive Wren module names. The menu does not offer a
module already present in the entry, and the host removes exact duplicates
assigned through the menu API. syncterm_menu, syncterm_picker, and
picker_bootstrap are reserved and cannot be selected.
The editor catalog is rebuilt from root user-script files with the exact
lowercase .wren suffix on each request, in case-sensitive byte order. It
does not include modules embedded in the executable. Files with invalid
module names and the three reserved names above are omitted.
The entry editor’s Wren Scripts row opens the ordered-list editor. Select the
blank final row or press Insert to add a root module; Delete removes one.
Enter tags the selected module, Up and Down move it, and Enter places it.
Escape while moving restores its original position. A configured module
whose file is no longer present remains visible as [Missing] so opening and
saving the entry does not silently discard it.
Only personal named entries load this field. Defaults, installed system entries, web-list entries, and quick-connect records cannot activate scripts. At connection time, an unreadable configured module is reported in the connected VM log and error indicator, and loading continues with the next configured module.
A script’s top-level code runs once in the VM which owns its event. Top-level code commonly registers hooks or creates the long-lived menu controller; persistent state should be stored on classes (static fields).
The built-in main_menu module is also the host entry-point contract.
An override must export class MainMenu with these static methods:
-
prepare()loads the directory, performs any password interaction, and returns a Bool indicating whether the model is ready. -
run(currentName, connected)presents the directory.currentNameis a String ornull. Whenconnectedis false, return a current DirectoryEntry or Profile to start that connection ornullto exit. Connected invocations are edit-only; their return value is ignored. -
offerSave(source, name)receives a detached Profile and a separate suggested entry name after an unsaved quick-connect or command-line connection ends, including a return to the directory via Alt-H, and returns whether it was saved. The host callsprepare()first, then copies the C record into menu storage; no connection-owned pointer or foreign value is passed into Wren.
Additional trusted auto/menu scripts can extend the shipped controller
without replacing it:
import "syncterm" for Mod
import "main_menu" for MainMenu
MainMenu.registerCommand(121, Mod.command, "Alt-Y", "Open an offline planner",
Fn.new {|app, connected| Planner.show(app) })
registerCommand(key, modifiers, keyName, description, callback) replaces an earlier
extension on the same key/modifier pair or appends a new one. The overload
without modifiers uses zero. Registration happens during
menu-VM startup, before MainMenu.run builds its controller. The callback
receives the running App and the connected-directory Bool, is suppressed
while another modal is open, and its key name and description are appended to
the directory help.
When the built-in module is loaded, it paints the main-menu background and
title bar immediately. Startup alerts and progress panes therefore appear
over initialized menu chrome before MainMenu.run() constructs the
interactive directory.
The host validates and copies a record returned by run while the menu
VM is still selected, so the Wren foreign object itself never crosses
into the connected VM.
For an independently packaged frontend using this override contract, see Modern UI. Its directory/settings scripts are installed into the user script directory and are not embedded in SyncTERM.
The shipped controller binds Ctrl+` to the menu VM’s REPL in graphical
and native-console backends, and Ctrl+Q in ANSI and ncurses modes. A
CP437 ‼ in the top-right corner reports unread output from that VM: yellow
for print output and red for errors. Synchronous key and mouse handlers
run through an error boundary; an abort is added to the menu VM’s log,
the indicator is refreshed, and the main menu continues running. This
boundary does not hide layout or painting failures, which still abort
MainMenu.run rather than repeatedly failing during every redraw.
The Classic controller defines the following main-menu interaction contract. The Retro presentation shares its directory operations and host entry point, with the navigation and draft-editing differences described in Built-in main interfaces. After a connection or failed connection attempt, the offline directory restores its selected entry and viewport rather than returning to the first row. The selection follows the entry’s name across reloads and sort changes; if that entry disappeared, the previous row is retained and clamped to the new list. Connected-directory editing keeps a separate bookmark and does not overwrite the offline return position. Viewports are clamped when the list or screen size changes so the selected row remains visible.
Tab from the directory enters the selected entry’s comment field, then advances to the
simultaneously visible settings pane; Backtab traverses the same path in
reverse. Left and Right move directly between the directory and settings.
The first completed left click in an inactive pane transfers focus without
activating a row; a second click activates the row. A wheel event moves the
active list regardless of which pane is under the pointer. A completed left
click on the main-screen background transfers focus to the other pane.
Enter connects (or edits while connected) from the directory and invokes one
settings action from the settings pane. F2/Ctrl-E, Insert, Delete, F5/F6,
Ctrl-S, </>, Ctrl-D, and Alt-B invoke their documented commands. F2 does
nothing on the blank append row; Ctrl-E invokes the row’s add operation. The
comment row is also clickable for direct editing. An override may present the
model differently while preserving the host entry-point and ownership contracts.
The comment is edited only in the main screen’s footer. It is not a field in the full directory-entry editor. F1 and Ctrl-Z in the footer display the directory help. Operation-specific alerts and confirmations display the context help for the operation which opened them.
The footer advertises edit, copy, paste, insert, and delete only while the directory pane owns focus. The SyncTERM Settings pane advertises only Help and Exit, matching the operations available from that pane. While a comment is being edited, the footer shows the hints for the pane that opened it.
Lists which support appending provide a selectable blank final row.
Activating the blank row or pressing Insert invokes the same add operation.
The shipped directory, sort-profile, sort-field, web-list, custom-font, and
short-palette editors expose both forms; the palette row is omitted once all
sixteen colors are present. + aliases Insert, while - and ASCII DEL alias
Delete. Ctrl-Insert aliases F5 Copy, Shift-Insert aliases F6 Paste, and
Shift-Delete invokes Cut where that operation is available. Backspace and a
right click alias Escape after the focused widget declines the event. Delete
and the editor-specific copy, paste, rename, and cut keys are direct list
commands.
Adding a directory entry prompts for its name, connection type, and address,
then writes it immediately and returns to the directory. A single :port
suffix is accepted for network addresses. F2 or Ctrl-E opens the full entry
editor. Editing a read-only entry first offers to create a personal entry
with the same name. F5/F6 prompts for a new name when pasting a personal
entry; pasting a copied read-only entry uses the copied name.
The specialized editors provide direct menu operations. Enter on a sort
profile opens its field list, and Enter on a sort field reverses that
field; [ and ] move between profiles without returning to the profile
list. Enter on a web list edits its URI. Font details are a flat Name plus
four cell-size paths, and selecting a path opens the picker directly.
The encryption screen has distinct Change Password, algorithm, and Decrypt
operations; changing algorithms reuses the password already held by the
host. Palette editing uses a combined RGB, HSV, and hexadecimal colour
picker. The RGB ramps accept exact decimal entry, every ramp supports
keyboard and mouse adjustment, and the contrast grid selects the
foreground/background pair shown in the sample. % restores the mode
default; Enter accepts the colour and Escape cancels it.
In safe mode, accepted default-entry and web-list changes update the in-memory model but are not written to configuration files. Encryption conversions are no-ops; Change Password presents its password prompt before returning.
When an action rebuilds a repeating editor’s list, the editor retains the
same row and viewport position. This applies to entry logging and palettes,
sort profiles and fields, program settings and their nested lists, web lists,
and font management.
Directory editing commands apply only while the directory pane owns focus.
Directory, pasted-entry, command-line-save, sort-profile, and web-list name
prompts repeat after an invalid or duplicate name. Entry-editor prompts
distinguish empty, reserved, and duplicate names. Directory add and
command-line-save prompts treat an empty edit as cancellation while still
distinguishing reserved and duplicate names; an entry creation failure is
reported separately. Sort-profile field navigation returns to the last
profile visited. New entries are inserted according to the active sort
profile after their connection details are accepted. Quick Connect limits
the directory address field to 64 characters. Current Screen Mode and
Startup Screen Mode use distinct dialog titles and context help.
When PromptSave is enabled, every unsaved quick-connect or command-line
session offers to save its complete entry after disconnect. Accepted SSH
host keys remain in the temporary profile until that entry is saved; host-key
verification updates only existing personal entries and preserves their
list encryption.
Directory password and system-password rows are obscured in the editor
list, but selecting one uses ordinary text editing so the existing value can
be inspected and corrected. Personal-directory encryption prompts are
masked.
Rate choices select the first supported rate at or above a configured value,
or Current when no supported rate is high enough.
An OS window-close request sets a sticky process-exit latch. It does not ask
the main menu or connected session for confirmation. An App unwinds nested
widgets through their normal Escape path one modal frame at a time, allowing
each Wren call to return and run its normal cleanup. A widget explicitly
marked atExit remains interactive; the command-line directory-entry save
workflow uses this for its confirmation, prompts, errors, and editor.
Accepted Classic Theme colour changes rebuild the active theme immediately
while Classic Theme is selected. A selected file theme is unaffected.
Renaming a persisted entry also renames its per-entry cache directory after
the directory file is written successfully.
Font Management treats an empty name as cancellation when adding a record.
Otherwise, it accepts the entered name and the file returned by the picker as
the record values. It reports a full custom-font table before prompting for
another name. The preformatted File Locations and Build Options viewers use
the titles File Locations and Build Options. Their maximum dimensions are
78 by 21 and 60 by 21 cells respectively, capped to preserve the standard
modal margins and complete drop shadow. Their Markdown content defines the
label emphasis, indentation, and section layout rendered by the shared Help
viewer.
Palette Insert is exposed only while the palette has room for another color,
and Delete is exposed only while a color can be deleted. Sort-profile Paste
is exposed only after Copy or Cut has supplied a clipboard profile. Font
Details and the outer Font Management list both support Insert, Delete, and
the blank add row.
Adding a web list skips its initial fetch when no cache path is available but
records the configuration; explicit refresh reports the missing cache.
Left and Right move directly between the directory and settings panes.
Leaving the comment field by mouse, pane navigation, or application exit
commits the accepted edit before focus moves. The entry editor reselects its
highlighted field after [ and ] move between entries. Program Settings
summarizes enabled audio backends, and entry rows distinguish automatic
terminal types, unset passwords, and nonzero communication rates.
Web-list edits update the in-memory configuration immediately and are written
when the Web Lists screen closes.
Saving an existing directory entry does not change its Added timestamp.
Clearing the Terminal Type field writes the empty override, so a subsequent
directory reload uses automatic terminal-type selection. In the palette
component editor, % resets all three components of the selected colour from
the mode palette without moving focus to another field.
Creating or copying a personal entry with the same name as a read-only entry
replaces that row immediately. The model stores the read-only entry beneath
the personal override. Deleting the override exposes the read-only entry;
renaming and saving the personal entry exposes the read-only entry under its
own name.
Adding an entry may create such an override. Pasting a copied personal entry
instead requires a name unique across all currently visible entries.
The inactive directory comment is centered across its line. While the
directory pane has focus, its selection supplies the OS window title; while
the settings pane has focus, the title is the bare SyncTERM version. Editing
a comment leaves the title from the pane where editing began until focus moves
again. The active editor is left-aligned within the middle
screen width - 4 cells.
Its existing value initially appears selected in the text-input lightbar, so
typing or deleting replaces the complete comment. Cursor movement or mouse
positioning leaves the value unchanged and switches to the normal menu colors
for ordinary editing. Leaving the editor immediately centers the inactive
row, even when its value was unchanged.
The shipped menu keeps context help beside the Wren screen that owns each
control. Directory, sort-profile, entry-editor, settings, web-list, font,
and encryption panes assign Markdown helpText to their panes and nested
dialogs. F1 therefore resolves to the general screen description from the
list and to field-specific help while a choice or prompt is open. Menu
overrides should use the normal Help Markdown contract described under
Help viewer. Help content must be Markdown; legacy help-buffer
markup is unsupported.
The shipped editors distinguish accepting an edit from writing its backing file. A confirmed entry field immediately updates the entry-backed Profile view, and a confirmed program setting is immediately applied to the running settings. Their files are written when the owning entry or Program Settings editor closes. Font changes stay in the font model until Font Management closes. Sort-profile operations update the working profile model, which is written when Sort Profiles closes; profile cycling from the main directory writes immediately. None of these screens exposes the persistence boundary as a selectable Save or Cancel row.
Escape from a nested prompt or choice cancels only that nested operation. Escape from an owning editor closes it without rolling back accepted edits. An owning menu stays on the modal stack and is rendered behind a nested prompt, picker, viewer, or submenu until that child is dismissed.
Headless Tests
The CMake test suite drives menu and picker VMs against headless consoles and isolated temporary data trees. After building a configured tree, run the Wren tests with:
ctest --test-dir build --output-on-failure -R '^(wren_|st_wren_)'
The wren_host test covers the shared host bindings. The wren_* tests run
the menu, picker, and individual UI-script suites through the same embedded
module loader used by the application. The current tree does not provide a
standalone source-tree connected-VM script runner.
VM Lifetimes and Trust Boundaries
SyncTERM deliberately uses three Wren VMs. They do not share Wren objects, handles, modules, globals, hooks, timers, result queues, or foreign objects.
The persistent menu and picker VMs each own a logical console. A VM’s normal UI and its REPL share that console rather than copying the screen into a separate REPL console. Their cells, fonts, palette, cursor, dimensions, and pending input remain independent while one physical display switches synchronously between them. Work on the inactive console remains off-screen until it is selected. The connected terminal still uses the existing screen-ownership path pending its migration to the same display model.
-
The menu VM is created once after conio and configuration are initialized. It owns
scripts/auto/menu/, survives connections, is parked while the connected screen is active, and is destroyed at application shutdown. It can edit the BBS list and settings and can request a picker operation. -
A fresh connected VM is created by
wren_host_init(bbs)for each BBS session and freed bywren_host_shutdown()on every exit path. It ownsscripts/auto/connected/. Module statics, hooks, timers, claims, and queued results do not survive disconnect. -
The picker VM is created once after the menu VM, owns
scripts/auto/picker/, and remains parked except while a picker request is active. It cannot importsyncterm_menu, inspect BBS records, change settings, establish connections, or open files. Its request object exposes only directory listings, path resolution and metadata, and one-shot completion methods.
The remote system is considered hostile. A remotely supplied script
may know the active entry’s username, password, and system password;
those values are already meaningful to that remote. It must not gain
the authority to enumerate or edit other BBS entries, change global
settings, start another connection, or mint arbitrary local-file
access. Consequently syncterm_menu is not merely omitted from the
connected documentation: the connected loader explicitly rejects it,
and menu foreign objects cannot cross the VM boundary.
Menu auto-script overrides are trusted application code, not a sandbox for
downloaded scripts. In addition to directory and settings mutation, the
menu VM can invoke picker-mediated local-file operations, open URLs from the
completed session’s scrollback, and update trusted application chrome. Do
not install a remotely supplied script under scripts/auto/menu/; remote or
otherwise untrusted session automation belongs in the per-connection VM and
receives only that VM’s capabilities.
Connected scripts intentionally retain Input.ungetKey,
Input.ungetMouse, physical-key synthesis, and the other synthetic
input bindings. User scripts need them to automate the current remote
session. Isolation is provided by the VM and transition barriers, not
by removing those session-local controls.
At every ownership transition (connect, disconnect, entry to or return
from the menu through Alt+E, and entry to or return from the picker), the
host establishes a new input epoch. It discards pending conio keyboard
and mouse pushback and rejects late input-shaped results tagged with an
older epoch. Input claims remain parked in the VM that owns them and
cannot run while another VM owns the screen. This prevents a connected
script from placing synthetic input in
ungetkey() / ungetmouse() just before the trusted menu or picker
takes control. The same barrier protects the connected VM when control
returns from a trusted UI. Physical-key production is suspended while
the menu owns input, restored when returning to a live connection, and
disabled with its held-key state cleared when the connection ends.
The picker VM is the local-file consent broker. Neither its caller nor
the picker script receives arbitrary pathname-open authority. A
single-file or multi-file completion is converted by C into read-only
File handles. A save completion explicitly reports create or
overwrite consent; C converts it into a one-shot write-only grant without
retesting the pathname. These rights remain attached to the foreign
File handle as documented in Write consent.
The request object is invalidated as soon as the picker returns, so it
cannot retain listing or completion authority between calls.
Picker overrides under scripts/auto/picker/ are trusted local
application code, but the picker VM still receives only the capabilities
needed by the browser. The host always interprets the embedded
picker_bootstrap first. A picker implementation compile or runtime
failure therefore enters a recovery screen instead of terminating
SyncTERM: Ctrl+` opens the picker VM’s REPL, Escape cancels the
request, and Key.quit exits the application. The normal picker shows
that VM’s unread or error indicator at the top right and uses the same
Ctrl+` binding. Only failure to initialize the VM or reserved
bootstrap disables picker operations.
C-owned startup and connection flows also render their dialogs through the persistent menu VM. These calls do not expose a dialog capability to connected scripts. Blocking alerts, confirmations, prompts, and choices save and restore the current screen and establish input barriers both before and after the dialog, so synthetic connected-session input cannot answer a trusted question. Progress overlays deliberately do not clear or claim input: connection setup continues polling conio so the user can abort a stalled operation. Clearing progress restores the exact screen, palette, fonts, video flags, and cursor state saved when the first update was shown.
The embedded menu_host_ui module exports class MenuHostUI with static
methods alert(title, message), alertWithHelp(title, message, helpText),
help(title, body), confirm(title, message),
prompt(title, message, initial, maxLen, masked),
choice(title, message, options, current),
ripChoice(title, message, options, hotkeys, required), status(title, lines), and
statusClear(), plus disconnected(title, details) for the post-session
bottom-row notice. That notice keeps the completed terminal visible until
Enter, with F1 opening session details and the final protocol log. Alt-B
(Cmd-B on macOS) opens that session’s scrollback; Escape returns to the
notice. If the connection had a status bar, its row stays blank in the
disconnected style outside the viewer’s content area. With the status bar
disabled, the viewer uses the full terminal height, including the bottom row.
Without a status bar, the terminal scrolls once to make room for the notice.
History is saved before that scroll, so opening scrollback reconstructs the
completed screen apart from its scrollback indicators. Terminal dimensions
and status layout are preserved, and the notice does not enter saved history.
hidePopups and local hangup/exit skip the notice. This is a host-controller
ABI rather than a public menu script API: application C code holds the call
handles and invokes it.
ripChoice is the C-owned RIP pick-list bridge: hotkeys are Unicode scalar
values (zero disables one), and required lists ignore Escape and outside clicks.
Closing the application still unwinds the dialog and restores its saved screen.
The progress pane fits the wider of its title and status rows, capped to the
standard screen margins. The pane itself is centered, but all status rows
share one padded left edge so preformatted columns remain aligned between
rows. Text wraps within that common content width on narrower screens.
Menu auto-script overrides are trusted and may replace its presentation,
but must keep those signatures and return Bool, String/null, and
numeric choice indexes as appropriate or host dialogs fail closed.
Every reconnect rebuilds the connected VM from scratch. Connected
scripts needing cross-session state must persist it through an
authorized Cache / Download file or picker token. Menu scripts can
keep ordinary Wren state for the application lifetime, but durable
changes still require the explicit model save methods.
Console entries, cached entry handles, REPL state, and unread markers belong to one VM. Opening the menu through Alt+E therefore shows the menu VM’s log, not output produced by the parked connected VM, and no console object or handle crosses the trust boundary.
The owner thread is captured at init; dispatchers called from any
other thread (background SFTP and SSH writes invoke conn_send from
worker threads) short-circuit to pass-through. Scripts run on the
foreground thread only.
Importing the API
Shared host bindings live in module syncterm. Every script imports
the classes it needs:
import "syncterm" for Screen, Input, Conn, Hook, Key
An import does not grant all methods declared by that module. The host resolves known shared declarations so UI libraries can load in each VM. Calling a known capability owned by another VM aborts with "this capability is not available in this VM". Unknown foreign method declarations fail immediately during module loading, identifying the module, class, and signature. Constructing an unknown foreign class aborts with a missing-allocator error; the host never supplies an unrelated native payload. Namespace classes use ordinary Wren classes with foreign static methods. Menu-only data APIs are imported separately:
import "syncterm_menu" for Menu, DirectoryEntry, Settings, MenuFont, MenuError, BBSLoadDiagnostic, BBSListSource, MenuEncryption, MenuFontSlot
Cache is injected into the syncterm module from C as a
module-level Directory object — there is no Wren-callable
constructor. Import it like any other binding:
import "syncterm" for Cache
Hook Events
Hooks are registered as Wren callables (block, function, or method
reference). Each call site walks its hook list in registration
order; the first hook returning true consumes the event and stops
dispatch. Returning false, returning a non-Bool, or throwing
passes through to the next hook and ultimately to SyncTERM’s default
handling.
Every registration returns a HookHandle (or null if the per-event
limit is hit) — see HookHandle. Save it if the script needs to
remove the hook later or read its metrics; toss it if not.
Hooks must run synchronously
Every hook fire is wrapped in a child fiber via Hook.dispatch_.
For C1-contract hooks (see Two return contracts) the dispatcher needs
the hook’s return value before it can decide what to do next; a hook
that yields up to the dispatcher would strand it with no value to
act on. C2-contract hooks ignore returns, but yielding still
breaks the dispatch chain.
If a hook callback yields its own fiber directly (for example by awaiting an operation directly inside that callback), the dispatch wrapper detects the yield and logs:
hook handler must not yield directly; wrap parking work in
Fiber.new { ... }.call()
The hook is then treated as if it returned a non-Bool — the input
passes through to the next hook and to SyncTERM’s default handling.
A Fiber.abort from the hook is caught the same way: logged with a
stack trace, treated as passthrough.
A hook that needs to wait on async results has two options that keep the hook itself synchronous. The first wraps the work in a child fiber and `.call()`s it from the hook body:
Hook.onKey { |k|
if (k == Key.f2) {
Fiber.new { runModalBrowser() }.call()
return true
}
return false
}
.call() runs the child fiber synchronously until it yields (e.g.
on an SFTP op or a Fiber.yield() waiting for a Wake.post).
The child’s yield returns to the hook body — the immediate
.call() caller — not up to the dispatcher. The hook still
returns its Bool; the child resumes later via the framework’s
result-queue drain.
The second option is to observe the operation with .then(fn), whose
callback runs when the result arrives. The hook returns
synchronously without ever yielding; the callback fiber is invoked
later by the drainer:
Hook.onKey { |k|
if (k == Key.f2) {
SFTP.realpath(".").then(Fn.new {|r|
// handle r …
})
return true
}
return false
}
Two return contracts
Every hook callback follows one of exactly two return-value contracts. Knowing which contract a hook uses tells you what (if anything) your return value does.
| Contract | Behaviour |
|---|---|
|
|
|
The return value is ignored entirely. These hooks fire as a
side-effect notification; the event continues regardless. A |
onKey, onPhysicalKey, and onMouse use C1 but have no meaningful
interpretation for String returns (a key event, a
PhysicalKeyEvent, or a MouseEvent isn’t a byte stream), so a String
return from those is silently treated as passthrough. Use onWire for
wire-byte replacement, or onInput for Unicode text replacement.
| Method | Argument | Contract |
|---|---|---|
|
|
C1 |
|
Filtered by logical key and modifier mask; the short form uses zero
modifiers. Caps Lock and Num Lock are ignored. Other modifier bits must
match exactly. The callback receives a complete |
C1 |
|
|
C1. String replacements are NFC-normalized semantic UTF-8 text, capped at 256 bytes. Invalid UTF-8 or an oversized replacement logs an error and passes through the original scalar. |
|
Filtered: |
C1 |
|
|
C1. A returned String contributes its exact bytes to the parser, without revisiting wire hooks. Replacements are capped at 256 bytes; an oversized replacement logs an error and passes through the original byte. |
|
Filtered: |
C1 |
|
Receives mapped controller value changes before graphics and CTerm. The
Map has numeric |
C1 |
|
|
C1 |
|
Filtered: |
C1 |
|
|
C2. An "honor |
|
Same as |
C2 |
|
|
C1 |
|
Filtered: |
C1 |
|
|
C2 |
|
Fires once when the SSH shell channel closes but the session is still alive (e.g. SFTP transfers may still be in flight). Typical use: pop a status / queue UI so the user can watch transfers finish, or signal a worker to wind down. See Session for owned lifetime leases that keep auxiliary work running after shell EOF. |
C2 |
|
Fires at the end of the disconnect path, after the main loop has fully exited but before the BBS / Wren VM tear down. SFTP is no longer available at this point (sftpc_finish has already run); use this for final local-state flushes (queue persistence, log close, etc.). |
C2 |
Filtered variants share the same per-event registration array as the unfiltered forms, so dispatch order = registration order regardless of which form was used.
Hook.onWire fires on post-transport bytes before RIPscrip or CTerm
classifies controls and text. It is the explicit byte-oriented hook
for wire protocols; a returned String remains raw bytes. The default
Hook.onInput and streaming match hooks are Unicode-facing: they see
decoded text independent of whether the remote uses UTF-8 or a legacy
codepage. Their replacements stay in the semantic text path rather
than being re-encoded as if they had arrived from the remote.
Sequence parameters and opaque protocol payloads bypass these Unicode hooks.
onMatch retains control markers such as ESC; use onWire to inspect entire
protocol sequences, and onMatchClean to match text across them.
Hooks run in registration order; the first one that returns Bool true
(drop) or a String (replace) wins, and later hooks don’t see that unit.
An onWire replacement is emitted before the next received byte,
without recursively invoking the wire-hook chain.
Hook.every fires from the main-loop deadline check just before the
sleep call. If the loop stalls long enough that more than one
interval has elapsed, the deadline jumps forward to "now" rather
than firing repeatedly to catch up.
The status bar is a separate dispatch path — see Status.
A single render callable (rather than a hook chain) builds the row
into a Surface the host hands it.
Streaming regex hooks
Hook.onMatch(pattern, fn) registers a regex against the decoded
UTF-8 input stream. Each decoded byte is fed to a streaming Pike VM (Russ
Cox’s NFA simulation, vendored under re1/); when a match completes,
fn is called with a Wren List:
Hook.onMatch("login:") { |m|
Conn.sendText("user\r")
return false
}
Hook.onMatch("user (joe|jane|bob)") { |m|
// m[0] = "user joe", m[1] = "joe"
System.print("hi %(m[1])")
return false
}
m[0] is the matched substring; m[1..] are the user-pattern’s
capture groups in registration order. Both onMatch and
onMatchClean are passthrough-only: the callback’s return value is
ignored, and the matched text always reaches the terminal. Matching
completes only after preceding bytes have passed through cterm, so these
hooks cannot drop a complete matched span. Use the scalar-granular
Hook.onInput hook when input must be dropped before reaching cterm.
Hook.onMatchClean(pattern, fn) omits ESC markers from CTerm’s decoded text
stream. CTerm already withholds sequence bodies and opaque payloads from
Unicode hooks. The matcher does not run a second escape parser, so an escape
cannot leave it waiting for bytes which CTerm has already consumed. UTF-8 and
legacy-codepage text use the same matching path, including sequences and
Unicode characters split across receive buffers.
Grammar
RE1 implements a deliberately minimal regex dialect. These are all of the supported metacharacters:
| Construct | Meaning |
|---|---|
literal byte |
matches itself. Backslash has no special meaning —
|
|
any byte (including NUL — the streaming VM does not treat NUL as end-of-input) |
|
capturing group |
|
non-capturing group |
|
alternation |
|
greedy: zero-or-more, one-or-more, optional |
|
lazy (non-greedy) variants |
Notably not supported (will be parsed as literal characters or syntax errors):
Patterns are anchored at the current buffer start. "Match
anywhere in the stream" is achieved by the dispatcher: when the VM
returns IMPOSSIBLE (no thread can ever complete from the current
buffer head), the oldest byte is dropped and the survivors are
re-fed. In practice this means a pattern like "hello" matches the
substring "hello" wherever it appears in the stream.
This trick requires that the pattern can produce IMPOSSIBLE — i.e.,
the first byte either advances the NFA or kills every thread.
Patterns whose leading construct can match without consuming a byte
keep threads alive on every input forever, the buffer fills, and
matches start being silently dropped. Hook.onMatch therefore
rejects patterns whose leading construct is *, +, or ? at
registration time with Fiber.abort:
| Allowed (1-byte anchor) | Rejected (variable-width leading) |
|---|---|
|
|
|
|
|
|
|
|
If you want a quantifier inside the pattern, anchor it with a fixed
prefix: bbs (.) ` rather than `(.) bbs.
Match semantics
Pike VM has a leftmost-first-completing tie-breaking rule: as soon
as any thread reaches a Match opcode, the match commits and
remaining threads in the current step are discarded. In a streaming
context this means open-ended quantifiers fire as soon as the
shortest acceptable prefix is seen — a* matches the empty string
at the first byte, a+ matches the first 'a' and stops.
For greedy-feeling behavior, terminate variable-length sub-patterns
with a literal that follows them: user (.) ` (capture text up
to a space) instead of bare `user (.). Newlines must be encoded
as literal \n bytes in the Wren string (“\n” in the source code,
which Wren resolves to a single 0x0A byte).
Limits
-
Buffer is capped at 4 KB per hook. When a partial match grows past the cap, the oldest half is dropped and the VM restarts — patterns that demand more than 4 KB of context will silently miss.
-
Up to 9 capture groups (RE1’s
MAXSUB = 20minus the whole-match pair). -
Pattern compile errors (bad syntax, internal asserts) surface as
Fiber.abortat the registration site, with the RE1 error text attached. The exception trace points at the offendingHook.onMatchcall.
HookHandle
Every successful Hook.on* and Hook.every registration returns a
HookHandle. The class has no Wren-callable constructor, so a
script can’t fabricate one to remove arbitrary hooks — only its
own.
import "syncterm" for Hook
var h = Hook.onKey { |k|
if (k == 0x4200) { // F8
System.print("F8 pressed")
return true
}
return false
}
// ...later...
h.remove() // no further dispatch
| Member | Meaning |
|---|---|
|
Remove the hook from future dispatch. Safe to call from inside its
own callback; in-flight dispatch finishes before resources are reclaimed.
Returns |
|
Number of times the host has invoked this hook. Counts every
|
|
Cumulative wall-clock seconds spent inside |
|
Smallest / largest single invocation time in seconds. Both read
back as |
HookHandle.remove() is safe from inside the hook’s own callback.
The callable handle is released immediately and subsequent dispatches
skip the removed entry. Outside dispatch, the host unlinks removed entries
and frees their regex resources before registration, on the next pump, or
when a host interpretation returns. The metrics remain alive until the
script also drops the HookHandle and its foreign finalizer runs.
Dropping a handle alone leaves an active hook registered.
Metric getters on a removed handle keep working until the script
drops the handle.
Modal Input
The conventional Input.next() / Input.next(ms) / Input.poll()
primitives all return promptly; while a script is calling them in a
loop the doterm() main loop is blocked, and inbound server bytes
queue up in the socket buffer until the script returns.
For modal dialogs that should not block the main loop while the
script idles between events, use Input.pushClaim(fn). The
foreign installs fn as the current claim on a stack of input
claims; whenever a key or mouse event arrives, the C-side
dispatcher walks the stack head-first (newest first) and invokes
the first claim whose owning fiber is still alive. The claim’s
return value is a Bool — true consumes the event (no other claim
or hook sees it), false passes it through to the next claim down
and ultimately to the registered Hook.onKey / Hook.onMouse
chain.
import "syncterm" for Input, Key, Wake, Screen, CTerm
var saved = Screen.save()
CTerm.suspended = true
var me = Fiber.current
var claim
claim = Input.pushClaim(Fn.new {|ev|
// Decide consume / passthrough synchronously here — handlers
// run from the C dispatch frame and must not yield. Anything
// we want to *do* with the event is dispatched by waking the
// worker fiber via Wake.post; the worker yields/resumes on
// its own schedule.
Wake.post(me, ev)
return true
})
while (true) {
var ev = Fiber.yield()
if (ev is KeyEvent && ev.matches(Key.escape, 0)) break
Screen.window.print("got: %(ev)\n")
}
claim.pop()
Screen.restore(saved)
CTerm.suspended = false
The claim is a per-fiber slot: pushing twice from the same fiber
replaces the existing claim in place (preserving stack position).
Pushing from a different fiber adds a new entry on top, which
becomes the foreground. Auto-prune at dispatch time drops claims
whose owning fiber is isDone (so a script that aborts mid-claim
doesn’t leave a dead handler installed). The returned
ClaimHandle is the explicit way to remove the
claim; pop() is idempotent.
CTerm.suspended is independent of the claim mechanism — any
script can set it to claim the screen, and remote bytes pile up in
the conn buffer behind it. When the TCP receive window fills, the
remote sees its send() calls block or EAGAIN. Clearing the
flag releases the backpressure and the buffered bytes drain
through cterm normally.
The claim handler runs from the C dispatch frame via the same
Hook.dispatch_ wrapper that protects regular hooks (see "Hooks
must run synchronously" above) — so a yield inside the handler is
caught and treated as not-consumed, and the input falls through to
the next claim or hook chain. Heavy work belongs in a separate
fiber that the handler wakes via Wake.post.
A hook callback can install its own claim and let it persist past the hook return — perfect for "F2 opens a modal that captures input until Esc":
Hook.onKey(Key.f2) { |k|
var worker
worker = Fiber.new {
var claim = Input.pushClaim(Fn.new {|ev|
Wake.post(worker, ev)
return true
})
while (true) {
var ev = Fiber.yield()
if (ev is KeyEvent && ev.matches(Key.escape, 0)) break
// ...
}
claim.pop()
}
worker.call()
return true
}
For more elaborate UIs, the App class (see App) wraps
this pattern and provides synchronous claim decisions based on its
own state (modal stack, focused widget, mouse hit-test) plus a
runChild helper that lets handler code yield safely on async
work without breaking the App’s event loop.
Built-in REPL
The immediate-mode REPL belongs to the VM which owns the current screen.
In graphical and native-console backends, Ctrl+` opens it from the main
menu or a connected session. In ANSI and ncurses modes, Ctrl+Q opens it
from the main menu; while connected, press Ctrl+S and select Wren Console
from the Online Menu. The shared UI is implemented in
scripts/wren_console.wren and can be overridden with
~/.local/share/syncterm/scripts/wren_console.wren. The connected
entry point is scripts/auto/connected/console.wren; the persistent menu
binds its backend-appropriate key in scripts/auto/menu/main_menu.wren.
While the connected console is open the doterm() main loop is suspended. Connection bytes accumulate in the socket buffer but aren’t drained until you exit the console. This is acceptable for a development tool; not appropriate for "watch a slow BBS scroll" use cases. The menu already uses a synchronous event loop, so opening its console does not change its event-pumping model. When the menu was entered through Alt+E, the connection is already parked for the entire menu visit.
When physical-key reporting is active, the console drains and ignores
PhysicalKeyEvent press/release edges; editing commands use the corresponding
translated KeyEvent. This keeps host key state synchronized without sending
console keystrokes to the connected application.
The editor stores cursor positions as UTF-8 byte offsets for Wren string
slicing, but Left, Right, Backspace, Delete, and Ctrl+W move only across
complete Unicode codepoints. The displayed cursor column follows the glyph
width selected by Screen.textWidth() and eight-column tab stops. Editing is
codepoint-based: grapheme-cluster navigation and Unicode word-breaking are not
performed. Display boundaries normalize text to NFC and measure complete
extended grapheme clusters.
The REPL evaluates input through REPL.eval(module, src). The
input is pre-classified by inspecting its leading non-whitespace
token: source that begins with a Wren statement keyword (var,
class, import, return, break, continue, if, while,
for) is compiled as a statement; everything else is compiled as
an expression. Successful expressions print their result quoted
with C-style escapes (so "7" the string and 7 the number are
visibly distinct); statements print nothing.
Variables and class declarations persist across submissions inside the active module:
> var x = 1 + 2
> x * 10
30
> class Foo { static greet { "hi" } }
> Foo.greet
"hi"
REPL Commands
| Command | Action |
|---|---|
|
Print commands, editing keys, history navigation, scrollback navigation, and exit keys. |
|
Switch the eval target to |
|
List every Wren module currently loaded into the VM, alphabetically
sorted. Includes |
|
Close the REPL and return to the connected session or main menu. |
Modules can plug in their own /<command> entries via
WrenConsole.register(name, help, fn):
import "wren_console" for WrenConsole
WrenConsole.register("greet", "say hello [<name>]") { |args|
if (args == "") {
System.print("hello!")
} else {
System.print("hello, %(args)!")
}
}
The handler is called with the raw argument string — everything
after the command name and its first separating space, or "" if
none. Re-registering an existing name overwrites the previous
binding. Names can’t contain spaces (the dispatcher splits on the
first one). The dispatch wraps the handler in Fiber.new {}.try()
so a runtime abort surfaces as a logged error instead of tearing
the console out from under itself. /? lists every registered
command with its help text alongside the built-ins.
WrenConsole.unregister(name) drops a registration (idempotent —
no-op if not registered); WrenConsole.commands returns the sorted
list of currently-registered names for tooling.
REPL Key Bindings
| Key | Action |
|---|---|
Left / Right |
Move the cursor within the current input line. |
Home / End |
Jump to start / end of the current input line. |
Backspace |
Delete the character before the cursor. |
Delete |
Delete the character at the cursor. |
Up / Down (live mode) |
Walk command history. If the line currently has typed text, that text becomes a prefix anchor — only history entries starting with it are visited. |
PgUp / PgDn |
Page through the scrollback log buffer. PgUp from live mode pins the current top of view; PgDn returns to live once you’ve scrolled past the tail. |
Up / Down (scrollback mode) |
Single-row scroll. Down past the tail rejoins live mode. |
Enter (blank or whitespace-only) |
Advance to a fresh prompt row without evaluating. |
Ctrl+W |
Backward kill-word, ending at the cursor (the tail past the cursor is preserved). |
Ctrl+L |
Clear the screen and the in-memory log. Returns to live mode. |
Middle-click |
Paste from the system clipboard at the cursor. Valid Unicode text and Tab are inserted. CR, LF, and CRLF each delimit one submitted line. Other C0, DEL, and C1 controls, malformed UTF-8, and non-scalar encodings are discarded without discarding valid text around them. |
Alt+drag |
Hand off to the existing select-and-copy gesture. |
Ctrl+` (graphical/native-console) / Ctrl+Q or Ctrl+S (ANSI/ncurses) |
Close the REPL and return to the owning screen. |
Esc / |
Close the REPL in every backend. |
Object Model
The remainder of this document is a reference for every foreign
class exposed in the syncterm module.
A note on toString: every class with an explicit toString method
returns it strictly for human-readable debug output — the format
that System.print(value) and string interpolation "%(value)"
emit when no other rendering is appropriate. The exact string is
not part of the API contract; it may change between SyncTERM
versions to add or remove fields, reformat, etc. Scripts that need
specific data should call the named property accessors (cell.ch,
event.key, surface.width) — never parse toString output.
Without an explicit toString a foreign would print as something
like [instance of Cell], which is uniformly less useful than even
a minimal Cell(0x41 attr=0x07); that’s the only motivation for
having these methods at all.
Error / ScriptError
Error is the polymorphic base for every recoverable-failure value
type the API hands back: SFTPError,
FileError, WONError,
ConnError, TransferError,
CTermError, ScreenError,
FontError, menu-only
MenuError, plus any user-defined
ScriptError subclass. Lets a script catch any of
them with one check:
import "syncterm" for Error
var v = something_that_might_fail()
if (v is Error) {
System.print("failed: %(v)") // toString includes the type
return
}
// proceed with the typed result
Every concrete Error subclass guarantees the contract:
| Member | Description |
|---|---|
|
Numeric error code from the type’s enum
(e.g. |
|
Human-readable diagnostic, may be |
|
Format with the subclass name as prefix. |
Type-specific extras (FileError.errno, WONError.offset,
ConnError.partial, FontError.nativeCode, MenuError.nativeCode, SFTPError.serverStatus,
SFTPError.isTransient) live on the subclass.
Error itself is empty by design: foreign subclasses (FileError
etc.) need the parent to be field-free or Wren rejects the
inheritance at module-load time (the
numFields == -1 && superclass→numFields > 0 check at
wren_vm.c:559-563).
ScriptError
Concrete Wren-side base for script-defined error types. Use this when a script wants to surface its own typed error without writing C bindings:
import "syncterm" for ScriptError
class ConfigError is ScriptError {}
if (something_bad) {
return ConfigError.new(42, "missing required field 'host'")
}
ScriptError provides the same code / message / toString
getters every foreign Error subclass exposes, so callers see uniform
behaviour from is Error and the field accesses regardless of
whether the value came from C or Wren. The default toString uses
the runtime class name ("ConfigError(42): missing required field
'host'"); subclasses may override for a different format.
| Member | Description |
|---|---|
|
Construct. |
|
The integer passed to the constructor. |
|
The string passed to the constructor. |
|
|
Screen
Drawing/state queries return their documented successful value or a
ScreenError. Drawing/state actions return null on success
or ScreenError; test for Error before using a returned value. These operations
are available in the menu, picker and connected VMs, each using its own console.
Read/write access to the terminal display surface. Screen itself
exposes whole-screen and absolute-coordinate operations; per-window
operations live under Screen.window.
| Member | Description |
|---|---|
|
|
|
Save the entire screen contents. Returns a host-created |
|
Restore a previously saved |
|
Run |
|
Read a rectangle of cells (1-based, inclusive). Returns a
|
|
Blit a |
|
Compose synchronous cell, pixel, and cursor updates in one presentation batch. Returns the callback result; nesting is supported, yielding is not. See Pixel screen operations for error and cleanup behavior. |
|
Internal raster size as |
|
Character-cell size as |
|
Capture a 0-based raster rectangle as a |
|
Set one 0-based raster pixel to a native pixel color. |
|
Draw a |
|
Read or set the active text attribute byte. |
|
Hyperlink ID attached to subsequent window writes. |
Screen.supports, Screen.font, Screen.palette, Screen.cursor,
Screen.videoFlags, Screen.color, and Screen.window are getters
that return the helper class so the script can call its static
members.
ScreenError
Immutable ScreenError is Error values expose code, message and toString,
with no public constructor or setters. code preserves the actual portable
native result, including unrecognized integers. Existing binding-owned rejected
regions, unavailable pixel capabilities and capture-storage allocation failures
use IOErr.outOfRange, IOErr.notSupported and IOErr.outOfMemory respectively;
these are binding diagnoses rather than fabricated native results. The owned
message identifies the failed operation/check. Errors hold no console, session,
input or borrowed native resources and remain valid across later calls and GC.
Native operations may change logical state before presentation fails. A returned error therefore does not imply rollback or permit automatic replay. Success reports native acceptance, not completion of a later asynchronous presentation. Restoring a screen snapshot synchronizes its saved Wren font slots whenever native state was applied, including a later presentation failure. Rejected restores leave them unchanged. Snapshots retain their existing owner, geometry and lifetime limits.
Screen.update, Screen.modalRun, CustomCursor.preserve and
VideoFlags.preserve return acquisition/cleanup ScreenError values. Failed
acquisition does not run the callback. Required cleanup is attempted after entry;
a callback’s returned Error takes precedence over cleanup failure, and callback
aborts propagate unchanged. Otherwise cleanup failure replaces the normal callback
result. Update callbacks still cannot yield; modal/preserve callbacks retain their
existing cooperative-yield, Operation and shutdown cleanup behavior. Finalizers
remain native cleanup boundaries and cannot return errors to an absent caller.
Live setters were replaced with explicit methods without aliases. Local staged cursor/flag setters and local offscreen-object APIs are unchanged. The bundled UI checks drawing results, propagates unhandled errors through its existing fiber handling and attempts independent restoration. Unsupported decorative title and pointer operations are skipped; URL-open failure still falls back to copying, with success announced only after copying succeeds. No clipboard protocol or VM authority changed.
Screen.supports
Read-only capability flags (Bool or ScreenError) reflecting what the current
display backend (SDL, X11, Win32, etc.) can do. Unsupported capabilities return
false; failure to acquire the native capability state returns ScreenError.
Scripts that adapt
their output to the backend should branch on these.
| Flag | True when the backend can… |
|---|---|
|
Replace the bitmap font in any slot at runtime. |
|
Select a registered alternate font with the source blink bit. |
|
Select a registered alternate font with the source bright bit. |
|
Render at least sixteen indexed colours, so the source blink bit can also select a bright background. |
|
Mutate the active palette at runtime. |
|
Address individual pixels (pixel-aware backends only — needed for RIP, SIXEL, SkyPix). |
|
Render a non-default cursor shape. |
|
Switch fonts via the SyncTERM font-selection UI. |
|
Set the OS window title. |
|
Advertise native clipboard text read/write support. |
|
Advertise native URL-opening support. |
|
Set the OS window’s class / icon name (X11). |
|
Set the OS window’s icon image. |
|
Address palette indices beyond 16. |
|
Use nearest-neighbour scaling for the pixel-doubled display. |
|
Defer scaling to the OS / window manager. |
|
Inhibit the OS window close button while a BBS session is active. |
The clipboard and URL flags mirror the native capability bits for the current VM’s console, including in menu, picker and connected VMs. They describe advertised backend support, not permission to use an operation or a guarantee that it will succeed. Reading them does not access the clipboard or open a URL.
Screen.window
Operations scoped to the active text window. Cursor position,
character output, line edits, and clearing all act inside the
window’s rectangle. Coordinates are window-relative (1, 1 is the
top-left of the window, not the screen). Invalid bounds, out-of-window
positions and invalid character values remain programmer errors. Native console
failures return ScreenError; an error can follow partial drawing or a committed
state change and does not promise rollback.
| Member | Description |
|---|---|
|
|
|
|
|
Write one character at the cursor. |
|
Write a string at the cursor. |
|
Clear the window with the current attribute. |
|
Clear from cursor to end of line. |
|
Line editing inside the window. |
Screen.font
Per-slot font management. Five slots (0..4) match SyncTERM’s font slot model.
Screen.font[i] reads the font index in slot i. Screen.font[i] = n
selects font n for slot i; assigning slot 0 also resets the
normal slot 1, matching the legacy default-font operation. Slots 1 through 4
are respectively normal, source-bright, source-blink, and source-bright plus
source-blink. VideoFlags.altChars and blinkAltChars enable the two
selectors. Selection happens when text is written, and the resolved internal
font identifier is retained in the cell. Clear, line insertion/deletion, and
scroll operations likewise resolve the font for the blank cells they create.
Later flag or slot changes do not reinterpret existing cells, and
Screen.putRect preserves the already-resolved fonts in its Surface. Use the
Font class (see Font) for the named built-in indices.
Screen.palette
24-bit-RGB palette as 0xRRGGBB integers.
Screen.palette[i] reads an RGB value or returns ScreenError.
Screen.palette.set(i, c) writes an entry and returns null or ScreenError.
Both retain the existing script index range, 0 through 255.
The first 16 entries are the legacy-attribute palette. Read each entry through the indexed API and write it through set.
|
Note
|
term.c, cterm.c, and ripper.c all do their own palette
manipulations. Concurrent edits from a script and from the terminal
code may not compose cleanly.
|
Screen.cursor — CustomCursor
Cursor geometry: scanline range, blink rate, visibility.
The class supports two usage modes:
-
Static (live state): static getters read the cursor and explicit static methods update it immediately.
Screen.cursor.setBlink(false)hides the blink on the next refresh. Each live setter method under the hood does a full read-modify-write of the renderer’s cell cursor state — so a single static write IS atomic for that one field, but a chain of static writes is NOT atomic across fields. The renderer can paint between them, briefly showing intermediate states. For multi-field changes, use the instance path. -
Instance (staged edit):
CustomCursor.new()(orCustomCursor.current) snapshots the current values. Modify the instance’s properties locally, thenapply()to commit as one locked state change regardless of how many fields changed.
CustomCursor.preserve(fn) is a convenience for the common
"snapshot, change, restore" pattern: snapshots the live cursor,
runs fn in a scoped child fiber, then re-applies the snapshot. It returns
fn’s result and restores state before propagating a callback error. Nested
calls, cooperative yields, Operation awaits, and VM shutdown have the same
cleanup semantics as `Screen.modalRun.
Static getters and instance properties: startLine, endLine, range,
blink, visible. Live writes use setStartLine(n), setEndLine(n),
setRange(n), setBlink(b) and setVisible(b), returning null or
ScreenError. Instance setters edit only the local snapshot; apply() returns
null or ScreenError. new(), current and the preset getters return a
snapshot or ScreenError, with no fabricated defaults after a failed read.
Pre-defined snapshots:
| Snapshot | Equivalent legacy code |
|---|---|
|
Mode-default cursor shape (legacy code 2). |
|
Solid block cursor (legacy code 1). |
|
Hidden cursor (legacy code 0). |
A CustomCursor.current snapshot also retains a terminal-owned pixel cursor
opaquely, so applying an unchanged snapshot or using CustomCursor.preserve
restores it. Editing a cursor field or applying a preset selects the ordinary
cell cursor. SkyPix’s native cursor position/colour/timer is owned by the
terminal; it is not a bitmap drawing operation and is excluded from pixel
captures and scrollback rasters.
Screen.videoFlags — VideoFlags
Boolean video-output flags, with the same static-vs-instance pattern
as CustomCursor — including the chained-static-writes
non-atomicity caveat and the VideoFlags.preserve(fn) snapshot
helper. Static reads return Bool or ScreenError; static writes use
setAltChars(b), setNoBright(b), setBgBright(b), setBlinkAltChars(b),
setNoBlink(b) and setLineGraphicsExpand(b), returning null or
ScreenError. new() and current return a snapshot or ScreenError;
instance setters remain local and apply() returns null or ScreenError.
expand remains read-only.
| Property | Meaning |
|---|---|
|
Let source attribute bit 3 select font slot 2 instead of slot 1 (and slot 4 instead of slot 3 when bit 7 also selects a font). |
|
Prevent source attribute bit 3 from selecting a bright foreground palette entry. This does not change the independent bold style flag or the source bit’s use as an alternate-font selector. |
|
Treat the high-intensity bit on the background nibble as a bright background. Its blink and alternate-font meanings remain independently controlled. |
|
Let source attribute bit 7 select font slot 3 instead of slot 1 (or slot 4 when bit 3 also selects a font). |
|
Prevent source attribute bit 7 from blinking. The same bit may still select a bright background or alternate font. |
|
Read-only. True when the backend is using
a cell one pixel wider than its font. The
extra column is blank unless
|
|
Apply the right-edge duplication to box-
drawing glyph indices in the 0xC0..0xDF range
when |
Screen.color — Color
Build and inspect 24-bit RGB values. Returned values are raw
0xRRGGBB without the high RGB-mode bit; the bit is added when
writing into a Cell field via fgRgb= / bgRgb=.
| Method | Description |
|---|---|
|
Pack three 8-bit components into a uint32. |
|
Decode an attribute byte into |
|
Map 24-bit RGB foreground and background colours to the nearest legacy
text attribute byte in that same active palette. Matching uses YCoCg
distance; bright foreground or background candidates are included only
when the current video flags give those attribute bits a colour meaning.
Returns |
Pixel graphics
The pixel API exposes ciolib’s internal raster directly in the connected,
menu, and picker VMs. Raster coordinates are 0-based and refer to the
unscaled video-mode surface, not operating-system window coordinates. User
display scaling does not change these coordinates. Screen.pixelSize
includes any raster rows that do not belong to a complete text cell.
Pixel buffers, masks, and blit descriptors are foreign objects owned by the VM that created them. Their native allocations are released by Wren’s garbage collector. They cannot be passed between SyncTERM’s isolated VMs.
PixelColor
Pixel buffers retain ciolib’s native colour words. A native word is either a
palette index in 0..65535 or a 24-bit RGB value tagged with
CIOLIB_COLOR_RGB. A plain 0xRRGGBB number is therefore not necessarily a
native RGB colour; construct it with PixelColor.rgb before placing it in a
buffer.
| Member | Description |
|---|---|
|
Tag a raw |
|
Construct a native palette colour. |
|
Return |
|
Return raw |
|
Return the index for a palette colour, or |
|
Return raw |
All methods reject fractional, negative, out-of-range, or malformed native colour values by aborting the calling fiber.
PixelBuffer
PixelBuffer is a row-major Sequence of native colour words. Linear index
i is (y * width) + x. Ordinary reads, writes, fills, and blits operate on
the native array directly.
| Member | Description |
|---|---|
|
Allocate a buffer, initially palette index 0 or |
|
Dimensions and total pixel count. |
|
Read or write one row-major native colour word. |
|
Read or write one 0-based buffer coordinate. |
|
Fill the primary plane. |
|
Copy the buffer and both blink-phase planes. Returns |
|
Composite another PixelBuffer into this buffer, using PixelBlit and an optional PixelMask. Returns null on success or PixelError. Available in all three VMs independently of Screen.supports.pixels. |
|
Import packed RGB bytes in |
|
Export the primary plane as packed RGB bytes. Palette words are resolved through the active palette. |
|
Inspect the optional alternate blink-phase plane. |
|
Read or set a pixel’s Boolean blink rate. False selects slow blink. The first true bit allocates a packed rate mask and, if needed, an alternate plane initialized from the primary colours. Clearing the alternate plane releases the mask. Edits to individual colours preserve the pixel’s chosen rate. |
|
Create or update the alternate plane. Its first creation copies the complete primary plane before applying the requested change. |
|
Export the alternate plane as packed RGB, or return |
|
Remove the explicit alternate plane. Native drawing then uses the primary plane for both blink phases. |
|
Decode the first P3 or P6 PPM image. Values use PPM’s BT.709 transfer function and are converted to 8-bit sRGB; maximum values through 65535 are accepted. |
|
Decode JPEG XL. Returns |
|
|
Decoder source may be a binary Wren String or a readable, consent-bounded
File. A File is mapped and decoded directly; SyncTERM does not
first copy its contents into a Wren string. Decoded images contain only a
primary plane.
Capture and clone preserve the primary and alternate colours and the packed blink-rate mask. RGB24 export is a conversion and resolves palette references at export time; use native indexing when palette identity must survive a round trip.
Buffer blits use the existing descriptor’s source rectangle, signed destination origin, mask origin, flips and independent integer scaling. Zero source extents mean the remainder, resolved on each call without changing the descriptor. The destination is clipped; masks control transparency and there is no alpha blending. Native palette words and tagged RGB values are copied without palette resolution. Source, mask and descriptor remain unchanged, except that a self-blit also changes its source because source and destination are the same object.
The two colour planes and the optional blink-rate bits are preserved. A source alternate plane causes the destination to acquire one, initially copying its whole primary plane; unpainted pixels keep those values. Without a source alternate plane, primary pixels supply both destination phases. Native plane creation happens before clipping/mask drawing, so a blit that paints no pixels can still create a plane or fail its allocation. Overlapping self-blits snapshot the source colours and rate bits before drawing. Distinct-buffer blits allocate missing alternate or rate storage as needed. No screen, file or network operation is performed, and no arguments are retained after the synchronous call.
Wrong argument types abort the calling fiber. The masked overload requires a PixelMask; use the two-argument overload rather than null for an unmasked blit. Invalid source/mask regions, including empty source regions, return PixelError with IOErr.outOfRange. An empty destination returns the native IOErr.invalidArgument. Native allocation/validation failures preserve their actual code. Returned errors leave destination pixels and plane ownership unchanged.
PixelError
Immutable PixelError is Error values expose code, message and toString,
with no public constructor or setters. code retains the actual native integer
status, including unrecognized values; binding-rejected source/mask regions use
IOErr.outOfRange. The owned message identifies the operation and reason. Errors
retain no buffer, mask, descriptor or console resources and survive later calls
and garbage collection independently. This result type applies to PixelBuffer.blit;
other existing pixel operations retain their documented result contracts.
PixelMask
PixelMask is a row-major Sequence of Bool values. A true bit draws its
source pixel; a false bit leaves the destination unchanged.
| Member | Description |
|---|---|
|
Allocate a false-filled mask, or initialize every bit to |
|
Import continuous row-major packed bits, most-significant bit first. The
string length must be |
|
Decode a P1 or P4 PBM from a binary |
|
Dimensions and linear Boolean access. |
|
0-based coordinate access and bulk fill. |
|
Export continuous row-major packed bits, most-significant bit first. |
PixelBlit
PixelBlit is a reusable mutable descriptor. PixelBlit.new() selects the
whole source, destination (0, 0), scale (1, 1), mask origin (0, 0), and
no mirroring.
| Member | Description |
|---|---|
|
0-based source origin. Values must be non-negative integers. |
|
Source extent. Zero means the remainder of that source dimension, evaluated when the descriptor is used. |
|
Signed 0-based destination origin. Negative values request clipping at the left or top edge. |
|
Positive integer nearest-neighbour scale factors. |
|
0-based mask origin. The mask region has the same unscaled extent as the source region. |
|
Mirror the selected source and corresponding mask region before scaling. |
Descriptor setters reject wrong types, fractional values, out-of-range coordinates, and zero scale by aborting the calling fiber. Reusing a descriptor does not retain a source, mask, or destination reference.
Pixel screen operations
Screen.update(fn) composes synchronous cell, pixel, and cursor changes as
one presentation batch. The callback runs immediately, may nest another
Screen.update, and returns its result. Ordinary presentation, including
blink and expose repaint events, waits until the outermost update ends.
The batch closes before a callback error is propagated; yielding from the
callback is rejected and also closes it. This groups drawing; it does not
roll back changes on error. Do not wait for input, open a modal, switch
screen modes, or run an event loop inside the callback. Native code that
explicitly forces a presentation can still bypass batching.
Use this when text cells provide a graphical UI’s metadata and base glyphs,
with pixel operations completing its appearance. Screen.readPixels can
inspect the composed raster inside the batch without presenting it.
Screen.readPixels(x, y, width, height) captures a positive-sized rectangle
and returns a new PixelBuffer. Passing force=true first requests a full
refresh from text vmem before capture; use the default false when capturing
pixel changes that have already been drawn. Capture returns ScreenError for an unsupported backend
(IOErr.notSupported), an out-of-screen rectangle (IOErr.outOfRange), or
allocation failure (IOErr.outOfMemory).
Screen.setPixel(x, y, color) and both Screen.blitPixels overloads return
null on success or ScreenError. A blit validates the source and optional mask regions, clips the scaled
destination to the screen, and returns null without drawing when the entire
destination is off-screen. Scaling is nearest-neighbour and independent in
X and Y. If the source has no alternate plane, its primary pixels are used
for both destination blink phases. Masks are the transparency mechanism;
there is no alpha blending.
Blitting uses the supplied native buffers directly and provisions missing rate storage as needed. Keep decoded or constructed buffers and descriptors for repeated sprite draws rather than rebuilding RGB strings. Capture, decode, clone, RGB24 conversion, and first alternate-plane creation do allocate.
var sprite = PixelBuffer.fromPpm(ppmBytes)
var mask = PixelMask.fromPbm(pbmBytes)
var blit = PixelBlit.new()
blit.destinationX = 40
blit.destinationY = 24
blit.scaleX = 2
blit.scaleY = 2
blit.flipX = true
if (sprite != null && Screen.supports.pixels) {
Screen.blitPixels(sprite, mask, blit)
}
Invalid argument types, fractional or out-of-range integers, invalid native
colours, malformed packed lengths, and invalid descriptor fields abort the
calling fiber. Constructors also abort on allocation failure because Wren
foreign constructors cannot return null; offscreen factories, decoders and clone return null for recoverable
allocation or decoding failure. Screen capture returns ScreenError.
The alternate-plane mutators leave the buffer unchanged and abort the calling
fiber if the plane’s first allocation fails.
Input
Unified blocking and nonblocking reader for keyboard and mouse events.
| Member | Description |
|---|---|
|
Block until the next event; return |
|
Wait up to |
|
Return immediately with the next pending event, or |
|
Push an exact copy of a |
|
Synthesize a physical key edge. |
|
Hand off to SyncTERM’s full-screen drag-select gesture. This uses the
current screen dimensions and does not depend on a connected terminal.
In a live RIP3 connection, selection uses the selected text window’s grid,
font and pixel origin. Suspended terminal UI continues to use its own screen.
The default is line selection; |
|
Show or hide the mouse cursor; return |
|
Read or set the bitmask of |
|
Single-event toggles for the same mask. |
|
Push |
Once a process-close request has been read, Input.next(), Input.next(ms),
and Input.poll() continue returning Key.quit until SyncTERM exits. UI code
should use App, which reserves the event for call-stack unwinding and
supports the explicit Widget.atExit exception.
For posting a synthetic resume to a parked fiber (the wake
mechanism that Hook.onInput-style callbacks use to nudge a UI
fiber), see Wake.
Claims and wakes are stored independently for each VM. The persistent menu
and picker currently use the synchronous Input.next path; the
connected-session owner loop is responsible for invoking claim dispatch and
draining wakes. Registering a claim alone does not create a background pump.
KeyEvent
Carries committed Unicode text, a logical named key, a numeric keypad byte,
or a DoorWay scan. These meanings remain distinct. Display font selection
never determines input text; connection encoding is applied only when an event
is forwarded through CTerm.sendKey.
| Member | Description |
|---|---|
|
Construct a named |
|
Construct from exactly one strictly valid UTF-8 scalar. NUL and non-BMP scalars are supported. Empty strings, malformed bytes, and multiple scalars are rejected. No NFC normalization or grapheme segmentation occurs. |
|
Construct an explicit numeric keypad byte, from 0 through 255. |
|
Construct a DoorWay scan with an explicit enhanced-key flag. |
|
Unicode scalar for committed text, a named |
|
Full event-time |
|
Original committed Unicode scalar, or |
|
Exact UTF-8 committed scalar, or |
|
Explicit numeric keypad byte, or |
|
DoorWay scan and Bool flag, or |
|
Compare logical key and modifiers, ignoring Caps Lock and Num Lock only. |
Alt+Keypad entry without a leading zero remains a raw byte in every Wren VM. Leading-zero Unicode entry produces committed Unicode text. The terminal resolves raw bytes using its active remote encoding; Wren UI code must not reinterpret them through the selected display font.
Wren Strings can contain arbitrary bytes. count counts decoded scalars in
valid UTF-8, while integer String and codePoints subscripts use byte offsets.
Neither count == 1 nor text[0] validates a Unicode scalar. The native text
constructor validates the entire byte sequence, including embedded NUL.
Input.unget preserves the full event and its native source type. Forwarding
through CTerm.sendKey uses that source, including text, modifiers, raw bytes,
physical edges and DoorWay scans; it does not re-enter key hooks.
PhysicalKeyEvent
Represents one physical key press or release edge using the same evdev key
code namespace as CTerm’s physical-key reporting protocol. Returned by
Input.next() / Input.poll(), passed to Input.pushClaim handlers, and
passed to Hook.onPhysicalKey callbacks.
Physical events remain separate from logical keys and committed text. The
host does not synthesize a second logical event from a physical press. A
backend may subsequently deliver a translated key or committed text; scripts
must choose the appropriate stream for a shortcut rather than bind both.
Repeated presses retain repeat; releases remain explicit physical events.
| Member | Description |
|---|---|
|
Construct a synthetic physical-key edge. |
|
evdev key code number. |
|
|
|
Event-time modifier mask: Shift=1, Control=2, Alt=4, GUI=8, Caps Lock=16, and Num Lock=32. |
|
|
MouseEvent
Represents one normalized SyncTERM mouse event. Returned by
Input.next() / Input.poll(), passed to Input.pushClaim
handlers, and passed to Hook.onMouse callbacks — every mouse
surface uses this same shape.
| Member | Description |
|---|---|
|
Construct from raw fields. Five overloads dispatched by arity.
Omitted |
|
Construct a fully explicit synthetic event including internal raster coordinates. This is a named factory rather than a sixth overloaded constructor so pixel and cell coordinates cannot be confused by arity. |
|
The fully explicit factory, including signed wheel-axis values. |
|
Mouse event type code. |
|
Snapshot of the button-state bitmask at the moment the event
fired (the |
|
Event-time keyboard modifier mask, using the same bits as
|
|
Click-down coordinates (1-based). |
|
Release coordinates (1-based). |
|
Click-down coordinates in the 0-based internal raster. Native backends that
cannot report pixel positions use |
|
Release coordinates in the 0-based internal raster, with the same |
|
Signed native wheel magnitude. A vertical event has |
Mouse event constants
Mouse.button1* through Mouse.button5* identify left, middle, right, X1,
and X2 events. Each family occupies nine stable values in the order Press,
Release, Click, double/triple/quadruple Click, DragStart, DragMove, and DragEnd.
Native translation currently produces Press, Release, Click, DragStart,
DragMove, and DragEnd; multi-click values remain available to synthetic input.
Mouse.wheelUp, wheelDown, wheelLeft, and wheelRight are values 46
through 49. The older wheel*Press and wheel*Click names remain aliases.
ClaimHandle
Returned from Input.pushClaim. Drop the claim by calling
pop().
| Member | Description |
|---|---|
|
Remove the claim entry from the stack. Idempotent — stale handles (after a same-fiber re-push bumped the entry’s id, or after another path popped it, or after the foreign finalizer ran) no-op silently. The C-side foreign finalizer also pops on GC, so a forgotten handle still cleans up — but explicit pop is cheaper and more predictable. |
Wake
Owner-thread fiber-resume primitive. Wake.post(fiber, value) queues a
synthetic resume of fiber, delivering value as the return of
its next Fiber.yield(). It is held in that VM’s FIFO and delivered by the
owning host’s next explicit wake drain — never in the middle of the current
foreign call. It may be called while executing that VM on its owner thread
(hooks, claim handlers, and worker fibers). value may be any Wren
object — the deliverer pins it as a WrenHandle until delivery,
then loads it into the fiber’s resumed-value slot. Multiple posts
queue up; each becomes one resumption in arrival order.
| Method | Description |
|---|---|
|
Queue a resume. Returns immediately; the wake is dispatched on
the next main-loop drain. Convention: pass a discriminated value
the fiber’s main-loop demuxer can recognise (a foreign
|
Key
Named key identifiers occupy 0x110000..0x11ffff, above the Unicode scalar
range. They identify keys independently of modifiers. Committed text uses
its Unicode scalar directly; for example, U+0100 and Key.up are distinct.
Key.quit is a separate sticky host shutdown marker at 0x120000.
Available names are escape, enter, backspace, tab, delChar, up,
down, left, right, insert, delete, home, end, pageUp,
pageDown, and f1 through f12. delChar represents a native ASCII DEL
key, separately from the dedicated Delete key. Modified keys use the same
identifier plus an explicit modifier mask; for example,
event.matches(Key.tab, Mod.shift) tests Shift-Tab.
Mod
Modifier constants are shift=1, control=2, alt=4, gui=8,
capsLock=16, and numLock=32. command selects GUI on macOS and Alt
elsewhere for bundled application command policy. Event masks retain the
actual modifiers reported by the backend. Applications should match the full
mask they intend; Caps Lock and Num Lock may be ignored for shortcuts.
Clipboard
| Member | Description |
|---|---|
|
Read the system clipboard as an NFC string, or return |
|
Write a string to the system clipboard; return |
Codepage
Enum-style class identifying a character-set encoding. Returned by
Font.codepage and Font.codepageOf(i) to tell scripts which
legacy character encoding a selected font uses. Cells expose Unicode text;
these values describe explicit conversions at a legacy byte boundary.
Codepage.encodes_(s) accepts exactly one Unicode codepoint and reports
whether the codepage of the selected primary font (Screen.font[0]) can
encode it. It returns false when that font is unavailable. It does not consult the process locale.
Codepage.encodeByte(codepage, scalar) explicitly encodes one Unicode scalar
using the chosen legacy codepage. The scalar is an integer Number from 0 through
0x10FFFF, excluding surrogates (0xD800 through 0xDFFF), rather than a String.
Return a byte Number from 0 through 255, or null when that scalar is unmappable.
Native aliases choose the first mapping in the legacy table. There is no
normalization, replacement character or dependency on the selected font,
connection encoding or locale. For example,
Codepage.encodeByte(Codepage.cp1251, 0x0410) returns 0xC0.
Wrong types, nonfinite/fractional Numbers, invalid codepages and invalid scalars
abort the calling Fiber.
Codepage.decodeByte(codepage, byte) explicitly decodes one legacy display
byte to a Unicode String. The codepage must be one of the constants below
and the byte an integer from 0 through 255. It uses graphical character
meanings for control positions: CP437 byte 1 becomes ☺, byte 0xB3
becomes │, and byte 0 remains NUL. Invalid arguments abort the calling
fiber. The result is independent of the selected font, connection encoding,
locale, and output mode. For example, a CP437 character picker can assign
cell.ch = Codepage.decodeByte(Codepage.cp437, value).
Codepage.decodeByte(codepage, byte, graphicControls) adds a strict Bool choice
of native decoding mode. true matches the two-argument display form; false
selects semantic control meanings. For CP437, byte 1 then returns U+0001 rather
than ☺, byte 0x7F returns DEL rather than ⌂, and byte 0x7C returns |
rather than ¦. The native tables determine the remaining mappings; byte 0
can return a one-byte NUL String. Invalid arguments abort the calling Fiber.
Encoding and decoding are not promised to be inverse operations for every table.
Codepage.brokenVertical(codepage) returns the native compatibility Bool for a
valid Codepage constant. It describes the broken-bar display glyph at byte
0x7C, not gaps in box-drawing lines. A _b suffix identifies an explicit
broken-vertical variant; some other codepages, including CP437, also have the
flag. A false flag does not imply that an arbitrary loaded raster has an
unbroken bar. Invalid arguments abort the calling Fiber.
These conversion and metadata methods are synchronous and available in all three VMs. They retain no inputs and grant no file or terminal authority.
| Constant | Index | Description |
|---|---|---|
|
0 |
IBM PC code page 437 — English plus box-drawing. The default for traditional ANSI BBSes. |
|
1 |
Windows-1251 — Cyrillic (Russian, Bulgarian, Ukrainian, etc.) in a "swiss" font variant. |
|
2 |
Windows-1251 with the broken-vertical glyph variant. |
|
3 |
KOI8-R — Russian Cyrillic. Common on 1990s Russian Linux/Unix systems. |
|
4 |
ISO-8859-2 (Latin-2) — Central European (Polish, Czech, Hungarian, …). |
|
5 |
ISO-8859-4 (Latin-4) — Northern European / older Baltic. 9-bit-mapped wide-glyph variant. |
|
6 |
CP866 — Russian DOS, "(c)" modified variant. |
|
7 |
ISO-8859-9 (Latin-5) — Turkish. |
|
8 |
ISO-8859-8 — Hebrew. |
|
9 |
KOI8-U — Ukrainian Cyrillic. |
|
10 |
ISO-8859-15 (Latin-9) — Western European with the Euro sign. |
|
11 |
ISO-8859-5 — Latin/Cyrillic. |
|
12 |
CP850 — Multilingual Latin-1 (DOS Western European). |
|
13 |
CP850 with the broken-vertical glyph variant. |
|
14 |
CP865 — Nordic DOS (Danish, Norwegian). |
|
15 |
CP865 with the broken-vertical glyph variant. |
|
16 |
ISO-8859-7 — Greek. |
|
17 |
ISO-8859-1 (Latin-1) — Western European, classic Unix default. |
|
18 |
CP866 — Russian DOS, second modified variant. |
|
19 |
CP866-U — Ukrainian variant. |
|
20 |
CP1131 — Belarusian DOS. |
|
21 |
ARMSCII-8 — Armenian. |
|
22 |
HAIK-8 — older Armenian set; used with the ARMSCII-8 screen map. |
|
23 |
ATASCII — Atari 8-bit native character set. |
|
24 |
PETSCII (uppercase/graphics mode) — Commodore 64/128 default. |
|
25 |
PETSCII (lowercase/shifted mode) — Commodore 64/128 after a Shift+Commodore key. |
|
26 |
UK Prestel / Viewdata teletext — block mosaic graphics, double-height, conceal. |
|
27 |
Prestel separated mosaics — block mosaics with gaps between cells. |
|
28 |
Atari ST GEM character set. |
Cell
Wraps one st_console_cell: its resolved drawable glyph/font, colours, source
attributes, flags, and hyperlink. Read a Surface through Screen.readRect,
edit its cells, and blit it back through Screen.putRect.
The three-argument Surface.cellAt(x, y, cell) overload can retarget
the same Cell object to successive cells of a Surface. This changes
what storage that object refers to; it does not copy cell contents.
| Member | Description |
|---|---|
|
Construct an empty cell. |
|
Character as one NFC extended grapheme cluster. Assignment accepts exactly
one valid cluster, normalizes it to NFC, then resolves one drawable glyph in
the selected font and Unicode fallback font. An unsupported cluster is one
missing glyph, including emoji modifier sequences that do not use ZWJ.
+
Unlike ordinary text output and |
|
Font catalog selector at the Wren boundary. The selected and actual glyph font identifiers are retained separately in stored cells. Assignment resolves the current Unicode text in the new font and its fallback. Cell creation, character assignment, and font changes perform no legacy byte conversion. |
|
Legacy attribute byte (foreground in low nibble, background in
high nibble, plus source bright/blink bits). Setting it marks both
colours as legacy-derived. The active |
|
Source attribute bit 3. This is distinct from the |
|
Blink bit. |
|
Selects the fast cadence when |
|
Draws a one-pixel foreground line across the centre row of an odd-height cell or the lower middle row of an even-height cell. |
|
Draws a foreground line across the top pixel row of the cell. |
|
Draws the bottom pixel row and the row two pixels above it when present. Enabling either underline style replaces the other. |
|
Read/write Boolean drawing styles. Single underline spans the inked rows of the font’s underscore; bold thickens the glyph; reverse exchanges foreground/background when drawn; conceal hides the glyph unless its retained reveal flag is set. Bold is independent of the source-bright attribute. All style setters require Bool; wrong types abort rather than being ignored. |
|
Read or replace the drawing styles together using |
|
Read-only Booleans reporting retained SAA5050/teletext presentation state: serial-attribute mode, double height, reveal concealed content, and separated mosaics. These are observations, not independent serial-attribute controls. |
|
Read-only retained seven-bit source control as a Number, or null when none is recorded. Changing serial attributes requires editing the source stream and reconstructing the affected line or screen; Cell does not provide that operation. |
|
Read-only. |
|
Foreground / background palette indices. |
|
Foreground / background as 24-bit RGB. Setters change only the selected colour channel and its legacy-derived marker; source bright/blink and all other cell state remain intact. |
|
Hyperlink ID attached to this cell. |
|
Structural equality of every content field. This is not a |
c |
c.eqContent(template) }`).
+
Returns |
CellStyle
Named masks for Cell.styleFlags, available in all script VMs. bright is
0x400000, blink is 2, underline is 0x10000, bold is 0x20000,
reverse is 0x40000, conceal is 4, fastBlink is 0x2000000, strikethrough is 0x4000000, doubleUnderline is 0x100000, and overline is 0x200000.
all is their union (0x6770006).
These native bit values fit Wren’s ordinary bitwise operators. Renderer state,
serial attributes and pixel-graphics ownership are excluded from this mask.
cell.bold = true
cell.styleFlags = CellStyle.bold | CellStyle.underline
Surface
A width × height grid of Cells backed by a contiguous
st_console_cell buffer. Surface is Sequence, so the linear [i]
subscript, count, and the standard sequence helpers (each,
where, map, all, any, reduce, join, take, skip,
toList, …) all work — handy for "tell me where any 'X' lives"
without switching to 2D indexing. Linear order is row-major:
buf[y * width + x].
Screen.readRect returns a Surface sized to the requested rect, with optional
pixel strips for rows containing graphics. Captured strips retain RGB colours
and both blink phases; plain-text rows allocate no pixel storage. Rectangle
copies, including clipped and overlapping self-copies, preserve those strips.
Glyph edits and text fills replace the affected cells' raster content; style
edits do not recolour captured pixels. Screen.putRect restores cells and
pixel-marked regions in one presentation batch, so UI overlays remain visible. The
UI library uses Surfaces as per-widget backbuffers and composites
them into a screen-sized backbuffer Surface that’s blitted once
per frame.
| Member | Description |
|---|---|
|
Allocate a fresh Surface of the given size. Cells start as spaces using the current screen style. |
|
Dimensions in cells. |
|
|
|
Linear-indexed read of the cell at offset |
|
2D-indexed |
|
Retarget an existing |
|
Sequence protocol — yields each cell linearly in row-major order
(the cell at |
|
Sequence-of-Sequence view, outer-by-y. |
|
Sequence-of-Sequence view, outer-by-x. |
|
Detect an ASCII HTTP, HTTPS, FTP, FTPS, or bare |
|
Paste a source Surface into this Surface at |
|
Bulk-fill the intersection of |
|
Debug-only string form, e.g. |
Scrollback
Read-only logical access to the active cterm scrollback ring. The ring stays
in its native wrapped representation: these methods do not append rows,
rotate storage, or change CTerm.scrollbackStart / scrollbackPos.
SkyPix pixel scrolling can leave an unfinished strip between complete rows
and the live screen. Reads compose it into rows aligned at the live boundary,
within the configured capacity. A change of geometry finishes the strip in its original grid. Any padding precedes that run of rows.
Pixel colours and both phases were captured when they left the screen, so a
later palette change does not recolour the pending strip. Row copies do not
flush it. Aligned cell text is preserved; a fractional row view carries pixels
with blank cell metadata rather than stale text at the wrong position.
| Member | Description |
|---|---|
|
Current projection width in cells, or zero when no ring exists. |
|
Number of retained logical history rows, or zero when no ring exists. |
|
Return |
|
Return an owned, one-row Surface at its original width, with font, glyph,
hyperlink and available bitmap data. The indexes match |
|
Copy whole logical history rows, oldest-first, into an owned
|
Font
A "font" in SyncTERM is one of 257 indexed slots, each a complete
glyph table for a particular character set or display style. Slots
0–45 ship with built-in fonts, covering the codepages enumerated by
Codepage plus several Amiga and 8-bit display styles.
Slots 46+ hold configured or remotely supplied fonts. Font.count
reports the current catalog extent; use Font.available(i) to determine
whether a catalog slot has a bitmap for the active cell dimensions.
Application UI uses system CP437, independently of the connection’s font.
Font.cp437English remains the system font for Wren drawing even when SkyPix
or a remote command replaces terminal slot zero. The status bar, online menu,
file picker and transfer dialogs use it; built-in/loaded theme snapshots resolve
explicit font choices to system CP437. SkyPix keeps the screen mode’s system
cell grid independent of the Amiga strike: at 640x200 UI uses 8x8 CP437 even
with Diamond 20. The console scales a system strike only when the chosen
screen-mode cell dimensions have no exact system strike. Text
backends retain Unicode presentation and use their external terminal’s font.
The Font class itself only exposes named constants for the most
useful slots; every slot is reachable numerically through
Screen.font[i] regardless. The full built-in table follows.
| Named constant | Index | Slot description |
|---|---|---|
|
0 |
Codepage 437 English (default). |
1 |
Codepage 1251 Cyrillic, "swiss" variant. |
|
2 |
Russian KOI8-R. |
|
3 |
ISO-8859-2 Central European. |
|
4 |
ISO-8859-4 Baltic wide (VGA 9-bit mapped). |
|
5 |
Codepage 866 (c) Russian. |
|
6 |
ISO-8859-9 Turkish. |
|
7 |
HAIK-8 (used with the ARMSCII-8 screen map). |
|
8 |
ISO-8859-8 Hebrew. |
|
9 |
Ukrainian KOI8-U. |
|
10 |
ISO-8859-15 West European, "thin" variant. |
|
11 |
ISO-8859-4 Baltic (VGA 9-bit mapped). |
|
12 |
Russian KOI8-R, alternate (b) variant. |
|
13 |
ISO-8859-4 Baltic wide. |
|
14 |
ISO-8859-5 Cyrillic. |
|
15 |
ARMSCII-8 (Armenian). |
|
16 |
ISO-8859-15 West European. |
|
17 |
Codepage 850 Multilingual Latin I, "thin". |
|
18 |
Codepage 850 Multilingual Latin I. |
|
19 |
Codepage 865 Norwegian, "thin". |
|
20 |
Codepage 1251 Cyrillic. |
|
21 |
ISO-8859-7 Greek. |
|
22 |
Russian KOI8-R, alternate (c) variant. |
|
23 |
ISO-8859-4 Baltic. |
|
24 |
ISO-8859-1 West European. |
|
25 |
Codepage 866 Russian. |
|
26 |
Codepage 437 English, "thin" variant. |
|
27 |
Codepage 866 (b) Russian. |
|
28 |
Codepage 865 Norwegian. |
|
29 |
Ukrainian CP866-U. |
|
30 |
ISO-8859-1 West European, "thin". |
|
31 |
Codepage 1131 Belarusian, "swiss". |
|
|
32 |
Commodore 64 (uppercase / graphics). |
|
33 |
Commodore 64 (lowercase / shifted). |
|
34 |
Commodore 128 (uppercase / graphics). |
|
35 |
Commodore 128 (lowercase / shifted). |
|
36 |
Atari 8-bit. |
|
37 |
P0T NOoDLE — Amiga BBS classic. |
|
38 |
mO’sOul — Amiga BBS classic. |
|
39 |
MicroKnight Plus — Amiga. |
|
40 |
Topaz Plus — Amiga. |
|
41 |
MicroKnight — Amiga. |
|
42 |
Topaz — Amiga Workbench font. |
|
43 |
Prestel — UK Viewdata mosaic. |
|
44 |
Atari ST GEM. |
|
45 |
RIPterm — RIP graphics terminal font. |
The "thin" variants are the same character set rendered with thinner strokes in the VGA BIOS style. A "swiss" variant uses a Helvetica-style sans rendering. An "(a)" / "(b)" / "(c)" annotation distinguishes bundled font variants that use the same codepage encoding.
| Method | Description |
|---|---|
|
Human-readable font name for slot |
|
Current catalog extent. |
|
|
|
Native static broken-vertical compatibility flag of a built-in selector (0 through 45). Available in all three VMs, even if its bitmap is unavailable. This describes the bundled catalog entry independently of configured, downloaded or session raster replacements; it does not inspect a live font. Custom selectors, wrong types and nonfinite/fractional/out-of-range Numbers abort the calling Fiber. |
|
Actual mapping of the font selected in |
|
Actual mapping of the font selected in script-output
slot |
|
Actual mapping of the registered catalog
selector (0 through 255), or |
|
Register a 256-glyph bitmap using the terminal’s current
|
|
Register with an explicit |
Both load forms return the allocated selector (46 through 255), a FileError
for a file access/read failure, or a FontError. Loading requires
an active terminal and ScreenSupports.loadableFonts. It reads an actual
readable File grant belonging to the calling VM; path Strings are rejected.
Revoked/stale read authority returns FileError with IOErr.permissionDenied.
Loading neither selects the font nor changes the File’s stream position, consumes
its grant, or saves settings. The bitmap remains usable after the File is closed
or collected. Failed loads publish no catalog entry. Configured selectors and
selectors occupied by downloaded font variants are reserved.
The default mapping is captured at load time from CTerm.codepage; it does not
follow Screen.font, the process locale, or later terminal encoding changes.
The explicit overload accepts the serialized Codepage enum, not a text label
or UTF-8 encoding sentinel. An unsupported mapping is a font failure. Font files
contain raw bitmap bytes, never normalized text. Their dimensions must match the
current console cell, with exactly 256 glyphs.
var selector = Font.load(file, Codepage.cp1251)
if (selector is Error) return selector
CTerm.font[0] = selector
FontError
FontError is Error reports font failures separately from file failures. It has
read-only code, nativeCode, message, and toString properties and no public
constructor. nativeCode preserves the underlying portable native I/O status,
or zero when no native operation failed. Its diagnostic starts with FontError.
| FontErr value | Code | Meaning |
|---|---|---|
|
1 |
No active terminal or the backend cannot load/select fonts. |
|
2 |
The bitmap size or dimensions are invalid. |
|
3 |
No bitmap mapping is available for the codepage. |
|
4 |
No free custom selector remains. |
|
5 |
The requested selector has no available registration. |
|
6 |
Another native font/registration operation failed. |
Wrong types, inexact/out-of-range numbers, invalid codepage enums, invalid assignment indices, and invalid masks are programmer errors and abort the calling Fiber. Recoverable load failures are returned as Error values.
Hyperlinks
Typed-ID lookup table over the application-lifetime hyperlink registry. It
is available to the menu and connected VMs, but not the file-picker VM.
Despite the
[id] / containsKey(id) shape, this is not a Map — there is no
keys / values / count / iteration. IDs flow into a script from
add() returns or from Cell.hyperlinkId on cells under the cursor;
scripts can’t enumerate the ID space. IDs range from 1 through 65535 and zero
means no hyperlink. IDs attached to live console cells, Wren Cell/Surface
storage, terminal scrollback, or retained session history remain stable. If
the registry fills, IDs not reachable from those roots may be reclaimed and
reused. Consequently, scripts should resolve or attach an ID promptly rather
than treating a detached number as permanent application-lifetime storage.
| Member | Description |
|---|---|
|
URI string for |
|
|
|
Allocate a hyperlink ID for |
|
Parameter string for |
To attach hyperlinks to text, allocate an ID and assign it to
Screen.hyperlinkId before writing through Screen.window.print.
Console
Read-only access to the current VM’s always-on print/error log buffer. The buffer has 1024 entries of up to 8 KB each; older entries are evicted in FIFO order. Sequence numbers are monotonic across the VM’s lifetime, including across eviction, so an incremental "show only entries newer than X" reader works correctly even after the ring has wrapped.
| Member | Description |
|---|---|
|
Number of valid entries currently in the ring. |
|
Monotonic count of entries ever written. Survives |
|
Entry with monotonic sequence |
|
Drop all entries. |
|
Snapshot the current |
|
Wren iteration protocol — works in |
|
|
e |
e[1] == LogSource.runtimeError
}.toList
----
+
|
LogSource
Enum values for the source field on Console entries.
-
LogSource.print(0) — scriptSystem.print. -
LogSource.compileError(1) — Wren compile diagnostic. -
LogSource.runtimeError(2) — Wren runtime error message. -
LogSource.stackFrame(3) — one frame of a runtime-error stack trace.
REPL
Primitive for the immediate-mode REPL. Most scripts will not use
this directly; the embedded wren_console script wraps it.
| Method | Description |
|---|---|
|
Compile and run |
|
As above, in |
|
|
|
List of every module name currently loaded in the VM (including
|
The [value] wrapper for expressions distinguishes "this was a
statement" from "this was an expression whose value is `null`".
Runtime errors propagate normally. Wrap the call in
Fiber.new {}.try() to catch them.
Session
Session.current is the stable VM-scoped view of the connected session, or
null in menu/picker VMs and during session teardown. Session lifetime holds
belong to independent SessionLease objects, separately from terminal state.
| Member | Description |
|---|---|
|
Stable read-only Profile snapshot of the connection configuration. Its
|
|
Captured connection name. |
|
Captured directory ID and |
|
Captured entry timestamps and connection count. These are metadata, not editable Profile fields. |
|
Run an installed DOS door terminal on the active connection. Use an absolute
|
|
Acquire a lease that keeps the session pumping after shell EOF while its owner has auxiliary work. A lease cannot release another owner’s hold. Native pending SFTP requests also keep their work alive independently. |
|
Run |
|
Number of live script leases; excludes native pending requests. |
|
Release this hold. Returns |
|
Whether this lease has been released explicitly, by GC, or during shutdown. |
Install door terminals and their data files under the SyncTERM data
directory’s dosbox-x subdirectory. Connected DOS sessions mount it
read-only as S:. Configure clients that save settings there from
Settings > DOS Shell. Any graphics profile can launch a local terminal on
a bitmap display when libdosbox is available and safe mode is off.
To enable automatic launch for a particular BBS, manually copy the
corresponding add-on from the source tree (addons/lod_gterm.wren or
addons/pit_terminal.wren) into the SyncTERM data directory’s scripts/
subdirectory, then select it for that personal dialing entry.
For Land of Devastation 5.11, install GTERM and its data files in
dosbox-x/LOD and set WrenScripts = lod_gterm in the personal dialing
entry’s INI section. The script starts GTERM on the stock welcome line so
it can answer the door’s version probe (5C 47 45 08) on COM1. If the
welcome line is absent, the first probe starts GTERM. Press Enter at the
main or wasteland menu to have the door probe again. Ctrl-Esc returns to
SyncTERM, and later menu probes leave it there until the next welcome or
reconnection.
To start GTERM manually, enter these lines in the connected Wren Console.
var door = Session.current
door.runDos("S:\\LOD\\GTERM.EXE", "COM 1 BAUD 9600")
For The PIT! 4.17, extract the terminal archive
PIT417_T.ZIP into
dosbox-x/PIT417 so it contains PTERM.EXE, its configuration and its
data files. Set WrenScripts = pit_terminal in the personal dialing
entry’s INI section to enable the add-on.
It watches for the door’s graphics terminal invitation and launches PTERM
on COM1 at the session baud rate. Press any key at PTERM’s startup screen
to connect to the door. To start it manually, use
door.runDos("S:\\PIT417\\PTERM.EXE", "1 9600").
While DOS owns COM1, SyncTERM pauses terminal parsing. Unread bytes remain
available when the terminal resumes. A wire or input hook runs during byte
dispatch and cannot take ownership there. A pending script send, wire lease
or file transfer can also return IOErr.busy.
Leases are host-created and have no public constructor. Keep the lease reachable while it is needed; collecting an abandoned lease releases its hold. Explicit disconnect and actual connection loss still end the session. The bundled SFTP queue owns a lease while it has runnable work; the public-key installer uses a scoped lease. Neither client controls the other’s lifetime.
Conn
Connection-level send and receive.
| Member | Description |
|---|---|
|
Queue Unicode text using the session’s wire encoding and transport
processing (including Telnet IAC escaping or MQTT framing). Returns an
|
|
Queue the String’s exact bytes, including malformed UTF-8, NUL and CR/LF, applying transport framing (Telnet IAC and NVT CR escaping, MQTT framing). No Unicode conversion, text newline folding or local XON/XOFF interpretation occurs. Returns an Operation with the text send completion contract. |
|
Close the connection. |
|
Request a session end. Sets a flag that doterm() picks up at the
top of its next iteration, runs the (UI-free) cleanup
(cterm shutdown, conn close, mouse/cursor restore), then either
returns to the main menu ( |
|
Paste from the system clipboard onto the wire — codepage-aware, bracketed-paste-aware. No-op when the clipboard is empty. This is the operation bound to Shift+Insert by the default key hooks. |
|
Invoke |
|
Bool — is the link up? |
|
Monotonic seconds since the connection provider reached the active
connected state, clamped to |
|
|
|
A String snapshot of the current application’s session log, including
protocol, CTerm, and transfer messages accepted by their respective log
levels. It is independent of the optional log filename and contains only
this connection’s diagnostics. The application retains up to 1 MiB of
recent records, discarding whole old lines when needed. An empty log is
|
|
Bytes in the transport output ring that have not gone out yet. This does not include the unsent storage owned by pending send Operations. |
Owned terminal-channel I/O
Session.current.claimWire() returns a WireLease, or a ConnError when
another owner, native transfer, transfer reservation, pending script send or
active terminal input callback prevents acquisition. Await earlier sends before
claiming. This is terminal-channel input after transport decoding, not access
to encrypted network packets. Native terminal display and output, key forwarding
and other script sends pause while it is owned. UI dispatch continues.
CTerm.suspended is independent and retains its previous value.
| Member | Description |
|---|---|
|
Number of available bytes in FIFO order: returned transfer input, unread terminal read-ahead, then the connection queue. |
|
Consume up to 65536 bytes; nonempty String on data,
|
|
Same results and limits without consumption or capture. |
|
Framed binary payload Operation, as for Conn.sendBytes. |
|
Deliberately bypass transport framing and text conversion. Use only for a protocol that requires such bytes; MQTT payloads require sendBytes. |
|
Idempotent Bool; cancel pending owned sends and return unread input to terminal processing in order. Already queued output stays queued. |
|
Bool. |
|
Call |
Send failure, drained EOF, read failure, GC and VM/session teardown release the lease. An input capture failure can consume bytes before reporting its error. A pending send retains its owner until completion or cancellation. A released lease returns ConnError for input and failed Operations for output; claim a new lease for later work. A live lease alone does not keep a disconnected session alive; use Session.hold when auxiliary work must finish after EOF. The old unowned Conn receive/peek/pending and sendRaw entry points are removed.
ConnError
Conn.sendText and Conn.sendBytes own the remaining output and retry queue
pressure internally. Requests run in FIFO order within the VM. At most 64
pending requests and 1 MiB of owned encoded storage (including terminators)
are allowed; an individual input must be smaller than 1 MiB. Oversized or
excess requests complete immediately with ConnErr.queueFull and send
nothing. Text is submitted in complete encoded scalar units. Other terminal
writers may run between those units; await completion before sending a key
or starting a protocol that must follow the text.
Cancellation discards the unsent remainder and completes with the usual
OperationError. Bytes already queued cannot be recalled. Dropping an
Operation handle does not cancel its send. Shutdown cancels pending sends.
File-transfer ownership rejects new or pending sends with ConnErr.busy.
A WireLease rejects sends from Conn; use the lease for protocol output.
Recoverable connection failures complete the Operation with ConnError:
| Member | Description |
|---|---|
|
|
|
Bool: some of this request was accepted before the failure. This is diagnostic, not an input offset. Do not resend a whole request after a partial failure unless duplication is acceptable. |
|
Human-readable diagnostic. |
|
|
ConnErr constants:
| Constant | Code | When emitted |
|---|---|---|
|
1 |
The connection is down. |
|
2 |
The transport rejected the remaining output. |
|
3 |
The script request/storage limit was reached. |
|
4 |
Malformed UTF-8 or text unrepresentable in the session’s codepage. No output from this request was queued. |
|
5 |
A wire lease or file transfer owns or has reserved the connection. |
var error = Conn.sendText("café").await()
if (error == null) {
CTerm.sendKey(KeyEvent.new(Key.enter))
} else {
System.print(error)
}
As with other Operations, a hook with a synchronous return contract must
start a child Fiber to await completion; an App handler uses app.runChild.
Capture
Streaming-log control for the active session. The Wren-side
CaptureMenu in scripts/auto/connected/capture_menu.wren implements
the user-facing Alt+C flow with these primitives. All methods are
no-ops when no terminal is active.
| Method | Description |
|---|---|
|
Bool — true while a streaming log is open (regardless of pause state). |
|
Bool — true when the active log has been paused via
|
|
Open a streaming log to the path authorized by |
|
Close the active log. No-op when not capturing. Idempotent. |
|
Set the PAUSED bit on the active log. No-op when not capturing or already paused. |
|
Clear the PAUSED bit. No-op when not capturing. |
Use CTerm.saveScreenshot for a one-shot binary screen
snapshot with optional SAUCE metadata. Screen snapshots are terminal
state rather than streaming logs and therefore are not part of
Capture.
CTerm
The active terminal’s state and local operations. Most state properties are
read-only. Useful from Hook.onInput and Status.callable for emulation-aware
logic. Terminal operations are available in the connected VM.
For RIP3, these properties and local operations address the selected virtual
text window. Its cursor and dimensions are independent of the main Screen
canvas, which retains the entry’s configured video mode. CTerm.write and
CTerm.reset present their local changes inside that window.
| Group | Members |
|---|---|
Cursor (1-based, on the terminal) |
|
Origin (1-based, on the host screen) |
|
Geometry |
|
Color state |
|
Fonts |
|
Scrollback |
|
Mode flags |
|
Screenshot |
|
Mouse state |
|
Throttle |
|
Bitfield snapshots |
|
CTerm.font[i] is a live, writable view of terminal font assignments. Indices
0 through 9 correspond to SGR 10 through 19. All ten start with the configured
default font. In the primary rendition, positions 0 through 3 also supply the
normal, source-bright, source-blink, and bright-plus-blink fonts.
Reading returns a selector; writing changes only that assignment. This is
independent of the five Screen.font slots for script drawing.
CTerm.setFont(selector, mask) changes all requested assignments together.
CTermFontMask.normal is 1, .bright is 2, .blink is 4, .brightBlink is 8,
and .all is 1023. Use 1 << i for an individual position. Combine bits with
|; zero and unknown bits are invalid.
Selection requires an available registration and a capable backend. It finishes
pending output before committing; failed selection leaves every assignment
unchanged. Existing cells retain their resolved fonts. Selection does not change
the video flags which enable source-bright/blink font selection.
The method returns null on success or FontError on an operational failure.
An indexed write raises that same FontError through ordinary Fiber abort,
so failed assignment statements cannot silently discard a returned error.
Assignment expressions can capture setter results in standard Wren; this
particular indexed setter deliberately aborts on failure. Catch it with a
Fiber’s .try() when recovery is needed. The terminal assignment interface is
connected-VM-only. The old CTerm.altFont and detached CTerm.altFonts List
are removed without aliases. The shipped picker still changes only the normal
assignment when selecting an existing font; loading only registers a new font.
| Action | Description |
|---|---|
|
Render strict UTF-8/NFC text directly through the native semantic-input path,
independently of the wire encoding. Returns |
|
Forward a |
|
Bool. Reports whether the active RIP3 or DDO F/X scene has locked keyboard input. A shortcut that submits terminal data directly can check this before sending. |
|
Enable or disable the Thieves' Guild front end for the current Atari ST
session. Pass a Bool. The method returns null on success or a |
|
Locally arm the Musicomm receiver and read whether it still owns received
bytes (including startup/end drains). Start returns null on success or
|
|
Invoke the direct native terminal reset synchronously. Returns null on native success or CTermError with the exact native failure code. Requires the connected VM’s assigned terminal, independently of whether the network is still connected. Menu/picker and missing-terminal calls abort without invoking reset. + The native operation finishes pending input, resets parser/mode and cursor settings, and rebuilds enabled RIP state, including reloading its persisted variables. Finishing a buffered RIP command can invoke its existing host prompt or other callback before reset proceeds. This is distinct from feeding a reset escape sequence through CTerm.write. The binding adds no screen/history clear, resize, encoding change, reconnect, wire claim or suspension change. Existing native generated-response suppression under WireLease/transfer ownership remains in force; local reset does not create a new busy/network failure policy. + Failure may follow pending-output processing or partial reset, including a partially rebuilt RIP engine. It provides no rollback or automatic retry and does not guarantee that the terminal remains usable. The operation retains no arguments or native resources. |
|
Read or write the wire-pump suspend flag. When set true, the main
loop stops draining bytes from the conn buffer. Bytes pile up in the
conn buffer; the TCP receive window eventually fills and the remote
sees its |
|
Read or toggle the session gate for forwarding mouse events to the
remote tracking protocol. Changes take effect immediately; local UI
subscriptions remain controlled by |
|
Read-only effective native mouse protocol: BIG reports mode |
|
Read-only Bool; true while DECSET 1016 is the active SGR pixel-position reporting mode. False for IGS, SkyPix and an active BIG pointer. SkyPix controller reports use their own pixel-coordinate format even if an ANSI mouse mode was requested. |
|
Read or write the cterm doorway-mode flag. When true, the input pump passes most keys through verbatim instead of decoding them; used by door programs that want raw scancodes. |
|
Read or write the Operation Overkill ][ terminal mode
( |
|
Current network character-pacing rate in BPS. |
|
Walk |
CTermError
An immutable Error returned by write, sendKey and reset above. There is no
public constructor. It owns scalar diagnostics and message storage, retains no
input String, terminal or session, and remains usable through later calls and GC
within its VM.
| Member | Description |
|---|---|
|
Exact native I/O integer, comparable to |
|
Nonempty human-readable operation/reason diagnostic. |
|
Write errors only: native consumed count in the normalized
UTF-8 input; |
|
Key errors only: the native acceptance Bool, including local-only
actions; |
|
Includes |
Wrong types, invalid event objects, malformed UTF-8 and missing required native terminal/session state remain programmer errors raised through ordinary Fiber abort. An impossible native consumed count, or native success with incomplete consumption, also aborts as a native contract violation; no I/O status is invented. Native output policy is unchanged: key errors can reflect retained output failures, and disconnect suppression permits auxiliary work to continue. These values provide no rollback, automatic retry or network-delivery guarantee.
var result = CTerm.sendKey(KeyEvent.new(Key.enter))
if (result is CTermError) Fiber.abort(result)
// result is now the native acceptance Bool.
ExtAttr
Snapshot of cterm’s extended-attribute bitfield. All members are read-only Booleans reflecting the corresponding terminal mode.
| Member | Description |
|---|---|
|
DECAWM — characters past the right margin wrap to the next line. |
|
IRM — graphic characters shift text to the right when inserted. |
|
DECOM — cursor coordinates are relative to the active scroll region rather than the screen. |
|
SIXEL scroll: when a SIXEL image extends past the bottom of the screen, scroll the screen up to make room. When clear, the image is clipped at the bottom row. |
|
DECLRMM — left/right margin mode enables horizontal scroll regions. |
|
DEC mode 2004 — pasted text is bracketed by ESC[200~ / ESC[201~ markers. |
|
DECBKM — Backarrow key sends BS (0x08) instead of DEL (0x7F). |
|
Prestel mosaic graphics character set is active. |
|
Current row is rendered double-height. |
|
Concealed (hidden) text mode. |
|
Separated mosaics — gaps between mosaic blocks. |
|
Hold-graphics mode — control codes render as the most recently emitted mosaic glyph rather than blanking. |
|
DECKPAM — numeric keypad sends application keypad codes instead of digits. |
LastColumnFlag
Snapshot of cterm’s last-column-flag state. Used by emulations that distinguish "cursor at the right margin" from "cursor wrapped to next line" (the so-called phantom-column).
| Member | Description |
|---|---|
|
Bool — the flag is currently set: the cursor sits at the right margin awaiting the next character to wrap it. Cleared by any cursor-positioning sequence. |
|
Bool — last-column-flag tracking is enabled at all. Some emulations disable it. |
|
Bool — tracking is forced on regardless of the
underlying mode (set by SyncTERM’s emulation-bridge
code or the BBS list’s |
StatusDisplay
Referenced by CTerm.statusDisplay. VT320 DECSSDT (Select Status
Display Type) values: which status line, if any, the bottom row is
acting as.
| Constant | Code | Description |
|---|---|---|
|
0 |
No status line — the bottom row is part of the main display area. |
|
1 |
Indicator status line — terminal-managed diagnostic line (e.g. "INSERT", connection state). The host can’t write to it. |
|
2 |
Host-writable status line — the bottom row is a separate addressable region the BBS can direct writes to via DECSASD. |
Profiles
Profile in syncterm is the shared connection-configuration contract in all
VMs. DirectoryEntry.profile and Menu.defaults are views into the working
menu model. Session.current.profile is a cached, read-only snapshot of the
configuration captured for this connection. profile.copy() returns an
independently owned editable value, without a directory identity or statistics.
Quick-connect configurations are independently owned values too; later quick
connections and menu reloads do not overwrite or invalidate them.
readOnly identifies system/web views and session snapshots. Their setters
abort. All other Profile fields below have getters and setters, except the
derived display string connTypeName. Profiles have no rename/save/delete,
entry IDs, statistics, or cache authority. Use Menu.copy(profile, name) to
create an entry; selecting a Profile starts a transient connection without
updating another entry’s statistics.
| Group | Fields |
|---|---|
Address |
|
Network |
|
Auth |
|
Presentation |
|
Files and logging |
|
Serial and protocol |
|
Scripts |
|
Connection strings, credentials, paths, and comments use the normal strict
UTF-8/NFC text boundary without NUL, with field-specific size limits.
tlsPsk is literal text, without
hexadecimal or Base64 decoding. sshFingerprint is an exact byte String of
length 0, 20 or 32; use .bytes.count for its length. palette and
wrenScripts return fresh Lists; their lengths replace the old redundant
size getters. Invalid assignments leave existing values intact.
profile.customScreenMode returns null when Custom follows Program Settings,
or a fresh List in the order [columns, rows, fontHeight, aspectWidth, aspectHeight].
Assign a complete List to store an override, or null to clear it. Columns and
rows accept integers from 1 through 255, font height from 1 through 64, and
each aspect component from 1 through INT_MAX. The matching optional BBS-list
key uses comma-separated integers, for example CustomScreenMode=96,32,8,3,1.
An incomplete or malformed tuple inherits the program mode. A saved profile
retains its override when another screen mode is selected.
Configured profile.encoding uses the profile encoding catalog and remains
unchanged when terminal decoding changes. CTerm.encoding reports the live
TerminalEncoding.utf8 (0) or TerminalEncoding.codepage (1);
CTerm.codepage reports the live Codepage value. Session.current.name,
entryId, entrySource, added, lastConnected and calls describe the
session’s captured identity and connection statistics. Conn.elapsedSeconds
is live elapsed time. The former BBS classes and static namespace are removed.
Menu BBS Model
The menu VM imports Menu, DirectoryEntry, and MenuError from
syncterm_menu. Menu owns a C-side transactional view of the
personal, installed system, and web-cache BBS lists. It is not
available in a connected VM.
| Method | Description |
|---|---|
|
Load all lists and replace the current model only after the complete
load succeeds. |
|
Return a fresh List of immutable BBSLoadDiagnostic snapshots from the current installed list, in native order; empty without a loaded model. Reading does not reload files or change the model. See BBS load diagnostics. |
|
Parse a String using SyncTERM’s normal URL rules and return an owned editable
Profile, or null for an unusable address. It remains valid across further
quick connections and reloads. It can be returned from MainMenu.run; use
Menu.copy(profile, name) to create a directory entry.
The |
|
Return a detached |
|
Number of rows in the most recently completed session, including its saved terminal page, subject to the configured capacity. |
|
Read one detached row or its original geometry, using the same coordinates
and return types as |
|
Select the completed session’s text mode, restore its mode-specific fonts
and palette, and draw the terminal background. Returns |
|
Restore the original menu geometry after preparing detached history; returns null or ScreenError. It is idempotent and leaves an enclosing disconnected session’s mode bracket intact. The shipped viewer pairs this with preparation through its cleanup scope. |
|
Return whether the completed session’s terminal layout reserves a status row. The shipped viewer uses the full screen height for Page Up/Page Down and this value to recover the terminal height used by H/L. |
|
Open a detected plain-text URL with the configured local URL handler.
Returns whether it opened, or |
|
Resolve an ID from the shared hyperlink registry and open HTTP, HTTPS, FTP,
or FTPS URIs with the configured local URL handler. Scheme matching is
locale-independent and case-insensitive. Returns |
|
Select the link pointer when |
|
Return the classic header text, combining the SyncTERM version and active conio output-backend description. This is display data and does not change the OS window title. |
|
Return the current local time in the classic 24-character
|
|
Return the current Unix timestamp as a Num. Trusted offline applications
can use it to initialize date-oriented widgets without a connected Session
or |
|
Set the OS window title to the classic name/call-count/last-connected
summary for a current DirectoryEntry or Profile. Passing |
|
Set SyncTERM’s process exit latch after trusted menu code has completed any required work. This is available for explicit menu commands; OS window-close requests set the same latch in the host. |
|
Return a new List of host-created DirectoryEntry views in current sort order. The records themselves remain C-owned. |
|
Return whether the combined personal and read-only directory has room for another personal entry. |
|
Return a fresh List of valid root script-module names available for
per-entry connected loading. The list is rebuilt from user
|
|
Maximum byte length of the comma-separated |
|
Return the mutable defaults Profile view, or null before loading. Scripts are configured per entry: root-section WrenScripts is ignored, defaults expose an empty script list, and assigning scripts to defaults aborts. The defaults editor omits scripts. New entries start without scripts; entries without their own WrenScripts stay empty when edited. |
|
Bool indicating unsaved default configuration changes. |
|
Persist the working defaults to the root section. Returns null/MenuError; safe mode returns IOErr.readOnly. Profiles have no persistence methods. |
|
Test whether a new personal entry name is valid and unused by another
personal entry. Names are 1..30 Unicode scalars and at most 60 UTF-8 bytes;
identity uses Unicode canonical caseless matching. The reserved
|
|
Create an unsaved personal entry from |
|
Create an unsaved personal copy of |
|
Reapply the configured BBS-list sort profiles. Returns null/MenuError. |
|
Return fresh |
|
Return fresh |
|
Zero-based index of the active profile. |
|
Select a profile in memory, apply its order, and re-sort the loaded directory. Returns null/MenuError; invalid indices abort before the native call. |
|
Insert a profile. Names are 1..19 Unicode scalars, at most 38 UTF-8 bytes,
and canonically caseless-unique. They cannot contain controls, leading or
trailing Unicode whitespace, |
|
Replace a profile’s name and field order. Updating the active profile also re-sorts the loaded directory. Returns null/MenuError; invalid arguments and duplicate names abort. |
|
Delete a profile and re-sort with the resulting active profile. Deleting the last profile restores the built-in profiles. Returns null/MenuError. |
|
Write the working profiles, active profile, and current order to
|
The shipped offline viewer saves the menu screen, calls
prepareOfflineScrollback(), captures the resulting background, and restores
the saved mode, fonts, palette, video flags, cursor, mouse subscriptions, and
screen when it closes. It starts at the newest screen. Up/J and Down/K move
one line, Page Up/Page Down move by the physical screen height, H/L move by
the terminal content height, the mouse wheel moves one line, F1 opens the
Markdown help, and Escape returns to the directory. Clicking opens OSC 8 or
detected plain-text URLs, hovering shows an OSC 8 URL in the status row, and
button-one drag copies text in reading order. Alt at button press selects a
rectangle. In mixed geometry the viewer shows the hovered URL in its title row.
Horizontal arrows pan, and holding a dragged pointer at the viewport edge
continues scrolling. Both selection modes use each row’s original columns.
In v2, MenuReadStatus and Menu.statusMessage are removed without aliases, including obsolete migration status values. Successful loads can still contain warnings about skipped sources or sections, or truncated entry names. The bundled menu opens a scrollable Directory Warnings summary when any warning comes from a personal or shared list. Up/Down scroll one line, PgUp/PgDown scroll a page, and Home/End jump to the top/bottom. Enter continues and Escape closes the dialog. Once dismissed, an unchanged warning summary does not reopen during subsequent loads in the same menu VM, including returns after disconnect. A changed summary can reopen it; a successful load without an automatic warning clears the remembered summary. Warnings remain available through Menu.loadDiagnostics on every load. Warnings exclusively from web lists do not open the dialog automatically, but remain in the diagnostics and appear alongside other warnings when the dialog opens. Dismissal continues with usable entries; missing optional files remain silent. A diagnostic retrieval failure still opens the dialog every time as warnings unavailable, without treating the successful load as failed. Password cancellation and fatal load errors retain their existing prompts and error dialogs, even when all retained warnings are from web lists. There are no automatic retries.
A DirectoryEntry owns name, searchKey, source, sourceName, shadowed, id, added,
connected (persisted LastConnected timestamp), lastCallText, calls, readOnly, dirty,
profile and cache. Only sortOrder has a property setter. rename(name),
save() and delete() return null/MenuError; toString returns its name.
id survives sorting, rename, save and unrelated model edits. An unsaved draft
has -1 until its first successful save. IDs are local to a load and are not
serialized. Native ownership also distinguishes replaced records independently
of their names, addresses or numeric IDs.
lastCallText formats the persisted last-connected timestamp as a local-time
YYYY-MM-DD date, Never for zero, or Unknown if it cannot be represented.
It performs no I/O and follows the entry handle’s ordinary lifetime.
source preserves the native list source using BBSListSource.personal (0),
shared (1), webSystem (2), or webNamed (3). sourceName returns null for
personal entries, the shared-list path, "System List" for the system web list,
or the configured named web-list name. Source names are validated as UTF-8 and
normalized to NFC on access. A conversion failure returns MenuError with the
actual status in code and nativeCode; it does not change the loaded model.
Reading other fields does not construct a source-name String or Profile snapshot.
New and copied personal entries have personal provenance and no source name.
shadowed returns a read-only DirectoryEntry view of the next lower-priority
record retained by the native or working directory model, or null. Traverse only
the records actually retained; this does not enumerate every list containing
that name or change native precedence. Its profile is a read-only view,
cache is null, setters abort and rename/save/delete return read-only MenuError.
Explicit Menu.copy() and profile.copy() use the ordinary copy rules.
The view creates no file authority and remains excluded from Menu.entries.
Hidden entry/profile views follow normal directory lifetimes: sorting and unrelated edits preserve them, a successful load replaces them, and a failed load preserves them. Restoring a hidden record to the visible list invalidates its old hidden view; an old visible view does not revive when that record is restored. Captured Strings and detached Profile copies remain independent.
The former directory classification getter entry.type is removed. It now
inherits Wren’s standard Object.type, returning the DirectoryEntry class.
Use entry.source for provenance and entry.readOnly for editability.
BBSListType and Session.entrySource still represent the native profile’s
separate personal/system classification; no Profile.source getter is exposed.
searchKey retains the NFD full-default-casefold form of the name. The shipped
list uses it as a cheap search prefilter and verifies grapheme boundaries.
Configuration lives on entry.profile; its setters share the working record
and mark the entry dirty. Saving persists those edits and an in-memory rename
together. Deleting a persisted entry updates disk before removing the record;
deleting an unsaved draft only discards that draft. System/web views reject
configuration setters; rename/save/delete return MenuError with IOErr.readOnly. Menu.copy produces a
personal editable entry. Safe mode permits working edits but rejects persistence.
entry.cache is a Directory for a saved personal entry, created through the
normal cache resolver. It returns null for unsaved/system/web entries and a
FileError on native failure. Before a pending rename is saved it refers to the
persisted name’s cache. Saving the rename uses the native cache move policy.
Previously issued cache grants and their descendants become stale at that
point, on removal/replacement, and on reload. They cannot access a later entry
at the same name/path. An already open File retains its stream and can always
be closed; path-based operations still require a current grant. Displayed
paths confer no new authority. This adds no arbitrary filesystem constructor.
The shipped entry editor invokes those setters, including rename(),
after each nested field editor accepts a changed value. It calls
save() for a dirty entry when the entry editor closes.
The Wren Scripts editor applies additions, deletions, and completed moves to
the working Profile immediately; save() writes them as the comma-separated
WrenScripts value in that entry’s INI section.
The fingerprint has no direct editor row; the shipped F5/F6 clipboard carries
it through the draft so copying an entry preserves an accepted SSH host key.
TLS certificate/key and PSK identity/secret pairs can be edited one field at a time. The editor validates complete pairs before saving and remains open when a pair is incomplete. C-backed text fields also enforce their UTF-8 byte limits before invoking a setter.
Download Path and Upload Path remain direct entry rows. Log Configuration opens Log Filename, File Transfer Log Level, Protocol Log Level, CTerm Log Level, and Append Log File. Accepted values still update the working Profile before the logging submenu closes.
The persisted INI name is ProtocolLogLevel. During the pre-release
rename, a missing ProtocolLogLevel falls back to the legacy
TelnetLogLevel value; saving the entry writes the new name and removes
the old one. When neither global key exists, the default protocol log
level is Error.
CTermLogLevel is saved independently for each entry and connection default;
its default is Error. CTerm diagnostics share the configured LogFile and
append setting, with a CTerm source prefix. Warning includes detected
unsupported or invalid sequences, rejected parameters, and malformed UTF-8.
Debug also reports final missing grapheme clusters (.noglyph) with their
Unicode code points, selected console font identifier, and screen position.
An exact match supplied by compatible font zero is not a missing glyph.
A successful full load invalidates entry/default views and cache grants from the replaced model. A failed load preserves them. Creating/deleting unrelated entries, sorting and saving preserve existing identities. Deleted or shadowed entries become stale; restoring a shadowed system record does not revive an old view of it. Detached Profile values and session snapshots remain valid.
BBS load diagnostics
Menu.loadDiagnostics creates snapshots only when requested. BBSLoadDiagnostic is menu-only, host-created, and immutable, with no public constructor or setters:
| Property | Description |
|---|---|
source |
BBSListSource.personal (0), shared (1), webSystem (2), or webNamed (3), preserving native source values. This is distinct from BBSListType. |
sourceName |
Nullable source identifier: null for the personal list, the shared list path, "System List", or the configured named web-list name. |
sectionName |
The original section name for a skipped or truncated entry, or null for a source-level failure. |
error |
A fresh MenuError with the native portable diagnostic status in both code and nativeCode, and a readable reason. Constructed only on access. |
Snapshots own their names and scalar data, survive reloads and garbage collection, and retain no borrowed list pointers, secrets or filesystem authority. Their names are strict UTF-8/NFC host text. Allocation or text-conversion failures raise MenuError through ordinary Fiber abort; they do not alter the loaded model. The returned List is independently mutable; its records are immutable. Diagnostics come from the installed native list, including its existing rebuild behavior, not from a failed replacement candidate. Entry provenance and shadowed records are separate from these warnings.
Overlong entry names are loaded using the longest valid prefix within 30 Unicode scalars and 60 UTF-8 bytes, preserving complete UTF-8 scalars and removing trailing whitespace at the cutoff. Their diagnostic has IOErr.nameTooLong and retains the full original section name. Values are read from that original section; the shortened name determines entry identity and the usual duplicate/priority rules. Editing or deleting a personal entry still addresses its original section. Malformed or otherwise invalid names retain the existing rejection policy.
import "syncterm_menu" for Menu
var failure = Menu.load(null)
if (failure != null) {
System.print(failure.message)
} else {
for (item in Menu.loadDiagnostics) {
System.print("%(item.sourceName): %(item.error.message)")
}
}
Menu operation results
In v2, BBS and Settings mutation actions return null on success or a host-created,
immutable MenuError. Creators (Menu.create, copy, createFromProfile, createFont) return their
object or MenuError. This covers entry rename/save/delete, defaults/encryption/sort,
Settings apply/save/reload, font/web/sort collection actions, Menu.load, and
theme operations described below.
Predicates retain their own contracts. There are no Boolean compatibility forms.
| Member | Description |
|---|---|
|
Portable IOErr reason, or null when the called C API supplies no portable reason. Classify by the API’s contract, never by the raw integer alone. |
|
Actual integer C failure, or null for Boolean/pointer failures and host-only policy rejection. ThemeDocument.save retains its separate native ThemeSaveErr enum here with code null. Generic -1 from older collection APIs is retained here with code null; it is not classified as IOErr.invalidArgument. |
|
Owned operation-specific diagnostic; portable failures include their reason. |
|
Diagnostic prefixed by `MenuError: `. |
MenuError has no public constructor or setters, retains no borrowed native data, secrets or resource authority, and remains usable after reloads and collection. It is available only in the trusted menu VM and inherits the ordinary Error base. Existing invalid-argument and stale-handle aborts remain. Native mutation failures in property setters raise MenuError through ordinary Fiber abort.
Native C APIs, call order and partial effects are preserved. A list KDF rewrite may succeed before a Settings save fails. Collection edits may precede a later native failure, and installed settings may precede a runtime application failure. Messages identify completed earlier steps where known. Once settings are installed, generation/dirty transitions still occur even if applying a runtime option fails. There is no rollback or transaction-state API. Inspect current models as needed; no automatic retry is performed. Optional cache housekeeping remains outside primary BBS mutation success. Safe-mode blocked operations return IOErr.readOnly, including saveSortProfiles, which formerly reported a successful no-op.
var error = entry.save()
if (error != null) System.print(error.message)
Saving detached menu drafts
The Retro editors use the existing Profile.copy() to keep profile changes out
of the working directory until Save. The following menu-only additions accept
an owned, editable, detached Profile; passing another foreign type or a borrowed
profile view aborts. They do not consume the supplied Profile.
| Operation | Result and behavior |
|---|---|
|
Update an existing personal entry and persist it, returning null/MenuError.
Preserve entry identity, provenance, call statistics, and other entries.
|
|
Persist a new personal entry and return its DirectoryEntry or MenuError. Reset call statistics using the same rules as Menu.copy; normal name, capacity, and shadowing rules apply. A failed creation leaves no unsaved entry. |
|
Persist replacement new-connection defaults, returning null/MenuError. The existing zero-argument overload still saves the mutable working defaults. |
Preparation and persistence are serialized on the menu thread. No application callback observes a partially prepared record. Failure restores the working record and preserves its views; success publishes the replacement and reapplies sorting. Existing native write-error and secondary-cache semantics remain: a failed write can partially modify the file, and cache maintenance is separate from primary mutation success. These operations do not create a general-purpose transaction or filesystem rollback facility. Safe mode returns IOErr.readOnly.
Menu Program Settings
Menu.settings returns a C-owned Settings snapshot. Property
setters validate the assigned value, change only that snapshot, and set
dirty. apply() applies the snapshot to the running program without
writing syncterm.ini. Values copied from the running settings are not
revalidated, so values accepted by older versions pass through unchanged.
reload() discards changes not yet applied and repopulates the same handle
from the current running settings. It does not reread syncterm.ini, including
when another process has edited that file. The native raw global reload is
intentionally not exposed: it replaces configuration data and the merge baseline
without coordinating runtime fonts, themes, audio or layout. There is no full
application disk-reload method.
dirty specifically means that the snapshot differs from the running
settings. A successful apply() clears it. It does not indicate
whether those running settings have subsequently been written to
syncterm.ini; code which separates apply() from save() must track
that persistence obligation itself.
save() preserves unrelated INI sections, writes the existing
syncterm.ini keys, and applies the settings which have immediate effects.
These include scrollback capacity, scaling, mouse-wheel direction, audio
backends, custom-mode dimensions, cursor style, and the Classic Theme
colours used when the built-in theme is active. It returns
MenuError when preparation, encrypted-list rewriting, INI persistence, or runtime
application fails; success is null. A failure before installation does not apply
an unapplied snapshot; settings already
accepted through apply() remain active. Changing the KDF work factor may
rewrite an encrypted BBS list during apply(). Saving syncterm.ini is
disabled in safe mode: save() returns MenuError with IOErr.readOnly before applying the snapshot,
and the snapshot remains dirty.
The allowed audio-backend mask changes immediately. Backend selection occurs when the process first opens its audio engine; changing an already-open backend requires restarting SyncTERM. Startup screen and video output preferences also take effect on the next startup. In safe mode, applying a KDF change which would rewrite an encrypted directory returns IOErr.readOnly without changing the directory or installed settings.
Installing a snapshot during apply() or save() advances the settings generation,
even if a later runtime application step fails.
The object which performed the operation remains valid and clean, but
any other outstanding Settings handles become stale and abort when
used. Reacquire a snapshot from Menu.settings after another component
applies or saves settings.
The Classic Program Settings editor calls apply() after each accepted
setting and calls save() once when the editor closes. Thus settings
with immediate effects change at field-confirmation time while the INI
write remains grouped at the Program Settings screen-exit boundary.
If the write fails, the screen remains open so saving can be retried.
promptSave controls the save offer for a temporary URL connection when the
application exits. The offer is suppressed in safe mode, when that entry has
hidePopups set, and for entries already saved in the directory.
The Classic editor keeps Classic Theme Colours and Custom Screen Mode as nested groups instead
of flattening their fields into Program Settings. A connected invocation
omits Custom Screen Mode. The connected settings list also omits Current
Screen Mode and List Encryption; List Encryption is omitted in every mode
when Menu.encryptionAvailable is false.
| Property | Meaning |
|---|---|
|
Bool, defaults to true. Enables local Atari ST keyboard clicks independently
of the terminal bell and remote sound effects. The Program Settings row
toggles on selection and applies immediately, including during a connection.
Persists as |
|
Built-in main interface: 0 is Classic (default), 1 is Retro. Other assignments
abort. |
|
Bool program options. |
|
Modem strings and the terminal name exported to local shell
connections. The shipped editor accepts 1024 bytes for the device,
1023 bytes for either modem command, and 30 bytes for |
|
Stored personal-list path or URI. The host resolves it to the active
local or cached list path after a successful apply or save. The shipped
editor limits it to |
|
Catalog-backed display, backend, and audio selections. |
|
OpenGL scaler selection when |
|
Scrollback capacity is 1 through |
|
Stored transfer completion acknowledgement preferences in seconds, from
0 through |
|
The effective scrypt cost exponent for encryption rewrites; accepted
range is 8 through 20. Unsupported older persisted specifications report
the effective default of 15. This is policy, not the loaded file’s KDF;
use |
|
Custom text-mode geometry. Rows are 14..255, columns are 40..255,
font height is exactly 8, 14, or 16, and both aspect values are
1 through |
|
Palette indexes used to construct the built-in Classic Theme.
Frame, text, and lightbar foreground use |
The six values are persisted under [ClassicTheme]. On load, each
missing key falls back independently to the same key under the former
[UIFC] section, so a partial new section does not discard old
preferences. The next successful Program Settings save writes all six
[ClassicTheme] values and removes [UIFC]. A failed save leaves the
existing file unchanged.
Program Settings includes an Amiga Fonts manager. User-installed families live
under fonts/amiga/ beside the active syncterm.ini; the 11 bundled families
(39 strikes) are compiled into SyncTERM and are not copied there. The per-BBS SkyPix Font
choice stores Profile.amigaFont (family name, default Pearl.font) and
Profile.amigaFontSize (exact strike height, 1..65535, default 8). Initial
selection tries an exact installed name/height, an exact bundled strike, then
Pearl 8; it does not stretch a neighbouring size. Reset restores that configured
initial strike. Unavailable remote font requests also fall back to it. A selected font remains valid
if its installed package is subsequently replaced or removed. Catalog queries
and management are menu-only; connected scripts cannot import this interface.
The host supplies display catalogs rather than requiring scripts to duplicate platform-dependent enum tables:
| Menu member | Result |
|---|---|
|
Ordered |
|
Screen-mode picker rows with square pixels. Current uses the live console
geometry. Pass a profile or draft’s five-value Custom geometry to filter
Custom for that entry. The getter and a |
|
Ordered |
|
Lists of display names indexed by the corresponding numeric setting. |
|
Lists of |
|
The former returns compatible |
|
Fresh List of immutable |
|
Open the local Amiga |
|
Remove the installed portion of the current family snapshot; return null or MenuError. Bundled fonts cannot be removed. A snapshot retained across another install/remove operation must be reacquired before removal. |
|
Return the built-in default port for a connection-type value. RLogin uses 513, Telnet 23, SSH 22, MBBS GHOST 65535, Telnet TLS 992, and MQTT 8883. Types without an inherent network port return zero. |
|
Open the named serial device and return its supported rates as
|
|
Return the |
|
Return |
|
Build-dependent List of |
|
Build-dependent List of |
|
Build-dependent List of |
|
Bool. True in the persistent menu VM when the static libdosbox emulator can run on the current bitmap display and safe mode is off. |
|
Open an interactive DOS prompt in the local menu. Returns an integer status after the guest exits and the menu display is restored. Zero indicates success. See the DOS drive mappings. |
|
List of |
|
List of |
|
Build-specific |
|
Bool indicating whether this build exposes personal-list encryption. |
|
Foreground and background color-name Lists, including their final
|
|
Current SyncTERM screen-mode enum value. |
|
Apply a concrete screen mode immediately and restore the configured
default cursor. |
|
Map containing |
Controller mapping in syncterm_menu
Menu.controllers lists attached devices as [localId, label] pairs. An empty
list means zero devices and null means no provider. Menu.controllerFields(id)
returns one row per physical control in HID descriptor order or XUSB provider order, containing its
label, binding index (−1 if unassigned), inversion flag and current preview
value (null if unknown). Each physical hat also has four button fields appended
after the descriptor fields, one per cardinal direction. A diagonal presses
both adjacent directions. Libretro devices expose no editable fields.
Menu.controllerTargets(id, field) lists compatible targets as
[bindingIndex, label, kind]. Use field −1 for all targets. Kinds 0, 1, 2
and 3 denote button, centered axis, one-way axis and hat respectively.
Menu.controllerHatButton(id, field, direction) returns the button field
for a cardinal direction of a hat, or −1 for a non-hat, diagonal or neutral.
Menu.armController(id) starts identification using the current baseline.
Menu.armController(id, target) captures only fields assignable to that
target. Pass −1 to capture any control.
Menu.controllerMotion(id) returns [field, value], with field −1 until a
new actuation. Hat preview and captured values are clockwise directions
0..7 from up, with −1 for neutral.
Menu.bindController(id, field, target, inverted) applies a binding. Target
−1 clears it. Assigning an occupied target moves it to the selected field.
The method returns true on success, null if the device disconnected, or a
MenuError if saving failed. Safe mode applies the mapping in memory.
Menu Themes
Theme storage and file syntax are documented in Themes.adoc.
Menu.themes refreshes the C-owned catalog and returns a List of rows in the form
[filename, name, author, description, version, error], or MenuError if refresh
fails. Native failure preserves the previous catalog; already returned rows remain
usable. The built-in
Classic Theme has an empty filename. Optional metadata is null when
absent. An invalid or missing theme has an error String and cannot be
selected, but remains available for display in the browser.
Menu.selectedThemeFile returns the committed filename, or an empty String
when Classic or a cloud package is selected. Menu.selectedThemePackage
returns the committed repository/id, or an empty String for Classic and
local files. Menu.previewTheme(filename) installs a temporary
process-wide preview and returns null/MenuError without changing the committed
selection. Menu.cancelThemePreview() restores the
committed theme. Both operations advance Host.themeGeneration when they
change the active snapshot.
Menu.selectTheme(filename) validates the catalog entry, writes
[SyncTERM] ThemeFile, and commits the preview as one operation. Selecting
Classic removes the key. It returns null/MenuError. In safe mode the running selection changes but the INI file is not
written. A successful selection advances both the theme and settings
generations, so scripts should reacquire outstanding Settings snapshots.
Selection failure preserves its original native reason and existing restoration
attempts; messages describe failed restoration if detected. No new rollback or
unchanged-file guarantee is made.
Menu.deleteTheme(filename) removes a local theme file and returns null/MenuError. Deleting the selected file first commits and saves Classic
Theme. If deleting the file then fails, Classic remains selected and saved
while MenuError reports the deletion failure and the completed Classic selection/save.
Menu.refreshCloudThemes() refreshes the official manifest, updates cached
packages whose SHA-256 changed. It returns null for clean native success, a
String for native success with a warning, or MenuError for native failure. A
warning may accompany a usable cached manifest. The binding does not invent a
numeric reason for warning text whose underlying status C has already discarded.
Menu.cloudThemes returns a fresh List of read-only CloudThemeEntry live
views in the menu VM. They have no public constructor, setters or positional
indexing. Local Menu.themes rows keep their existing interface.
The native catalog is initialized from the cached manifest during startup,
without fetching the manifest or packages. Downloaded packages are therefore
available before opening Online Themes. Missing or invalid optional catalog
metadata does not prevent restoring the previously selected cached theme.
| Property | Meaning |
|---|---|
|
Native package identity and descriptive metadata. Optional fields are null when absent. |
|
The source URI from the manifest, or null when unavailable. |
|
The expected SHA-256 hexadecimal manifest text, preserving its spelling and case. It is not a freshly computed cached-file digest. Null when unavailable. |
|
Live native cache-state Bools; reading them does not inspect files or download. |
|
Native catalog diagnostic text, or null. It does not manufacture a numeric status for a diagnostic whose underlying native reason is unavailable. |
Text fields create Wren Strings only on access, validating UTF-8 and normalizing
to NFC. A conversion failure returns MenuError with the actual status in code
and nativeCode. This also applies to reading the diagnostic text in error.
A selected package absent from the manifest can have null sourceUri and
expectedSha256. Metadata views retain no borrowed strings or parsed-theme
pointers and grant no file or network authority.
Successful replacement of the native cloud catalog makes old views stale, including refreshes returning a warning. A failed refresh before replacement preserves them. Stale field reads abort; reacquire through Menu.cloudThemes. In-place cache, selection and deletion updates remain visible without replacing the view. Changes to the displayed theme alone do not invalidate catalog views. Captured Strings remain independent after updates or replacement. Property reads perform no downloads, cache checks or file reads.
Menu.previewCloudTheme(package) previews a validated cached package and
returns null/MenuError. Menu.cacheCloudTheme(package) downloads
and validates a package without selecting it. Menu.selectCloudTheme(package)
does the same as needed, writes [SyncTERM] ThemePackage, removes
ThemeFile, and commits the selection. Menu.copyCloudTheme(package)
returns an unsaved ThemeDocument populated from the cached package, or MenuError.
Caching and selecting return null/MenuError. These
catalog and document operations are menu-VM capabilities; the cache location
is never exposed as general filesystem authority.
Menu.deleteCloudTheme(package) removes a cached package so it appears in
Online Themes again, returning null/MenuError. Deleting the
selected package first commits and saves Classic Theme. If deleting the cache
file then fails, Classic remains selected and saved; MenuError describes that
completed step and preserves the deletion failure. Both deletion operations are unavailable in safe mode.
The shipped Themes browser combines Menu.themes with cached entries from
Menu.cloudThemes, using distinct identities for Classic, local files, and
packages when tracking its selection. Its Online Themes browser displays
only Menu.cloudThemes entries whose cached member is false. Downloading a
package therefore moves it from the online-only browser to the main Themes
browser. Both browsers publish the highlighted row’s description through
the main menu’s comment callback and reserve the comment row when sizing
their shadowed panes.
Menu.newThemeDocument() returns a new C-owned ThemeDocument containing a
minimal sparse overlay on the compiled default, or MenuError on native failure. Its filename is empty and
it is dirty until saved. Menu.openThemeDocument(filename) accepts the
nonempty basename of a file accepted by the current theme loader, returning
ThemeDocument/MenuError. Empty names and invalid arguments abort the Fiber.
Menu.copyCloudTheme likewise returns ThemeDocument/MenuError. These constructors
and all document methods are menu-VM capabilities; documents cannot be
created or passed into the connected or picker VMs.
ThemeDocument.metadata(field) and setMetadata(field, value) use field IDs
0 Name, 1 Author, 2 Description, and 3 Version. The optional fields return
null when absent; setting an optional field to an empty String removes it.
Name cannot be empty. Metadata/style/glyph mutation and import return
null/MenuError with the portable native reason, replacing error Strings in v2.
Existing type/range/enum validation aborts remain; native semantic failures are
recoverable values.
ThemeDocument.styles returns rows
[role, builtin, present, font, legacyAttr, foreground, background].
present is a bit mask for fields 0 Font, 1 LegacyAttr, 2 Foreground, and
3 Background. setStyle(role, field, mode, value) uses mode 0 to remove the
file value and restore the compiled default, mode 1 to write inherit, and
mode 2 to write the supplied numeric value. addStyle(role) creates a
custom role with inherited fields. removeStyle(role) removes only a custom
role.
ThemeDocument.glyphs returns rows
[name, builtin, present, cp437, ascii, codepoint]. Its present bits are
0 CP437, 1 ASCII, and 2 Codepoint. setGlyph(name, field, mode, value)
accepts modes 0 Default and 2 Explicit; mode 1 is not meaningful for glyphs.
addGlyph(name, ascii) creates a custom glyph with its required ASCII value;
the other representations can then be set explicitly. removeGlyph(name)
removes a custom glyph.
ThemeDocument.themeData returns a fresh Wren theme-data snapshot for the
draft. Theme.fromData(data) decodes such a snapshot without changing the
process-wide selected theme. dirty, canUndo, and canRedo report the
document state; undo() and redo() return whether they changed it.
importTheme(filename) replaces all style and glyph sections from an
installed theme as one history entry while retaining the document filename
and metadata. It preserves custom definitions and unknown content rather
than limiting the import to the built-in registry.
ThemeDocument.save(filename, force) persists only, returning null/MenuError
instead of the former [code, error] pair. A null filename saves to the current
basename. Native save failures use code == null and their distinct enum in
nativeCode; they are not portable IOErr values. The named ThemeSaveErr constants
preserve the native enum: ok=0, invalid=1, conflict=2, exists=3, readOnly=4 and io=5.
Success is null. Host safe-mode rejection uses IOErr.readOnly with nativeCode null,
rather than inventing a native call/result. A true force permits overwriting after
conflict or exists; it bypasses neither validation nor safe mode.
Save preserves untouched source text, writes through the destination without replacing its filesystem entry, and clears editing history after successful write and close. Symbolic/hard links retain their relationship; write/close failure can leave partial contents. Saving does not change the active theme or its generation.
ThemeDocument.activate() installs an independent native copy of the document’s
resolved in-memory theme and returns null/MenuError. It requires a clean, saved
document matching the manager’s committed local theme under the existing platform
filename identity rules. Unsaved, dirty, differently selected, Classic and cloud
selections return IOErr.invalidArgument. Allocation failure leaves the active theme,
preview and generation unchanged. Success clears temporary preview and advances
Host.themeGeneration once; selection, Settings generation, document history and
files are unchanged. Activation performs no filesystem I/O, including when the
backing file has been removed or edited externally, and is allowed in safe mode.
Later document edits or collection do not modify the installed copy. Native APIs
continue to own manager/document lifetime; no new script resource owner is created.
The editor confirms replacement only for conflict/exists, then saves with explicit force if accepted. After saving it activates only a matching selected local theme, using the native identity guard rather than Wren filename case assumptions. Failure to activate is reported as saved-but-not-activated; the document stays clean and persistence is treated as complete. There is no automatic resave or activation retry.
var failure = document.save(null, false)
if (failure != null) {
System.print(failure.message)
} else {
var activation = document.activate()
if (activation != null) System.print(activation.message)
}
The shipped menu_theme_editor module keeps the document rows as the editing
source of truth and builds a separate Theme.fromData(document.themeData)
snapshot for each draft refresh. Its cascade inspector distinguishes file
values, explicit inheritance, compiled defaults, compiled inheritance, and
absent roles for every field. The interactive widget preview reports the
theme role associated with its focused control and can return that role to
the exhaustive atlas. Glyph values are chosen as raw bytes from 16-column
CP437 and printable-ASCII grids rather than entered as decimal integers.
These operations remain menu-VM-only because they retain and modify a
ThemeDocument.
Menu List Encryption
Menu.encryptionInfo returns a fresh, read-only ListEncryptionInfo
snapshot of the personal list in memory, or null if no list model is loaded.
Plaintext is a snapshot with format == ListEncryptionFormat.plain,
algorithm == MenuEncryption.none, keyBits == 0, and kdf == ListEncryptionKdf.none.
It is distinct from an absent model. This getter performs no I/O or rewrite.
Snapshots have no public constructor or setters. They copy scalar metadata, retain no secrets or borrowed pointers, and remain usable and unchanged after reloads, encryption changes and failed operations. Invalid native metadata, including integers outside Wren’s exact Number range, aborts the calling Fiber. These classes and Menu operations are available only in the menu VM.
| Snapshot property | Result |
|---|---|
|
|
|
A |
|
Key length in bits, or zero for plaintext. |
|
|
|
|
|
Actual PBKDF2 iteration count; otherwise |
|
Actual scrypt cost exponent (N = 2^costLog2); otherwise |
|
Actual scrypt parameter r; otherwise |
|
Actual scrypt parameter p; otherwise |
|
Native recommendation Bool; reading it performs no rewrite. |
MenuEncryption defines none (0), tripleDes (1), idea (2), cast (3),
rc2 (4), rc4 (5), aes (6), and chacha20 (7). Legacy cipher values
identify loaded files; they do not enable legacy writes. The former
Menu.encryptionAlgorithm, Menu.encryptionKeySize, and Menu.encryptionName
getters are removed in v2. Use one snapshot for consistent reporting:
var info = Menu.encryptionInfo
if (info != null) System.print(info.name)
The shipped encryption dialog shows Change Password only when encryption is available and the loaded combination is writable: AES-128, AES-256, or ChaCha20. Unsupported loaded combinations (including AES-192) retain explicit conversion and decryption choices. SyncTERM reads the file metadata; users do not need to parse or enter headers.
Menu.setEncryption(algorithm, keySize, password) rewrites the current
personal list and returns null/MenuError. AES accepts 128- or 256-bit keys;
ChaCha20 accepts zero to select its fixed 256-bit key (explicit 256 is also
accepted), and unencrypted lists use key size zero. The current kdfShift
is used when encrypting, changing algorithms, or changing a password.
password may
be null to reuse the password already held by the host. Enabling
encryption fails if neither source supplies a non-empty password. A
successful rewrite updates the current algorithm, key size, and held
password; a failure leaves them unchanged. The operation is disabled
in safe mode, where it returns IOErr.readOnly without rewriting the list or changing
the algorithm, key size, or held password.
Menu Web Lists
Menu.webLists returns a fresh List of [name, uri] rows. Names must contain
1..50 Unicode scalars and at most 100 UTF-8 bytes, be canonically
caseless-unique, and have no controls, leading or trailing Unicode whitespace,
or =/:, and cannot begin with ; or [. System List is reserved.
Indexes refer to the order shown by that returned List. Menu.webListsDirty
reports whether the in-memory list has unpersisted edits.
| Method | Description |
|---|---|
|
Fetch the URI into the web-list cache and insert the in-memory entry.
Returns |
|
Change an in-memory entry’s URI. Returns null/MenuError. It does not refresh the cached list. |
|
Remove an in-memory entry. Returns null/MenuError. |
|
Persist the in-memory entries to the |
|
Fetch the current URI into the cache without changing configuration.
Returns |
In safe mode, add, update, and delete still update the running configuration,
and add still performs its initial fetch. saveWebLists() returns IOErr.readOnly
without writing syncterm.ini, so those changes last only for the current
process. Refresh remains permitted. No web-list method exposes its cache
pathname as a file capability.
Menu Custom Fonts
Each menu host owns a custom-font draft separate from the loaded console font
slots and from unrelated program settings. Menu.fonts returns a fresh List
of MenuFont handles. Menu.fontsDirty reports whether that draft has unsaved
edits.
| Method | Description |
|---|---|
|
Return whether another custom-font record can be added. This includes the available custom slots and safe mode. |
|
Insert a blank custom font at |
|
Merge only the draft’s |
|
Activate the installed custom-font configuration using the existing native loader. Returns null/MenuError. Failure preserves previous live mappings. Native missing/unsupported bitmap skip rules are unchanged. The bundled editor saves first, then activates, and reports activation failure without resaving. |
|
Discard unsaved font edits and reread only the |
|
Read/write the display and INI-section name using the same nonempty,
INI-safe and case-insensitively unique rules as |
|
Configured pathname String for display, or |
|
Assign a path from a live, read-authorized |
|
Clear one configured size and return null/MenuError. |
|
Remove the record from the in-memory model and return null/MenuError. Call
|
MenuFontSlot values and their picker masks are:
| Constant | Code | Bytes | Typical mask |
|---|---|---|---|
|
0 |
2048 |
|
|
1 |
3584 |
|
|
2 |
4096 |
|
|
3 |
10240 |
|
Create and delete advance the font-model generation, invalidating all
previously obtained MenuFont handles. Rename, file assignment,
clear, and save preserve handles. Font mutation, activation and persistence return IOErr.readOnly
in safe mode; reload remains available because it only reads
the existing configuration.
Menu BBS Constants
Profile properties use the following numeric constants in both menu and connected VMs. Prefer the catalogs returned by Menu when constructing a user-facing choice list.
ConnType
| Constant | Code | Description |
|---|---|---|
|
0 |
Unset / not yet decided. |
|
1 |
RLogin (TCP/513) — classic BBS auth-on-connect protocol. |
|
2 |
RLogin with the handshake byte order reversed (some servers). |
|
3 |
Telnet (TCP/23) — IAC negotiation in NVT mode. |
|
4 |
Raw TCP — no protocol layer; bytes pass straight through. |
|
5 |
SSH-2 — encrypted with password / key authentication. |
|
6 |
SSH-2 with the "none" authentication method (anonymous). |
|
7 |
Phone modem dial-out via AT commands. |
|
8 |
Direct serial port. |
|
9 |
Serial without RTS/CTS hardware flow control. |
|
10 |
Local subprocess (shell command). |
|
11 |
MajorBBS / Worldgroup "GHost" client interface. |
|
12 |
Telnet over TLS (TCP/992). |
|
13 |
Synchronet node terminal stream over MQTT 5/TLS. |
|
14 |
Binary Telnet over WebSocket (TCP/80). |
|
15 |
Binary Telnet over WebSocket with TLS (TCP/443). |
Emulation
| Constant | Code | Description |
|---|---|---|
|
0 |
ANSI-BBS — ANSI X3.64 / VT-style escape sequences with PC-style color attributes. The default. |
|
1 |
Commodore 64 / 128 PETSCII control codes. |
|
2 |
Atari 8-bit ATASCII control codes. |
|
3 |
UK Prestel / Viewdata teletext — block mosaic graphics, double-height, conceal. |
|
4 |
BBC Micro Mode 7 teletext. |
|
5 |
Atari ST GEM VT-52 emulation. |
BBSListType
| Constant | Code | Description |
|---|---|---|
|
0 |
User-edited entry from the user’s BBS list. |
|
1 |
Entry from a shared, system-web or named-web list. Read-only in its source directory. |
TLSVersion
| Constant | Code | Description |
|---|---|---|
|
0 |
No authenticated TLS version has been recorded. |
|
1 |
TLS 1.2. |
|
2 |
TLS 1.3. |
ScreenMode
Standard modes encode their dimensions in the name (e.g. c80x25 =
80 columns × 25 rows). Codes are stable enum values.
| Constant | Code | Description |
|---|---|---|
|
0 |
"Don’t change" — keep the current mode. |
|
1 |
80×25 (CGA / VGA standard). |
|
2 |
80×25 with LCD-style cell aspect (SyncTERM-specific). |
|
3 |
80×28 (extended VGA). |
|
4 |
80×30 (extended VGA). |
|
5 |
80×43 (EGA-extended). |
|
6 |
80×50 (VGA 8-pixel-tall cell). |
|
7 |
80×60 (extended VGA). |
|
8 |
132×37 (Super VGA). |
|
9 |
132×52 (Super VGA). |
|
10 |
132×25. |
|
11 |
132×28. |
|
12 |
132×30. |
|
13 |
132×34. |
|
14 |
132×43. |
|
15 |
132×50. |
|
16 |
132×60. |
|
17 |
Commodore 64 (40×25 PETSCII). |
|
18 |
Commodore 128 (40-column mode). |
|
19 |
Commodore 128 (80-column mode). |
|
20 |
Atari 8-bit native (40×24 ATASCII). |
|
21 |
Atari 8-bit with XEP80 80-column expansion box. |
|
22 |
Custom dimensions configured per-BBS. |
|
32 |
CGA 80x25, 640x200 with an 8x8 cell and 4:3 display aspect. |
|
23 |
EGA 80×25 with hardware-accurate pixel aspect (8×14 cell). |
|
24 |
VGA 80×25 with hardware-accurate pixel aspect (8×16 cell). |
|
25 |
Prestel teletext (40×24). |
|
26 |
BBC Micro Mode 7 (40×25 teletext). |
|
27 |
Atari ST 40×25 (low-res color). |
|
28 |
Atari ST 80×25 (medium-res color). |
|
29 |
Atari ST 80×25 monochrome (high-res). |
|
30 |
Amiga 640×200 pixel canvas, displayed at 4:3. |
|
31 |
Amiga 640×400 pixel canvas, displayed at 4:3. |
AddressFamily
| Constant | Code | Description |
|---|---|---|
|
0 |
As per DNS (default): connect only to the system resolver’s preferred address, IPv4 or IPv6. |
|
1 |
Connect only to the preferred IPv4 address. |
|
2 |
Connect only to the preferred IPv6 address. |
|
3 |
Race IPv4 and IPv6 addresses with attempts staggered by 250 ms. Use the first successful connection and close the others. Extra connections can allocate BBS nodes or activate serial bridges; this mode is opt-in. |
MusicMode
Controls how SyncTERM interprets ANSI music sequences (CSI … character).
| Constant | Code | Description |
|---|---|---|
|
0 |
SyncTERM’s strict mode — only the CSI MNML sequence triggers music; less-anchored sequences are passed through as text. The default. |
|
1 |
BANSI-style — older BBS music parsing rules. |
|
2 |
Most permissive — all forms accepted. |
GraphicsMode
| Constant | Code | Description |
|---|---|---|
|
0 |
Remote graphics disabled for this connection. |
|
1 |
RIPscrip v1.54 compatibility mode. |
|
2 |
SyncTERM’s "idealized" RIP v3 — bug-fixed and extended; not bug-compatible with v1.54. |
|
3 |
Practical SkyPix dialect, with Kickstart 1.3 rendering. |
|
4 |
Practical SkyPix dialect, with Kickstart 3.1 rendering. |
|
5 |
IGS 2.21 Atari ST graphics; see coverage. |
|
6 |
BIG 1.03 terminal graphics; see current coverage. |
|
7 |
DDO F/X 2.0. See current coverage. |
Selecting IGS presets Atari ST 40x25 (320x200), Atari ST encoding and font.
The ST 80x25 colour and monochrome modes are also available. UTF-8 can be
selected while retaining ST glyphs. IGS and RIP enter the same pre-ANSI
receive stage; ordinary bytes continue to the selected base emulation.
Profile.graphics stores the entry’s initial engine. CTerm.graphicsMode
reports the engine active on the connection, including changes negotiated
with the graphics APCs in the terminal protocol reference.
Selecting BIG presets ScreenMode.ega80x25 (640x350), CP437 and the original
IBM console font. ScreenMode.cga80x25 (640x200) and ScreenMode.c80x30
(640x480) are also supported initial profiles; UTF-8 retains the CP437 glyph
mapping. An unsupported or Current profile starts in EGA without rewriting
the saved profile. BIG mode installation selects the exact 8x8, 8x14 or 8x16
ROM bank. A different console font/codepage or unsupported screen choice in
the editor switches back to ordinary emulation. BIG shares the same pre-ANSI
receive insertion as IGS/RIP. All45 BIG command entries have native integration;
the coverage ledger records verification and the native protocol adaptations.
Both SkyPix variants use
the practical protocol recorded in SkyPix conformance,
Pearl 8 by default, measured native-glyph wrapping and 50 Hz delays including
short delays. Command 17 selects eight/sixteen colours; brush palettes apply
on first blit and promote depth when required. Kickstart differences concern
ellipse arithmetic and per-character proportional-glyph overhang. Selecting SkyPix initially presets
ScreenMode.amiga640x200 (4:3) and Latin-1. ScreenMode.amiga640x400 is also
available at 4:3, with an 80×50 system grid of 8×8 cells. Native Amiga font
strikes retain their pixel dimensions in either mode; the 400-line canvas
provides more vertical space. Screen Mode selects the pixel canvas,
Encoding selects the wire encoding, and Font selects an installed or bundled
Amiga family/height for initial text and reset. These choices remain editable.
The system cell grid comes from the screen mode, independently of the native
Amiga text metrics; graphics clip to the drawable area. The optional status row
uses the last system-cell row inside the selected mode; resolution and aspect
ratio remain unchanged. Ordinary Profile.font remains available
for other graphics modes. Classic Amiga fonts are byte-indexed and carry no
charset tag; codepage connections use that codepage’s glyph positions, and
UTF-8 text uses Latin-1 glyph mapping. C1 positions may contain glyphs even when
a selected terminal decoding mode interprets those bytes as controls.
CTerm.skypix reports the selected graphics engine, rather than inferring it
from a remote command. RIP sessions do not interpret SkyPix commands.
SkyPix command-16 transfers accept IFF brushes (type 1), IFF sound (type 2),
FutureSound samples (type 3), and general files (type 20). All use CRC XMODEM
and the active BBS’s shared SkyPix cache subdirectory, matching SkyTERM’s
single BRU: destination. Completed files are reused; partial or invalid
brush downloads are discarded. Types 2, 3 and 20 preserve cached bytes, including
XMODEM padding, without replacing the current brush. Type 3 also loads the
sample after receipt or on a cache hit; an unsuccessful load leaves the file
cached and retains the previous sound. Type 2 has no IFF sound decoder.
They do not use RIP asset framing. Gadget command
22 retains the definition in slot 1–20 and draws its foreground rectangle;
clicks still report raw controller-1 pixel coordinates. Controller-2 menu reports
and local execution of stored gadget commands remain unsupported. See
SkyPix conformance for the precise supported subset.
Type-3 samples contain a big-endian unsigned 32-bit PCM-byte count and unsigned 16-bit rate, followed by signed 8-bit mono PCM. The declared payload must be present, positive, and no larger than 4 MiB; the rate must be nonzero. Odd lengths are accepted and trailing bytes are ignored. Command 9 uses only its loop count and plays the entire sample. Zero deliberately means one play; the originals instead wait indefinitely for continuous playback.
SkyPix uses the shared effects stream (logical channel 1), independently of
channel-0 music, with its existing gain/pan. A custom incremental linear
converter uses the originals' 16-bit period (3579545 / rate) & 65535 and
converts its effective rate to 44100-Hz stereo. It does not emulate analog
filters or artificial gaps at Amiga device-write boundaries. Remote parsing
waits for playback and backend latency while local UI continues. Synchronous
connected/menu/picker input waits service pending audio without consuming remote
input or extending the requested input deadline. Reset/EOF
cancel playback; reset/destruction release the loaded sample. Disabled or
unavailable audio skips playback and the wait. There is no new script audio API.
Parity
| Constant | Code | Description |
|---|---|---|
|
0 |
No parity bit (8N1 framing). |
|
1 |
Even parity bit. |
|
2 |
Odd parity bit. |
FlowControl
Constants for the numeric Profile.flowControl setting.
| Constant | Code | Description |
|---|---|---|
|
0 |
RTS/CTS hardware flow control. |
|
1 |
XON/XOFF software flow control. |
|
2 |
Hardware and software flow control. |
|
3 |
No flow control. |
LogLevel
Standard syslog severity values (RFC 5424). emergency is the most
severe; debug is the least.
| Constant | Code | Description |
|---|---|---|
|
0 |
System is unusable. |
|
1 |
Action must be taken immediately. |
|
2 |
Critical condition. |
|
3 |
Error condition. |
|
4 |
Warning condition. |
|
5 |
Normal but significant. |
|
6 |
Informational. |
|
7 |
Debug-level diagnostic. |
Host
Module-private bridge for state the host owns but Wren shouldn’t
be able to construct directly. The members below are foreigns;
the Cache / Download module-level vars (see below) are
pre-bound from these at module load.
| Member | Description |
|---|---|
|
Monotonic process-wide generation for the active theme. Preview, cancellation, and committed selection changes advance it. |
|
Return fresh immutable-by-ownership snapshots of the active theme and
compiled fallback respectively. Each result is |
|
Returns a fresh |
|
Returns a fresh |
|
The BBS’s configured |
|
User-consent escape hatch for "upload from anywhere": invokes the
isolated picker VM and returns a |
|
The same consent picker with a caller-supplied title String. The title changes only the picker presentation and grants no additional file authority. |
|
Multi-select counterpart of |
|
Save-mode picker with path entry and overwrite confirmation. The user
can pick an existing file or type a new filename. The picker reports
create, overwrite, or append consent explicitly, and the caller does not
stat the path again. The two-argument form offers overwrite for existing
files. Pass |
|
Re-construct a |
|
Status-bar transfer-indicator arrows (CP437 ↑ / ↓, painted by the
default Status render at the row’s right edge).
Generic — any Wren script that knows it’s transferring something
can light them; the canonical user is the SFTP queue’s worker
fibers, but a Zmodem / HTTP fetcher / etc. could too. Pure
Wren-side state on the |
|
|
|
|
|
|
|
Display name of the modifier key that produces Alt keycodes on
this platform. |
|
Write |
|
Full path of the Wren script supplied via the |
|
Wren-console activity since the user last visited the REPL.
|
|
ANSI music mode display strings and help blurb, returned as a
fresh |
|
Throttled-output ladder. |
|
Transfer log threshold ( |
|
|
|
Highest valid OOII mode value ( |
|
Suspend terminal byte consumption and enter the persistent trusted menu VM over a saved copy of the connected screen. The connected VM is parked, no Wren or foreign object crosses between VMs, and trusted input barriers discard queued synthetic keyboard and mouse input in both directions. On return, the host restores the terminal screen, title, scrollback configuration, and prior suspension state. This is the default Alt+E path. |
|
The first locally-configured SSH public key, as a Map
|
FilePickerOptions
Public option bits for Host.pickFile and Host.pickFiles. The
numeric assignments are stable so scripts may combine or persist them.
| Member | Value | Meaning |
|---|---|---|
|
0 |
No optional behavior. |
|
1 |
Display the mask but do not let the user edit or replace it. |
|
2 |
Match file and directory masks case-sensitively. |
|
4 |
Sort entry names case-sensitively. |
|
8 |
Select a directory rather than a file. |
|
16 |
Reject a typed path which does not exist. |
|
32 |
Reject a typed filename which does not exist. |
|
64 |
Include hidden entries in directory listings. |
|
256 |
Allow the always-visible Path field to receive focus and accept a
typed directory or filename. Single-file pickers which permit a new
path (neither |
|
512 |
Ask before accepting an existing destination. |
|
1024 |
Ask before accepting a destination which does not exist. |
|
2048 |
Save picker only. When an existing destination is selected, offer Append alongside Overwrite and Cancel. |
allowEntry, confirmOverwrite, confirmCreate, and allowAppend are
invalid with Host.pickFiles. Host.pickSavePath(initialDir, mask)
supplies its save-mode options itself. Its three-argument overload
accepts save-picker option bits; currently only allowAppend is
meaningful there.
Cache
Module-level Directory injected from C (pre-bound from
Host.cacheDirectory), pointing at SyncTERM’s per-user cache
directory (SYNCTERM_PATH_CACHE). Use this for script-private
state that should survive restarts.
The visible syncterm-cache-name.txt file in each BBS cache records its entry
name. It is reserved for SyncTERM and excluded from script cache grants and
APC/RIP cache operations. Hash collisions use numbered directory suffixes; scripts
receive the directory matching the stored name automatically.
Cache.list returns a Map keyed by entry name; values are File
objects for regular files and Directory objects for subdirectories.
That’s the read-side handle factory — a script reads existing cache
content by indexing into Cache.list, and creates new content with
Cache.create(name):
import "syncterm" for Cache, FileError
var entries = Cache.list
if (entries is FileError) Fiber.abort(entries)
var f = entries["greetings.txt"]
var firstRun = f == null
if (firstRun) f = Cache.create("greetings.txt")
if (f is FileError) Fiber.abort(f)
var opened = f.open()
if (opened is FileError) Fiber.abort(opened)
var result = firstRun ? f.write("Hello, world!") : f.read()
var closed = f.close()
if (result is FileError) Fiber.abort(result)
if (closed is FileError) Fiber.abort(closed)
if (!firstRun) System.print(result)
// Subdirectories appear in the same map. Walk into them by chaining
// `.list` lookups:
// Cache.list["RIP"] → Directory for /RIP
// Cache.list["RIP"].list["icons.dat"] → File inside /RIP
There is no Wren-callable factory for Directory — Cache,
Download, and Cache.list[someSubdir] (and the analogous
Download.list[…]) are the only paths to one.
Download is a module-level Directory binding pre-bound from
Host.downloadDir at import time. It is null when the
configured DownloadPath is empty, set to the user’s $HOME,
or doesn’t exist as a directory on disk; scripts MUST null-check
before use. Its relaxed-name predicate is what makes typical
SFTP filenames ("file with spaces.zip", "doc-v1.0.tar.gz")
usable as local paths in transfer queues.
There is intentionally no Upload counterpart. All uploads must
go through Host.pickFile / Host.pickFiles, which mint a
per-file consent token tied to the file’s content hash. The
script then enqueues uploads by token (File.token); the worker
re-opens the source via Host.openLocalFile(token). Use
Host.uploadPath to feed the configured UploadPath to the
picker as initialDir.
Filesystem results
Local and remote filesystem APIs use these result conventions. Remote methods return an Operation; the table describes its completed value.
| Operation | Result |
|---|---|
Create/open a resource |
The requested resource object or an Error. Local |
Mutation or close |
|
|
A nonempty byte String, including a successful short read; |
Zero-byte read |
|
Zero-byte |
|
|
Complete file bytes from offset zero, including |
|
|
|
A line String (including |
|
Bool for presence/absence; |
Every filesystem error inherits from Error. Check result is Error when
either domain is possible, or the concrete class when inspecting its native
details. Invalid arguments, invalid names, missing rights and operations on
closed/closing streams abort the calling fiber before native I/O. Repeated
close is allowed. Property setters return the assigned Number on success or
FileError on a recoverable failure; their result can be captured explicitly.
Byte data is never UTF-8-validated or normalized. Local/remote path names and picker strings use the normal host text boundary: valid UTF-8 normalized to NFC, without NUL. This does not change Wren’s String semantics.
Directory
Opaque handle containing a directory pathname grant. The grant applies to the pathname, not to a particular filesystem object that occupied it when the handle was created.
| Method | Description |
|---|---|
|
|
|
A Map keyed by entry name; values are |
|
Atomically create a new zero-byte file named |
|
Atomically create a new subdirectory named |
|
Remove the entry named |
|
Atomically replace a regular file with the complete byte String. The
host writes and closes an exclusive sibling temporary file before the
rename, so any write or close failure leaves the prior file unchanged.
Returns |
Pathname grants
File and Directory foreign objects retain an absolute pathname and the
operations granted for that pathname. They are not filesystem snapshots and
do not preserve the identity of a particular file or directory. A closed
handle therefore addresses the current entry at its pathname. Removing,
replacing, or recreating that entry does not revoke the grant, whether the
change came through Directory.delete or from outside SyncTERM.
Operations validate the state they require. An unavailable pathname returns
FileError with the native reason (IOErr.notFound, notDirectory,
permissionDenied, etc.); it does not revoke the grant. A recreated directory
or file can be used through the same grant. File.path, File.token, and
Directory.toString report stored metadata without filesystem access.
File.close() is also independent of pathname availability.
Open files are exempt
A File whose stream is currently open (between File.open() and
File.close()) performs stream operations on that opened stream and bypasses
the closed-path existence check. This matches platform reality:
-
On Unix, an open file descriptor remains valid after the path is unlinked; reads and writes continue to work, and the inode is freed only when the last reference closes.
-
On Windows, deleting a file that’s currently open fails at the OS layer, so the situation never arises.
After File.close(), a later open resolves the pathname again and may open a
replacement file. Properties implemented as pathname operations, including
mtime and digest(algorithm), continue to resolve the pathname even while a
stream is open. Stored metadata properties do not access the filesystem.
Filename Policies
Directories below Cache use the strict portable cache-name policy:
-
Length 1..64 bytes.
-
Characters from
[A-Za-z0-9._-]only. -
Must not begin with
.or-. -
Must not end with
.. -
Must not contain
... -
Must not match a Windows reserved device name (
CON,PRN,AUX,NUL,COM1..COM9,LPT1..LPT9), case-insensitively and with or without an extension.
Directories below Download use the relaxed safe-leaf policy. Names are
1..255 bytes, must not be . or .., and may not contain a path separator,
NUL, an ASCII control byte, DEL, or a Windows reserved device basename.
Spaces, leading dots or dashes, trailing dots, parentheses, and non-ASCII
bytes are otherwise accepted. Descendant directories inherit their root’s
policy. Invalid names abort every directory method before filesystem access.
Names are validated as UTF-8 and normalized to NFC before the name policy
checks and filesystem access.
File
Every File carries rights assigned by the host when it is created:
-
Files reached through
CacheorDownloadare read/write. -
Files returned by
Host.pickFile/Host.pickFiles, or reconstructed byHost.openLocalFile, are read-only.open()usesrb; write methods andmtime=()abort the fiber. Read-consuming bindings such asScreen.loadFont()accept these Files. -
Files returned by
Host.pickSavePathare one-shot write-only grants. Read methods, hashes, and read-consuming bindings reject them. See Write consent.
Permissions apply to the stored pathname, not to a particular file object at
that pathname. The foreign handle retains those permissions so a script
cannot substitute a different pathname. Passing a File to another binding
does not broaden its authority.
| Method | Description |
|---|---|
|
Open the file using the mode authorized by its host-assigned rights.
Sandbox Files use |
|
Close the stream; returns |
|
Read up to |
|
Same results at an absolute offset; restore the current offset even after a successful short read or EOF. Zero count performs no seek. |
|
Read file bytes from offset 0, returning |
|
Write the byte String at the current or given offset. Returns |
|
Replace file contents with |
|
Resize an open writable file to an exact nonnegative integer byte length;
see Native integer limits. Shrinking discards the tail; extending fills
the added bytes with zero. Preserve the current offset, even beyond the new
EOF. Synchronizes buffered input/output first, so later reads cannot return
discarded bytes and buffered writes cannot regrow the truncated tail.
Zero and unchanged lengths still perform the native operation.
Returns |
|
Read from the current offset to the first LF (0x0A) or EOF and
return the bytes read with LF and its optional preceding CR removed.
An unterminated trailing CR is preserved. Advances the
offset past the LF on a hit, or to EOF if none was found. Returns
|
|
Write |
|
Current read/write position. Nonnegative exact integer; see Native integer limits. |
|
Length in bytes, subject to Native integer limits. Flushes this stream’s buffered writes before querying native metadata; flush failure is a FileError. |
|
Signed POSIX seconds within Native integer limits. The setter uses
the native filesystem API by path, requires write rights, and works on open and closed
handles. Pending output is flushed first. A filesystem which ignores or
rounds a timestamp returns |
|
|
|
Opaque consent token for picker-sourced |
|
Hash the complete file using a |
A closed File whose pathname is unavailable returns a
FileError with the native reason, such as IOErr.notFound from the
existence check, whether the entry was deleted through Directory.delete or
outside SyncTERM. The pathname grant remains valid. If a regular file is
later created at the same pathname, the original File can open it.
Write consent
Files minted by Host.pickSavePath carry a
write-only consent — a single-shot grant to open the user-picked path
exactly once, in a specific mode determined at pick time:
| Picker outcome | open() mode |
|---|---|
Path didn’t exist at pick time |
|
Path existed and the user confirmed overwrite |
|
Path existed and the user selected append |
|
The consent is consumed by the first successful open(). After
the matching close(), every subsequent open() / writeBytes /
write / writeLine / etc. aborts the fiber with "write consent
already used". Re-pick the path to write again.
The grant never includes read authority. read, readBytes,
readLine, digest(algorithm), and bindings which consume a readable File
reject a save-picker File, both before and while it is open.
File.token is null on write-consent Files: persisting a write
consent across sessions would defeat the single-shot rule. The
existing token mechanism is exclusively for read consent (the
Host.pickFiles / openLocalFile upload-resume flow).
Other bindings consume write consent on the caller’s behalf:
-
Host.pickSavePathmints the consent. -
Capture.start(file, raw)— opens for streaming-log output and transfers the FILE pointer into `cterm’s logfile. -
CTerm.saveScreenshot(file, withSauce)— writes the screen as IBM-CGA / BinaryText with optional SAUCE block.
After any of these calls the File is inert — calling open() on it
yourself is no longer valid.
FileError
FileError represents a recoverable local filesystem failure, following
Filesystem results. Its portable code describes the native reason rather
than the operation which happened to fail. Existing targets, missing paths,
permissions, full storage and native range failures remain distinguishable.
The fixed-purpose Emoji.recordUse operation also returns FileError for failure to
persist recents; its session update has already occurred and its errno is zero.
| Member | Description |
|---|---|
|
Stable negative native |
|
Captured C errno when available; zero for native APIs without errno
or a synthesized failure. Interpret |
|
Operation-specific diagnostic text, or |
|
Numeric code and diagnostic, plus errno when present. |
IOErr exposes all shared native I/O reasons in every script VM. In v2 it
replaces FileErr without an alias; FileError remains the filesystem error type:
| Constant | Code |
|---|---|
|
-1 |
|
-2 |
|
-3 |
|
-4 |
|
-5 |
|
-6 |
|
-7 |
|
-8 |
|
-9 |
|
-10 |
|
-11 |
|
-12 |
|
-13 |
|
-14 |
|
-15 |
|
-16 |
|
-17 |
|
-18 |
|
-19 |
|
-20 |
|
-21 |
|
-22 |
|
-23 |
|
-24 |
|
-25 |
|
-26 |
|
-27 |
|
-28 |
|
-29 |
|
-30 |
|
-31 |
|
-32 |
|
-33 |
|
-34 |
|
-35 |
|
-36 |
|
-37 |
|
-38 |
Success is null, never a zero-code error. EOF is a read result, never a
FileError. Programmer errors (wrong types, invalid names/counts/offsets,
missing rights, unopened streams, opening an already-open stream) abort;
check the input contract rather than treating them as recoverable I/O.
The binding manages C update-stream direction changes and buffered writes. Scripts may mix reads/writes without inserting C-specific seeks or flushes. The current offset remains a logical stream position; metadata queries that need pending output flush it and report any failure normally.
Picker consent tokens
Wren scripts must not synthesize File foreigns from arbitrary
paths — that’s the whole point of the Cache / Download
sandboxed roots and the relaxed-name predicate. The escape
hatch is Host.pickFile / Host.pickFiles, where the isolated
picker interaction is the user’s signal of consent.
To let queued picker-sourced uploads survive a disconnect, the
picker mints a capability token at consent time: an
HMAC-SHA256 binding of the absolute path and the file’s SHA-256,
signed by a per-installation key stored in the user’s encrypted
syncterm.lst. Wren can store the token freely (it’s opaque
bytes — exposed via File.token and accepted by
Host.openLocalFile); only the C side can mint or verify one.
The file-content hash routes through DeuceSSH’s
hardware-accelerated digest backend (Intel SHA-NI / ARM crypto
extensions, via OpenSSL or Botan) when the build has it, so
signing/verifying a multi-GB picked file stays in the
sub-second range on commodity hardware. WITHOUT_DEUCESSH
builds fall back to xpdev’s pure-C SHA-256 (src/hash/sha256.c)
— correct, just slower on huge files; signing key generation
in that build seeds from /dev/urandom (or time/PID) via
xp_random rather than the SSH backend’s CSPRNG.
At resume time, Host.openLocalFile(token) verifies:
-
The HMAC matches (token wasn’t tampered with; signing key hasn’t rotated).
-
The file at the encoded path still exists.
-
The file’s current SHA-256 still matches the SHA-256 captured at consent time.
Any failure returns null; the queued upload should be marked
failed and the user prompted to re-pick. The content hash
binding is deliberate: if the file’s content has changed since
consent, the original consent doesn’t authorize uploading the
new content.
The signing key is loaded only from the user’s personal BBS list
(USER_BBSLIST) — never from shared/system or web-fetched
lists. This stops a malicious shared list from injecting a
known key and forging tokens against the local install. Key
rotation is manual: remove the WrenPickerHmacKey line from
syncterm.lst; SyncTERM regenerates on next launch. All
in-flight picker tokens become invalid.
Host.pickFile / Host.pickFiles continue to work even when
the signing key is unavailable (e.g. an unencrypted list, OOM
during generation) — the returned File`s have `null .token,
so picker uploads in such sessions don’t persist across
reconnects but otherwise behave normally.
Hook
The dispatcher registry. See Hook Events for the contract on each method, and HookHandle for the return type.
Hook.onKey(fn), Hook.onPhysicalKey(fn), Hook.onInput(fn),
Hook.onMouse(fn), Hook.every(ms, fn),
plus the filtered variants Hook.onKey(key, modifiers, fn), Hook.onInput(byte,
fn), Hook.onPhysicalKey(evdev, fn), Hook.onMouse(event, fn), and
Hook.onMatch(pattern, fn).
Each call returns a HookHandle.
Status
Wren-driven status bar. The host invokes a single render callable
on every status-bar update with a width×1 Surface that has been
pre-filled to the default attribute (yellow on blue, spaces). The
callable mutates cells in place and returns; its return value is
ignored.
In RIPv3, the supplied cells use the active RIP text-window font after a text-window font change. Other emulations retain the local status font.
import "syncterm" for Status, Surface, Screen, Session, CTerm
Status.callable = Fn.new { |surf|
if (!Status.enabled) return
var s = "%(Session.current.name) | %(Session.current.profile.connTypeName) | %(Session.current.profile.bpsRate) bps"
var x = 1
for (ch in s) {
var columns = Screen.textWidth(ch, surf[0].font)
if (columns == 0) continue
if (x + columns > surf.width) break
surf[x].ch = ch
x = x + columns
}
}
In a connected terminal, a left click on an OSC 8 hyperlink activates its actual destination. Ctrl+click also detects plain-text URLs and remains a local action when the BBS has enabled mouse reporting; ordinary clicks then continue to the BBS. A locally activated gesture is consumed through release or drag end so it cannot open twice or send an unmatched mouse release. Opening uses the desktop URL handler for HTTP, HTTPS, FTP, and FTPS. Other schemes, unavailable handlers, and safe mode copy the URI to the clipboard and show a notice unless popups are hidden. These actions are attached to user input and do not grant connected scripts a URL-launch API.
The default implementation lives at
scripts/auto/connected/status_default.wren. It uses the layout
name (flags) │ ConnType │ speed │ HH:MM:SS │ ALT-Z menu with
right-pinned indicators for mouse mode (M) and SFTP transfers
(arrows). To override it, place a same-named file in the auto-load
directory, or set Status.callable = … from any later script. The
host releases the previous handle when the callable changes.
| Member | Description |
|---|---|
|
The currently installed render |
|
Install (or clear) the render callable. |
|
Optional no-argument callable returning a complete human-readable status
String. SyncTERM snapshots it when the disconnect notice appears and
shows it in the F1 details popup, so fields omitted by narrow visual
layouts remain available. Set it to |
|
The OSC 8 hyperlink destination under the last unclaimed mouse position,
or |
|
|
The recycled Surface is reallocated only when the terminal width
changes, so per-frame allocation churn stays out of the hot path.
Out-of-bounds writes (surf[i] for i >= surf.width) throw —
treat surf.width as authoritative and clip your own loops.
Transfer
Session-owned bridge between the Wren transfer UI and C protocol workers.
upload(), uploadBatch() and download() return null after starting a worker,
or TransferError if startup fails. The terminal owner continues pumping protocol input while
TransferApp renders progress and handles cancellation on a child fiber.
Workers never call Wren or CTerm. Only one in-band transfer can own a
session’s stream at a time; SFTP uses its separate SSH channel.
import "syncterm" for Transfer
import "transfer_app" for TransferApp
Fiber.new {
var error = Transfer.beginSession("fake")
if (error != null) Fiber.abort(error)
TransferApp.new("Transfer demo").run()
var result = Transfer.result
Transfer.endSession()
if (result != null) System.print(result)
}.call()
The built-in upload/download flows are available through Alt-U, Alt-D and the
online menu. ZMODEM auto-start watches the incoming bytes for Ctrl-X followed by
B00 (download) or B01 (upload). Each byte reaches normal terminal processing
as it arrives. The transfer engine checks the complete header CRC. Downloads use the configured download directory;
unsafe roots and existing non-file destinations are rejected. If the configured
directory is unavailable, the connected UI shows a notice with the Download Path
setting to change. The detector checks the directory on each request and groups
retries less than 30 seconds apart into one notice. Existing files
can be overwritten, skipped, or renamed. ZMODEM resumes a partial file only
after checking its prefix CRC against the sender.
For a DDO F/X entry, a completed ZMODEM download batch installs recognized
$LI$ command packages in that BBS’s DDOFX cache before the session resumes.
Installation errors go to the transfer log. Ordinary downloads retain their
chosen destination.
RIP block-transfer commands use that BBS’s RIP cache subdirectory instead of
the download directory. RIP 1.54 display-only and active dynamic modes render validated
blocks as they arrive, using status-row progress so a modal restore cannot erase the
scene. RIPv3 displays successfully received scenes and images after the transfer
returns, using the active RIP3 style and parser. A failed RIPv3 receive
removes the incomplete destination. Earlier completed files in the batch
retain their own completion results. Host-requested uploads always
require confirmation and read regular files in the BBS cache. RIP 1.54 accepts
one filename per upload. RIPv3 batch uploads can name several files. RIP
transfers use the same cancellation, completion and log APIs as manual transfers.
| Member | Description |
|---|---|
|
Start the synthetic 100-KiB |
|
Latch an abort if the worker hasn’t already finished, join the
thread, and clear session state. Idempotent — safe to call after
a natural completion. Returns |
|
Drain the log ring under mutex; return a |
|
Read the "tick state changed" flag under the mailbox mutex. |
|
Return |
|
|
|
Read-only completion result: |
|
Latch an abort flag the worker polls between protocol steps.
Returns |
|
Read the abort flag without modifying it. |
|
Whether a session owns a transfer and its direction. |
|
Start one file using |
|
Start a List of readable |
|
Start |
|
Pending worker decision: 0 for none, 1 for an existing file, 2 for an XMODEM filename when a YMODEM receive falls back to XMODEM. |
|
Answer a pending decision with 0 (overwrite/accept filename), 1 (skip), or 2 (rename). The worker waits on a condition variable while the owner continues pumping. Abort and disconnect also wake that wait. |
All startup methods return null or TransferError; they do not wait for
completion. Wrong argument types, malformed UTF-8, embedded NUL in protocol tokens
or required download filenames, unsupported protocol/direction, invalid handshake
bytes and invalid upload grants abort as programmer misuse. Host text normalizes
to NFC; raw file bytes do not. Native filename validation remains authoritative.
Runtime restrictions and download roots are unchanged: real transfers require a
permitted connected session, and safe mode blocks them. The internal RIP-upload
acceptance method also returns null/TransferError; no pending request is misuse.
The bundled progress App derives its success convenience property from the
completion result, retains its local aborted property and displays the actual
failure message or cancellation. Inline flows capture the result before cleanup.
Startup failures display once and do not enter the progress UI. Existing cleanup
and partial-file behavior remain; an error is not a guarantee of rollback or a
safe offset from which to retry automatically. The detailed transfer log remains
separate from the result.
TransferError
An immutable Error value, available with Transfer in each VM. It owns its
diagnostic and retains no worker or session pointer. There is no public constructor.
| Member | Description |
|---|---|
|
The exact native portable I/O integer; compare with |
|
Nonempty human-readable startup or completion diagnostic. Detailed per-file/protocol diagnostics remain in the transfer log. |
|
Includes |
Platform
OS identification and preferred UI languages. No shell execution, stdio, or process model is exposed.
| Method | Description |
|---|---|
|
OS identifier as a String. Returns |
|
Fresh, nonempty List of unique language-tag Strings in preference order,
such as |
Digest
Stateless synchronous hashing, available in menu, picker and connected VMs.
Digest.hash consumes bytes already in a Wren String; File.digest separately
uses a native file mapping and requires a readable File grant. Byte hashing
provides no filesystem authority.
| Algorithm constant | Native value / output bytes |
|---|---|
|
1 / 32 |
|
2 / 48 |
|
3 / 64 |
|
4 / 16 |
|
5 / 20 |
Digest.size(algorithm) returns the output byte length even when the selected
provider cannot compute that algorithm. It is not an availability query.
Digest.hash(algorithm, bytes) returns the raw digest bytes as a String or a
DigestError. Every input byte participates, including NUL and malformed UTF-8;
no text validation or normalization occurs. Canonically equivalent Unicode
spellings can therefore have different hashes. Compare raw results directly,
and use .bytes.count for their lengths.
import "syncterm" for Digest, Error
var hash = Digest.hash(Digest.sha256, "abc")
if (hash is Error) Fiber.abort(hash)
System.print(hash.bytes.count) // 32
Wrong input types, fractional/nonfinite numbers and unknown algorithm constants
abort the fiber before hashing or file effects. Byte-String input must also fit
the Wren C byte API’s signed-int length range; this limit does not constrain
native mapped-file input. Known algorithms whose native
operation fails return DigestError; no availability preflight or automatic
retry is performed. Builds with provider none support MD5 and SHA-256. SHA-1,
SHA-384 and SHA-512 return the native disabled status in those builds. External
providers can also fail according to their native policy; those failures are
not relabelled as disabled.
DigestError
Host-created, immutable Error subclass with read-only code, message, and
toString. code is the exact nonzero native digest status, including an
unrecognized future status. message identifies Digest.hash or File.digest
and describes the native reason; toString also includes the code. Success
returns bytes, never a zero-code error. DigestErr.failed (-1) names the generic
native failure; DigestErr.disabled (-5) names disabled digest support.
File.digest retains FileError for pathname, flush and mapping failures, and
returns DigestError for failures from the native hashing operation. Check the
common Error base if either is relevant. A pending-write flush can succeed
before hashing fails; no partial digest is returned. Input is borrowed only for
the synchronous native call, mappings are released before return, and returned
Strings and errors remain valid through later calls and garbage collection.
Text
Locale-independent Unicode 18 comparison helpers. All inputs are normalized to NFC at the Wren host boundary. Caseless matching uses full default Unicode case folding with canonical equivalence; ordering uses the non-ignorable DUCET collation table and an identical tie-break for deterministic results.
| Method | Description |
|---|---|
|
Return a List of NFC extended grapheme cluster Strings using the shared Unicode text engine. Used by UI drawing so joined emoji resolve as one glyph. |
|
Return the UTF-8 byte count after NFC normalization. Use this when checking input against byte limits on C-backed text fields. |
|
Return the NFD full-default-casefold key used by caseless equality. This is useful for retained search prefilters; use the matching methods below to verify a candidate when grapheme-cluster boundaries matter. |
|
Canonical caseless equality. |
|
Caseless prefix matching at extended grapheme-cluster boundaries. |
|
Caseless substring matching at extended grapheme-cluster boundaries. |
|
Return a negative number, zero, or a positive number using Unicode 18 DUCET ordering. The Boolean selects tertiary (case-sensitive) rather than secondary (case-insensitive) strength. |
Timer
Timers are connected-session operations. Timer.after(ms) returns an
Operation that completes with null after the delay. The delay
must be an integer from 0 through 4294967295 milliseconds. Invalid arguments,
allocation failure, and exceeding the 32 pending timers per VM abort the
calling fiber. Cancellation removes the timer immediately and frees its slot.
A zero delay completes on the next owner-loop pump, never inside after.
Timer.now returns monotonic seconds as a Num; only differences between
readings are meaningful. For recurring callbacks, use Hook.every(ms, fn).
import "syncterm" for Timer
var delay = Timer.after(250)
var result = delay.await()
// result is null, or OperationError if another owner cancelled the delay
Format
Number-to-string helpers for human-readable display. Both methods auto-pick a unit based on the magnitude of the input and use one decimal of precision; negative inputs are clamped to zero.
| Method | Description |
|---|---|
|
Format |
|
Format |
Combined idiom — display a transfer rate and ETA:
import "syncterm" for Format, Timer
var startedAt = Timer.now
var startBytes = job.done
// ... later ...
var elapsed = Timer.now - startedAt
var moved = job.done - startBytes
if (elapsed > 0) {
System.print("%(Format.bytes(moved / elapsed))/s")
var remain = job.total - job.done
if (remain > 0) {
System.print("ETA %(Format.duration(remain / (moved / elapsed)))")
}
}
SFTP
SSH-channel side-band file transfer. Each operation queues work on the
connection-owned SFTP worker and returns an Operation.
Both immediate and deferred recoverable failures are SFTPError result
values; .await() obtains the result in either case. Arguments of the wrong
type abort the calling fiber before work is submitted. Up to 256 provider
requests may be outstanding; a full queue returns a completed operation with
an SFTPError rather than accepting unbounded work.
| Method | Description |
|---|---|
|
Lazily open and negotiate the SSH SFTP subsystem. Completes with |
|
|
|
The remote |
|
|
|
Resolve |
|
Stat a remote path. Completes with |
|
Open a directory cursor. Completes with |
|
Open a file with explicit rights. Completes with |
|
Mutation ops. Each completes with |
|
Set both atime and mtime of |
|
Fetch the server’s long description for |
FileFlag
OR-able bitmask constants for SFTP.open’s flags argument; each
matches the corresponding `SSH_FXF_* wire constant.
| Constant | Wire value |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
SFTPEntry
One entry from RemoteDirectory.readEntries.
| Member | Description |
|---|---|
|
Filename relative to the parent directory. |
|
Server-formatted long name (when the
|
|
A fresh, immutable |
|
|
|
|
|
SHA-1 / MD5 digest bytes from |
SFTPStat
Result of SFTP.stat, or the metadata returned by SFTPEntry.stat. All members
are read-only; there is no public constructor. Size and timestamps follow
Native integer limits; mode, UID and GID retain their unsigned 32-bit values.
Attributes omitted by the server retain the native API’s zero defaults.
entry.stat constructs its native metadata copy only when accessed. Each access
returns a new object holding the metadata from the directory listing, without
issuing a request or refreshing it. The copy survives directory closure, entry
collection and later responses. It grants no remote-resource authority.
For current metadata, explicitly await SFTP.stat(path) instead.
In v2, SFTPEntry.size and SFTPEntry.mtime are removed. Use entry.stat.size
and entry.stat.mtime, or capture var metadata = entry.stat once when reading
several fields. Inexact size or timestamps in any listing entry fail the entire
listing Operation with a non-transient SFTPError.
| Member | Description |
|---|---|
|
File size in bytes. |
|
Modification time, POSIX seconds. |
|
Access time, POSIX seconds. |
|
SFTP-wire permission bits (Unix-style on POSIX servers). |
|
Owner user ID. |
|
Owner group ID. |
RemoteFile and RemoteDirectory
These host-created objects own a remote resource in one connected VM. They have no public constructor and cannot be used in another session. The SFTP namespace owns path operations; resource operations belong to these objects.
| Member | Description |
|---|---|
|
Read at an absolute offset. Returns an Operation completing with a nonempty
byte String, |
|
Write a byte String at an absolute offset; Operation completes with |
|
Append a byte String using the server’s current end of file. Requires an open with write and append flags; no misleading offset argument is accepted. The same native write-size limit and zero-byte result apply. |
|
The rights and append mode granted by the successful open. |
|
Read the next directory batch. Operation completes with |
|
Returns an Operation completing with |
|
Explicit resource state. Reads/writes after close starts abort. Cancelling a close Operation does not revoke the submitted native close: the object remains closing until the provider reply establishes success or failure. |
|
Run |
Pending native operations retain their receiver, even after cancellation, until their replies are drained. Collecting an abandoned open resource submits a best-effort close and tracks its reply as auxiliary work. GC is a fallback; use an explicit close or scope when completion matters. VM shutdown cancels pending work, marks every resource closed and releases ownership without resuming parked user callbacks. Shutdown cleanup never waits on the network. The browser and public-key installer use scopes; the parallel transfer queue awaits its workers before closing each resource explicitly.
var file = SFTP.open(path, FileFlag.read).await()
if (file is SFTPError) return file
return file.use(Fn.new {|source| source.readBytes(4096, 0).await() })
SFTPError
Returned in place of the typed result on any failure. Two error
layers — distinguish via code:
| Member | Description |
|---|---|
|
|
|
|
|
Human-readable diagnostic text accumulated by the
library (may be |
|
|
The toString override produces "SFTPError: <name>: <message>"
for System.print / interpolation; useful for log-line debug.
Persistent transfer queue
The shipped sftp_queue module runs one cooperative worker fiber per
direction. Jobs have stable numeric IDs; the browser and queue UI retain
selection and cancel the intended job by ID even when status sorting changes.
Duplicate pending jobs with the same direction and remote path reuse the
existing job.
Each claimed interval is filled completely, including when a successful remote or local read returns fewer bytes than requested. Parallel interval completion advances a persisted resume point only across the contiguous prefix of the file, so data beyond a gap is never treated as durable progress. Downloads stat the remote before resuming and restart from zero when its size or mtime changed. Uploads revalidate the picker consent token and fail when the local source changed; a compatible remote partial resumes from the saved frontier.
The queue stores only queued and active work in
Cache/sftp_queue.won. Schema version 2 records the next stable job ID,
source identity, cancellation request, and contiguous resume point. Version
1 documents are imported conservatively with resume set to zero. Malformed
or unsupported documents make the queue unavailable without rewriting the
file. Every mutation uses Directory.replace, so a failed persistence write
leaves the previous complete document in place and makes the live queue fatal
rather than continuing with state that cannot survive disconnect.
Ordinary transfer failures retain partial data for diagnosis or a later
explicit retry. A user cancellation removes the local download partial or
remote upload partial before publishing cancelled; a transient transport
failure suspends the queue and preserves that cleanup request for the next
connected VM. Local and remote close failures affect the final job status.
Best-effort mtime updates do not turn an otherwise complete transfer into a
failure.
Async Ops
Operation
SFTP, timers, and connection sends return an owned Operation for each
request. No caller supplies a target fiber, and immediate errors follow the same result contract
as asynchronous completion. Operations have object identity, so overlapping
requests remain distinguishable even when their result types are identical.
| Member | Description |
|---|---|
|
Bool indicating completion, including cancellation. |
|
Bool indicating explicit or abandoned-owner cancellation. |
|
Completed value or typed |
|
Obtain the result, parking only when necessary. Multiple fibers may await the same operation; each receives the same retained result. |
|
Run |
|
Return true on cancellation, false if already complete. The
result becomes an |
var left = SFTP.stat("/a")
var right = SFTP.stat("/b")
var a = left.await()
var b = right.await()
// Either provider reply may arrive first; identity selects the right result.
SFTP.realpath(".").then(Fn.new {|result|
if (result is Error) System.print(result.message)
else System.print(result)
})
Await registers the calling fiber with that specific operation. The owner
loop delivers an operation notification to resume it. Unrelated Wake.post
messages remain queued in arrival order until the operation wait completes;
they cannot substitute for the result. Use .await() rather than a raw
Fiber.yield() when waiting for an operation. A direct await in an App
handler postpones that handler’s UI events; App.runChild keeps dispatching
those events while its child waits.
Pending native work retains its operation even if the script drops the handle. Dropping a handle alone does not cancel the request. Dead or aborted awaiters are pruned at the next pump; when the last awaiting owner dies, its pending operation is cancelled. Completed result storage is released when its operation is collected. VM shutdown cancels pending operations before running disconnect hooks, then releases all roots and waiters without resuming asynchronous script code after teardown.
Timer cancellation removes the native timer. SFTP cancellation abandons the script’s interest in the reply; the provider may already have performed a remote side effect, and cancellation does not roll it back. Late replies are discarded, and late open results receive a best-effort close. A cancelled request ID continues counting toward the provider limit until its reply is drained. Explicitly close successful SFTP handles when finished.
OperationError inherits Error and exposes code, message, and toString.
Programming errors, including an invalid private await target or non-Fn
callback, abort the calling fiber rather than becoming result values.
WON
The Wren Object Notation — round-trip serialisation between Wren values
and a textual literal format. Output is a strict subset of valid Wren
syntax (and therefore also pasteable into Wren source). Deserialisation
runs a hardened C parser, not eval, so feeding untrusted text to
WON.deserialize cannot execute code.
Supported types:
| Type | Notes |
|---|---|
|
|
|
|
|
|
|
quoted with Wren-style escapes; |
|
|
|
|
|
coerced to |
|
any other |
Values of any other type abort serialisation in strict mode and are
silently omitted (or replaced with null at the top level) in lossy
mode. Cyclic Lists / Maps abort in both modes.
| Member | Description |
|---|---|
|
Strict compact form. |
|
Strict pretty-printed form. |
|
Compact form that silently omits unsupported items from Lists and Maps;
a top-level unsupported value becomes |
|
Pretty-printed lossy form. |
|
Parse |
WONError
Returned IN PLACE of the parsed value when WON.deserialize fails.
The script demuxes via is WONError. Mirrors the
SFTPError / FileError /
ConnError shape.
| Member | Description |
|---|---|
|
|
|
Byte offset where the error was detected. Useful for flagging a position in the input. |
|
Human-readable diagnostic, may be |
|
|
WONErr constants:
| Constant | Code | When emitted |
|---|---|---|
|
0 |
Sentinel; never appears on a returned WONError. |
|
1 |
Expected token / unexpected character / malformed number. |
|
2 |
Unterminated string, premature end of input. |
|
3 |
Malformed |
|
4 |
A |
|
5 |
Nesting exceeded the parser’s recursion budget (256 levels). |
|
6 |
A complete value was followed by more (non-whitespace) data. |
OOM during parsing aborts the fiber (no recoverable path — the
parser can’t allocate a WONError to return either).
import "syncterm" for WON
var data = {
"name": "syncterm",
"items": [1, 2, [3, 4]],
"flags": {"verbose": true, "depth": 7},
}
System.print(WON.serialize(data))
// {"name":"syncterm","items":[1,2,[3,4]],"flags":{"verbose":true,"depth":7}}
System.print(WON.serialize(data, " "))
// {
// "name": "syncterm",
// "items": [
// 1,
// 2,
// [
// 3,
// 4
// ]
// ],
// "flags": {
// "verbose": true,
// "depth": 7
// }
// }
var roundTripped = WON.deserialize(WON.serialize(data))
System.print(roundTripped["flags"]["depth"]) // 7
// Lossy mode skips unsupported entries instead of aborting.
var mixed = [1, Fiber.new {}, 2, Fiber.new {}, 3]
System.print(WON.serializeLossy(mixed)) // [1,2,3]
Built-in UI Library
SyncTERM ships a pure-Wren widget library on top of the
Modal Input primitive. It reuses mutable Cell views while
drawing into Surfaces, avoiding a new Wren object for every cell. Drawing
still uses foreign cell and text-width methods. The library composites
through a screen-sized backbuffer and applies a final Screen.putRect per
frame, so the whole thing runs without flicker even on slow remote BBSes. The
visual style follows SyncTERM’s classic conventions: cyan-on-blue dialog frames,
yellow titles, lightbar selection, drop shadows on modals, and a
distinct cyan inactive palette for any pane that’s currently behind
a modal.
A minimal session looks like:
import "ui" for App, Pane, ListView, Alert, Rect
import "syncterm" for Screen
var snap = Screen.save()
var app = App.new()
var size = Screen.size
var pane = Pane.new()
pane.bounds = Rect.new(2, 2, size[0] - 2, size[1] - 2)
pane.title = "Pick one"
pane.focused = true
pane.onClose = Fn.new { app.quit() }
app.root.add(pane)
var list = ListView.new()
var ib = pane.innerBounds
list.bounds = Rect.new(ib.x, ib.y, ib.w, ib.h)
list.items = ["alpha", "beta", "gamma"]
list.onSelect = Fn.new {|i, item| Alert.show(app, "Picked: %(item)") }
pane.add(list)
app.runSync()
Screen.restore(snap)
App.run() and App.runSync() differ in how they pump events.
run() parks a fiber on Fiber.yield() between events — claim
handler posts each accepted event via Wake.post, the result
queue resumes the fiber. Inbound bytes flow normally,
Hook.every and Timer.after keep firing. runSync() blocks
the VM on Input.next() instead; use it from contexts where
doterm can’t dispatch back into the App, e.g. the Wren console
(whose REPL itself runs inside a Hook.onKey).
runSync() dispatches each key or mouse event in a child fiber. A
runtime abort from a synchronous handler therefore does not unwind the
App’s event loop. By default the App writes the error and trace to the
current VM’s console log; set app.onError = Fn.new {|failedFiber| … }
to replace that reporting. Layout and painting remain outside this
boundary so a deterministic redraw failure is not retried forever. Modal
frames pushed by a failed event are discarded before error reporting, so an
orphaned dialog cannot consume the next Escape or Backspace. A modal that
the handler dismissed before aborting remains dismissed.
Key.quit is reserved for the host’s sticky process-close request. App
claims it before ordinary widget or global-keymap dispatch. With a modal
open, the App sends that modal an Escape for normal cleanup and then removes
it if it did not close itself; subsequent pump iterations unwind the
remaining Wren call stack. With no modal, the App stops. A widget whose
atExit property is true is the explicit exception: it remains interactive
while the quit latch is set, and modals it opens inherit atExit. Use this
only for work that must finish or be decided during shutdown, such as a save
confirmation. The connected-session host handles a real process-close
request before dispatching to the connected VM, so remotely supplied scripts
cannot use atExit to delay termination.
Importing
Every public class is exported from individual ui_*.wren modules
and re-exported from the convenience aggregator ui:
import "ui" for App, Pane, ListView, TextInput, SelectOnFocusInput, Button,
Checkbox, RadioGroup, SpinBox, DatePicker, CalendarDate,
MenuBar, StatusBar,
Form, Alert, Confirm, Prompt, Find, Help, PopStatus,
Painter, Style, Theme, Glyphs,
Widget, Container, Rect
If you only need a couple of classes, the per-topic modules cut
load cost: import "ui_pane" for Pane, import "ui_popup" for
Confirm, etc. They’re listed in UI Modules.
App
App is the root of a UI session. It owns:
-
root— aContainerthat hosts the foreground widget tree. -
a modal stack — synchronous dialogs push themselves onto it via
app.modal(widget), which blocks until the widget pops itself (typically from its owndismissWith_(value)helper). -
a global keymap —
app.bind(key, modifiers, fn)registers a hotkey that fires when no widget consumes the key. The overload without modifiers uses zero;unbindandbindingaccept the same optional mask. F1 is bound by default toshowHelp. -
a Theme initialized from
Theme.current, which decodes the C-owned active theme and refreshes its per-VM cache whenHost.themeGenerationchanges. The menu, picker, and connected VMs therefore use the same selected theme. Assignapp.themeonly when the App intentionally needs a different per-App theme. Assignment invalidates the complete root, transient-status, and modal widget trees so every mounted widget repaints on the next draw. -
a single run-fiber that pumps the event loop.
run()pushes an input claim (see Modal Input) whose handler decides synchronously, from App state alone, whether each event is "for the App" — modal up consumes everything; with a focused widget, keys are claimed and mouse events are claimed when they hit the visible widget tree (or start a drag, which the App owns for rectangular select); otherwise the event falls through to lower claims and then to registeredHook.onKey/Hook.onMouse. Claimed events are delivered to the run-fiber viaWake.post; the nextdrainOnce_iteration picks them up and dispatches into the widget tree. -
a backbuffer
Surfacesized to the term area (Screen.sizeminus one row whenCTerm.statusDisplay > 0, so the App’s blit doesn’t overwrite the SyncTERM status bar) and a one-shot screen capture (Screen.readRect) used as the backdrop behind everything. Areas not covered by widgets show that capture rather than a styled fill.
Methods of interest:
-
run()/runSync()— enter the event loop in a cleanup scope. Mouse subscriptions, cursor shape and position, and text attributes are restored after normal return, a callback error, or VM shutdown. The input claim and timers are released andrunningbecomes false. Re-entering an active App is an error; a stopped App can run again.tickMs=schedules a periodiconTick_callback (overridable; no-op by default). Only one tick timer is pending at a time; input and external posts do not accumulate additional timers.runSync()contains runtime errors raised by key and mouse handlers as described above. Errors from layout, painting, ticks, or an error reporter propagate after cleanup, retaining the original error object. -
onError=(fn)— replacerunSync()’s default reporting for a failed event handler. The callback receives the failed `Fiber, whoseerrorandstackTracedescribe the abort. -
quit()— break out of the loop. Widgets and global handlers call this from their key/mouse handlers. -
modal(widget)— push a modal, drain events until it pops or the App stops, then return the widget so the caller can read itsresult. A modal whoseclosesOnOutsideClick(event)method accepts a mouse event receives an Escape when that event occurs outside its bounds. List-style popups accept button 1 and right-click; Help accepts any ordinary mouse-button click. Text prompts and specialized editors reject outside clicks. -
popStatus(message)— show or clear a transient centered overlay that does not intercept input. Useful for "Working…" status while blocking onInput.nextor a long Wren computation. The overlay sits above the foreground widget tree but below the modal stack, so a dialog the user is actively working with isn’t obscured by an indicator behind it. -
releaseFocus()/restoreFocus()— wrap a picker call, where another VM temporarily owns the screen, so the App’s foreground tree doesn’t also draw as focused. Without this, the picker host’s pre-call screen save captures the App’s panes in their focused colour scheme, and the post-call restore re-paints them that way until the next App-driven repaint — visually, two widgets are focused at once. Operates onmodalTop(so a release while a modal is up defocuses the modal’s leaf, not the root’s) and forces an immediate paint so the unfocused state lands on screen before the host UI saves it. Both are idempotent: a secondreleaseFocusbeforerestoreFocusis a no-op, andrestoreFocuswithout a prior release is a no-op. -
invalidateCursorState()— call after a host operation changes conio’s cursor directly. The next draw reapplies the shape, visibility, and colour requested by the focused widget instead of trusting the App’s cached state.releaseFocus() var picked = Host.pickFiles(Host.uploadPath, "*", 0) restoreFocus() -
showHelp()— walks from the focused leaf up the parent chain to the first widget withhelpTextset, then opens aHelpdialog with that text. No-op if nothing in the chain has help. -
post()/post(value)— wake the App’s run-fiber from outside the input / timer paths. See "Externally-driven repaint" below. -
onPost=(fn)— handler for posted values that aren’t the no-payload sentinel. See below. -
runChild(fn)— runfnin an owned child while pumping the async App’s events. Return its result or propagate its error, including errors after an Operation await. Early exit cancels the child through its cleanup scopes. See "Async work in handlers" below. -
onLayout=(fn)— register a callback receiving(width, height)on the first paint and whenever the effective App area changes size. The root Container is resized before the callback runs, allowing the callback to assign stable responsive bounds to its children. -
onUnhandledMouse=(fn)— register a callback receiving(event, hit)after a non-modal mouse event is declined by the hit widget.hitis the declined Widget, ornullwhen the event is outside the root. Returningtrueconsumes the event; returningfalseleaves normal App fallback handling, including right-click Escape and drag selection, in place. The callback is not invoked while a modal owns input. -
theme=— install a custom Theme (see Theme).
Async work in handlers
runChild(fn) spawns a child fiber and pumps the App’s event loop until
that child finishes. Use it when a handler should keep input, ticks, and
repaints responsive while awaiting an operation. Direct operation await is
also safe: its wait defers unrelated wakes, but the handler does not dispatch
those UI events until the operation completes.
Call runChild from the active asynchronous App event fiber (including its
scoped continuations). Calling from an inactive App, runSync, or an
unrelated fiber is an error before the callback starts. Immediate and deferred
callback failures propagate as the same error object. Child completion wakes
the App even when it has no ticks or incoming input. If the App stops before
the child finishes, runChild raises "App stopped before child completed"
and detaches the child’s native waits. Registered host cleanup runs without
resuming the parked user callback. Operation ownership releases abandoned waits.
VM shutdown runs retained cleanup without resuming the parked user callback.
fetchDescAndShow_(path) {
popStatus("Fetching ...")
var d = runChild(Fn.new {
return SFTP.descs(path).await()
})
popStatus(null)
if (d is SFTPError) Alert.show(this, "Failed: " + d.toString)
else Alert.showPreformatted(this, d)
}
The child fiber yields on SFTP.descs; the run-fiber drops into
its own drainOnce_ loop, dispatching keys, mouse, ticks, and
repaints normally while the child is parked. When the SFTP
result wakes the child, its body completes and runChild
returns the value. Modal calls (Alert, Confirm) belong on the
run-fiber side after runChild returns — modals pump
drainOnce_ from whichever fiber called them, and only the
run-fiber receives wakes from the App’s claim handler.
Externally-driven repaint
The async run() parks the run-fiber on Fiber.yield() between
events. A network-driven app (chat client, ticker, log viewer fed
by remote bytes) needs a way for Hook.onInput to nudge the UI
without faking a key press. That’s what post is for:
import "syncterm" for Hook
import "ui_app" for App
var app = App.new()
// ... build widget tree ...
Hook.onInput { |b|
buffer.add(b) // mutate state
someWidget.markDirty() // mark UI as needing repaint
app.post() // wake the App so drainOnce_ runs again
return false
}
app.run()
app.post() calls Wake.post(runFiber, WakeOnly.instance) — a
no-payload sentinel. The next main-loop drain delivers it,
drawAll runs at the top of drainOnce_, and the dirty widget
repaints. The hook returns synchronously — post only
enqueues, satisfying the hooks-must-run-synchronously rule.
app.post(value) carries an arbitrary Wren value. When a non-
sentinel value arrives, onPost (if set) is called with it after
the redraw. Pass anything you can recognise:
app.onPost = Fn.new {|v|
if (v is String && v == "irc.PRIVMSG") chatPane.scrollToBottom()
}
Hook.onInput { |b|
// ...parse, accumulate...
if (gotPrivmsg) app.post("irc.PRIVMSG")
return false
}
post is a no-op when the App isn’t running (no run-fiber).
It’s not supported under runSync — the synchronous variant
blocks on Input.next() at the C level, not on Fiber.yield,
so a wake through the result queue won’t reach it. Use run()
for any app that needs external wake-ups.
App is not itself a Widget but exposes effectiveTheme and
markDirty() so widget tree-walks can terminate at it. Setting a
widget’s parent to an App is supported and is what pushModal
does internally.
The built-in Retro directory sets app.menuPanels = true so MenuUi list
choices use its full-page panel presentation. The default is false, keeping
Classic and custom applications' compact menus. Attached form dropdowns retain
their field-relative layout in either presentation.
Widget
Base class for everything paintable. Holds:
-
bounds— aRectin 1-based screen coords. -
parent— pointer to the containingContainerorApp. -
theme=— a per-widget Theme override; otherwise inherited viaeffectiveThemewalking the parent chain. Changing an override or reparenting an inheriting widget invalidates affected cached surfaces; an explicit descendant override ends that inherited-theme branch. -
focused,visible,focusable,activitySensitive,dirty— boolean state flags. SettingactivitySensitivetofalsemakes ambient screen chrome use its base theme roles regardless of modal activity; it does not affect focus or input dispatch. -
atExit—falseby default. Whentrue, this widget remains interactive after a sticky process-close request. Modals pushed while it is active inherit the property. Ordinary widgets are unwound through Escape and cannot consumeKey.quitthemselves. -
helpText=— string surfaced byApp.showHelp(F1). -
keyHints=— list of[keyLabel, actionLabel]pairs for ambient footer/status UI.App.keyHintsresolves it from the focused tree using the same nearest-widget rule ashelpText. -
closesOnOutsideClick(event)— returns whether the App should send Escape to this widget wheneventoccurs outside its modal bounds. The base implementation returnsfalse. -
shadow=— when true, the parent paints a drop shadow on the cells immediately right and below the widget’s bounds. -
surface— the widget’s private Surface backbuffer, allocated lazily and resized whenboundschanges. -
preferredWidth,preferredHeight— auto-layout sizing hints. Defaultnull(no preference, fill whatever bounds the parent gives). Widgets with a natural minimum size (ListViewwith N items, aFormwith measured rows, …) override these so containers that know how to lay out children (Pane.fitContent) can size themselves around the content.
Layer-aware painting: every widget tracks the App’s active layer
state (whether it or an ancestor is the modal top of stack) and
repaints itself when the cached state no longer matches. No
tree-wide dirty pass is needed when modals push or pop — each
widget notices on its next draw() and repaints with the inactive
theme variant. Subclasses override onPaint_() to draw into
surface; the base Widget.draw() calls onPaint_(), clears the
dirty flag, and returns the surface.
Hardware cursor: cursorPos returns [x, y] in 1-based screen
coords (or null); cursorVisible returns whether the cursor
should be shown while focused; cursorShape optionally returns
"normal" or "solid"; and cursorAttr optionally returns the
legacy text attribute whose foreground colors the cursor. App
reads all four off the focused leaf each frame and applies them. A
visible null shape defaults to "normal"; a null attribute leaves
the current conio cursor color unchanged. Containers forward the
focused child’s values.
tryHotkey(ev) is a parent-driven hotkey hook. Container.handle
scans its children with this when a printable key fell through the
focused child, so a typed letter can activate a button advertising
that letter even when focus is elsewhere.
Container
Widget subclass that manages a child list, a focused-child index,
and event dispatch. add(child) / remove(child) mutate the tree;
the first focusable child added becomes focused automatically.
Focus traversal:
-
Tab/Right—focusNext(), ordered ring with wrap. -
BackTab/Left—focusPrev(). -
Up/Down— spatial nearest-focusable scan. Picks the focusable child whose centre is above / below the current focus’s centre and minimises Manhattan distance. Ties (children on the same row) go to the lower-indexed sibling — i.e. tab order.
Spatial Up/Down does not wrap; it falls back to a hotkey scan if
nothing matches. Widgets that need arrows for their own semantics
(TextInput consumes Left/Right, ListView consumes Up/Down) catch
the keys before they bubble.
Mouse: Container.hitTest(px, py) walks children top-to-bottom
(last-added wins) and returns the deepest visible widget covering
the point, or the Container itself when nothing under it does.
focusedIndex is readable as a property and writable as a setter
for explicit focus management — e.g. the App-level
releaseFocus() / restoreFocus() pair clears and restores it
around blocking host UIs. The getter returns null when no
child is focused, otherwise an integer in 0..count - 1. The
setter toggles .focused on the previously- and newly-focused
child; pass null to clear focus. Direct day-to-day focus
changes still go through focusNext / focusPrev etc., not this
setter.
Pane
Container with a frame, optional title, [?] and [X] corner
buttons, and an inset interior. The default is a control-bearing pane:
the stronger double-line frame, title in its own bar row with a horizontal
separator underneath, and both corner buttons enabled.
Configuration knobs:
-
frameKind=—"control"(the default) or"display". A control frame marks a pane that contains choices, buttons, or editable input and uses the stronger double-line family. A display frame marks informational content and uses the single-line family. Assigning any other value aborts the calling fiber. -
titleAsBar=— when true, the title sits inside the frame in its own row with a horizontal separator underneath. When false, the title is embedded in the top border (-| Title |-). Classic list views use the bar form;Popupsubclasses use the embedded form. -
helpable=/closeable=— show or hide the[?]and[X]corner buttons. Help button callsonHelpif set, elseApp.showHelp(). Close button callsonCloseif set. -
onHelp=,onClose=— function callbacks for the corner buttons.
pane.innerBounds returns the drawable interior Rect after the
frame, title row, and separator are accounted for — children should
size themselves against this.
pane.contentBounds is innerBounds inset by one cell on every
side so text never touches the frame.
Popup-style widgets (Alert / Confirm / Prompt / PopStatus /
Help) lay themselves out inside contentBounds; bare Pane use
sites that want the full frame interior (e.g. a ListView filling
its parent pane) keep using innerBounds.
Pane.focused is a visual flag — set it from the App or a parent
container when the pane is the foreground. It does NOT redirect
keyboard focus; that still flows through `Container’s normal
focused-child routing to a leaf widget inside.
Auto-layout
Pane.fitContent() sizes the pane around its single child’s
preferredWidth / preferredHeight, plus whatever the title bar
and corner buttons require. It repeats measurement after assigning
the child’s bounds, so preferences that depend on the resulting
viewport, such as a ListView scrollbar, settle in one call. The
width is the largest of:
-
the child’s
preferredWidth + 2(left + right border), -
the title’s outer-width demand (see below), and
-
the corner buttons' outer-width demand (each visible button contributes 3 cells; total + 2 corners).
The two title modes have different geometry:
-
titleAsBar— title is centered on its own row inside the frame; outer width =title + 4(frame(2) + 1-cell padding on each side so the title never butts up against the side frame). -
frameTitle(titleAsBar = false) — title sits in the top frame border between─ ` and ` ─brackets; outer width =title + 6(corners(2) + brackets(2) + spaces(2)).
Multi-child panes are not auto-sized — fitContent only inspects
the first child. Lay them out manually via bounds / add.
Pane.fitContent(maximumWidth, maximumHeight) performs the same
layout while constraining the complete pane to the supplied maximum
dimensions. Pane.fitContentToScreen() applies the standard menu
modal limits. It preserves the title row and two-row footer, leaves
room for the two-column right shadow and one-row bottom shadow, and
centers the result in the remaining work area. For a pane with a
requested fixed size rather than a child-defined size,
Pane.fitToScreen(width, height) applies those same limits and
centering. Pane.modalBounds(width, height) returns that constrained
and centered rectangle for manually laid-out shadowed panes.
Pane.centerOnScreen() repositions the pane so its bounds are
centered on the current Screen.size, then re-anchors its single
child into the new innerBounds. Use fitContentToScreen() for the
usual constrained and centered modal layout:
var pane = Pane.new()
pane.title = "ANSI Music Setup"
pane.add(list)
pane.fitContentToScreen()
ListView
Scrollable list of items with a selection cursor and an optional
scrollbar. Items can be anything; rendering goes through
formatItem(item, width) which subclasses can override for rich
per-row formatting. Default is item.toString.
Setup:
var list = ListView.new()
list.bounds = Rect.new(x, y, w, h)
list.items = ["alpha", "beta", "gamma"]
list.onChange = Fn.new {|i, item| /* selection moved */ }
list.onSelect = Fn.new {|i, item| /* ... */ }
Navigation: Up, Down, PageUp, PageDown, Home, End move
the selection. Enter fires onSelect with (index, item).
Mouse: a single click on a row both selects it and fires onSelect;
each wheel notch over the list content moves the selection one row using
the same wrapping rules as Up and Down. Over the scrollbar, a wheel notch
moves one page. The scrollbar’s top and bottom arrow cells invoke PageUp
and PageDown; track clicks jump proportionally while keeping the lightbar
on the same screen row. The separator column between content and scrollbar
is inert. Button-1 drags fall through to screen selection.
wrap= controls single-row Up/Down movement and defaults to true:
Up at the first row wraps to the last, and Down at the last wraps to
the first. Set it to false to clamp at the ends. PageUp/PageDown,
Home/End, and direct selected= assignments do not wrap.
onChange is independent of activation. It fires with (index, item)
whenever navigation, assignment, search, or a row click changes the
current row. Replacing items also fires it so a detail pane can
refresh even when the selected numeric index remains zero. An empty
list reports (null, null).
items= preserves the selected index and scrollTop when replacing a
populated list, clamping them only when the replacement is shorter. This
allows a menu to rebuild changed row labels without moving its viewport.
resetItems(list) replaces the collection and explicitly selects its
first row at scrollTop=0; use it when navigating to a different
collection rather than redrawing the current one.
Repeating MenuUi.choice and MenuUi.commandChoice loops recreate their
pane after each activation. Construct one ChoiceViewState before the loop
and pass it as the final argument to the callback overload so each pane uses
the same ListView; row-label updates then retain both selection and
scrollTop. Use a separate state for each logical menu.
selected is null when no row is selected (empty list, or
explicitly cleared with list.selected = null); otherwise an
integer in 0..count - 1. selectedItem mirrors the same
contract — null when nothing is selected, the item otherwise.
When a selection is assigned before the list has bounds, first layout
centres an offscreen selected row where possible. A selection already in
the initial viewport leaves that viewport at the top. Normal navigation
scrolls only far enough to keep the moving selection visible.
The selected row is highlighted even when the list does not have focus.
Set highlightWhenUnfocused=false in a multi-list control when only the
list receiving keyboard input should display its selection lightbar. This
does not apply the inactive palette to the other list.
Search
Two complementary search modes, both using Unicode canonical caseless matching and wrapping at the end of the list:
-
Type-to-search — printable text without Control, Alt or GUI grows a rolling buffer and jumps to the first item whose search text starts with it. If the new buffer doesn’t match anywhere, falls back to just the new character (fresh prefix from current+1). Buffer resets on any navigation or activation key, so a paused-then-resumed search starts clean.
-
Ctrl-F / Ctrl-G — Ctrl-F opens an inline
Finddialog (see the Popup family) for a substring query, jumps to the first match. Ctrl-G repeats the last query.
Find and repeat-find use the logical key and modifiers, including native C0 Control-letter events from X11, ANSI and curses. Other modified shortcuts, such as Ctrl-S (Sort Profiles) and Ctrl-D (Quick Connect), pass through type-to-search to the menu dispatcher. The Wren console uses Ctrl+` on graphical backends and Ctrl-Q in ANSI/curses modes, where physical key events are unavailable.
The hook searchTextFor_(item) returns the string to match against;
defaults to formatItem(item, 1024) (the normal display string).
Override in subclasses when the displayed row decorates the underlying
text — the SFTP browser’s BrowserListView, for example, returns
item.name so users type bare filenames rather than the chip-prefixed
[==] foo.dat line.
searchKeys= optionally accepts a List parallel to items, with each value
produced by Text.caselessKey(searchTextFor_(item)). A valid list prefilters
prefix and substring searches without changing their grapheme-boundary-aware
result. A non-List or count mismatch disables the optimization. Replacing
items clears the keys, so callers set searchKeys after items.
Tag mode
selectionMode= accepts "single" (default) or "tag". In tag mode
each row tracks an independent tag flag, toggled by Space on the
current row; tagged returns the indices that are flagged on. A
1-cell marker column appears at the leftmost content position using
the theme’s tag.on / tag.off glyphs (» / blank by default;
> / blank in ASCII-only mode). Switching modes resets the flags;
so does setting items=.
Scrollbar layout knobs:
-
scrollbarSide=—"right"(default) or"left". -
scrollbarSeparator=— when true, paints a|divider between the scrollbar column and the content area. -
showScroll=— set to false to disable the scrollbar entirely.
The scrollbar is only painted when items.count > bounds.h.
ListView always reserves a 1-cell padding between the frame and
the items on the side that doesn’t have a scrollbar (both sides
when no scrollbar is shown at all), so item text never butts up
against the frame the parent Pane draws. innerWidth is
bounds.w - leftInset - rightInset accordingly.
Auto-layout: preferredWidth returns the longest item’s display
length plus the active insets (left + right padding, or scrollbar
+ padding when overflow is expected); preferredHeight returns
items.count, clamped to at least one row. The parent layout owns
screen and container constraints. Combined with
Pane.fitContentToScreen, a list-in-pane modal sizes itself to its
contents:
import "ui_pane" for Pane
import "ui_list" for ListView
var list = ListView.new()
list.items = Host.musicNames
var pane = Pane.new()
pane.title = "ANSI Music Setup"
pane.add(list)
pane.fitContentToScreen() // sized to list, constrained, and centered
Emoji picker
import "syncterm" for Emoji, EmojiEntry provides an offline catalog of
canonical emoji supported by all three bundled emoji banks. Emoji.entries
returns base representatives; Emoji.search(query) returns exact variants
matching a localized name or CLDR keyword substring, using canonical caseless
Unicode matching at grapheme boundaries (an empty query returns the base list).
English names and keywords are also searchable. Each EmojiEntry exposes
text, localized name, keywords (a List of localized and English search
keywords, with duplicates removed), and variants. Language preferences are
discovered once on first metadata lookup for a host, shared by its menu/picker VMs.
Bundled CLDR 49 annotations and derived annotations supply names for joined,
gender, skin-tone, and flag sequences. Locale aliases, likely scripts, and
CLDR parent locales resolve regional/script preferences; missing fields fall
through later preferences, then English. The lookup never changes the process
locale or connection encoding and does not require network access.
text retains the fully-qualified sequence including joiners and selectors.
Entry IDs ending in _ are internal catalog indexes, not persistent values.
The picker shows the highlighted name above a parenthesized keyword list,
truncated to one line to fit the pane.
It uses the screen dimensions with a one-cell margin on each side, reflowing
the emoji grid and preserving the selected entry when the screen is resized.
Emoji.recent returns up to 32 exact entries, newest first.
Emoji.recordUse(entry) promotes an entry in session recents, then persists the
merged recent list. It returns null or a FileError, replacing the former error
String in v2. code preserves the exact native IOErr reason; errno is zero
because the C operation does not supply a captured errno. The error diagnostic
explains that session recents were updated but saving failed. Native partial-write
behavior is unchanged; an error does not imply that the settings file is unchanged.
No rollback or automatic retry is performed. Successful insertion or transmission
is not undone or repeated when recording recents fails; bundled callers log the
returned error. Safe mode changes only session memory, performs no file writes,
and returns null. This existing fixed-purpose operation is available in menu,
picker and connected VMs and grants no arbitrary filesystem access. Invalid
catalog entry arguments retain their ordinary Fiber abort behavior.
Emoji.canSend reports whether this VM has a UTF-8 terminal connection; it
does not restrict local text-field insertion in a menu VM.
App.openEmojiPicker() opens ui_emoji_picker for its focused TextInput.
The default bindings are Alt+P and, when Host.localControlKeys is true,
Ctrl+P. It returns false without a running App and focused text field. Modal
completion preserves the insertion target’s cursor and selection. A changed
or detached target is not written. A full field leaves the picker open with
an explanation rather than inserting part of a sequence.
The mouse wheel scrolls the emoji viewport independently of the selection,
respecting its native magnitude and clamping at either end. Keyboard navigation
reveals the selected entry again; mouse hit testing uses the scrolled rows.
The connected emoji_pick module uses EmojiFlow.run() for Alt+P and the
Online Menu. It saves/restores the screen and mouse settings, suspends terminal
output during the picker, and sends a successful selection with Conn.sendText.
Ctrl+P is not a connected hook. Local Apps reached through Alt+E use their
normal field bindings regardless of the parked connection’s encoding.
TextInput
Single-line text edit field. Stores the value as a list of
codepoint strings, so editing indexes codepoints without splitting UTF-8.
Cursor placement, scrolling, and painting use Screen.textWidth, which
normalizes to NFC and resolves each extended grapheme cluster once. Full
grapheme-cluster editing is not currently provided.
insertText(text) inserts a complete String at the cursor (or replaces the
whole-field selection). It respects insert/overwrite mode and the codepoint
maxLen, returning false without changing the field if the entire payload
does not fit or contains C0/DEL controls. Success returns true and emits one
onChange callback when the value changes. The picker uses this preflight to
preserve joined emoji.
var t = TextInput.new()
t.bounds = Rect.new(x, y, w, 1)
t.value = "hello"
t.maxLen = 64 // optional cap
t.mask = "*" // optional display-only mask
t.onSubmit = Fn.new {|s| /* Enter */ }
t.onChange = Fn.new {|s| /* per-keystroke */ }
t.selectAll() // optional replace-all entry state
Keys use SyncTERM’s standard line-editor behavior. Left, Right, Home, End,
Backspace, and Delete / DelChar move and delete; Ctrl-B and Ctrl-E
alias Home and End, and Ctrl-Y truncates at the cursor. Insert toggles
insert/overwrite mode. Ctrl-C / Ctrl-Insert copy the whole field,
Ctrl-X / Shift-Delete cut it, and Ctrl-V / Shift-Insert paste at the cursor.
Ctrl-Z opens the focused field’s contextual help when one is available.
Enter fires onSubmit; printable codepoints edit at the cursor. Tab,
BackTab, Up, and Down are NOT consumed so containers can use them for
focus traversal. A left click positions the cursor; middle- and right-click
paste there. An unconsumed right-click elsewhere is Escape. Drag events
fall through to the App’s screen-selection handler.
selectAll() puts a non-empty value into a transient whole-field selection
state, reported by the read-only allSelected getter. The next printable,
keyboard paste, Backspace, Delete, or Ctrl-Y operation replaces the complete
value. Cursor movement and mouse positioning preserve the value and dismiss
the selection before ordinary editing continues; other non-editing key events
also dismiss it without changing the value. Assigning value clears the
state, so callers opt into it explicitly after assignment when needed.
SelectOnFocusInput is the existing-value editing variant used by
SyncTERM prompts:
prompts and inline editors. It calls selectAll() whenever it gains focus,
clears the selection on focus loss, highlights only the selected text, and
uses the surrounding default style after cursor movement begins ordinary
editing. Use TextInput when focus should leave an assigned value ready for
appending; use SelectOnFocusInput when typing should replace that value.
insertMode reports whether printable input inserts (true, the initial
mode) or overwrites existing characters (false). The mode is shared by
all TextInput instances, so toggling it in one field applies to the next
field. cursorShape is "normal" in insert mode and "solid" in overwrite
mode, matching SyncTERM’s insert/overwrite cursor convention.
cursorAttr supplies
the focused input style’s legacy attribute so bitmap backends render the
cursor in the field foreground instead of an unrelated global color. Pasted
control characters are discarded, matching typed-input filtering, and
maxLen applies to pasted text.
mask= accepts null or a non-empty String and uses its first
codepoint when painting every stored character. It does not change
value, cursor movement, length, or callback arguments, making it
suitable for password and system-password fields. Changing the mask
recalculates the horizontal viewport because the replacement glyph may
have a different display width.
Assigning or resizing bounds recalculates the horizontal viewport.
An initial value wider than the field displays its end followed by a
cell for the insertion cursor, regardless of whether value or
bounds was assigned first. scrollOff reports the first displayed
codepoint index.
cursorVisible returns true and cursorPos reports the cell that
corresponds to the current insertion point in screen coords —
backends that show the hardware cursor track the input as the user
types.
Button
Single-row "[ label ]" widget. Activates on Enter, Space, or
mouse click within bounds. onPress= sets the activation
callback. intrinsicWidth returns label.count + 4 for sizing
parents.
var b = Button.new("OK")
b.bounds = Rect.new(x, y, b.intrinsicWidth, 1)
b.onPress = Fn.new { app.popModal() }
hotkeyIdx= selects which label letter to highlight (default 0,
the first letter). tryHotkey matches that letter case-
insensitively against typed input, so a button labeled "Yes" with
hotkeyIdx = 0 activates on Y from anywhere in the same
container — even when focus is on a sibling.
Checkbox
Single-row "[X] Label" toggle. value is a Bool, label is a
String. Space or Enter flips the value when focused; mouse
click anywhere on the widget toggles too.
var c = Checkbox.new("Show shadows")
c.bounds = Rect.new(x, y, c.intrinsicWidth, 1)
c.value = true
c.onChange = Fn.new {|v| /* ... */ }
onChange fires only when the value actually changes — assigning
the current value is a no-op. Theme roles: checkbox,
checkbox.focused. Glyphs reused: check.on (√ U+221A), check.off
(space).
RadioGroup
Multi-row mutually-exclusive selector. Owns its own item list and selected index — the whole group is a single focusable widget.
var g = RadioGroup.new()
g.bounds = Rect.new(x, y, w, h)
g.items = ["None", "SSL", "SSH"]
g.selected = 0
g.onChange = Fn.new {|i, item| /* ... */ }
Two pointers: cursor (visually highlighted row) and selected
(the committed value). Up/Down move the cursor; Home / End
jump to ends; Space or Enter commits the cursor as the
selection. Mouse click selects directly. onChange fires only
when the selection actually changes. Both pointers are null
when the group is empty (or explicitly cleared by assigning
null); otherwise integers in 0..count - 1. The cursor highlight only
appears while the widget itself has focus — leaving the group
shows just the filled • glyph on the selected row, so a
multi-field Form doesn’t confuse the user with a stale lightbar.
wrap= controls the edge behavior of Up/Down. Default true:
Up at the top wraps to the bottom and vice versa; every press is
consumed. When false, Up at the top and Down at the bottom
return false instead, letting the parent Container move focus to
the previous / next sibling. Form.addField flips this to false
on RadioGroup children so vertical traversal escapes the group at
its edges.
Theme roles: radio.item, radio.item.focused. Glyphs reused:
radio.on (• U+2022), radio.off (○ U+25CB).
SpinBox
Single-row numeric input with up/down step buttons. Layout:
[ 42 ▲▼].
var s = SpinBox.new()
s.bounds = Rect.new(x, y, w, 1)
s.min = 0
s.max = 100
s.step = 1
s.value = 50
s.onChange = Fn.new {|v| /* ... */ }
Keys: Up / + adds step; Down / - subtracts; PageUp /
PageDown move ten steps; Home / End jump to min / max.
Mouse wheel scrolls one step; clicks on the up/down arrow cells
step ±1. Pressing an arrow steps immediately; holding it waits 400 ms and
then repeats at 8 Hz, accelerating to 16 Hz after two seconds and 32 Hz after
five seconds. Acceleration changes only the repeat rate, so every update is
still one configured step. Releasing or beginning a drag stops repetition,
and a delayed UI wake never produces a burst of catch-up updates.
value= clamps to [min, max]. Theme roles: spinbox,
spinbox.focused. Glyphs reused: scrollbar.up, scrollbar.down.
DatePicker
Embeddable month calendar with a named month/year header, Sunday-through- Saturday columns, and six date rows. Neighboring-month dates fill unused grid cells and can be selected directly. The control does not provide dialog buttons; its caller owns acceptance and cancellation.
var picker = DatePicker.new(2026, 7, 23)
picker.bounds = Rect.new(x, y, picker.preferredWidth,
picker.preferredHeight)
picker.onChange = Fn.new {|year, month, day| /* update preview */ }
picker.onAccept = Fn.new { /* commit picker.value */ }
year, month, and day expose the selected components; date returns
them as a three-element List, and value returns YYYY-MM-DD.
setDate(year, month, day) clamps to years 1 through 9999 and to the
selected month’s valid day range. moveDays(offset) and
moveMonths(offset) provide programmatic navigation. onChange fires
only when the selected date changes; onAccept fires on Enter, Space, or
a date double-click.
Left/Right moves one day, Up/Down moves one week, PageUp/PageDown changes month, and Home/End selects the first/last day of the month. Header-arrow clicks and the mouse wheel change month. A single click selects a visible date.
CalendarDate supplies Gregorian helpers used by the widget:
monthNames, daysInMonth(year, month), iso(year, month, day),
fromTimestamp(seconds), isoFromTimestamp(seconds),
daysFromCivil(year, month, day), civilFromDays(days), and
weekday(year, month, day) (Sunday is 0). Timestamp conversion is UTC.
Preferred size is 28x8 cells. Theme roles: button, list.item,
list.item.focused, and list.item.disabled.
ColorPicker
Embeddable 24-bit colour editor with a compact live sample, editable Red/Green/Blue ramps, visual Hue/Saturation/Value ramps, and six-digit hexadecimal input. The control does not provide dialog buttons; its caller owns acceptance, cancellation, and any application-specific preview.
var picker = ColorPicker.new(0x336699)
picker.bounds = Rect.new(x, y, 44, picker.preferredHeight)
picker.onChange = Fn.new {|rgb| /* update a live preview */ }
value is the current 0xRRGGBB integer. valid is false while the
hexadecimal field is incomplete, and commitEdits() returns false until
the field contains six valid digits. The RGB ramps accept decimal typing
from 0 through 255. HSV ramps remain fully interactive but omit the
rounded numeric labels and do not accept decimal typing.
RGB ramps show their numeric value and accept decimal input. HSV ramps do not show rounded numeric values. A digit starts replacement after focus, after a complete or out-of-range entry, or after Delete. Left/Right and the mouse wheel move one unit. PageUp/PageDown move RGB by 16, hue by 15 degrees, and saturation/value by 10 percent. Up/Down moves between fields, and a containing dialog may complete the navigation ring at the picker boundaries. A completed button-1 click jumps to the clicked ramp position. Button presses and drag events remain unconsumed so App can hand drag selection to conio’s normal text-copy path.
sampleColors(foreground, background) replaces the automatic contrasting
sample pair. The dialing-directory palette editor uses this to make either
row of its sixteen-position contrast grid clickable: selecting a cell shows
that foreground/background combination in the larger sample.
Ramp rows use default while idle and list.item.focused for their
edge-to-edge focus lightbar. Only the three-character RGB numeric field and
the seven-cell hexadecimal field use input / input.focused. Hex input
is limited to six digits; the final cell displays the insertion cursor after
a complete value without scrolling away its first digit. Complete valid
edits are normalized to uppercase without moving the active caret or
discarding its selection; assigning ColorPicker.value externally still
replaces the field and leaves its cursor at the end.
RGB is the canonical value. HSV conversion retains hue for greys and
retains hue/saturation for black, so moving away from those edge cases does
not unexpectedly reset the user’s HSV selection. Ramp and sample cells
carry both 24-bit RGB and a Color.toLegacyAttr() fallback.
The dialing-directory palette editor composes this generic control with a
separate palette-only preview. That preview shows the candidate colour as
both foreground and background against all sixteen effective palette
positions; this behavior is not part of ColorPicker. In that dialog,
Home selects the first ramp and End selects the button row when a ramp has
focus. The same keys retain normal text-cursor behavior in the hex field.
MenuBar
Horizontal strip of activatable items, typically at the top of the
screen. Each item is a [label, Fn] pair; activation calls the
Fn. No nested submenus in v1 — pop a Popup from the callback if
you want one.
var bar = MenuBar.new()
bar.bounds = Rect.new(1, 1, sz[0], 1)
bar.items = [
["File", Fn.new { Alert.show(app, "...") }],
["Edit", Fn.new { /* ... */ }],
["Help", Fn.new { app.showHelp() }],
]
Keys: Left / Right move focus between items with wrap; Home /
End jump to ends; Enter / Space activate the focused item; a
typed Unicode scalar (canonical caseless) matched against item labels'
first characters activates that item. focusedItem is null
when the bar is empty (or explicitly cleared); otherwise an
integer in 0..count - 1. tryHotkey(ev) is exposed
on the widget so a Container parent can route a letter pressed
elsewhere into the bar’s matcher. The focusedItem cursor is painted with
the focused role only while the MenuBar widget itself has focus, so multiple
bars may retain their navigation positions without appearing simultaneously
active. Set onFocus= when a containing editor needs a mouse click to move
its own focus to the bar before activation. A completed mouse click activates
the clicked item; the initial press and any drag do not. Clicks on inter-item
gaps are dropped. Theme roles:
menubar, menubar.item, menubar.item.focused.
StatusBar
Single-row strip used at the bottom (or top) of the screen for status text and key hints. Not focusable.
var s = StatusBar.new()
s.bounds = Rect.new(1, sz[1], sz[0], 1)
s.text = "F1 Help Esc Quit"
// or — multi-segment:
s.segments = [
["F1 Help", "left"],
["Connected", "center"],
["09:42", "right"],
]
text= sets a single left-aligned string. segments= takes a list
of [text, align] pairs where align is "left", "center", or
"right". Left segments stack from the left edge with a 2-cell
gap; right segments flush to the right edge inward; one center
segment is centred in the remaining space. Setting either form
overrides the other. Theme role: statusbar (black on cyan).
Form
Container subclass that lays out (label, widget) pairs in a
vertical stack with right-aligned labels in a column on the left.
Optional OK / Cancel buttons appear on the row below the last field
when onSubmit / onCancel are wired.
var f = Form.new()
f.bounds = pane.innerBounds
f.addField("Name:", nameInput)
f.addField("Port:", portSpin)
f.addFieldH("Encryption:", encRadio, 3) // 3 rows tall
f.addField("", autoCheckbox) // no label
f.onSubmit = Fn.new { /* read field values */ }
f.onCancel = Fn.new { app.quit() }
pane.add(f)
-
addField(label, widget)— queues a one-row field. -
addFieldH(label, widget, h)— queues a multi-row field (e.g. RadioGroup). -
clearFields()— drops every queued field and removes the widgets as children. -
rowGap=— blank rows between fields. Default 0. -
rowH=— default per-field height. Default 1.
The label column width auto-sizes to the longest label; widgets
start one column past the longest label plus a 2-cell gap. Form keeps its
managed child order as fields in addField declaration order followed by
the implicit OK and Cancel buttons, regardless of when their callbacks are
assigned. Container’s normal insertion-order Tab / BackTab traversal then
uses that order. Esc fires onCancel if wired.
onSubmit= / onCancel= are idempotent setters — assigning the
same callback twice doesn’t double-add the OK / Cancel button, and
assigning null removes the button.
Popup family
Modal dialogs built on Pane (control frame, embedded title, drop
shadow) and pushed onto the App’s modal stack. Each show is
synchronous: the App’s modal() pumps drain until the popup pops itself,
then control returns with the result. Help is the informational
exception and selects the display frame; transient PopStatus uses the
display frame as well.
import "ui" for Alert, Confirm, Prompt, LinePrompt
Alert.show(app, "Disk full")
Alert.show(app, "Warning", "Disk full")
Alert.show(app, "Warning", "Disk full", "# Disk Full\n\nFree space first.")
if (Confirm.show(app, "Delete file?", "# Delete\n\nThis cannot be undone.")) {
// ...
}
var name = Prompt.show(app, "Your name?", "anonymous")
if (name != null) {
// user submitted
}
var path = LinePrompt.show(app, "Path", "/tmp")
Alert — single OK button. Enter, Space, O, Esc, or a mouse click
on OK dismisses it; unrelated keys do not. show returns null.
Confirm — Yes / No buttons. Y / N letter shortcuts dismiss
directly; Enter activates the focused button; Tab cycles focus.
show returns true on Yes, false on No or Esc.
The four-argument titled Alert.show(app, title, message, helpText)
and three-argument Confirm.show(app, message, helpText) forms attach
Markdown context help to the popup. F1 and Ctrl-Z display that text
while the popup owns focus.
Prompt — SelectOnFocusInput plus OK / Cancel buttons. A non-empty
initial value starts selected: typing, keyboard paste,
Backspace, or Delete replaces it, while cursor movement or mouse positioning
preserves it and begins ordinary editing. Enter in the input or on OK
submits the value; Esc or Cancel returns null. The read-only input
getter exposes that input so trusted UI code can set maxLen or a display-only
mask before presenting the popup.
Prompt.new(message, initial, true) creates a required prompt. Escape
keeps the current edit in place and Enter accepts the field, including an
empty value.
sizeForInput(inputWidth) and
sizeForInput(inputWidth, minimumWidth) size the field for the requested
capacity and cap the complete popup to the standard menu modal work area. The
MenuUi.prompt wrappers use the field’s maxLen for this width.
Short fields retain the normal minimum while URI, path, password,
and other long fields use the available screen width.
LinePrompt — compact UIFC-style single-row entry. Its label appears
to the left of the input on the only interior row; there is no OK / Cancel
button row. Enter submits and Esc returns null. The read-only input
getter and sizeForInput methods have the same purpose as Prompt’s. A
distinct optional title may be placed in the top frame, but menu prompts
omit it when it would merely repeat the field label. MenuUi.prompt uses
this form for ordinary menu editing and application filename entry; host
prompts retain Prompt because their explanatory message is separate from
the dialog title. LinePrompt.runStandalone(app, label, initial) is the
standalone equivalent.
Find — compact single-row variant of Prompt. Title sits in the
top frame border, the input fills the entire innerBounds row (no
padding, no buttons, no [X]). Total height is 3 cells. Its previous query
starts selected under the same replacement rules as Prompt. Used by
`ListView’s Ctrl-F.
import "ui" for Find
var q = Find.show(app, "Find", lastQuery)
if (q != null && q.count > 0) {
// ...
}
Layout
All popups use the standard frame interior padding via
Pane.contentBounds — a 1-cell pad on every side so text never
touches the frame. Buttons (Alert OK, Confirm Yes/No, Prompt
OK/Cancel) anchor hard against the bottom frame; the empty row
between the message and the button row falls out of the height
math as a natural visual separator.
Popup.centeredBounds_(message, extraRows, minW) sizes the dialog
around the wrapped message: width is longest-line + 4 (frame
padding), height is 4 + msgRows + extraRows (2 frame + 2 padding
content). Subclasses pass extraRows for whatever they paint
below the message — 1 for Alert/Confirm (button row), 2 for
Prompt (input + button rows). Message width is measured in display
cells with the resolved default style font; wrapping never splits a
UTF-8 codepoint. A single glyph wider than the available row remains
intact and is left to the painter’s clipping policy.
PopStatus is the non-modal companion: a centered frame with a
message and no buttons, used by App.popStatus(message). It does
not push onto the modal stack — purely decorative — and is
dismissed with app.popStatus(null). Its sizing, centering, and
single-line truncation use the same painted-font display widths, and
truncation stops only at a Unicode codepoint boundary.
Standalone popups
Confirm.show(app, …) (and the other Popup.show family methods)
expect app to already be running — they call app.modal(p), which
pumps drainOnce_() on the existing run loop’s input claim. When
you need a popup from a context with no enclosing app — a
Hook.onKey handler being the canonical case — use the standalone
variants, which push the popup, wire onDismiss to app.quit(),
and run the App so key events are routed:
var app = App.new()
if (Confirm.runStandalone(app, "Disconnect... Are you sure?")) {
// user clicked Yes
}
Standalone helpers are available as Alert.runStandalone(app, msg),
Alert.runStandalone(app, title, msg),
Confirm.runStandalone(app, msg), and
Prompt.runStandalone(app, msg, initial).
For custom popup drivers, onDismiss=(fn) fires from dismissWith_
after the popup pops itself off the modal stack, with the dismissed
value (Bool / String / null depending on the popup subclass). If you
call app.run() yourself, wire onDismiss to app.quit(); otherwise
app.run() would loop forever on an empty modal stack.
Help viewer
A modal scrollable text viewer for context help. The body is parsed once as a markdown subset (see "Markdown subset" below) and laid out lazily — text wraps to the dialog width and reflows on resize.
Set literal = true on a Help instance to display plain text with wrapping
and scrolling, preserving punctuation such as Markdown markers. This mode is
used for the embedded license notices. preformatted = true instead keeps
source lines unwrapped; combining it with literal also disables inline
Markdown parsing.
import "ui" for Help
Help.show(app, "Help — Editor",
"# Editor\n\n" +
"- `Up`/`Down` scroll\n" +
"- `Enter` close\n")
Keys: Up, Down, PageUp, PageDown, Home, End scroll;
any other key dismisses. Wheel scrolls one line over the text and one
page over the scrollbar. Scrollbar clicks jump proportionally; button-1
drags fall through to screen text selection. An ordinary mouse-button
click also dismisses, including a click outside the dialog. Same scrollbar
knobs as ListView (scrollbarSide=, scrollbarSeparator=). Clicking
the frame’s [X] corner button dismisses (inherited from Pane).
App.showHelp (F1 by default) walks from the focused leaf up the
parent chain looking for a widget with helpText set, then calls
Help.show with the title "Help" and that text. Set helpText
on whichever widget is the most-specific scope you want help to
fall back to.
App.helpText, App.helpAvailable, and App.keyHints expose that same
focused context without opening a dialog. The main-menu footer queries
these values only when it paints; command ownership remains with the focused
widget or its nearest containing pane. Custom modal widgets should set
keyHints for their direct commands. The standard choices, prompts,
popups, and Help viewer already do so.
Prompts and other modal widgets can also carry helpText. Because the
focused input or list is their child, the same parent walk finds the modal’s
field-specific help before any help attached to the underlying screen.
Default placement: Help.centeredBounds_() uses the standard menu modal
work area. The frame remains below the title row, its bottom shadow remains
above the two-row footer, and it retains the 2-cell horizontal margins.
Pass an explicit Rect via the bounds= setter after construction to
override.
Padding: 1-cell margin on every side except the scrollbar column, where text is flush. The scrollbar defaults to the right, and its column plus optional separator span the full inner height (between the top and bottom frame chars); only text rows inset by the top/bottom padding.
Markdown subset
Help body strings (and any helpText) are parsed as a small
CommonMark + Pandoc subset by ui_markdown.wren. Supported syntax:
-
Block:
# / / #headings;- ` or `* ` bullets; blank-line- separated paragraphs; Pandoc-style definition lists (term line followed by one or more `: descriptionlines). -
Inline:
bold,. Backslash escapes a literalcode*,`, or\outside a code span. Inside a code span, only the closing backtick is syntax: bold markers and backslashes are literal. Closing code resumes the surrounding bold or ordinary role. -
Hard line break: a line ending in two trailing spaces forces a break at that point inside a paragraph or bullet. Continuation uses the same wrap indent as a soft wrap (so a bullet’s hard- break still hangs under the text). An unmarked source line belongs to a bullet only when the preceding bullet-owned line has this hard break; the rule can chain across multiple lines.
-
Italics are intentionally omitted — terminal italic support varies and dim grey on dark blue is hard to read.
Each block-level token resolves to a style role (help.heading.1,
help.bold, help.code, help.bullet, etc.) that cascades through
help and finally default, so themes can restyle without touching
the parser. Unknown markup falls through as literal text.
Definition lists pad each term to a common column width — capped at
half the dialog — and wrap descriptions inside the description
column, with continuation lines indented to the description start.
Term and description default to help.bold and help.text
respectively.
Headings render as a single-row reverse-video bar: blue-on-cyan
text with one styled space cell on each end (" Title ").
Layout is reflow-on-width: Markdown.layout(doc, cols) returns a
list of MdLine`s, each carrying pre-resolved style runs ready for
`Painter.text. The public layout helper uses font zero; Help
measures every run with the font resolved for that run’s role so its
layout matches painting. Help re-runs layout whenever its bounds,
scrollbar-separator width, or effective theme changes (as well as when
the scrollbar appears or disappears), and clamps the scroll position
accordingly.
Example combining heading + def-list:
# Capture Type
ASCII
: Plain text, no escape sequences
Raw
: Preserves ANSI escape sequences
Binary
: Saves the current screen as IBM-CGA / BinaryText
Theme, Style, Glyphs
A Theme bundles a role → Style map and a Glyphs (name →
glyph) lookup. Style is a four-field tuple (font, legacyAttr,
fgRgb, bgRgb); any field may be null to inherit from a parent
role. Painting picks one of the two color paths based on what the
backend supports — RGB on capable terminals, legacy attr otherwise.
Role cascade: Theme.style(role) walks dotted role suffixes,
merging partial Styles at each level until every field is
populated. "list.item.focused" falls back to "list.item" falls
back to "default". "default" is the cascade terminator and
must be a complete Style.
Inactive cascade: when a role ends in .inactive, the Theme walks
a parallel chain — X.inactive, then parent(X).inactive, …,
finally default.inactive. Falls through to default if the
theme has no inactive variants at all. Widget.style(role)
auto-suffixes .inactive whenever inActiveLayer is false, so a
single layer-state flag cascades through frame, title, list rows,
input field, button labels, and scrollbar without per-widget
bookkeeping.
A widget lands in the inactive layer for either of two reasons:
-
It isn’t part of the App’s modal-top subtree (a modal is on top, and the widget is in the layer behind it).
-
An ancestor that gates focus visibility has
focused == false.Widget.gatesActiveLayerdefaults tofalse;Paneoverrides it totrue, so an unfocused Pane in a multi-pane layout dims every cell it owns AND every descendant’s surface — frame, title, bg fill, list rows all agree on active-vs-inactive without each subclass having to know.
activitySensitive=false opts a widget out of this style selection.
It continues to report its computed inActiveLayer value, but
style(role) always resolves the base role. This is intended for
ambient screen backgrounds, title bars, and status/help bars which do
not have active and inactive forms. Do not use focusable=false for
this purpose: display-only children such as progress bars still need to
inherit an inactive containing Pane.
Theme.default is the C-owned compiled fallback decoded into Wren and
memoized so
someTheme == Theme.default works as identity equality. Theme builders
use it to populate roles and glyphs they do not override, and an unattached
Widget falls back to it when it has no Theme in its parent chain. It uses a
white-on-blue palette, yellow frame/title, lightbar selection, gray-on-blue
scrollbar, and bright-white-on-cyan inactive palette.
Theme.current decodes Host.themeData and caches the result against
Host.themeGeneration. App.new() initializes from this process-wide
selection. The built-in Classic Theme and file themes use the same host
representation; their storage and complete role/glyph registry are
documented in Themes.adoc. Scripts may still construct a Theme directly
or assign app.theme to replace the program theme for one App. Such a Wren
object does not modify the C-owned selection or any other VM.
Theme.fromData(data) constructs an independent Theme from the same
[styleRows, glyphRows] representation returned by Host.themeData and
ThemeDocument.themeData. It is intended for draft previews and other
host-provided snapshots; modifying the returned object does not modify its
source or the process-wide selection.
Glyphs entries are either a single string or [primary,
fallback] pairs — primary is the rich Unicode glyph, fallback is
an ASCII-safe substitute. The host resolves each theme glyph at load time in
Codepoint, CP437, then ASCII order and supplies the resulting Unicode primary
to Wren. Glyphs caches that primary by name. Set
theme.glyphs.asciiOnly = true
to force the fallback for every entry that has one — useful when
the user has selected a font that can’t render line-drawing
characters at all.
Glyph families used by the library:
-
frame.display.*— single-line--borders for informational viewers, plustee.left/right,title.left/right, andseparator. -
frame.control.*— double-line==borders for panes containing choices, buttons, or editable input.Pane.frameKindselects between the two frame families. -
scrollbar.track,scrollbar.thumb,scrollbar.up,scrollbar.down,scrollbar.separator— scrollbar pieces. -
focus.left,focus.right— selection-arrow shapes. Existing atlas arrows uselist.item.focused.indicatorand its.inactivevariant for colours; these inherit the selected-row styles unless overridden. OrdinaryListViewrows do not draw these arrows.
Painter
Painter is the low-level drawing toolbox. Every primitive takes
a Surface as its first argument and mutates the cells in place;
no calls reach Screen.putRect from here. Coordinates inside a
Surface are 0-based (0..width-1, 0..height-1); widgets that
work in absolute screen coords convert at composition time.
The most useful entry points:
fill(s, rect, ch, style) |
Bulk-fill a Surface rect with a single character + Style. |
|---|---|
|
Draw |
|
Box around |
|
Frame with a centered `+ |
|
+` in the top border. |
|
Single-row / single-column lines. |
|
Vertical scrollbar with always-visible up/down arrows on the top/bottom rows when |
|
Resolve a click at row |
|
Paint a drop shadow on the cells around the rect: 2 columns wide on the right, 1 row tall on the bottom. Each shadow cell keeps its existing character and font. The five-argument form uses the compiled |
|
Apply a Style to an existing Cell, leaving null fields untouched. Exposed for callers that mutate a cell view directly. |
UI Modules
The library is split across one module per topic, plus the convenience aggregator:
|
Re-exports every public class. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Demo gallery
scripts/ui_demo.wren is a playground for the library; run it from
the Wren console (see Built-in REPL):
import "ui_demo" for UiDemo
UiDemo.run()
Top level is a list of widget demos; pick one with Enter to launch
it, Esc returns to the gallery. Each demo runs its own App via
runSync (the console blocks the main loop, so doterm can’t
dispatch through to a parked fiber); nesting is fine because every
App restores mouse subscriptions, cursor shape/position, and text attributes.
The caller uses Screen.save/restore or Screen.modalRun to restore screen
contents.
Worked Example: Auto-respond to a Prompt
A small script that watches inbound text for known prompts and sends
canned responses. Hook.onMatch is the right tool for this — it
runs a streaming regex against the inbound byte stream and fires the
callback on each match, no manual buffering required:
import "syncterm" for Hook, Conn
Hook.onMatch("Press any key to continue") { |m|
Conn.sendText("\r")
}
Hook.onMatch("Logon: ") { |m|
Conn.sendText("myhandle\r")
}
onMatch is passthrough-only, so the matched text always reaches
the terminal — the callback just acts on the side (sending bytes
back to the BBS, updating script state, etc.). When a prompt is
preceded by colour codes, use Hook.onMatchClean instead so the
escapes don’t break the literal match.
onMatch substring-matches anywhere in the stream, not anchored to
line boundaries, so prompts that wait for input mid-line (like
`Logon: `) work the same as prompts followed by a newline. See
Hook Events for the regex grammar accepted, including
which constructs aren’t supported (no character classes, no anchors,
no backslash escapes).
Worked Example: Per-byte Inspection
Hook.onInput is the lower-level primitive — fires once per inbound
byte before the byte reaches the terminal. Use it when you need to
react to individual bytes rather than text patterns. Below: count
BEL (0x07) bytes received over the session.
import "syncterm" for Hook
class Stats {
static bells { __bells }
static bells=(n) { __bells = n }
}
Stats.bells = 0
Hook.onInput { |b|
if (b == 0x07) Stats.bells = Stats.bells + 1
return false
}
Inspect the count from the Wren console (see Built-in REPL) — Stats.bells
returns the running total. Returning false lets the byte through
to cterm; returning true would consume it (so the BEL never reaches
the terminal and never beeps). Filtered variants —
Hook.onInput(0x07, fn) — push the byte equality check to the C
side, avoiding a Wren entry on every non-target byte.