io.worxbend.tui.core

Members list

Packages

Type members

Classlikes

enum Alignment

Horizontal placement of content inside the columns it is drawn in.

Horizontal placement of content inside the columns it is drawn in.

A Line can carry one of these to say where that single row sits, and the widgets that draw text (a paragraph, a bordered title, a button caption) take one to place everything they draw. Content wider than the space it is placed in is clipped from the right regardless of alignment.

This enum lives in tui-core rather than in tui-widgets because Line — which is a core value — needs to name it, and the dependency edges only point downward: nothing in tui-core may reference a widget.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final class AnsiColors(val emitsColor: Boolean, legibleStyle: Style => Style, downsampleColor: Color => Color)

Which colours an SGR sequence may carry, and how a Style's colours are reduced to them — the colour policy every ANSI encoder in glyphora writes through.

Which colours an SGR sequence may carry, and how a Style's colours are reduced to them — the colour policy every ANSI encoder in glyphora writes through.

emitsColor false drops every foreground, background and underline colour code while keeping text attributes (the NO_COLOR rung). legible adjusts a whole style before encoding (a two-tone terminal flips a foreground that would vanish into its background), and downsample reduces one colour to what the device can show. AnsiColors.TrueColor is the identity policy: every colour in its own spelling. tui-terminal's ColorDepth.ansiColors answers the policy for each rung of its ladder; that is where a caller who has a colour depth gets one.

Immutable and pure; safe to share between threads.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
object AnsiColors

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
AnsiColors.type
object AnsiParser

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
AnsiParser.type
final class AnsiParser

Reads a stream of terminal output — text with SGR colour and attribute sequences and OSC 8 hyperlinks in it — back into styled Lines, keeping its place between chunks.

Reads a stream of terminal output — text with SGR colour and attribute sequences and OSC 8 hyperlinks in it — back into styled Lines, keeping its place between chunks.

This is the inverse of the terminal module's SGR encoder, written for the output of other programs: a compiler, a test runner or git run as a subprocess, whose colours should survive into a log or a paragraph instead of being stripped or, worse, written to the screen as raw escape bytes. Text.fromAnsi is the one-shot form; this class is for a caller that reads the output as it arrives, because a chunk boundary can fall anywhere — in the middle of an escape sequence, in the middle of a line — and only a parser that remembers where it was can put the pieces back together the way a terminal would have.

feed hands back every line the chunk completed (terminated by \n) and keeps the unterminated remainder, so parser.feed(chunk).foreach(logState.append) is the whole wiring for a log. finish returns that remainder as a final line once the stream has ended. A parser is used for one stream from start to finish; the style in force at the end of one chunk is the style the next chunk starts in, exactly as it would be on a terminal.

What is recognised:

  • '''SGR''' (ESC [ … m): the 16 named colours, the 256-colour and truecolour forms in both their ; and : spellings, bold, dim, italic, underline including the 4:n styled underlines and the SGR 58 underline colour, blink, rapid blink, reverse, hidden, crossed-out, and the reset codes for each of them. SGR 0 returns to Style.Default — silent, not Style.Reset — so the plain stretches of the output take whatever style the widget that draws the text gives them, the way plain text in that widget would.
  • '''OSC 8''' hyperlinks (ESC ] 8 ; params ; uri ST), carried on Style.link; an empty URI closes the link. The link is independent of SGR, as it is on a terminal: SGR 0 does not close it.

