diff --git a/.changeset/color-encoding-tiers.md b/.changeset/color-encoding-tiers.md new file mode 100644 index 0000000..97b1ed8 --- /dev/null +++ b/.changeset/color-encoding-tiers.md @@ -0,0 +1,20 @@ +--- +'@bomb.sh/tty': minor +--- + +Adds capability-aware SGR color encoding to the renderer. + +The renderer now derives its color encoding from terminal capability evidence instead of always emitting 24-bit truecolor. Terminals with truecolor evidence (`RGB`/`Tc`, `COLORTERM`, direct-color `max_colors`, or a `colordepth` probe folded through `term.update()`) continue to receive byte-identical truecolor output. Without truecolor evidence, cells emit 256-color SGR (`\x1b[38;5;Nm`) when `colors > 16`, or 4-bit SGR (`\x1b[31m`) at or below 16. Colors are downmapped deterministically. In 256-color output, RGB colors map onto the 6×6×6 cube and grayscale ramp (`rgba(255, 0, 0)` → `\x1b[38;5;196m`), never onto indices 0–15, which follow the terminal's theme. In 16-color output, they map to the nearest standard palette entry. Use the `-ansi-*` keywords when you want the terminal's own palette colors. A tier change between frames forces a complete redraw. + +The baseline — no capability evidence — now resolves to 256-color rather than truecolor. Pass `detectTerminal()` output to `createTerm` to restore truecolor output on terminals that support it. + +#### Migration + +```diff + import { createTerm } from "@bomb.sh/tty"; ++ import { detectTerminal } from "@bomb.sh/tty"; + +- const term = await createTerm({ width, height }); ++ const terminfo = await detectTerminal(); ++ const term = await createTerm({ width, height, terminfo }); +``` diff --git a/specs/color-encoding-spec.md b/specs/color-encoding-spec.md new file mode 100644 index 0000000..4b1b8d9 --- /dev/null +++ b/specs/color-encoding-spec.md @@ -0,0 +1,193 @@ +# Clayterm Color Encoding Specification + +**Version:** 0.1 (draft) **Status:** Proposed. Normative for the SGR color +encoding of rendered cells. + +--- + +## 1. Purpose + +The renderer encodes every non-default cell color as an SGR sequence. This +specification defines which encoding the renderer emits for a given capability +snapshot, and how 24-bit colors map into the 256-color and 16-color palettes +when the terminal lacks truecolor support. + +The capability snapshot ([terminfo-spec.md](terminfo-spec.md)) is the only input +that selects the encoding. There is no caller-facing override: callers control +the encoding by supplying capability evidence, either a terminfo entry at +creation or probe responses folded through `update()`. + +--- + +## 2. Scope + +### In scope + +- How `trueColor` and `colors` in the capability snapshot select the encoding + tier +- The SGR format for foreground and background colors in each tier +- The mapping from 24-bit RGB to the 256-color and 16-color palettes +- Output when the tier changes between renders + +### Out of scope + +- **The terminal's palette.** The renderer emits palette _indices_. How a + terminal renders index N is the terminal's concern. +- **An 8-color tier.** Terminals reporting fewer than 16 colors use the 16-color + tier (§5). +- **88-color precision.** Terminals reporting `17 ≤ colors ≤ 255` use the + 256-color tier (§5). + +--- + +## 3. Terminology + +**Color tier.** One of `"truecolor" | "256" | "16"`, the `ColorDepth` type +defined in [terminfo-spec.md](terminfo-spec.md) §6.2. The tier names the +emission encoding, not the terminal's full capability set. + +**Downmapping.** Producing the SGR sequence that represents a 24-bit RGB color +under a narrower tier. + +**Nominal palette.** The 16-entry RGB table defined in §7.1. It is the +renderer's model of what each 4-bit index means when the `"16"` tier picks the +nearest index. It is not a claim about any terminal's actual palette. + +**Fixed color.** An sRGB value. Its intended appearance does not depend on the +terminal's theme, unlike a terminal-themed color (renderer-spec §8.5). + +--- + +## 4. Invariants + +- **CI-1 — Total, deterministic resolution.** Every capability snapshot resolves + to exactly one tier by the rule in §5. The tier depends only on the capability + snapshot; resizing the Term does not change it. +- **CI-2 — Truecolor is exact.** Under the `"truecolor"` tier, every RGB color + is emitted with its exact channel values. +- **CI-3 — Deterministic downmapping.** Every downmapping decision in §7 is a + pure function of the RGB value and the tier. Ties resolve to the lowest index. +- **CI-4 — Fixed colors stay off the themed palette where possible.** Under the + `"256"` tier, an sRGB color never maps to indices 0–15, which the terminal's + theme controls. Every color of the cube or grayscale ramp (indices 16–255) + maps to its own index. Under the `"16"` tier no fixed alternative exists, so + an sRGB color maps to the nearest nominal palette entry, and every nominal + palette entry maps to its own index. +- **CI-5 — Tier change redraws.** When the tier differs from the previous + render's tier, the next render emits every cell, encoded in the new tier. +- **CI-6 — Terminal-themed colors are tier-independent.** Terminal default and + palette colors emit as renderer-spec §8.5 specifies, identically in every + tier. Style attributes (bold, dim, italic, underline, blink, reverse, + strikeout) also emit identically in every tier. + +--- + +## 5. Tier resolution + +The renderer resolves the tier from the capability snapshot: + +``` +tier = + trueColor ? "truecolor" + : colors <= 16 ? "16" + : "256" +``` + +The `colors ≤ 16` boundary matches the denial mapping in terminfo-spec §6.3, so +the tier agrees with a `colordepth` denial event for every static `colors` +value. A `colordepth` probe event folds into `trueColor`; no other fold changes +the tier. + +- `colors` values below 16, including a missing `max_colors` (0), resolve to the + `"16"` tier. +- Truecolor requires positive evidence (terminfo-spec §7.1): the `RGB`/`Tc` + terminfo extension, `COLORTERM`, a direct-color entry (`max_colors ≥ 2²⁴`), or + a `colordepth` probe response. +- With no evidence (the terminfo-spec §7.1 baseline), the tier is `"256"`. + +--- + +## 6. Emission formats + +For a non-default foreground or background under each tier: + +| Tier | Foreground | Background | +| ------------- | --------------------------------------------- | ---------------------------------------------- | +| `"truecolor"` | `\x1b[38;2;R;G;Bm` | `\x1b[48;2;R;G;Bm` | +| `"256"` | `\x1b[38;5;Nm`, N ∈ 0–255 | `\x1b[48;5;Nm`, N ∈ 0–255 | +| `"16"` | index 0–7: `\x1b[3Nm`; index 8–15: `\x1b[9Nm` | index 0–7: `\x1b[4Nm`; index 8–15: `\x1b[10Nm` | + +In the `"16"` tier, `N` is the palette index for indices 0–7 and `index − 8` for +indices 8–15. Standard red (index 1) emits `\x1b[31m` foreground and `\x1b[41m` +background. + +--- + +## 7. Downmapping + +### 7.1 Nominal palette + +| Index | RGB | Name | Index | RGB | Name | +| ----- | --------- | ------- | ----- | --------- | -------------- | +| 0 | `#000000` | black | 8 | `#808080` | bright black | +| 1 | `#ff0000` | red | 9 | `#ff5555` | bright red | +| 2 | `#00ff00` | green | 10 | `#55ff55` | bright green | +| 3 | `#ffff00` | yellow | 11 | `#ffff55` | bright yellow | +| 4 | `#0000ff` | blue | 12 | `#5555ff` | bright blue | +| 5 | `#ff00ff` | magenta | 13 | `#ff55ff` | bright magenta | +| 6 | `#00ffff` | cyan | 14 | `#55ffff` | bright cyan | +| 7 | `#c0c0c0` | white | 15 | `#ffffff` | bright white | + +The primaries (1–6) are the pure hues and the bright variants are their pastel +counterparts. The `"16"` tier uses this table to choose the nearest index +(§7.2); the `"256"` tier does not use it. + +In the `"16"` tier, the named color `red` and `-ansi-red` both emit palette 1, +because the tier has no other way to show red. The terminal's theme decides what +palette 1 looks like. In the `"256"` and `"truecolor"` tiers, `red` is a fixed +color, while `-ansi-red` is palette 1 in every tier (§7.4). + +### 7.2 `"16"` tier + +Map the RGB value to the nearest nominal palette entry by squared Euclidean +distance over the three channels. On a tie, choose the lowest index. + +### 7.3 `"256"` tier + +The tier maps sRGB colors only onto the 6×6×6 cube (indices 16–231) and the +grayscale ramp (indices 232–255). It never emits indices 0–15, because the +terminal's theme controls them. Standard red emits `\x1b[38;5;196m`. + +The first matching rule wins: + +1. **Exact cube match.** If every channel is one of the six cube values + `{0, 95, 135, 175, 215, 255}`, emit `16 + 36r + 6g + b` for the channels' + cube steps. Gray cube values such as `#5f5f5f` resolve here. +2. **Grayscale.** If `r == g == b`, choose the nearest value among the grayscale + ramp `{8 + 10i : 0 ≤ i ≤ 23}` extended by the endpoints `0` (index 16) and + `255` (index 231). On a tie, choose the lower index. Emit `232 + i` for ramp + value `8 + 10i`, `16` for the low endpoint, and `231` for the high endpoint. +3. **Cube nearest.** Otherwise, map each channel to the nearest cube value (ties + to the smaller value) and emit `16 + 36r + 6g + b`. + +### 7.4 Resolved colors + +The tier applies to a cell's resolved color, after the render-time field +resolution of renderer-spec §8.5 (foreground inheritance, `currentcolor`, and +system colors). A resolved color is one of: + +- **sRGB.** Encoded for the active tier by §6 and §7. This includes a + cross-field `Canvas` or `CanvasText` resolved to a probed theme color, and a + `currentcolor` or inherited color that resolves to sRGB. +- **Terminal default or palette entry.** Not downmapped. It emits as + renderer-spec §8.5 specifies, in every tier (CI-6). + +Downmapping reads only a color's RGB channels and never alters style attribute +emission. + +--- + +## 8. Tier changes + +An `update()` that changes the tier returns no bytes (renderer-spec §7.7). The +next render emits a complete redraw in the new tier (CI-5). diff --git a/specs/renderer-spec.md b/specs/renderer-spec.md index 97925e1..92e3198 100644 --- a/specs/renderer-spec.md +++ b/specs/renderer-spec.md @@ -471,12 +471,9 @@ is valid until the next `render()` **or** `update()` call). The renderer consumes the read-only capability snapshot maintained by `Term.update()`. A protocol that changes emitted bytes MUST define its gating capability, output, and invalidation rules in its own section of this -specification. Synchronized output (§7.9) and pointer shape (§7.10) are -specified so far. - -Color encoding, Kitty keyboard mode setup, and Kitty graphics emission are -deferred to their respective follow-up PRs. The renderer continues to emit its -existing hardcoded ANSI output until each is specified. +specification or a companion specification: synchronized output (§7.9), pointer +shape (§7.10), and color encoding +([Color Encoding Specification](color-encoding-spec.md)). ### 7.9 Synchronized output (DEC mode 2026) @@ -601,7 +598,9 @@ parameters specify the terminal dimensions in character cells. The optional `terminfo` value (from `detectTerminal()`; see [Terminfo Specification](terminfo-spec.md) §10.1) initializes the Term's private `RuntimeCapabilities` from the static `Capabilities` it carries. When omitted, -the Term uses the §7.1 baseline. +the Term uses the §7.1 baseline. The renderer resolves its color encoding from +this capability snapshot; the derivation rule and downmapping behavior are +specified in the [Color Encoding Specification](color-encoding-spec.md). ### 8.2 Render invocation @@ -855,16 +854,17 @@ The renderer reads this from the OSC 10/11 theme probe, surfaced as `RuntimeCapabilities.theme.foreground` / `.background` (terminfo-spec §6.4), using the theme in effect when the frame renders. The result is an ordinary opaque sRGB color (alpha 255): it renders exactly like the equivalent `rgba()` -value, as truecolor. When the theme has not yet reported that color, the keyword -falls back to its field's own terminal default instead (the same-field behavior -above). A theme report that `update()` folds in after a frame renders takes -effect starting with the next render. +value, encoded for the active color tier +([Color Encoding Specification](color-encoding-spec.md) §5). When the theme has +not yet reported that color, the keyword falls back to its field's own terminal +default instead (the same-field behavior above). A theme report that `update()` +folds in after a frame renders takes effect starting with the next render. For example, once the terminal has reported its default foreground color, -`text({ bg: "CanvasText" })` paints that color as an opaque truecolor -background. Until then it falls back to the default background: a terminal -offers no way to paint its default foreground color as a cell background without -knowing its RGB value, and the renderer never guesses one. +`text({ bg: "CanvasText" })` paints that color as an opaque background. Until +then it falls back to the default background: a terminal offers no way to paint +its default foreground color as a cell background without knowing its RGB value, +and the renderer never guesses one. A terminal-themed color (a same-field default, or a palette entry) is opaque. A palette color in a foreground field is emitted as SGR `30`–`37` for palette 0–7 @@ -881,8 +881,9 @@ including cells an enclosing element painted. This is distinct from an omitted Cell diffing treats terminal-themed colors like any other attribute: a cell whose color changes between a palette color, a terminal default, and an sRGB color in consecutive frames MUST be re-emitted, and an unchanged cell MUST NOT -be. The renderer does not resolve a palette color to RGB to compare it with an -sRGB color. +be, except after a color tier change +([Color Encoding Specification](color-encoding-spec.md) CI-5). The renderer does +not resolve a palette color to RGB to compare it with an sRGB color. Transitions have special considerations for terminal-themed colors; see Transitions Specification §7.4. diff --git a/src/clayterm.c b/src/clayterm.c index d9cc79f..d5bb115 100644 --- a/src/clayterm.c +++ b/src/clayterm.c @@ -44,6 +44,8 @@ struct Clayterm { * CLAYTERM_THEME_KNOWN | 0xRRGGBB, or 0 until reported. Retained across * resize updates. */ uint32_t theme_fg, theme_bg; + /* max_colors evidence; the terminfo-spec §7.1 baseline is 256. */ + uint32_t colors; }; /* 128 bytes per cell: ~84 bytes worst-case for CUP + SGR sequences, plus up @@ -148,6 +150,128 @@ static void append_combining(struct Clayterm *ct, int x, int y, uint32_t cp) { report_combining_exceeded(ct); } +/* ── Color tiers and downmapping ──────────────────────────────────── */ + +/* Emission tiers (color-encoding-spec §5). */ +#define TIER_TRUECOLOR 0 +#define TIER_256 1 +#define TIER_16 2 + +/* Nominal 16-color palette (color-encoding-spec §7.1): the "16" tier's + * model of what each 4-bit index means when choosing the nearest one. + * Not a claim about any terminal's actual palette. */ +static const uint32_t NOMINAL_PALETTE[16] = { + 0x000000, 0xff0000, 0x00ff00, 0xffff00, 0x0000ff, 0xff00ff, + 0x00ffff, 0xc0c0c0, 0x808080, 0xff5555, 0x55ff55, 0xffff55, + 0x5555ff, 0xff55ff, 0x55ffff, 0xffffff, +}; + +/* 6x6x6 color cube channel values (indices 16-231). */ +static const int CUBE_STEPS[6] = {0, 95, 135, 175, 215, 255}; + +/* Resolve the emission tier from the capability evidence pushed by the + * host (color-encoding-spec §5). The colors <= 16 boundary matches the + * colordepth denial mapping in terminfo-spec §6.3. */ +static int resolve_tier(const struct Clayterm *ct) { + if (ct->caps & RENDER_CAP_TRUE_COLOR) + return TIER_TRUECOLOR; + if (ct->colors <= 16) + return TIER_16; + return TIER_256; +} + +/* Nearest nominal palette entry by squared Euclidean distance; ties + * resolve to the lowest index (color-encoding-spec §7.2). */ +static int map_16(uint32_t rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + int best = 0; + int best_dist = -1; + for (int i = 0; i < 16; i++) { + uint32_t c = NOMINAL_PALETTE[i]; + int dr = r - (int)((c >> 16) & 0xff); + int dg = g - (int)((c >> 8) & 0xff); + int db = b - (int)(c & 0xff); + int dist = dr * dr + dg * dg + db * db; + if (best_dist < 0 || dist < best_dist) { + best_dist = dist; + best = i; + } + } + return best; +} + +/* The cube step for an exact cube value, or -1 when the value is not a + * cube channel value. */ +static int cube_exact(int v) { + for (int i = 0; i < 6; i++) { + if (CUBE_STEPS[i] == v) + return i; + } + return -1; +} + +/* Nearest cube step for an arbitrary channel value; ties resolve to the + * smaller value (color-encoding-spec §7.3 rule 4). */ +static int cube_step(int v) { + int best = 0; + int best_dist = -1; + for (int i = 0; i < 6; i++) { + int d = v - CUBE_STEPS[i]; + if (d < 0) + d = -d; + if (best_dist < 0 || d < best_dist) { + best_dist = d; + best = i; + } + } + return best; +} + +/* Downmap a 24-bit RGB value to a 256-palette index in 16-255, leaving + * the theme-controlled 0-15 alone. Ordered rules; the first match wins + * (color-encoding-spec §7.3). */ +static int map_256(uint32_t rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + + /* 1. exact cube match */ + int cr = cube_exact(r); + int cg = cube_exact(g); + int cb = cube_exact(b); + if (cr >= 0 && cg >= 0 && cb >= 0) + return 16 + 36 * cr + 6 * cg + cb; + + /* 2. grayscale: nearest of the ramp extended by both endpoints. + * Candidates run in ascending index order (16, 231, 232..255), so a + * strict comparison resolves ties to the lowest index. */ + if (r == g && g == b) { + int best = 16; + int best_dist = r; /* value 0 at index 16 */ + int d = 255 - r; /* value 255 at index 231 */ + if (d < best_dist) { + best = 231; + best_dist = d; + } + for (int i = 0; i < 24; i++) { + int val = 8 + 10 * i; + d = r - val; + if (d < 0) + d = -d; + if (d < best_dist) { + best = 232 + i; + best_dist = d; + } + } + return best; + } + + /* 3. nearest cube value per channel */ + return 16 + 36 * cube_step(r) + 6 * cube_step(g) + cube_step(b); +} + /* ── Escape sequence generation ───────────────────────────────────── */ static void emit_palette(Buffer *out, int index, int base, int bright) { @@ -156,6 +280,39 @@ static void emit_palette(Buffer *out, int index, int base, int bright) { buf_put(out, "m", 1); } +/* Emit the SGR color sequence for one packed RGB value under the active + * tier (color-encoding-spec §6). `is_fg` selects the foreground + * (38, 3x/9x) or background (48, 4x/10x) code family. */ +static void emit_sgr_color(struct Clayterm *ct, uint32_t rgb, int is_fg) { + Frame *frame = ct->frames.current; + Buffer *out = &frame->context->output; + switch (frame->color_tier) { + case TIER_16: { + int idx = map_16(rgb); + int base = is_fg ? 30 : 40; + if (idx >= 8) + base += 60; /* aixterm bright codes: 90-97 / 100-107 */ + buf_str(out, "\x1b["); + buf_num(out, base + (idx & 7)); + buf_put(out, "m", 1); + break; + } + case TIER_256: + buf_str(out, is_fg ? "\x1b[38;5;" : "\x1b[48;5;"); + buf_num(out, map_256(rgb)); + buf_put(out, "m", 1); + break; + default: /* TIER_TRUECOLOR */ + buf_str(out, is_fg ? "\x1b[38;2;" : "\x1b[48;2;"); + buf_num(out, (rgb >> 16) & 0xff); + buf_put(out, ";", 1); + buf_num(out, (rgb >> 8) & 0xff); + buf_put(out, ";", 1); + buf_num(out, rgb & 0xff); + buf_put(out, "m", 1); + } +} + static void emit_attr(struct Clayterm *ct, uint32_t fg, uint32_t bg) { Frame *frame = ct->frames.current; Buffer *out = &frame->context->output; @@ -181,18 +338,12 @@ static void emit_attr(struct Clayterm *ct, uint32_t fg, uint32_t bg) { if (fg & ATTR_STRIKEOUT) buf_str(out, "\x1b[9m"); - /* foreground: palette, truecolor, or default (left by the reset) */ + /* foreground: palette, tiered RGB, or default (left by the reset) */ if (fg & ATTR_DEFAULT) { if (fg & ATTR_PALETTE) emit_palette(out, (int)(fg & 0xff), 30, 90); } else { - buf_str(out, "\x1b[38;2;"); - buf_num(out, (fg >> 16) & 0xff); - buf_put(out, ";", 1); - buf_num(out, (fg >> 8) & 0xff); - buf_put(out, ";", 1); - buf_num(out, fg & 0xff); - buf_put(out, "m", 1); + emit_sgr_color(ct, fg & COLOR_MASK, 1); } /* background: same */ @@ -200,13 +351,7 @@ static void emit_attr(struct Clayterm *ct, uint32_t fg, uint32_t bg) { if (bg & ATTR_PALETTE) emit_palette(out, (int)(bg & 0xff), 40, 100); } else { - buf_str(out, "\x1b[48;2;"); - buf_num(out, (bg >> 16) & 0xff); - buf_put(out, ";", 1); - buf_num(out, (bg >> 8) & 0xff); - buf_put(out, ";", 1); - buf_num(out, bg & 0xff); - buf_put(out, "m", 1); + emit_sgr_color(ct, bg & COLOR_MASK, 0); } frame->emission.lastfg = fg; @@ -812,6 +957,7 @@ struct Clayterm *clayterm_init(void *mem, int w, int h, int runlist_capacity) { struct Clayterm *ct = (struct Clayterm *)mem; *ct = (struct Clayterm){0}; ct->runlist_capacity = (uint32_t)runlist_capacity; + ct->colors = 256; /* §7.1 baseline until the host pushes evidence */ char *base = (char *)ct + align8(sizeof(struct Clayterm)); frame_context_init(&ct->frames, base, ct->runlist_capacity); clayterm_resize(ct, w, h); @@ -866,7 +1012,10 @@ void clayterm_resize(struct Clayterm *ct, int w, int h) { cells_fill(ct->frames.previous->cells, w, h, 0, 0, 0); } -void set_capabilities(struct Clayterm *ct, uint32_t caps) { ct->caps = caps; } +void set_capabilities(struct Clayterm *ct, uint32_t caps, uint32_t colors) { + ct->caps = caps; + ct->colors = colors; +} void set_theme(struct Clayterm *ct, uint32_t fg, uint32_t bg) { ct->theme_fg = fg; @@ -1413,6 +1562,13 @@ static void draw_current_frame(struct Clayterm *ct, static void write_current_frame(struct Clayterm *ct, int mode, int row) { Frame *frame = ct->frames.current; Buffer *out = &frame->context->output; + + /* A tier change forces a complete redraw (color-encoding-spec CI-5): + * zeroing the diff baseline makes every cell diff as changed. */ + frame->color_tier = resolve_tier(ct); + if (frame->color_tier != ct->frames.previous->color_tier) + cells_fill(ct->frames.previous->cells, ct->w, ct->h, 0, 0, 0); + if (mode == 1) { present_lines(ct); } else { diff --git a/src/clayterm.h b/src/clayterm.h index 9af5161..fd302d9 100644 --- a/src/clayterm.h +++ b/src/clayterm.h @@ -12,6 +12,7 @@ struct Clayterm; /* Capability bits for set_capabilities(). */ #define RENDER_CAP_SYNC_OUTPUT (1u << 0) #define RENDER_CAP_POINTER_SHAPE (1u << 1) +#define RENDER_CAP_TRUE_COLOR (1u << 2) /* Packed directives and their property-group masks. */ #define CLAYTERM_OP_OPEN_ELEMENT 0x02 @@ -50,7 +51,7 @@ struct Clayterm; int clayterm_size(int w, int h, int runlist_capacity); struct Clayterm *clayterm_init(void *mem, int w, int h, int runlist_capacity); void clayterm_resize(struct Clayterm *ct, int w, int h); -void set_capabilities(struct Clayterm *ct, uint32_t caps); +void set_capabilities(struct Clayterm *ct, uint32_t caps, uint32_t colors); void set_theme(struct Clayterm *ct, uint32_t fg, uint32_t bg); int reduce(struct Clayterm *ct, uint32_t *buf, int len, int mode, int row, float deltaTime, float px, float py, int pointer); diff --git a/src/frame.h b/src/frame.h index 40b727e..462f847 100644 --- a/src/frame.h +++ b/src/frame.h @@ -176,6 +176,11 @@ typedef struct { * (default). Inherited from previous until a shape change is emitted. */ uint8_t pointer_shape; + /* Color encoding tier this frame's output was emitted in, resolved from + * the capability snapshot before presentation. A tier that differs from + * previous forces a complete redraw. */ + uint8_t color_tier; + /* Caret declaration and placement state, reset on frame reuse or resize. */ CaretState caret; diff --git a/term-native.ts b/term-native.ts index 057a789..631801d 100644 --- a/term-native.ts +++ b/term-native.ts @@ -53,10 +53,13 @@ function themeWord(rgb: RenderRgb | undefined): number { export interface RenderCapabilities { syncOutput: boolean; pointerShape: boolean; + colors: number; + trueColor: boolean; } const RENDER_CAP_SYNC_OUTPUT = 1 << 0; const RENDER_CAP_POINTER_SHAPE = 1 << 1; +const RENDER_CAP_TRUE_COLOR = 1 << 2; /** Pointer passed to reduce(): absent, up, or down. */ export const POINTER_ABSENT = 0; @@ -164,7 +167,7 @@ export async function createTermNative( ): number; output(ct: number): number; length(ct: number): number; - set_capabilities(ct: number, caps: number): void; + set_capabilities(ct: number, caps: number, colors: number): void; set_theme(ct: number, fg: number, bg: number): void; pointer_over_count(ct: number): number; pointer_over_id_string_length(ct: number, index: number): number; @@ -192,8 +195,9 @@ export async function createTermNative( let opsBuf = 0; function setCaps(next: RenderCapabilities): void { let flags = (next.syncOutput ? RENDER_CAP_SYNC_OUTPUT : 0) | - (next.pointerShape ? RENDER_CAP_POINTER_SHAPE : 0); - ct.set_capabilities(statePtr!, flags); + (next.pointerShape ? RENDER_CAP_POINTER_SHAPE : 0) | + (next.trueColor ? RENDER_CAP_TRUE_COLOR : 0); + ct.set_capabilities(statePtr!, flags, next.colors); } // Native storage keeps both frames' runlists and metadata before the cells, diff --git a/term.ts b/term.ts index 6defecd..9d7cd89 100644 --- a/term.ts +++ b/term.ts @@ -189,6 +189,8 @@ export async function createTerm(options: TermOptions): Promise { let native = await createTermNative(width, height, { syncOutput: currentCaps.syncOutput, pointerShape: currentCaps.pointerShape, + colors: currentCaps.colors, + trueColor: currentCaps.trueColor, }); let { memory } = native; @@ -330,13 +332,19 @@ export async function createTerm(options: TermOptions): Promise { } } + // A color change resolves a new tier on the next render, which + // forces a complete redraw (color-encoding-spec §8). if ( next.syncOutput !== currentCaps.syncOutput || - next.pointerShape !== currentCaps.pointerShape + next.pointerShape !== currentCaps.pointerShape || + next.colors !== currentCaps.colors || + next.trueColor !== currentCaps.trueColor ) { native.setCapabilities({ syncOutput: next.syncOutput, pointerShape: next.pointerShape, + colors: next.colors, + trueColor: next.trueColor, }); } if ( diff --git a/test/border.test.ts b/test/border.test.ts index 79c083e..b134462 100644 --- a/test/border.test.ts +++ b/test/border.test.ts @@ -8,6 +8,7 @@ import { text, } from "../ops.ts"; import { createTerm } from "../term.ts"; +import { TRUECOLOR_INFO } from "./caps.ts"; import { describe, expect, it } from "./suite.ts"; import { print } from "./print.ts"; @@ -120,7 +121,11 @@ type OpenProps = Omit; * mode and parses the full-frame output into cells. Box corners are at * (0,0), (7,0), (0,3), (7,3). */ async function renderBox(props: OpenProps): Promise { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("box", { @@ -269,7 +274,11 @@ describe("structured sides", () => { }); it("does not retain a prior frame's side bg", async () => { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let frame = (bg?: number) => [ open("box", { layout: { width: fixed(8), height: fixed(4) }, @@ -455,8 +464,16 @@ describe("directive model", () => { describe("instances", () => { it("does not share side attributes between Term instances", async () => { - let a = await createTerm({ width: 12, height: 5 }); - let b = await createTerm({ width: 12, height: 5 }); + let a = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); + let b = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let frame = (top: number, bottom: number) => [ open("box", { @@ -495,7 +512,11 @@ const trim = (s: string) => s.split("\n").map((l) => l.trimEnd()).join("\n"); describe("box model", () => { it("full border with no padding reserves space: children visible, box is 3 rows", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -514,7 +535,11 @@ describe("box model", () => { }); it("partial borders (top+left) reserve only their sides", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -534,7 +559,11 @@ describe("box model", () => { }); it("padding is additive: border=1 alone gives height 3; border=1 plus padding=1 gives height 5", async () => { - let nopad = await createTerm({ width: 20, height: 10 }); + let nopad = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let r1 = nopad.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -548,7 +577,11 @@ describe("box model", () => { close(), ]); - let withpad = await createTerm({ width: 20, height: 10 }); + let withpad = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let r2 = withpad.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -573,7 +606,11 @@ describe("box model", () => { }); it("explicit padding > border width adds breathing room inside the border", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -597,7 +634,11 @@ describe("box model", () => { }); it("nested two-tone bevel lays out without manual padding compensation", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, @@ -623,7 +664,11 @@ describe("box model", () => { }); it("visual: full border renders border glyphs around content", async () => { - let term = await createTerm({ width: 20, height: 10 }); + let term = await createTerm({ + width: 20, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let out = trim( print( decode( @@ -725,7 +770,11 @@ describe("system colors", () => { }); it("renders a probed default background as a truecolor border side fg once the theme reports it", async () => { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -751,7 +800,11 @@ describe("system colors", () => { describe("currentcolor", () => { it("defaults border.color to currentcolor, inherited from an ancestor open", async () => { - let term = await createTerm({ width: 12, height: 5 }); + let term = await createTerm({ + width: 12, + height: 5, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: RED }), diff --git a/test/caps.ts b/test/caps.ts index ef81681..bef3d05 100644 --- a/test/caps.ts +++ b/test/caps.ts @@ -1,4 +1,8 @@ -import { type DetectOptions, detectTerminal } from "../terminfo.ts"; +import { + type DetectOptions, + detectTerminal, + type TerminalInfo, +} from "../terminfo.ts"; export function offlineDetect(options: Partial = {}) { return detectTerminal({ env: {}, ...options }); @@ -8,3 +12,23 @@ export function offlineDetect(options: Partial = {}) { export function trueColorDetect() { return offlineDetect({ env: { COLORTERM: "truecolor" } }); } + +/** Static truecolor evidence with no probe or key payload. Tests that pin + * truecolor byte sequences pass this at createTerm to select the truecolor + * tier (color-encoding-spec §5): without evidence the renderer resolves the + * 256-color baseline tier. */ +export const TRUECOLOR_INFO: TerminalInfo = Object.freeze({ + capabilities: Object.freeze({ + colors: 256, + trueColor: true, + bce: true, + autoMargin: true, + xenl: true, + altScreen: true, + styledUnderline: false, + syncOutput: false, + pointerShape: false, + }), + probe: new Uint8Array(0), + keys: new Uint8Array(0), +}); diff --git a/test/color-encoding-modes.test.ts b/test/color-encoding-modes.test.ts new file mode 100644 index 0000000..c4f232a --- /dev/null +++ b/test/color-encoding-modes.test.ts @@ -0,0 +1,386 @@ +// deno-lint-ignore-file no-control-regex +import { describe, expect, it } from "./suite.ts"; +import { createTerm } from "../term.ts"; +import type { TerminalInfo } from "../terminfo.ts"; +import { close, fixed, grow, type Op, open, rgba, text } from "../ops.ts"; + +const decode = (b: Uint8Array) => new TextDecoder().decode(b); + +/** Static capability evidence with a chosen `colors` value and optional + * truecolor grant. The renderer resolves its emission tier from these + * fields alone (color-encoding-spec §5). */ +function info(colors: number, trueColor = false): TerminalInfo { + return Object.freeze({ + capabilities: Object.freeze({ + colors, + trueColor, + bce: true, + autoMargin: true, + xenl: true, + altScreen: true, + styledUnderline: false, + syncOutput: false, + pointerShape: false, + }), + probe: new Uint8Array(0), + keys: new Uint8Array(0), + }); +} + +/** Frame: one full-screen text node carrying the given color/bg. */ +function coloredText( + color?: number, + bg?: number, +): Op[] { + return [ + open("root", { layout: { width: grow(), height: grow() } }), + text("X", { color, bg }), + close(), + ]; +} + +/** The SGR bytes emitted before the glyph. */ +function beforeGlyph(ansi: string): string { + return ansi.slice(0, ansi.indexOf("X")); +} + +describe("color encoding modes", () => { + describe("16-color tier", () => { + it("downgrades standard red foreground to the 4-bit code", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + let before = beforeGlyph(ansi); + // pins: standard-palette red maps to 4-bit \x1b[31m + expect(before).toContain("\x1b[31m"); + // pins: the 24-bit sequence must not survive the downgrade + expect(before).not.toContain("\x1b[38;2;255;0;0"); + }); + + it("downgrades standard red background to the 4-bit code", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode( + term.render(coloredText(undefined, rgba(255, 0, 0))).output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[41m"); + expect(before).not.toContain("\x1b[48;2;255;0;0"); + }); + + it("maps bright palette colors to aixterm codes", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode(term.render(coloredText(rgba(255, 85, 85))).output); + + // #ff5555 is nominal index 9 → bright red foreground + expect(beforeGlyph(ansi)).toContain("\x1b[91m"); + }); + + it("maps non-palette colors to the nearest nominal entry", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + // #aa0000 is nearer nominal red (index 1) than any other entry + let ansi = decode(term.render(coloredText(rgba(170, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[31m"); + }); + }); + + describe("256-color tier", () => { + it("maps sRGB red foreground to the fixed cube red", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + // pins: cube (5,0,0), not the theme-controlled palette index 1 + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[38;5;1m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[38;2;255;0;0"); + }); + + it("maps sRGB red background to the fixed cube red", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + let ansi = decode( + term.render(coloredText(undefined, rgba(255, 0, 0))).output, + ); + + expect(beforeGlyph(ansi)).toContain("\x1b[48;5;196m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[48;5;1m"); + expect(beforeGlyph(ansi)).not.toContain("\x1b[48;2;255;0;0"); + }); + + it("round-trips exact cube colors", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + // #5f5f5f is cube (1,1,1) → index 16 + 36 + 6 + 1 = 59 + let ansi = decode(term.render(coloredText(rgba(95, 95, 95))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;59m"); + }); + + it("maps equal-channel grays onto the grayscale ramp", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + // (100,100,100): nearest ramp value is 98 (i=9) → index 241 + let ansi = decode(term.render(coloredText(rgba(100, 100, 100))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;241m"); + }); + + it("maps non-palette colors to the nearest cube value per channel", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + // (250,10,10) → cube steps (5,0,0) → index 196 + let ansi = decode(term.render(coloredText(rgba(250, 10, 10))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); + }); + }); + + describe("truecolor tier", () => { + it("emits byte-identical historical sequences", async () => { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(256, true), + }); + let ansi = decode( + term.render(coloredText(rgba(255, 0, 0), rgba(0, 0, 255))).output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[38;2;255;0;0m"); + expect(before).toContain("\x1b[48;2;0;0;255m"); + expect(before).not.toContain("38;5;"); + }); + }); + + describe("tier resolution", () => { + it("resolves the 256-color baseline without evidence", async () => { + let term = await createTerm({ width: 4, height: 1 }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); + }); + + it("resolves the 16-color tier at and below 16 colors", async () => { + for (let colors of [8, 16]) { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(colors), + }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + expect(beforeGlyph(ansi)).toContain("\x1b[31m"); + } + }); + + it("resolves the 256-color tier above 16 colors", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(17) }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;5;196m"); + }); + + it("resolves the truecolor tier on a granted truecolor flag", async () => { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(16, true), + }); + let ansi = decode(term.render(coloredText(rgba(255, 0, 0))).output); + + expect(beforeGlyph(ansi)).toContain("\x1b[38;2;255;0;0m"); + }); + }); + + describe("dynamic evidence", () => { + it("applies a colordepth event from the next render", async () => { + let term = await createTerm({ width: 4, height: 1 }); + let ops = coloredText(rgba(255, 0, 0)); + + expect(decode(term.render(ops).output)).toContain("\x1b[38;5;196m"); + + term.update([ + { type: "capability", key: "colordepth", value: "truecolor" }, + ]); + + // The next render encodes in the new tier + expect(decode(term.render(ops).output)).toContain("\x1b[38;2;255;0;0m"); + }); + + it("redraws the complete frame after a tier change", async () => { + let term = await createTerm({ width: 4, height: 1 }); + let ops = coloredText(rgba(255, 0, 0)); + + term.render(ops); + // no redraw while the tier is stable + expect(term.render(ops).output.length).toBe(0); + + term.update([ + { type: "capability", key: "colordepth", value: "truecolor" }, + ]); + let out = term.render(ops).output; + // CI-5: the frame after a tier change is a complete redraw + expect(out.length).toBeGreaterThan(0); + expect(decode(out)).toContain("X"); + + // the tier has settled: diffing resumes + expect(term.render(ops).output.length).toBe(0); + }); + + it("downgrades on a colordepth denial event", async () => { + let term = await createTerm({ + width: 4, + height: 1, + terminfo: info(256, true), + }); + let ops = coloredText(rgba(255, 0, 0)); + + expect(decode(term.render(ops).output)).toContain("\x1b[38;2;255;0;0m"); + + term.update([{ type: "capability", key: "colordepth", value: "256" }]); + expect(decode(term.render(ops).output)).toContain("\x1b[38;5;196m"); + }); + }); + + describe("default colors", () => { + it("emits default fg/bg identically in every tier", async () => { + let outputs: string[] = []; + for (let caps of [info(16), info(256), info(256, true)]) { + let term = await createTerm({ width: 4, height: 1, terminfo: caps }); + let ansi = decode(term.render(coloredText()).output); + + expect(ansi).toContain("X"); + expect(ansi).not.toMatch(/\x1b\[(38|48);/); + outputs.push(ansi); + } + expect(outputs[1]).toEqual(outputs[0]); + expect(outputs[2]).toEqual(outputs[0]); + }); + }); + + describe("terminal-themed colors", () => { + it("emits palette colors as 4-bit codes in every tier", async () => { + for (let caps of [info(16), info(256), info(256, true)]) { + let term = await createTerm({ width: 4, height: 1, terminfo: caps }); + let ansi = decode( + term.render([ + text("X", { color: "-ansi-red", bg: "-ansi-bright-blue" }), + ]) + .output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[31m"); + expect(before).toContain("\x1b[104m"); + expect(before).not.toMatch(/\x1b\[(38|48);/); + } + }); + + it("encodes a probed theme color for the active tier", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(256) }); + term.update([ + { + type: "capability", + key: "foreground-color", + value: { r: 255, g: 0, b: 0 }, + }, + ]); + let ansi = decode( + term.render([text("X", { bg: "CanvasText" })]).output, + ); + + let before = beforeGlyph(ansi); + expect(before).toContain("\x1b[48;5;196m"); + expect(before).not.toContain("\x1b[48;2;"); + }); + }); + + describe("resolved colors", () => { + it("encodes inherited and currentcolor sRGB for the active tier", async () => { + let term = await createTerm({ width: 4, height: 1, terminfo: info(16) }); + let ansi = decode( + term.render([ + open("root", { + color: rgba(255, 0, 0), + layout: { width: grow(), height: grow() }, + }), + text("X", { bg: "currentcolor" }), + close(), + ]).output, + ); + + let before = beforeGlyph(ansi); + // inherited red foreground and currentcolor red background + expect(before).toContain("\x1b[31m"); + expect(before).toContain("\x1b[41m"); + expect(before).not.toMatch(/\x1b\[(38|48);/); + }); + }); + + describe("palette round-trip", () => { + it("never emits themed indices and round-trips cube and ramp colors", async () => { + let NOMINAL = [ + 0x000000, + 0xff0000, + 0x00ff00, + 0xffff00, + 0x0000ff, + 0xff00ff, + 0x00ffff, + 0xc0c0c0, + 0x808080, + 0xff5555, + 0x55ff55, + 0xffff55, + 0x5555ff, + 0xff55ff, + 0x55ffff, + 0xffffff, + ]; + let CUBE = [0, 95, 135, 175, 215, 255]; + let rgbOf = (i: number): number => { + if (i < 16) return NOMINAL[i]; + if (i < 232) { + let n = i - 16; + return (CUBE[Math.floor(n / 36)] << 16) | + (CUBE[Math.floor(n / 6) % 6] << 8) | + CUBE[n % 6]; + } + let v = 8 + 10 * (i - 232); + return (v << 16) | (v << 8) | v; + }; + + // A 16x16 grid whose cell k carries palette color k. + let term = await createTerm({ width: 16, height: 16 }); + let ops: Op[] = [ + open("root", { + layout: { width: grow(), height: grow(), direction: "ttb" }, + }), + ]; + for (let row = 0; row < 16; row++) { + ops.push( + open(`row${row}`, { + layout: { width: grow(), height: fixed(1), direction: "ltr" }, + }), + ); + for (let col = 0; col < 16; col++) { + let rgb = rgbOf(row * 16 + col); + ops.push(text(".", { + bg: rgba((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff), + })); + } + ops.push(close()); + } + ops.push(close()); + + let ansi = decode(term.render(ops).output); + let indices = [...ansi.matchAll(/\x1b\[48;5;(\d+)m/g)].map((m) => + Number(m[1]) + ); + expect(indices.length).toBe(256); + for (let k = 0; k < 256; k++) { + // Nominal colors stay off the themed 0-15; cube and ramp colors + // round-trip to their own index (CI-4). + if (k < 16) expect(indices[k]).toBeGreaterThanOrEqual(16); + else expect(indices[k]).toBe(k); + } + }); + }); +}); diff --git a/test/color.test.ts b/test/color.test.ts index 404b511..c9ad348 100644 --- a/test/color.test.ts +++ b/test/color.test.ts @@ -1,5 +1,6 @@ import { close, fixed, grow, type Op, open, rgba, text } from "../ops.ts"; import { createTerm } from "../term.ts"; +import { TRUECOLOR_INFO } from "./caps.ts"; import { describe, expect, it } from "./suite.ts"; const decode = (b: Uint8Array) => new TextDecoder().decode(b); @@ -72,7 +73,11 @@ function firstCell(cells: Cell[], ch: string): Cell { describe("foreground", () => { it("emits uncolored text with no foreground", async () => { - let term = await createTerm({ width: 12, height: 1 }); + let term = await createTerm({ + width: 12, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode(term.render([text("hi")]).output); expect(ansi).toContain("hi"); @@ -82,7 +87,11 @@ describe("foreground", () => { describe("background", () => { it("fills border cells with the requested border-level bg", async () => { - let term = await createTerm({ width: 12, height: 4 }); + let term = await createTerm({ + width: 12, + height: 4, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -112,7 +121,11 @@ describe("background", () => { }); it("leaves existing border-cell bg unchanged when border bg is omitted", async () => { - let term = await createTerm({ width: 12, height: 4 }); + let term = await createTerm({ + width: 12, + height: 4, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -140,7 +153,11 @@ describe("background", () => { }); it("fills glyph cells with the requested text-level bg", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -155,7 +172,11 @@ describe("background", () => { }); it("resets border bg on subsequent frames without border bg", async () => { - let term = await createTerm({ width: 12, height: 4 }); + let term = await createTerm({ + width: 12, + height: 4, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); // Frame 1: border with bg @@ -198,7 +219,11 @@ describe("background", () => { }); it("resets the background before writing trailing cells", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let bg = randomBgColor(); let ansi = decode( term.render([ @@ -222,7 +247,11 @@ describe("background", () => { describe("hex color strings", () => { it("renders text bg from a 3-digit hex string", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -235,7 +264,11 @@ describe("hex color strings", () => { }); it("renders text fg from a 6-digit hex string", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -248,7 +281,11 @@ describe("hex color strings", () => { }); it("matches hex case-insensitively", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -262,7 +299,11 @@ describe("hex color strings", () => { }); it("expands 4- and 8-digit hex with doubled digits", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -276,7 +317,11 @@ describe("hex color strings", () => { }); it("fills element bg from a hex string", async () => { - let term = await createTerm({ width: 8, height: 2 }); + let term = await createTerm({ + width: 8, + height: 2, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { @@ -307,7 +352,11 @@ describe("hex color strings", () => { describe("CSS color strings", () => { it("renders fg and bg from CSS color functions and names", async () => { - let term = await createTerm({ width: 20, height: 1 }); + let term = await createTerm({ + width: 20, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("root", { layout: { width: grow(), height: grow() } }), @@ -450,7 +499,11 @@ describe("system colors", () => { }); it("overwrites an enclosing bg with an explicit Canvas element bg", async () => { - let term = await createTerm({ width: 8, height: 1 }); + let term = await createTerm({ + width: 8, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { @@ -490,7 +543,11 @@ describe("system colors", () => { }); it("re-emits cells whose color changes between palette, default, and sRGB", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let frame = (color: number | string) => decode(term.render([text("Hi", { color })]).output); @@ -505,7 +562,11 @@ describe("system colors", () => { }); it("re-emits cells whose bg changes between palette, default, and sRGB", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let frame = (bg: number | string) => decode( term.render([ @@ -528,7 +589,11 @@ describe("system colors", () => { }); it("paints a probed default foreground as a truecolor text bg once the theme reports it", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let before = decode( term.render([text("Hi", { bg: "CanvasText" })]).output, ); @@ -548,7 +613,11 @@ describe("system colors", () => { }); it("paints a probed default foreground as a truecolor element bg once the theme reports it", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -569,7 +638,11 @@ describe("system colors", () => { }); it("paints a probed default background as a truecolor border side fg", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -612,7 +685,11 @@ describe("system colors", () => { }); it("keeps the probed theme across a resize", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -628,7 +705,11 @@ describe("system colors", () => { }); it("resolves a replayed cross-field keyword against a theme reported after its source render", async () => { - let term = await createTerm({ width: 8, height: 1 }); + let term = await createTerm({ + width: 8, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let result = term.render([ open("wrap", { layout: { padding: { left: 2 } } }), open("box"), @@ -670,7 +751,11 @@ describe("system colors", () => { describe("foreground inheritance and currentcolor", () => { it("inherits an ancestor open's color through nested opens to text", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -685,7 +770,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("overrides the inherited color for itself and its descendants", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -746,7 +835,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves text bg currentcolor to the inherited color", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -759,7 +852,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves text bg currentcolor to the element's own explicit color over an ancestor's", async () => { - let term = await createTerm({ width: 10, height: 1 }); + let term = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("outer", { color: "#ff0000" }), @@ -772,7 +869,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves open bg currentcolor to its own color", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( term.render([ open("box", { @@ -803,7 +904,11 @@ describe("foreground inheritance and currentcolor", () => { }); it("resolves text bg currentcolor to the probed theme foreground once reported", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); term.update([ { type: "capability", @@ -842,8 +947,16 @@ describe("foreground inheritance and currentcolor", () => { ...children, close(), ]; - let replayed = await createTerm({ width: 10, height: 1 }); - let direct = await createTerm({ width: 10, height: 1 }); + let replayed = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); + let direct = await createTerm({ + width: 10, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let result = replayed.render(frame("#ff0000", ...child)); direct.render(frame("#ff0000", ...child)); diff --git a/test/pack.test.ts b/test/pack.test.ts index d41aa86..8677f50 100644 --- a/test/pack.test.ts +++ b/test/pack.test.ts @@ -86,6 +86,8 @@ describe("pack", () => { let native = await createTermNative(8, 1, { syncOutput: false, pointerShape: false, + colors: 256, + trueColor: false, }); let overhead = pack([open(""), close()], new ArrayBuffer(64), 0) * 4; let id = "x".repeat(native.opsCapacity - overhead); diff --git a/test/term.test.ts b/test/term.test.ts index db44aa2..88b6c5c 100644 --- a/test/term.test.ts +++ b/test/term.test.ts @@ -4,7 +4,7 @@ import { createTerm, type Term } from "../term.ts"; import type { InputEvent } from "../input.ts"; import { close, fixed, grow, type Op, open, rgba, text } from "../ops.ts"; import { print } from "./print.ts"; -import { trueColorDetect } from "./caps.ts"; +import { TRUECOLOR_INFO, trueColorDetect } from "./caps.ts"; const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes); const trim = (s: string) => s.split("\n").map((l) => l.trimEnd()).join("\n"); @@ -34,9 +34,16 @@ describe("term", () => { expect(out).toContain("Hello, World!"); }); - it("text inherits parent background", () => { + it("text inherits parent background", async () => { + // Truecolor evidence selects the truecolor tier (color-encoding-spec + // §5); this test pins truecolor background bytes. + let local = await createTerm({ + width: 40, + height: 10, + terminfo: TRUECOLOR_INFO, + }); let ansi = decode( - term.render([ + local.render([ open("root", { layout: { width: grow(), height: grow(), direction: "ttb" }, bg: rgba(255, 0, 0), diff --git a/test/transitions.test.ts b/test/transitions.test.ts index 0ae41df..55f816d 100644 --- a/test/transitions.test.ts +++ b/test/transitions.test.ts @@ -9,6 +9,7 @@ import { rgba, text, } from "../mod.ts"; +import { TRUECOLOR_INFO } from "./caps.ts"; import { print } from "./print.ts"; const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes); @@ -121,7 +122,11 @@ describe("transitions", () => { describe("system colors", () => { it("switches between sRGB and a system color at half progress", async () => { - let term = await createTerm({ width: 4, height: 1 }); + let term = await createTerm({ + width: 4, + height: 1, + terminfo: TRUECOLOR_INFO, + }); let frame = (bg: number | string, deltaTime: number) => new TextDecoder().decode( term.render([ diff --git a/test/width.test.ts b/test/width.test.ts index 85477ac..ce42f83 100644 --- a/test/width.test.ts +++ b/test/width.test.ts @@ -141,6 +141,8 @@ describe("width", () => { let native = await createTermNative(10, 3, { syncOutput: false, pointerShape: false, + colors: 256, + trueColor: false, }); // TextEncoder never produces surrogate bytes, so pack a placeholder