Every other escape sequence — cursor movement, screen clearing, other OSC strings, DCS and APC payloads, two-byte escapes — is recognised far enough to be skipped whole and then dropped, with one exception: '''erase in line''' (ESC [ K, ESC [ 1 K, ESC [ 2 K), which a progress bar sends after its \r and which is applied to the line being built. Control strings and CSI parameter text are limited to 4096 UTF-16 units: reaching the limit abandons the malformed sequence and resumes ordinary text, rather than swallowing an unlimited remainder. CAN/SUB cancel pending sequences; newline, carriage return and tab execute even inside CSI.

Three controls move within the line the way a terminal's cursor would:

  • a '''tab''' advances to the next eight-column stop — columns counted in display width through CharWidth, so a wide character takes two — padding with spaces in the style in force;
  • a '''carriage return''' (\r) goes back to the first column, and the text after it overwrites the line cell by cell, keeping whatever it does not reach: "100%\r5%" reads 5%0%, as it would on screen, and "100%\r\u001b[K5%" reads 5%. A progress bar that redraws itself with \r therefore shows its latest state, and CRLF output still splits into clean rows. Overwriting half of a wide character blanks its other half;
  • a '''newline''' (\n) ends the line.

Every other control character is dropped: a control occupies no column but one Cell, and a text model that kept one would draw the rest of its row one column out of place (see CharWidth.withoutControls).

The widths of the lines produced are, as for every Line, measured through CharWidth. Plain text with no escape sequence or control in it comes out exactly as Text.raw would read it.

'''Ownership.''' A mutable object owned by its caller and confined to one thread at a time — the thread reading the subprocess, typically, with the finished lines then handed to the render thread. It holds no reference to anything it has returned.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
final class Buffer(val area: Rect)

A mutable grid of Cells covering area, the in-memory render target for one frame.

A mutable grid of Cells covering area, the in-memory render target for one frame.

x/y arguments are absolute terminal coordinates (the same space as area's offset), not area-relative — widgets receive a Rect positioned in absolute space and write to the buffer at those coordinates. Writes outside area are silently clipped, never errors; reads outside area return Cell.Empty.

Mutability is an implementation detail of the render loop — it never escapes through Widget.render's contract.

'''Not thread-safe.''' The grid is a plain array with no synchronization, so a Buffer is owned by whichever thread renders into it — in a running application that is the runner's render thread, the same thread Signal writes are pinned to. Staging content on a background thread is safe only if the buffer is fully written before the reference is published to the render thread (RenderThread.capture in tui-runtime is how background work hands its continuation back) and is never touched again afterwards. Concurrent writes, or reads racing a write, produce a torn frame or a dropped diff rather than an error.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
object Buffer

Ways of building a buffer from content that is already laid out, rather than from an empty rectangle.

Ways of building a buffer from content that is already laid out, rather than from an empty rectangle.

Buffer(rect) — the class's own constructor — remains how a render target is allocated. These factories are for the other direction: a test that wants to write the frame it expects as a literal, instead of allocating a Rect of the right size by hand and calling setString once per row.

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
Buffer.type
object BufferExport

Pure renderings of a Buffer into files a person can open without a terminal: an SVG picture, an HTML page and an ANSI text dump.

Pure renderings of a Buffer into files a person can open without a terminal: an SVG picture, an HTML page and an ANSI text dump.

All three keep colours, text attributes, wide glyphs and OSC 8 links. They are the substrate for documentation screenshots that cannot drift from the code (render the real widget, write the SVG), for the visual diff a styled golden fixture reports, and for "export what is on screen" commands. Everything here is a function of its arguments and allocates only the string it returns, so it may be called from any thread — including, for a frame snapshot, off the render thread.

The ANSI forms write each colour in its own natural SGR spelling (named colours as 30–37/90–97, indexed as 38;5;n, RGB as 38;2;r;g;b) rather than resolving it through the palette, so the colours survive a round trip through a parser; the palette decides only how the SVG and HTML paint them. Both go through SgrCodec under an AnsiColors policy — the very codec and policy the terminal's frame encoder writes with, so an export at a depth holds the bytes the terminal would have been sent.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
final case class Cell(symbol: String, style: Style)

One rendered terminal cell.

One rendered terminal cell.

symbol is a String, not a Char, because a cell can hold a multi-codepoint grapheme cluster (combining characters, emoji ZWJ sequences). A wide (two-column) grapheme lives in its left cell; the cell to its right is a continuation filler that backends skip when flushing.

That filler is an ordinary Cell.Empty — a Cell carries no continuation state of its own. It is Buffer that records which of its cells are fillers, so the same value means "blank" in one position and "the right half of the grapheme next door" in another.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Cell

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Cell.type
trait CellFilter

Which cells of an effect's area an Effect may touch — the argument to Effect.filtered.

Which cells of an effect's area an Effect may touch — the argument to Effect.filtered.

A filter is asked about the cell '''as it was rendered''', before the effect ran: CellFilter.fg(Color.Red) keeps a fade on the red text even when the fade has already darkened it. It is also told the cell's coordinates and the effect's area, which is what the geometric filters (CellFilter.inner, CellFilter.outer) answer from.

Filters are immutable values and compose with and, or and not; they hold no state, so one filter can be shared between effects and threads.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
object CellFilter

Attributes

Companion
trait
Supertypes
class Object
trait Matchable
class Any
Self type
CellFilter.type
object CharWidth

Terminal display-width arithmetic.

Terminal display-width arithmetic.

String.length counts UTF-16 code units, not terminal columns: CJK characters occupy two columns, combining marks occupy none, and one emoji ZWJ sequence can span many codepoints yet occupy two columns. All layout and rendering math in this library must go through this object — no code outside it may use String.length or String.substring for anything that affects layout.

Widths are derived from the Unicode Character Database: East Asian Width W/F codepoints (see WidthTable) are two columns; combining marks, format controls, and conjoining Hangul jamo are zero; everything else is one. East Asian Width A (Ambiguous) codepoints — box drawing, Greek, Cyrillic, arrows, ±, × — are one column, which is what a Western-locale terminal draws; the overloads that take a WidthMode answer the CJK-locale question instead, and that mode is the one thing here a caller may vary. Variation selectors override the base width — VS16 forces emoji presentation (two columns), VS15 text presentation (one) — but only after a base that has both presentations; after a letter or an ideograph they are inert. A regional-indicator pair (flag emoji) is two.

Everything here is a pure function of its arguments and holds no state, so it is safe to call from any thread. The one exception is graphemeClusters, which hands back a stateful iterator; its own documentation states who owns that iterator.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
CharWidth.type
enum Color

A terminal color: the 16 named ANSI colors (8 standard + 8 bright), a 24-bit RGB value, or a 256-color palette index.

A terminal color: the 16 named ANSI colors (8 standard + 8 bright), a 24-bit RGB value, or a 256-color palette index.

Reset restores the terminal's default foreground/background rather than naming a concrete color. The Bright* variants map to the SGR 90–97 / 100–107 codes; terminals downsample them to the standard 8 when they cannot show 16.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Color

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Color.type
object ColorScheme

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type

Whether the terminal is drawing light text on a dark background or the other way round — or nobody knows.

Whether the terminal is drawing light text on a dark background or the other way round — or nobody knows.

Three states and not a Boolean, for the reason terminal.Support gives: "the terminal said light", "the terminal said dark" and "the terminal said nothing" call for different behaviour. An application picking a theme reads Unknown as "dark", which is what every terminal looked like before any of them could be asked — so a terminal that cannot say gets exactly what it always got.

A pure value in tui-core rather than in tui-terminal, because it travels in two directions that cross the tier boundary: upward as the payload of Event.ColorSchemeChanged, and downward into whichever widget or theme wants to pick a colour by it. Where the value comes from — an OSC 11 background-colour reply, a mode 2031 notification — is the terminal tier's business and is read there.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Which colour layer of a cell a colour effect acts on — Effect.hslShift and Effect.paint take one.

Which colour layer of a cell a colour effect acts on — Effect.hslShift and Effect.paint take one.

  • Foreground changes the text colour of every non-blank cell; blank cells have no text to recolour.
  • Background changes the background of every cell in the area, blank ones included, because a filled panel is mostly blank cells. A cell with no background of its own is treated as black.
  • Both does both.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
enum Constraint

How much of a split axis one segment claims (see Layout.split).

How much of a split axis one segment claims (see Layout.split).

Length/Percentage/Ratio are fixed demands; Min is a floor that also competes for leftover space; Max is a cap that only takes leftover space; Fill divides leftover space by weight.

Auto asks the segment's own content: the measuring overload of Layout.split hands the solver one size per segment, and an Auto segment claims exactly what was measured for it. Where nothing was measured — the content cannot say, or the caller used the plain split — Auto is a Fill(1), never zero, for the same reason Measured makes None mean "cannot say" rather than "nothing".

Bounded(min, max, base) clamps whatever base would have been given: "fill, but at least 20 and at most 60" is Bounded(20, 60, Fill(1)), and atLeast / atMost build it one bound at a time. A segment pushed to a bound is frozen there and the space it gave up or took is shared out again among the others, so a bounded fill beside a plain one settles the way a flex layout does rather than the way a fixed Min floor does.

This enum grows: a match over it that must survive the next case should carry a wildcard.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Constraint

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Constraint.type
enum CrossAlign

Where a segment sits on the axis a Layout does not split — across a column, or up and down a row.

Where a segment sits on the axis a Layout does not split — across a column, or up and down a row.

A layout decides each segment's extent along its own Direction; across the other axis every segment used to span the whole area, so a button in a column was always as wide as the column. Stretch keeps that. The other three shrink the segment to its content's measured cross size and put it at the near edge, the middle, or the far edge.

The cross size comes from the content — a Measured widget's widthAt(height) in a column, heightAt(width) in a row — and when the content cannot say (None) every mode falls back to Stretch, for the same reason Measured forbids reading None as zero: an unmeasurable child drawn at zero width would simply vanish.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

What Buffer.diff is instructed to do with one position of a frame, regardless of whether its content changed.

What Buffer.diff is instructed to do with one position of a frame, regardless of whether its content changed.

A frame is normally flushed by comparing it against the frame before it and emitting only the cells that differ. That reasoning holds for exactly as long as glyphora is the only thing writing to the terminal, and there are two ways for it to stop holding — one in each direction:

  • Something else painted a region and glyphora must not paint over it. An inline-image protocol (Sixel, the kitty graphics protocol, iTerm2 inline images) fills a rectangle with an escape sequence that has no cell-by-cell representation, so re-emitting any column of it from the grid tears a hole in the picture. That is Skip.
  • Something else painted a region and glyphora must paint over it. A subprocess writing to the same terminal, or an image that has just been torn down, leaves the screen showing something the buffer never wrote — and because the buffer's own memory of those cells is unchanged, the comparison says "nothing to do" and the wrong pixels stay until something unrelated happens to touch them. That is AlwaysUpdate.

The two are cases of one enumeration rather than two independent flags because a single position cannot sensibly be both never-emitted and always-emitted, and an enumeration is the shape that makes that unrepresentable.

Directives are per position and per frame: they belong to the Buffer, not to the Cell (a Cell is a value that says what to draw, and the same value is skipped in one column and flushed in the next), and Buffer.reset clears them back to Default. A caller that owns a region re-declares it on every render, in the same render pass that draws the rest of the frame.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
enum Direction

The axis a Layout splits along: Horizontal divides an area into columns, Vertical into rows.

The axis a Layout splits along: Horizontal divides an area into columns, Vertical into rows.

It names the axis the constraints apply to, not the direction content flows — a Horizontal layout gives every segment the full height of the area and shares its width.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object DurationText

The clock-face readout of a duration, mm:ss under an hour and h:mm:ss from one up.

The clock-face readout of a duration, mm:ss under an hour and h:mm:ss from one up.

It lives in tui-core so the progress columns in tui-widgets and the Stopwatch/Timer readouts in tui-runtime (runtime.formatDuration, which delegates here) print the same moment the same way. Pure, and safe on any thread.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
enum Easing

Progress curves for effects and tweens: map linear time t ∈ [0, 1] to eased progress.

Progress curves for effects and tweens: map linear time t ∈ [0, 1] to eased progress.

The families follow the conventional Penner set; Back/Elastic/Bounce overshoot or oscillate, so they can leave [0, 1] mid-flight even though they start at 0 and end at 1.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Easing

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Easing.type
object Effect

Attributes

Companion
trait
Supertypes
class Object
trait Matchable
class Any
Self type
Effect.type
trait Effect

A post-render frame transform (the tachyonfx model, original implementation): widgets render normally, then active effects mutate the rendered cells based on elapsed time.

A post-render frame transform (the tachyonfx model, original implementation): widgets render normally, then active effects mutate the rendered cells based on elapsed time.

An effect holds no clock of its own — it is a pure function of the elapsed it is handed, which is what keeps the combinators (Effect.sequence, Effect.repeat, …) composable and replayable. The flip side is that the caller owns the clock: whoever calls process, directly or through Frame.applyEffect in tui-runtime, must remember when this particular effect started and pass the time since then. TuiApp.runEffect in tui-dsl keeps that timestamp per active effect, so a DSL app gets it for free; an app driving a bare Runner has to keep it itself. Passing time since the frame, or since the application started, compiles and type-checks but leaves the effect pinned at progress 1.0 or oscillating out of phase.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
enum Event

Everything a running application can receive from its event source.

Everything a running application can receive from its event source.

Key/Mouse/Resize originate from the terminal backend; Tick is synthetic, injected by the runtime's runner at its configured tick rate — it lives in this ADT because consumers pattern-match all four together.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object ExportOptions

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
final case class ExportOptions(font: String = ..., cellWidth: Int = ..., cellHeight: Int = ..., palette: ExportPalette = ..., foreground: Color = ..., background: Color = ..., title: String = ..., ansiColors: AnsiColors = ...)

What an export of a Buffer looks like: the typeface and cell geometry of the picture, the palette named colours resolve through, the colours a cell with no colour of its own is painted in, and a title.

What an export of a Buffer looks like: the typeface and cell geometry of the picture, the palette named colours resolve through, the colours a cell with no colour of its own is painted in, and a title.

cellWidth/cellHeight are pixels per terminal cell in the SVG; the HTML and ANSI forms carry no geometry and ignore them. foreground/background stand in for Color.Reset and for a cell that names no colour — the two things a terminal would paint from its own theme. title becomes the SVG `` and the HTML document title, and is omitted from both when empty. ansiColors is the colour policy of the two ANSI forms only (the default keeps every colour in its own spelling; terminal.ColorDepth.ansiColors gives the policy of a terminal depth). Every field keeps the value the bare ExportOptions() would have, so a caller sets only what differs.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

How an export paints a Color that has no RGB value of its own.

How an export paints a Color that has no RGB value of its own.

A terminal resolves a named or indexed colour through the user's theme; a file written by BufferExport has no terminal, so the palette makes that choice instead. Color.Rgb values pass through unchanged by every sensible palette; what a palette decides is the sixteen named colours and the 256-colour table. Color.Reset never reaches a palette — BufferExport resolves it to the export's own default foreground or background first.

Implementations must be pure: an export calls this once per cell, from whichever thread is exporting.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Xterm256
object ExportPalette

Attributes

Companion
trait
Supertypes
class Object
trait Matchable
class Any
Self type
enum Flex

How a Layout distributes any space its segments do not consume (ratatui's Flex).

How a Layout distributes any space its segments do not consume (ratatui's Flex).

Flex only has an effect when the constraints leave leftover space — i.e. there is no Fill/Min greedily absorbing it. With such a growing constraint present the leftover is zero and every mode behaves like Flex.Start.

  • Start — pack segments at the start; leftover trails at the end (the default).
  • End — pack at the end; leftover leads at the start.
  • Center — center the block; leftover splits evenly before and after.
  • SpaceBetween — first and last segments touch the edges; leftover splits between segments.
  • SpaceAround — equal space around each segment (edges get a half-gap).
  • SpaceEvenly — equal space in every gap including both edges.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

How adventurous the glyphs written into a Buffer are allowed to be.

How adventurous the glyphs written into a Buffer are allowed to be.

The three rungs run floor to ceiling: each one permits everything the rungs below it permit. They are a floor, not a measurement — nothing here can interrogate the font a terminal is drawing with, so a rung says "do not go above this", never "this is definitely renderable".

  • Ascii — nothing above U+007E. What survives a non-UTF-8 locale, a serial console, or a log file that someone will later open in an editor that is not a terminal at all.
  • BoxDrawing — the U+2500 box-drawing block on top of that. Present in essentially every fixed-width font, including the Linux virtual console's built-in one, which is why it is a rung of its own.
  • Full — anything glyphora draws, braille spinners and emoji included. The default, because a modern terminal emulator with a UTF-8 locale renders all of it.

A pure value with no environment reading of its own: tui-terminal's TerminalGlyphs.detect is what turns an environment into one of these, and it lives up there so that this type — and therefore tui-widgets — stays free of any notion of a terminal.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object GlyphSupport

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
final case class GraphicCrop(columns: Int, rows: Int, column: Int, row: Int)

Which part of a picture's box a cropped GraphicPlacement shows: the box was columns x rows cells, and the placement shows its own area's worth of them starting at cell (column, row) of that box.

Which part of a picture's box a cropped GraphicPlacement shows: the box was columns x rows cells, and the placement shows its own area's worth of them starting at cell (column, row) of that box.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final case class GraphicPayload(protocol: String, data: String)

A picture already encoded for one terminal image protocol: protocol names it ("kitty", "iterm2" — the terminal module's ImageProtocol.tag) and data is the payload that protocol sends, base64 included. Built off the render thread by whoever placed the picture, so the frame that draws it does no encoding of its own.

A picture already encoded for one terminal image protocol: protocol names it ("kitty", "iterm2" — the terminal module's ImageProtocol.tag) and data is the payload that protocol sends, base64 included. Built off the render thread by whoever placed the picture, so the frame that draws it does no encoding of its own.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final class GraphicPlacement

One picture a frame asks an out-of-band painter to draw: image, scaled into the box of cells area.

One picture a frame asks an out-of-band painter to draw: image, scaled into the box of cells area.

Recorded by Buffer.placeGraphic, which also reserves the box with DiffDirective.Skip. A terminal backend that speaks an image protocol reads Buffer.graphics after the frame is composed and draws each placement through its own escape sequence; one that does not ignores them and gives the cells back, so whatever the widget drew there as a fallback is flushed as ordinary text.

The placement remembers the cells that were under it when it was made. A popup, a toast or a menu drawn later in the same frame writes over those cells, and Buffer.covers notices: a picture an image protocol paints sits above the text grid, so the only way to show the popup is to take the picture down while it is covered and put it back once the cells match again.

A placement a blit cut — a picture straddling the edge of a scroll view's window — keeps the visible part of its box and says which part in crop; sourcePixels is the matching rectangle of the picture, so a backend draws exactly that slice into area instead of squeezing the whole picture into it.

payload is the picture already encoded for one image protocol, when whoever placed it encoded it ahead of the frame (the DSL's pixelImage does, off the render thread); a backend with no payload for its protocol encodes the picture itself.

Equality is the picture, the box and the crop — what decides whether the terminal already shows it — and ignores the remembered cells and the payload. Immutable; owned by the buffer that recorded it.

Attributes

Supertypes
class Object
trait Matchable
class Any
object GridAreas

Named grid areas from a text template, the way CSS grid-template-areas spells them.

Named grid areas from a text template, the way CSS grid-template-areas spells them.

Each string is one row; whitespace separates its cells; a name repeated across neighbouring cells makes that name's area span them, and a . leaves a cell unnamed. GridAreas.parse("top top", "main side") names a two-column top bar over two single cells.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
GridAreas.type
final case class GridCell(row: Int, col: Int)

A zero-based row and column in a grid. Immutable geometry, safe to share between threads.

A zero-based row and column in a grid. Immutable geometry, safe to share between threads.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object GridItem

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
GridItem.type
final case class GridItem(position: Option[GridCell], rowSpan: Int, colSpan: Int)

One child's request to GridLayout.autoFlow: a fixed position, or none and let the flow choose, plus its spans.

One child's request to GridLayout.autoFlow: a fixed position, or none and let the flow choose, plus its spans.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object GridLayout

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
GridLayout.type
final class GridLayout

A two-axis layout: a list of column Constraints and a list of row constraints, each solved by the same LayoutSolver a one-axis Layout uses, with a gap between neighbouring tracks.

A two-axis layout: a list of column Constraints and a list of row constraints, each solved by the same LayoutSolver a one-axis Layout uses, with a gap between neighbouring tracks.

The grid owns geometry only. It says where track i runs (tracks) and which rectangle a GridPlacement covers (cell): a span covers its tracks and the gaps between them, so a top bar spanning two columns is one rectangle wide enough to reach the far edge. Which child goes where is the caller's — explicit placements, GridLayout.autoFlow for children that did not say, or a template of named areas parsed by GridAreas.

Columns are solved first and do not depend on the rows, so a caller measuring an Auto row can ask for the widths the columns came out at before it decides the row heights.

Immutable and safe to share between threads; a final class with builders, like Layout, so a new field is not a breaking change.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
final case class GridPlacement(row: Int, col: Int, rowSpan: Int = ..., colSpan: Int = ...)

Where one child sits in a GridLayout: the top-left track it starts in and how many tracks it covers each way.

Where one child sits in a GridLayout: the top-left track it starts in and how many tracks it covers each way.

Rows and columns count from zero. A span below one is read as one, so a placement always names at least one cell.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final case class GridTracks(columns: Seq[Rect], rows: Seq[Rect])

The column and row tracks one GridLayout solved for one area — see GridLayout.tracks.

The column and row tracks one GridLayout solved for one area — see GridLayout.tracks.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
enum KeyCode

The key a key event reports: a printable character, a named editing/navigation key, or a function key.

The key a key event reports: a printable character, a named editing/navigation key, or a function key.

Char carries a Unicode code point, not a UTF-16 code unit, so keys outside the Basic Multilingual Plane (emoji, historic scripts) survive input decoding intact. KeyCode.Char('q') still compiles — a scala.Char widens to Int in both expression and pattern position — but code that binds the payload receives an Int; use text or Character.toString(codePoint) to turn it back into printable text.

The last group — the three lock keys, PrintScreen, Pause and Menu — reaches an application only from a terminal speaking the kitty keyboard protocol, with the one exception that Menu (the context-menu key beside the right-hand Ctrl) also arrives from xterm as CSI 29~. Bind them as a convenience, never as the only route to a command, because on an ordinary terminal they never arrive at all. The lock keys report the key being pressed; glyphora has no notion of whether Caps Lock is currently on, and there is no event when the light changes on its own. text is empty for all six, as it is for every other named key.

Media is the hardware transport and volume block — play, pause, next track, volume up — and carries which one in a MediaKey. It has the same caveat and one more: see MediaKey for why a desktop environment often takes these keys before an application ever sees them.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final case class KeyEvent(code: KeyCode, modifiers: KeyModifiers)

A key press: which key, plus the modifier keys held.

A key press: which key, plus the modifier keys held.

A standalone case class rather than an Event enum case so handler signatures like KeyEvent => Boolean can take exactly the key payload without partially matching an Event.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object KeyEvent

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
KeyEvent.type
object KeyModifiers

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type

The implementation behind the key"…" interpolator above.

The implementation behind the key"…" interpolator above.

Public only because an inline method's body is expanded in whichever module calls it, so this object has to be reachable from there. It is not an API: call the interpolator, or KeyEvent.parse for a spec that is not a literal.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
object Layout

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
Layout.type
final class Layout

Splits a rectangle into segments along one axis according to a list of Constraints.

Splits a rectangle into segments along one axis according to a list of Constraints.

Layout owns the positioning half of the problem: it deducts spacing, asks LayoutSolver how many cells each constraint gets, then places those sizes on the axis according to flex, clamping anything that would run past the far edge. How the sizes themselves are decided is documented on LayoutSolver.

When the fixed demands exceed the available space, trailing segments are truncated (possibly to zero width) rather than failing — consistent with the library-wide silent-clipping philosophy. A negative spacing is treated as zero for the same reason: a negative number in that field is almost always a mistake, and LayoutSolver already clamps every constraint input it reads rather than propagating a negative.

Overlapping segments are reachable, but only by asking for them by name. Set between to a Spacing.Overlap and each segment is pulled back over the one before it so the two share that many columns or rows — which is how two bordered blocks come to share one border line instead of drawing two adjacent ones. between takes precedence over spacing when it is set, and spacing is what every layout that has not heard of between keeps using.

Across the axis it does not split, every segment spans the whole area unless crossAlign says otherwise: the measuring overload of split takes each segment's cross size and places it by that mode, and a segment whose content cannot be measured stretches whatever the mode — see CrossAlign.

A final class with a private constructor rather than a case class, because new constraint or flex behaviour is expected to add fields here. A case class rewrites apply, copy and unapply on every new field, and a consumer compiled against the old shape fails with NoSuchMethodError; here the compatibility surface is Layout.horizontal, Layout.vertical and the builders withSpacing, withFlex, withCrossAlign, spaced and withoutBetween, all of which a new field leaves untouched. There is no copy and no pattern extractor; equality and hashCode are structural over every field.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
object LayoutSolver

Turns a list of Constraints into one integer size per segment.

Turns a list of Constraints into one integer size per segment.

This is the "how many cells does each segment get" half of Layout; where those cells sit on the axis (spacing, Flex offsets, clamping to the rectangle) is Layout's own job. The split is what lets either half be read without skimming the other.

The solver is a pure function of (constraints, available) and holds no state, so it is safe to call from any thread.

The algorithm is three steps:

  1. every constraint states its fixed demand, and those are handed out first;
  2. whatever is left over is shared among the constraints that grow (Fill by weight, Min and Max with weight one), honoring Max caps and re-distributing what a cap refuses;
  3. if nothing grew and the constraints between them claim the whole axis proportionally, the cells lost to integer division are handed back so the segments fill the container exactly.

Two constraints are resolved before those steps run. Auto becomes the Length the caller's measure function answers for that segment, or a Fill(1) when it answers None (or when the caller had nothing to measure with). Bounded is solved as its base and then checked: a segment that came out below its floor or above its ceiling is frozen at that bound as a fixed demand and the whole axis is solved again for the others, until no bound is violated. Each round freezes at least one segment, so there are at most as many rounds as bounded constraints.

Applications reach this through Layout.split and rarely call solve directly; it is public because how a toolkit decides sizes is the part users most need to be able to read, and a private object documents it to nobody.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
object Line

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Line.type
final case class Line(spans: Seq[Span], alignment: Option[Alignment] = ..., style: Style = ...)

One horizontal line of styled text, a sequence of differently-styled Spans.

One horizontal line of styled text, a sequence of differently-styled Spans.

alignment is this line's own horizontal placement. None, the default, means "whatever the widget drawing me was told to use" — that is what every line did before this field existed. Setting it overrides the widget for this one row, so a single block of text can hold a left-aligned heading above right-aligned numbers without being split into several widgets stacked by the layout solver.

style is the line's own base style, the middle layer of the three-layer cascade a renderer resolves for every character: the widget's style first, then this line's style on top of it, then the Span's style on top of that, each layered with Style.patch so the more specific layer wins wherever it speaks and the outer layer shows through wherever it stays silent. Before this field existed, "this whole row is dim" had to be repeated on every span, and a line a widget had built from spans could not be tinted by the widget drawing it without rebuilding every span. The default, Style.Default, sets nothing, so a line that does not use it renders exactly as it did.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object LineBreaks

Where a run of text may be broken onto the next row.

Where a run of text may be broken onto the next row.

CharWidth owns the question "how many terminal columns does this take"; this object owns the orthogonal question "is a break allowed here". They are separate because two characters that look identical on screen can answer them differently: U+0020 SPACE and U+00A0 NO-BREAK SPACE both draw one blank column, but a wrapper may break on the first and must never break on the second (NO-BREAK SPACE is what "10 kg" or "Fig. 3" is written with precisely so the two halves stay on one row).

The classification is deliberately Unicode-aware rather than a c == ' ' test:

  • java.lang.Character.isWhitespace already answers false for U+00A0 NO-BREAK SPACE, U+2007 FIGURE SPACE and U+202F NARROW NO-BREAK SPACE, which is exactly the behaviour a wrapper wants, and true for the ideographic space U+3000, the tab and the line separators. isBreakingSpace is therefore a thin, tested wrapper over it rather than a hand-written table.
  • U+200B ZERO WIDTH SPACE is the opposite case: it is a break opportunity that occupies no column at all (Thai and Japanese text, and long URLs, use it to say "you may break here"), so a wrapper driven purely by display width can never notice it. isZeroWidthBreak makes it visible to the wrapper.

Every method takes a grapheme cluster — one user-perceived character as produced by CharWidth.graphemeClusters — not a Char, because a cluster may span several code points (an emoji with a skin-tone modifier, a letter with combining marks) and such a cluster is never a break opportunity.

Pure and stateless: safe to call from any thread.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
LineBreaks.type
object MarkupLiteral

The implementation behind the markup"…" interpolator above.

The implementation behind the markup"…" interpolator above.

Public only because an inline method's body is expanded in whichever module calls it, so this object has to be reachable from there — the same reason KeySpecLiteral is. It is not an API: call the interpolator.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
final case class Masked(content: String, maskChar: String)

Text that must not be shown, paired with the glyph to show in its place — a password, a token, an account number.

Text that must not be shown, paired with the glyph to show in its place — a password, a token, an account number.

This hides characters on a screen. It is not encryption and not redaction: the original text is still held in memory, in this very value, and anything that can read the object can read content. It exists so that the display of a secret is correct and done in one place.

"Correct" is the whole point. The obvious hand-rolled version, "*" * secret.length, counts UTF-16 code units, so a secret containing an emoji or an accented letter written as a base plus a combining mark produces more mask characters than there are characters to hide — which leaks the shape of the secret and misaligns the row it is drawn in. value emits exactly one mask per grapheme cluster, the unit a terminal actually draws.

Use it wherever a secret is merely displayed: a paragraph, a table cell, a list row, a log line.

Value parameters

content

the text being hidden. Never rendered by anything on this type, toString included.

maskChar

the glyph shown in place of each grapheme cluster of content. Only its first grapheme cluster is used, so a multi-character argument cannot silently widen every masked position; an argument with no cluster at all — the empty string — or one whose first cluster occupies no column — a lone combining mark, a zero-width space or joiner, a control character — would draw a zero-width secret, so Masked.DefaultMaskChar stands in for it.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Masked

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Masked.type
trait Measured

A widget's own answer to "how much space does my content need?".

A widget's own answer to "how much space does my content need?".

Layout in this toolkit is top-down: a container hands a Widget a Rect and the widget paints inside it. That is enough for rendering, but not for the passes that have to decide how big the area should be in the first place — a scroll view needs the full height of content it is about to show a window onto, and a column that sums its children needs each child's rows. Before this trait each such widget grew its own private spelling of the same question (heightOf, preferredWidth, widthOf, preferredHeight), and every caller had to know which one its particular widget happened to expose. This is the single contract they all speak instead.

'''None is not a size.''' It means "this widget cannot say" — a chart that fills whatever it is given genuinely has no natural height. A caller must treat it as unmeasurable and fall back to something it can defend (the area it already has, an explicit constraint the user set), never as zero and never as one. Answering a made-up number here is worse than answering None, because a wrong measurement silently mis-sizes a layout while None at least tells the caller it is guessing.

Both methods take the other axis, because content size is usually a function of it: wrapped prose is heightAt(width), and a rotated or column-flowing widget would be widthAt(height). A widget that does not care about the axis it is handed ignores the argument.

'''Ownership.''' Implementations answer from their own immutable fields — the same fields render draws from — so measurement and rendering cannot drift apart. Nothing here touches a buffer or a terminal, so unlike Widget.render these methods are safe to call from any thread.

Attributes

Supertypes
class Object
trait Matchable
class Any
enum MediaKey

A hardware transport or volume key — the play, pause, next-track and volume buttons on a keyboard's top row or on a pair of headphones.

A hardware transport or volume key — the play, pause, next-track and volume buttons on a keyboard's top row or on a pair of headphones.

These are reported by the kitty keyboard protocol as the code-point block 57428-57440, and carried by KeyCode.Media. Two things have to go right for one to arrive: the terminal must speak that protocol, and the desktop environment must not swallow the key first — many take the volume and transport keys for themselves before any application sees them. So a binding on a media key is an enhancement for the people whose setup delivers it, never the only way to reach a command.

Pause here is the media transport pause, which is a different physical key from KeyCode.Pause — the Pause/Break key above the arrow cluster.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

A modifier key reported in its own right — as a key that was pressed, rather than as a bit set on some other key's event.

A modifier key reported in its own right — as a key that was pressed, rather than as a bit set on some other key's event.

Two different things are called a "modifier" here. KeyModifiers is the set of modifier keys that were held down while another key was pressed: Ctrl+a arrives as KeyCode.Char('a') carrying the Ctrl bit, and the Ctrl key itself produces no event of its own. A ModifierKey, by contrast, names the Ctrl key as the key: it is what a terminal sends when the user presses or releases Ctrl and nothing else. Applications that want to show a "Ctrl held" hint, or to treat holding a key as a mode, need the second kind; everything else only ever needs the first.

Only terminals speaking the kitty keyboard protocol report these, and only once the application has asked for them. Left and right are separate cases because the protocol distinguishes them and a binding on "the right Alt key" cannot be written if the two collapse into one name.

A plain immutable value: no ownership, no thread constraints.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Modifiers

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
Modifiers.type

Which way something moves across the screen: the direction of travel, not the edge it starts from.

Which way something moves across the screen: the direction of travel, not the edge it starts from.

Effect.slideIn(MotionDirection.Up) moves content upward, so it enters from the bottom edge; Pattern.sweep(MotionDirection.Right) sends its front rightward, so the left column leads. Distinct from Direction, which names the axis a Layout splits along and has no sense of travel.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Which physical mouse button a MouseEvent is about.

Which physical mouse button a MouseEvent is about.

Terminals number the buttons in the report they send: 0 is the left button, 1 the middle one (the wheel pressed as a button), 2 the right one. Unknown is the honest answer whenever the report names no button at all — a wheel notch scrolls without pressing anything, a Moved event happens with nothing held, and the legacy X10 encoding has a single "some button came up" release code that does not say which one it was.

The case is called Unknown rather than None so that it never reads as, or shadows, Scala's own None at a use site such as event.button == MouseButton.Unknown.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final case class MouseEvent(position: Position, kind: MouseEventKind, modifiers: KeyModifiers, button: MouseButton = ..., clickCount: Int = ...)

A mouse action at an absolute terminal position.

A mouse action at an absolute terminal position.

position is absolute and zero-based, in the same coordinate space as Position and Rect: column 0, row 0 is the top-left cell of the terminal, not of any widget. A handler that wants coordinates relative to the area it was given subtracts that area's own origin (event.position.x - area.x).

button names which physical button the action concerns, so an application can tell a right-click (open a context menu) from a left-click (activate the thing under the pointer). It defaults to MouseButton.Left so that every three-argument construction written before the field existed still compiles and still means what it meant. That default is a convenience for hand-built events only: what the decoder reports for a wheel notch, and for an X10 release that cannot name a button, is MouseButton.Unknown.

clickCount is how many presses in a row this Down is: 2 for the second press of a double click, 3 for a triple. Terminals report no such thing — every press arrives as a single Down — so the count is synthesised by whoever routes the events (the DSL's ElementHost counts presses of the same button on the same cell within 400 ms), and the decoder, like every hand-built event, leaves it at 1. It is 1 on every kind other than Down.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

What the mouse did.

What the mouse did.

Drag is motion with a button held; Moved is motion with none. Which of the two a terminal can even report depends on how the backend asked for the mouse: under button-event tracking (DEC modes 1000/1002/1006, the default) a terminal reports motion only while a button is down, so Moved never arrives. A backend asked for all-motion tracking (DEC mode 1003 as well) reports every pointer movement, which is what makes hover highlighting and tooltips possible — and a great deal more input traffic, which is why it is opt-in.

ScrollUp/ScrollDown are the vertical wheel. ScrollLeft/ScrollRight are the horizontal one (xterm buttons 66 and 67), which is what a sideways trackpad swipe sends. No built-in element consumes the horizontal pair, because no widget in this library scrolls sideways; they are decoded and delivered so that an application's own onMouseEvent can act on them, and they bubble untouched past every built-in that declines them.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Pattern

Attributes

Companion
trait
Supertypes
class Object
trait Matchable
class Any
Self type
Pattern.type
trait Pattern

A spatial shape for an effect: turns the whole animation's progress into each cell's own, so a fade can bloom from the centre, wipe diagonally or ripple instead of reaching every cell at once. Effect.patterned applies one.

A spatial shape for an effect: turns the whole animation's progress into each cell's own, so a fade can bloom from the centre, wipe diagonally or ripple instead of reaching every cell at once. Effect.patterned applies one.

Every pattern picks a '''delay''' in [0, 1] for each cell from its position in the effect's area and hands it to Progress.staggered, which owns the time-to-position arithmetic. So for every pattern a cell's progress is in [0, 1], is 0 everywhere at progress 0 and is 1 everywhere at progress 1. softness is how much of the run each cell's own transition takes: small values give a hard front, values towards 1 a broad gradient.

Patterns are pure, immutable values with no clock; one can be shared between effects and threads.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
object Position

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Position.type
final case class Position(x: Int, y: Int)

An absolute terminal coordinate: x is the column, y the row, both zero-based.

An absolute terminal coordinate: x is the column, y the row, both zero-based.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Progress

Where an animation is at a given elapsed — the one place that turns time into position.

Where an animation is at a given elapsed — the one place that turns time into position.

Two flavours of the same question, deliberately kept side by side so they cannot drift apart:

  • normalized is the '''one-shot''' answer: a fraction that runs past 1 once the animation is over. Tween and the timed Effects use it, then hand it to an Easing, which clamps.
  • stepped and steppedAtRate are the '''looping''' answers: a whole position in 0 until steps that wraps round and round forever. The animated widgets (Marquee, IndeterminateBar, the spinners) use those.
  • staggered is the '''per-cell''' answer: one cell's own progress through an animation that reaches different cells at different times. Every Pattern is a way of choosing each cell's delay for it.

stepped is exactly floor(normalized * steps) folded into one cycle, only evaluated in integer arithmetic so that a sample taken at an exact fraction of the period lands on the step that fraction names rather than one below it.

All three are pure functions of the time they are handed: they hold no clock, so the caller owns the clock. See Effect for what that means in a render loop.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
Progress.type
final case class Rect(x: Int, y: Int, width: Int, height: Int)

A rectangular region of the terminal in absolute coordinates.

A rectangular region of the terminal in absolute coordinates.

x/y locate the top-left corner; the region spans width columns and height rows. The right and bottom edges (x + width, y + height) are exclusive.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Rect

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Rect.type
final case class Rgb(r: Int, g: Int, b: Int)

Concrete red, green and blue channels in 0..255, as painted by an ExportPalette. Immutable and safe to share between threads; distinct from Color.Rgb, which is a terminal colour request.

Concrete red, green and blue channels in 0..255, as painted by an ExportPalette. Immutable and safe to share between threads; distinct from Color.Rgb, which is a terminal colour request.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object RgbaImage

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
RgbaImage.type
final class RgbaImage

A raster picture: width x height pixels, each four bytes — red, green, blue, alpha — in row-major order.

A raster picture: width x height pixels, each four bytes — red, green, blue, alpha — in row-major order.

The one pixel type every layer agrees on. The PixelImage widget samples it for its half-block fallback, a buffer carries it in a GraphicPlacement, and the terminal's kitty and iTerm2 encoders turn it into the escape sequence that draws it. That is why it lives in tui-core and not beside the widget: the encoders sit in tui-terminal, which cannot see tui-widgets.

Immutable. The byte array is copied in by every constructor and never handed out mutable, so an image can be shared across threads and frames freely — the terminal caches the encoded payload per image, keyed on this value's structural equality.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
object Size

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Size.type
final case class Size(width: Int, height: Int)

A terminal extent in cells: width columns by height rows.

A terminal extent in cells: width columns by height rows.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
enum Spacing

How much room a Layout leaves between two adjacent segments.

How much room a Layout leaves between two adjacent segments.

Gap(cells) inserts that many empty cells between them, which is what Layout's plain spacing: Int has always done. Overlap(cells) does the opposite: it pulls each segment back over the one before it so the two share that many columns or rows.

Overlap is what lets two bordered blocks sit side by side sharing a single border line, instead of drawing two adjacent lines with a doubled-up look — the "collapsed borders" style of a table or a grid. Draw the left block into the first segment and the right one into the second, and the right block's left border lands exactly on the left block's right border.

Both cases clamp a negative argument to zero: the direction is carried by which case you chose, never by the sign of the number. That is deliberate. Layout's spacing: Int field clamps a negative value to zero for the same reason — a caller who wrote spacing = -2 almost certainly meant a typo, not a request to overlap — and this type exists so that asking for an overlap is something you say out loud rather than something you get by accident.

Attributes

Companion
object
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Spacing

Attributes

Companion
enum
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Spacing.type
final case class Span(content: String, style: Style)

A run of text rendered with a single Style.

A run of text rendered with a single Style.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Span

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Span.type
final case class Spring(frequency: Double = ..., damping: Double = ..., deltaTime: Double = ...)

A damped-spring integrator (à la Charm's Harmonica) for physical, non-linear motion — scrolling, progress fills, layout transitions.

A damped-spring integrator (à la Charm's Harmonica) for physical, non-linear motion — scrolling, progress fills, layout transitions.

Unlike an Easing, a spring has no fixed duration: call step each tick with the current State and it eases toward target, overshooting or settling per frequency (stiffness) and damping (< 1 bouncy, 1 critically damped, > 1 sluggish). Integrated semi-implicitly, stable for the usual TUI tick rates.

deltaTime must be positive: a spring with a non-positive step can never advance, so the documented while !settled(...) do step(...) loop would hang. A defect in the caller, hence a construction-time throw.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Spring

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Spring.type
trait StatefulWidget[S]

A widget whose rendering reads mutable state owned by the caller (scroll offsets, selections).

A widget whose rendering reads mutable state owned by the caller (scroll offsets, selections).

The widget value itself stays immutable and reusable; all per-instance mutability lives in S, which the application owns and passes in at render time.

'''Threading and ownership.''' render runs on the render thread that owns buffer (see Widget and Buffer), and it is allowed to mutate state in place — clamping a scroll offset to the area it was just given, or memoising a viewport, is the reason the state is passed rather than copied. Because that mutation is unsynchronized, one S value must not be shared across threads, and must not be handed to two widgets that render concurrently. Like buffer, area and buffer must not be retained past the call; state belongs to the caller and outlives it.

Attributes

Supertypes
class Object
trait Matchable
class Any
object Style

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type
Style.type
final class Style

How a cell is drawn: optional foreground/background colors plus text-attribute modifiers.

How a cell is drawn: optional foreground/background colors plus text-attribute modifiers.

None for a color means "leave the terminal default in effect". Builders return a new immutable Style; they are with-prefixed for the color fields because a field and a def cannot share a name.

A final class with a private constructor rather than a case class, because this is the type most likely to gain a field as terminals grow attributes. A case class rewrites apply, copy and unapply on every new field, and a consumer compiled against the old shape fails with NoSuchMethodError; here the compatibility surface is Style.Default, Style.Reset, the Style.fg/Style.bg/Style.of/Style.mods factories and the with* builders, all of which a new field leaves untouched. There is no copy and no pattern extractor; equality and hashCode are structural over every field, which Cell — a case class holding a Style — and so Buffer equality, frame diffing and style memoisation all rely on.

Text attributes are carried in two bitsets, not one (ratatui's add_modifier/sub_modifier pair). modifiers is what the cell renders with; clearedModifiers records the flags the style was asked to turn off. Without the second set a style has no way to say "not bold" — only "bold" or "silent about bold" — and the moment it is layered onto a bolder one with patch, the flag it deliberately dropped comes back.

Value parameters

clearedModifiers

flags this style turns off when it is layered onto another with patch. Always disjoint from modifiers: every builder that sets a flag clears it here and vice versa, so the last call in a chain wins.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
final case class StyledGrapheme(cluster: String, style: Style)

One grapheme cluster together with the Style it is drawn in — the smallest unit a terminal cell can hold.

One grapheme cluster together with the Style it is drawn in — the smallest unit a terminal cell can hold.

A grapheme cluster is what a reader thinks of as one character: a base code point plus whatever attaches to it, so e followed by a combining acute accent is one cluster, and so is a multi-code-point emoji. Stepping through text this way rather than character by character is what keeps an accent from being separated from its letter.

The style is already fully resolved: whatever base style the enclosing widget supplies has been layered under the span's own with Style.patch, so a consumer never has to resolve anything itself.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Symbols

The named glyphs the library draws with.

The named glyphs the library draws with.

These characters were previously written as bare literals wherever they were needed, which meant the same four shading blocks appeared in three unrelated widgets and the eighth-block ladder existed twice — once growing upward and once growing rightward — with no name connecting them. A reader had to recognise ▒ on sight to know what a line of code drew, and an application that wanted to build a ramp matching a built-in widget had to copy the characters out of the source.

One vocabulary fixes both. Widgets name the glyph they mean, applications and themes can reach the same names, and a variant ramp is built from the same pieces rather than retyped.

Pure String constants in tui-core, depending on nothing, so every tier can reach them. They are String rather than Char because that is what a Cell holds — a cell's content is a grapheme cluster, which can be more than one Char.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
Symbols.type
final case class Text(lines: Seq[Line], alignment: Option[Alignment] = ..., style: Style = ...)

Multi-line styled text.

Multi-line styled text.

alignment is the horizontal placement this text asks for, and None, the default, means "whatever the widget drawing me was told to use" — which is what every text did before this field existed. A Line that carries an alignment of its own still overrules it for that one row, so the resolution order a renderer follows is: the line's alignment first, then the text's, then the widget's own argument.

style is this text's base style, the outermost of the three layers that decide how a character is drawn — the text's style, then the Line's, then the Span's, each laid over the last with Style.patch so the more specific layer wins wherever it speaks and the outer one shows through wherever it stays silent. The widget's own style sits underneath all three. The default, Style.Default, sets nothing, so a text that does not use it renders exactly as it did before the layer existed.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Text

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Text.type

What Buffer.diff emits into the reserved continuation column of an emoji-presentation cluster — the clearEmojiTrailingCell workaround as a named choice rather than a Boolean.

What Buffer.diff emits into the reserved continuation column of an emoji-presentation cluster — the clearEmojiTrailingCell workaround as a named choice rather than a Boolean.

A cluster containing U+FE0F — the variation selector that asks for a character's colourful emoji form — is two columns wide by the Unicode rules this toolkit measures with, so the buffer reserves the column to its right as a continuation and never emits that column: painting the glyph paints both halves. Several terminals draw such a sequence in a single column anyway, and then the second column is never repainted at all, so whatever stood there in an earlier frame stays on screen next to the emoji.

Which policy is right is a backend's decision rather than the buffer's, because the opposite artifact is just as real: on a terminal that does draw both columns, an extra blank lands on the right half of the glyph and clips it. Only the code that knows which terminal it is talking to can pick the lesser of the two.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final case class Tween(from: Double, to: Double, duration: FiniteDuration, easing: Easing = ...)

A value animated from from to to over duration with an easing curve — for animating gauge ratios, offsets, and the like from onTick state.

A value animated from from to to over duration with an easing curve — for animating gauge ratios, offsets, and the like from onTick state.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

The line drawn under a cell's glyph, independent of the plain underline modifier.

The line drawn under a cell's glyph, independent of the plain underline modifier.

Straight mirrors the classic Modifiers.Underline; the richer variants use the colon-parameterised SGR 4 extension (4:2…4:5) that modern terminals (kitty, VTE, WezTerm, iTerm2) understand and older ones ignore.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
trait Versioned

A caller-owned mutable state that counts its own mutations.

A caller-owned mutable state that counts its own mutations.

Why this exists. The interactive widgets keep their selection, scroll offset and text in plain mutable objects the caller owns (ListState, TextInputState, TreeState, …), and a plain object cannot tell the reactive layer it changed. A mutation made outside the event path — a background result written into a list on the render thread — used to leave the previous frame on screen until something unrelated repainted. version is the smallest thing that lets an observer notice instead: a number that moves on every mutation, which the DSL compares against the value it saw when it last painted the state and turns into a frame when the two differ.

The interface lives in tui-core because the states live in tui-widgets, which cannot see tui-runtime; the observer that turns a moved version into a redraw lives above both.

'''Contract.''' version never decreases, and every public method or setter that changes what the state holds raises it. A setter raises it even when handed the value already there — telling the two apart would cost a comparison per write for nothing — while a method that finds nothing to do (a page move with paging off) may leave it alone. Two reads with nothing in between return the same number. A composite state (a dropdown wrapping a menu) answers the sum of its parts' versions, which is monotone for the same reason each part is.

'''Threads.''' The states are render-thread-only, and so is version; it is a plain field, not an atomic.

Attributes

Supertypes
class Object
trait Matchable
class Any
Known subtypes
trait VersionedState extends Versioned

The counter most states mix in: version is a field, and touch is what each mutating method calls.

The counter most states mix in: version is a field, and touch is what each mutating method calls.

Attributes

Supertypes
trait Versioned
class Object
trait Matchable
class Any
trait Widget

Something that can draw itself into a region of a frame buffer.

Something that can draw itself into a region of a frame buffer.

A single abstract method, so any (area, buffer) => () lambda is a valid widget. Implementations must confine their writes to area (the buffer clips stray writes, but relying on that is a defect) and must route all width/truncation math through CharWidth.

'''Threading and ownership.''' render is called on the thread that owns buffer — in a running application the runner's render thread, the same thread Signal writes are pinned to (see Buffer's ownership paragraph). Neither area nor buffer may be retained beyond the call: the runner reuses and resets its buffer between frames, so a stored reference is written to under a later frame's ownership and produces a torn frame rather than an error. Writing into buffer from any other thread is likewise a defect.

Attributes

Supertypes
class Object
trait Matchable
class Any
enum WidthMode

How to measure Unicode East Asian Ambiguous codepoints — box drawing, Greek and Cyrillic letters, the arrow block, ±, × and a few hundred more.

How to measure Unicode East Asian Ambiguous codepoints — box drawing, Greek and Cyrillic letters, the arrow block, ±, × and a few hundred more.

Unicode gives these characters no single width. A terminal configured for a Western locale draws them one column wide; one configured for a Chinese, Japanese or Korean locale draws the same characters two columns wide, because the CJK fonts they use have full-width glyphs for them. Nothing an application sends can tell the emulator which to do, and nothing it receives says which was chosen — the choice lives in the user's terminal settings and font.

This is a measurement policy, not a rendering policy. Everything glyphora lays out and draws uses Narrow, and that does not change: a widget and the buffer it clips against have to agree on every column, so the answer the renderer uses has exactly one source. Passing Wide to the width functions that accept a mode answers a different question — "how many columns would a CJK-locale terminal give this text?" — which is what an application needs to detect the mismatch and compensate, for example by choosing ASCII borders or by leaving a margin.

The values are a sealed enumeration rather than a boolean flag so that a call site says which policy it means: CharWidth.of(text, WidthMode.Wide) reads as an answer about a locale, where CharWidth.of(text, true) would read as an answer about nothing in particular.

Attributes

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Types

opaque type KeyModifiers

Modifier keys held during a key or mouse event, packed into an Int bitset (same pattern as Modifiers; the arithmetic itself is FlagBits, shared between the two).

Modifier keys held during a key or mouse event, packed into an Int bitset (same pattern as Modifiers; the arithmetic itself is FlagBits, shared between the two).

Attributes

opaque type Modifiers

Text-attribute flags (bold, italic, …) packed into an Int bitset.

Text-attribute flags (bold, italic, …) packed into an Int bitset.

An opaque bitset rather than a Set[Modifier] on purpose: Style values are created per-cell, potentially thousands of times per frame, so Style must stay a small value with no boxed collection inside.

Attributes

Extensions

Extensions

extension (inline context: StringContext)
inline def hex(inline args: Any*): Color

The hex"#ff8800" literal: a hex colour checked by the compiler instead of at run time.

The hex"#ff8800" literal: a hex colour checked by the compiler instead of at run time.

Color.hex has to return an Option, because the string it is handed can come from a configuration file or a command-line flag and may well be malformed. But the overwhelmingly common case is a literal the author typed, and there the Option is pure friction: every call site ends in .get, .getOrElse(Color.Red) or a pattern match that can never take its other branch, and a typo is still only found when that line of code happens to run.

This interpolator moves both problems to compile time. hex"#ff8800" is checked while the file is compiled — a malformed literal is a compile error naming the offending string — and it expands to the constant Color.Rgb(255, 136, 0), so there is no Option to unwrap and no parsing left to do when the program runs.

import io.worxbend.tui.core.hex

val brand = hex"#c83232"     // Color.Rgb(200, 50, 50), checked by the compiler
val short = hex"#f80"        // the three-digit form expands the same way Color.hex does
// val oops = hex"#ff88"     // does not compile: "#ff88" is not a 3- or 6-digit hex colour

Accepts exactly what Color.hex accepts: #rrggbb, rrggbb, #rgb or rgb, case-insensitive, the leading # optional. Interpolated values are rejected, because a value that is not known until the program runs cannot be checked while it is compiled — reach for Color.hex there and handle the None the way the rest of your input handling does.

This is compile-time expansion, not runtime reflection: nothing here survives into the produced class files beyond the Color.Rgb constant, so native images stay free of reflection configuration.

Attributes

extension (inline sc: StringContext)
inline def key(inline args: Any*): KeyEvent

A key spec checked when the code is compiled rather than when it runs.

A key spec checked when the code is compiled rather than when it runs.

key"ctrl+s" is the same value KeyEvent.parse("ctrl+s") returns, except that a spec the parser rejects — a misspelt modifier (ctlr+s), a key name that does not exist, or one of the Ctrl combinations no terminal can deliver — stops the build with the parser's own message, instead of throwing the first time the binding is declared or silently declaring a key that can never fire.

Only a literal can be checked, because only a literal is known while the code is being compiled. An interpolation with a $ hole in it, or a spec read from a config file at run time, is a compile error here and must keep going through KeyEvent.parse, which reports the same problem as a Left.

The result costs nothing at run time: the parse happens during compilation and what is left in the compiled code is the constructor call for the event the spec named.

Attributes

extension (inline sc: StringContext)
inline def markup(inline args: Any*): Text

markup"[bold red]error[/] in [link=$url]$file[/]" — inline styling in a string literal, checked when the code is compiled.

markup"[bold red]error[/] in [link=$url]$file[/]" — inline styling in a string literal, checked when the code is compiled.

A tag is written in square brackets and holds one or more space-separated words; it styles everything up to the matching [/], and tags nest, each inner one layered onto the outer with Style.patch. The words are:

  • '''attributes''': bold, dim, italic, underline, blink, reverse, hidden, strike; underline=double, underline=curly, underline=dotted, underline=dashed for a styled underline;
  • '''colours''', in any spelling Color.parse reads — red, bright_cyan, #ff8800, 208 — plus ansi(n) for a palette index that reads as one at a glance. A bare colour is the foreground; on is the background, so [red on blue] is red text on blue. fg= and bg= are the explicit forms;
  • link=, an OSC 8 hyperlink, carried on Style.link.

[/] closes the innermost open tag. A named close — [/bold], [/bold red], [/link] for a [link=…] — closes it too, and is checked: it must name the innermost open tag (its words as written, ignoring case and spacing, or the key of a single key=value word), so [bold][red]x[/bold] is a compile error rather than a silent mis-nesting. [[ is a literal [; a ] outside a tag is already literal and needs no escaping. The usual string escapes work, and a \n in a literal or interpolated value starts a new row of the resulting Text.

An interpolated $value is '''text, never markup''': whatever it contains — [red] included — is rendered as the characters it is, in the style in force where it appears. That is what makes it safe to write markup"[bold]$input[/]" over input the program did not author. A value may also stand as the whole value of a link=, fg= or bg= word — [link=$url], [fg=$colour] — where it must be a String for a link and a Color for a colour, and the compiler checks that too.

Every error in the literal parts — a word that is not a style ([bogus]), a tag that is never closed, a [/] with nothing to close, a named close that names some other tag, a [ with no ] — stops the build with a message naming it, instead of being found the first time that view is drawn. What survives into the compiled code is the constructor calls for the spans, with every literal style already a constant: nothing is parsed when the program runs, and nothing is reflected over.

Attributes