Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
62
crates/luxe-tui/examples/fixture_svg/capture.rs
Normal file
62
crates/luxe-tui/examples/fixture_svg/capture.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
//! Capture — a fixture scenario rendered the way the event loop would, settled on one frame.
|
||||
|
||||
use super::color::hex;
|
||||
use super::fail;
|
||||
use luxe_tui::app::App;
|
||||
use luxe_tui::fixture::{seeded_app, FixtureScenario};
|
||||
use luxe_tui::view;
|
||||
use ratatui::backend::TestBackend;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::Terminal;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Frames a clock-pinned scenario is stepped before capture, matching `ui_fixture` so a still is
|
||||
/// the same picture in both tools.
|
||||
const REVEAL_FRAMES: u32 = 28;
|
||||
|
||||
/// A scenario rendered through the production view path, and the theme's text color.
|
||||
///
|
||||
/// The ink is what a cell the app left at the terminal default is drawn in, which a palette needs
|
||||
/// as a real value: one theme may paint a cell another leaves alone.
|
||||
///
|
||||
/// `overlay` opens a state over the scenario, by the names `ui_fixture`'s `LUXE_FIXTURE_OVERLAY`
|
||||
/// takes, so the interactive fixture and the still draw the same picture: `github`,
|
||||
/// `github-detail`, `github-conversation`, `github-draft`, `github-issue`, `github-pulls`,
|
||||
/// `github-search`, `github-merged`, `pr`, `pr-merge`, a login state, or `mention-<tab>`.
|
||||
pub(super) fn render(
|
||||
theme: &str,
|
||||
scenario: FixtureScenario,
|
||||
overlay: Option<&str>,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
) -> (Buffer, String) {
|
||||
let mut app = seeded_app(theme, scenario).unwrap_or_else(|error: String| fail(&error));
|
||||
let mut terminal = Terminal::new(TestBackend::new(cols, rows)).expect("in-memory terminal");
|
||||
app.update(luxe_tui::app::Msg::TerminalResized { width: cols, height: rows });
|
||||
if let Some(overlay) = overlay {
|
||||
if let Some(login) = luxe_tui::fixture::LoginFixture::parse(overlay) {
|
||||
luxe_tui::fixture::seed_login_wizard(&mut app, login);
|
||||
} else if let Some(tab) = overlay.strip_prefix("mention-") {
|
||||
luxe_tui::fixture::seed_mention_picker(&mut app, tab);
|
||||
} else if overlay.starts_with("pr") || overlay.starts_with("github") {
|
||||
luxe_tui::fixture::seed_github(&mut app, overlay);
|
||||
} else {
|
||||
fail(&format!("unknown overlay {overlay}"));
|
||||
}
|
||||
}
|
||||
|
||||
step_reveal(&mut terminal, &mut app);
|
||||
terminal.draw(|frame| view::render(frame, &mut app)).expect("render");
|
||||
let ink = app.theme_styles.text.fg.and_then(hex).unwrap_or_else(|| "#ffffff".into());
|
||||
(terminal.backend().buffer().clone(), ink)
|
||||
}
|
||||
|
||||
/// Runs a mid-animation scenario forward the way the event loop does, so the captured frame is the
|
||||
/// same one every time rather than wherever the clock happened to land.
|
||||
fn step_reveal(terminal: &mut Terminal<TestBackend>, app: &mut App) {
|
||||
let Some(base) = app.status.frame_clock else { return };
|
||||
for step in 1..=REVEAL_FRAMES {
|
||||
app.status.frame_clock = Some(base + Duration::from_millis(12) * step);
|
||||
terminal.draw(|frame| view::render(frame, app)).expect("render");
|
||||
}
|
||||
}
|
||||
92
crates/luxe-tui/examples/fixture_svg/color.rs
Normal file
92
crates/luxe-tui/examples/fixture_svg/color.rs
Normal file
@@ -0,0 +1,92 @@
|
||||
//! Color — a ratatui color as hex, through the ANSI and indexed palettes, and text attributes.
|
||||
|
||||
use ratatui::style::{Color, Modifier};
|
||||
|
||||
/// A ratatui color as `#rrggbb`, or `None` when the terminal would have chosen it.
|
||||
pub(super) fn hex(color: Color) -> Option<String> {
|
||||
let (red, green, blue) = match color {
|
||||
Color::Rgb(red, green, blue) => (red, green, blue),
|
||||
Color::Indexed(index) => indexed_rgb(index),
|
||||
Color::Reset => return None,
|
||||
// The sixteen named colors belong to the terminal's palette. Luxe's own themes are pure
|
||||
// RGB, so this is only reached by a user theme; xterm's defaults are the least surprising
|
||||
// stand-in available.
|
||||
named => indexed_rgb(named_index(named)?),
|
||||
};
|
||||
Some(format!("#{red:02x}{green:02x}{blue:02x}"))
|
||||
}
|
||||
|
||||
fn named_index(color: Color) -> Option<u8> {
|
||||
Some(match color {
|
||||
Color::Black => 0,
|
||||
Color::Red => 1,
|
||||
Color::Green => 2,
|
||||
Color::Yellow => 3,
|
||||
Color::Blue => 4,
|
||||
Color::Magenta => 5,
|
||||
Color::Cyan => 6,
|
||||
Color::Gray => 7,
|
||||
Color::DarkGray => 8,
|
||||
Color::LightRed => 9,
|
||||
Color::LightGreen => 10,
|
||||
Color::LightYellow => 11,
|
||||
Color::LightBlue => 12,
|
||||
Color::LightMagenta => 13,
|
||||
Color::LightCyan => 14,
|
||||
Color::White => 15,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The RGB an xterm-256 index stands for: sixteen system colors, a 6×6×6 cube, then a gray ramp.
|
||||
fn indexed_rgb(index: u8) -> (u8, u8, u8) {
|
||||
const SYSTEM: [(u8, u8, u8); 16] = [
|
||||
(0, 0, 0),
|
||||
(205, 49, 49),
|
||||
(13, 188, 121),
|
||||
(229, 229, 16),
|
||||
(36, 114, 200),
|
||||
(188, 63, 188),
|
||||
(17, 168, 205),
|
||||
(229, 229, 229),
|
||||
(102, 102, 102),
|
||||
(241, 76, 76),
|
||||
(35, 209, 139),
|
||||
(245, 245, 67),
|
||||
(59, 142, 234),
|
||||
(214, 112, 214),
|
||||
(41, 184, 219),
|
||||
(255, 255, 255),
|
||||
];
|
||||
if index < 16 {
|
||||
return SYSTEM[index as usize];
|
||||
}
|
||||
if index >= 232 {
|
||||
let level = 8 + (index - 232) * 10;
|
||||
return (level, level, level);
|
||||
}
|
||||
const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
|
||||
let index = index - 16;
|
||||
(LEVELS[(index / 36) as usize], LEVELS[(index % 36 / 6) as usize], LEVELS[(index % 6) as usize])
|
||||
}
|
||||
|
||||
/// Ratatui modifiers as SVG text attributes.
|
||||
pub(super) fn attributes(modifier: Modifier) -> String {
|
||||
let mut out = String::new();
|
||||
if modifier.contains(Modifier::BOLD) {
|
||||
out.push_str(" font-weight=\"700\"");
|
||||
}
|
||||
if modifier.contains(Modifier::ITALIC) {
|
||||
out.push_str(" font-style=\"italic\"");
|
||||
}
|
||||
if modifier.contains(Modifier::DIM) {
|
||||
out.push_str(" opacity=\"0.6\"");
|
||||
}
|
||||
match (modifier.contains(Modifier::UNDERLINED), modifier.contains(Modifier::CROSSED_OUT)) {
|
||||
(true, true) => out.push_str(" text-decoration=\"underline line-through\""),
|
||||
(true, false) => out.push_str(" text-decoration=\"underline\""),
|
||||
(false, true) => out.push_str(" text-decoration=\"line-through\""),
|
||||
(false, false) => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
209
crates/luxe-tui/examples/fixture_svg/geometry.rs
Normal file
209
crates/luxe-tui/examples/fixture_svg/geometry.rs
Normal file
@@ -0,0 +1,209 @@
|
||||
//! Glyph geometry — block, box and triangle glyphs drawn as exact cell fractions, not typeset.
|
||||
|
||||
use super::color::hex;
|
||||
use super::{CELL_H, CELL_W, HAIRLINE};
|
||||
use ratatui::buffer::Buffer;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// Every cell whose glyph is drawn rather than typeset.
|
||||
pub(super) fn geometry(buffer: &Buffer) -> String {
|
||||
let mut out = String::new();
|
||||
for row in 0..buffer.area.height {
|
||||
for column in 0..buffer.area.width {
|
||||
let cell = &buffer[(column, row)];
|
||||
let Some(glyph) = cell.symbol().chars().next() else { continue };
|
||||
let Some(fill) = hex(cell.fg) else { continue };
|
||||
if let Some(drawn) = draw(glyph, column, row, &fill) {
|
||||
let _ = writeln!(out, " {drawn}");
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether this glyph is drawn as geometry rather than typeset.
|
||||
pub(super) fn is_drawn(glyph: char) -> bool {
|
||||
block(glyph).is_some() || arms(glyph).is_some() || triangle_points(glyph).is_some()
|
||||
}
|
||||
|
||||
/// The SVG element for a drawn glyph, or `None` when the font should handle it.
|
||||
pub(super) fn draw(glyph: char, column: u16, row: u16, fill: &str) -> Option<String> {
|
||||
let (x, y) = (f64::from(column) * CELL_W, f64::from(row) * CELL_H);
|
||||
if let Some(parts) = block(glyph) {
|
||||
return Some(block_element(&parts, x, y, fill));
|
||||
}
|
||||
if let Some(points) = triangle_points(glyph) {
|
||||
return Some(triangle(&points, x, y, fill));
|
||||
}
|
||||
arms(glyph).map(|(arms, rounded)| box_line(arms, rounded, x, y, fill))
|
||||
}
|
||||
|
||||
/// A block glyph as `(fractional rects, opacity)`, in cell-relative units.
|
||||
///
|
||||
/// Rects are `(x, y, w, h)` with the cell as the unit square. The shade blocks have no geometry of
|
||||
/// their own — they are the full cell at a fraction of its ink, which is what they mean.
|
||||
type Block = (Vec<(f64, f64, f64, f64)>, f64);
|
||||
|
||||
pub(super) fn block(glyph: char) -> Option<Block> {
|
||||
let full = vec![(0.0, 0.0, 1.0, 1.0)];
|
||||
let eighth = |n: f64| n / 8.0;
|
||||
Some(match glyph {
|
||||
'\u{2588}' => (full, 1.0),
|
||||
// Shades: the same cell, thinned.
|
||||
'\u{2591}' => (full, 0.25),
|
||||
'\u{2592}' => (full, 0.5),
|
||||
'\u{2593}' => (full, 0.75),
|
||||
// Halves.
|
||||
'\u{2580}' => (vec![(0.0, 0.0, 1.0, 0.5)], 1.0),
|
||||
'\u{2584}' => (vec![(0.0, 0.5, 1.0, 0.5)], 1.0),
|
||||
'\u{258c}' => (vec![(0.0, 0.0, 0.5, 1.0)], 1.0),
|
||||
'\u{2590}' => (vec![(0.5, 0.0, 0.5, 1.0)], 1.0),
|
||||
// Lower eighths, one through seven.
|
||||
'\u{2581}'..='\u{2587}' => {
|
||||
let height = eighth(f64::from(glyph as u32 - 0x2580));
|
||||
(vec![(0.0, 1.0 - height, 1.0, height)], 1.0)
|
||||
}
|
||||
// Left eighths run the other way: U+2589 is seven eighths, U+258F is one.
|
||||
'\u{2589}'..='\u{258f}' => {
|
||||
let width = eighth(f64::from(0x2590 - glyph as u32));
|
||||
(vec![(0.0, 0.0, width, 1.0)], 1.0)
|
||||
}
|
||||
'\u{2594}' => (vec![(0.0, 0.0, 1.0, eighth(1.0))], 1.0),
|
||||
'\u{2595}' => (vec![(1.0 - eighth(1.0), 0.0, eighth(1.0), 1.0)], 1.0),
|
||||
// Quadrants, as a bitmask of the four sub-cells.
|
||||
'\u{2596}'..='\u{259f}' => {
|
||||
let mask = QUADRANTS[glyph as usize - 0x2596];
|
||||
let mut rects = Vec::new();
|
||||
for (bit, (qx, qy)) in
|
||||
[(0.0, 0.0), (0.5, 0.0), (0.0, 0.5), (0.5, 0.5)].into_iter().enumerate()
|
||||
{
|
||||
if mask & (1 << bit) != 0 {
|
||||
rects.push((qx, qy, 0.5, 0.5));
|
||||
}
|
||||
}
|
||||
(rects, 1.0)
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Quadrant fills for `U+2596..=U+259F`, as `upper-left | upper-right | lower-left | lower-right`.
|
||||
const QUADRANTS: [u8; 10] = [
|
||||
0b0100, // ▖ lower left
|
||||
0b1000, // ▗ lower right
|
||||
0b0001, // ▘ upper left
|
||||
0b1101, // ▙
|
||||
0b1001, // ▚
|
||||
0b0111, // ▛
|
||||
0b1011, // ▜
|
||||
0b0010, // ▝ upper right
|
||||
0b0110, // ▞
|
||||
0b1110, // ▟
|
||||
];
|
||||
|
||||
fn block_element(block: &Block, x: f64, y: f64, fill: &str) -> String {
|
||||
let (parts, opacity) = block;
|
||||
let body: String = parts
|
||||
.iter()
|
||||
.map(|(rx, ry, rw, rh)| {
|
||||
format!(
|
||||
"M{:.2} {:.2}h{:.2}v{:.2}h-{:.2}z",
|
||||
x + rx * CELL_W,
|
||||
y + ry * CELL_H,
|
||||
rw * CELL_W,
|
||||
rh * CELL_H,
|
||||
rw * CELL_W
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("");
|
||||
let alpha = if *opacity < 1.0 { format!(" fill-opacity=\"{opacity}\"") } else { String::new() };
|
||||
format!("<path fill=\"{fill}\"{alpha} d=\"{body}\"/>")
|
||||
}
|
||||
|
||||
/// Which cell edges a box-drawing glyph reaches, and whether its corner is rounded.
|
||||
///
|
||||
/// `(up, right, down, left)`. Only the light set: it is what Luxe draws with, and a heavy or double
|
||||
/// rule would need its own stroke width rather than a flag here.
|
||||
type Arms = (bool, bool, bool, bool);
|
||||
|
||||
fn arms(glyph: char) -> Option<(Arms, bool)> {
|
||||
let sharp = |arms: Arms| Some((arms, false));
|
||||
match glyph {
|
||||
'\u{2500}' => sharp((false, true, false, true)),
|
||||
'\u{2502}' => sharp((true, false, true, false)),
|
||||
'\u{250c}' => sharp((false, true, true, false)),
|
||||
'\u{2510}' => sharp((false, false, true, true)),
|
||||
'\u{2514}' => sharp((true, true, false, false)),
|
||||
'\u{2518}' => sharp((true, false, false, true)),
|
||||
'\u{251c}' => sharp((true, true, true, false)),
|
||||
'\u{2524}' => sharp((true, false, true, true)),
|
||||
'\u{252c}' => sharp((false, true, true, true)),
|
||||
'\u{2534}' => sharp((true, true, false, true)),
|
||||
'\u{253c}' => sharp((true, true, true, true)),
|
||||
'\u{256d}' => Some(((false, true, true, false), true)),
|
||||
'\u{256e}' => Some(((false, false, true, true), true)),
|
||||
'\u{256f}' => Some(((true, false, false, true), true)),
|
||||
'\u{2570}' => Some(((true, true, false, false), true)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A box-drawing glyph as a stroked path.
|
||||
///
|
||||
/// A rounded corner is one quadratic curve between the two edge midpoints, with the cell's center
|
||||
/// as its control point — which is exactly the quarter-round the glyph means, with no radius to
|
||||
/// pick.
|
||||
fn box_line((up, right, down, left): Arms, rounded: bool, x: f64, y: f64, fill: &str) -> String {
|
||||
let (cx, cy) = (x + CELL_W / 2.0, y + CELL_H / 2.0);
|
||||
let (x1, y1) = (x + CELL_W, y + CELL_H);
|
||||
let mut path = String::new();
|
||||
|
||||
if rounded {
|
||||
let (from_x, from_y) = if up { (cx, y) } else { (cx, y1) };
|
||||
let (to_x, to_y) = if left { (x, cy) } else { (x1, cy) };
|
||||
let _ = write!(path, "M{from_x:.2} {from_y:.2}Q{cx:.2} {cy:.2} {to_x:.2} {to_y:.2}");
|
||||
} else {
|
||||
for (present, (ex, ey)) in
|
||||
[(up, (cx, y)), (right, (x1, cy)), (down, (cx, y1)), (left, (x, cy))]
|
||||
{
|
||||
if present {
|
||||
let _ = write!(path, "M{cx:.2} {cy:.2}L{ex:.2} {ey:.2}");
|
||||
}
|
||||
}
|
||||
}
|
||||
format!("<path fill=\"none\" stroke=\"{fill}\" stroke-width=\"{HAIRLINE:.2}\" d=\"{path}\"/>")
|
||||
}
|
||||
|
||||
/// The half-cell a Powerline Extra triangle inks, in cell-relative units.
|
||||
fn triangle_points(glyph: char) -> Option<[(f64, f64); 3]> {
|
||||
Some(match glyph {
|
||||
'\u{e0b8}' => [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)], // lower left
|
||||
'\u{e0ba}' => [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0)], // lower right
|
||||
'\u{e0bc}' => [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], // upper left
|
||||
'\u{e0be}' => [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)], // upper right
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn triangle(points: &[(f64, f64); 3], x: f64, y: f64, fill: &str) -> String {
|
||||
let path: Vec<String> = points
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (px, py))| {
|
||||
let verb = if index == 0 { 'M' } else { 'L' };
|
||||
format!("{verb}{:.2} {:.2}", x + px * CELL_W, y + py * CELL_H)
|
||||
})
|
||||
.collect();
|
||||
format!("<path fill=\"{fill}\" d=\"{}z\"/>", path.join(""))
|
||||
}
|
||||
|
||||
pub(super) fn rect(column: u16, row: u16, cells: u16, lines: u16, fill: &str) -> String {
|
||||
format!(
|
||||
"<rect x=\"{:.0}\" y=\"{:.0}\" width=\"{:.0}\" height=\"{:.0}\" fill=\"{fill}\"/>",
|
||||
f64::from(column) * CELL_W,
|
||||
f64::from(row) * CELL_H,
|
||||
f64::from(cells) * CELL_W,
|
||||
f64::from(lines) * CELL_H
|
||||
)
|
||||
}
|
||||
73
crates/luxe-tui/examples/fixture_svg/grid.rs
Normal file
73
crates/luxe-tui/examples/fixture_svg/grid.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
//! Grid input — a terminal grid handed in on stdin, read into the buffer the exporter draws.
|
||||
|
||||
use super::fail;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::style::{Color, Modifier};
|
||||
|
||||
/// One cell of a grid handed in on stdin.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct GridCell {
|
||||
/// The character. Empty for the second half of a wide glyph.
|
||||
c: String,
|
||||
/// `#rrggbb`, or absent for the terminal's default.
|
||||
#[serde(default)]
|
||||
fg: Option<String>,
|
||||
#[serde(default)]
|
||||
bg: Option<String>,
|
||||
#[serde(default)]
|
||||
bold: bool,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Grid {
|
||||
width: u16,
|
||||
height: u16,
|
||||
/// Row-major, `width * height` of them.
|
||||
cells: Vec<GridCell>,
|
||||
}
|
||||
|
||||
/// Reads a grid from stdin into the buffer the exporter already knows how to draw.
|
||||
pub(super) fn buffer_from_grid() -> Buffer {
|
||||
let grid: Grid = serde_json::from_reader(std::io::stdin().lock())
|
||||
.unwrap_or_else(|error| fail(&format!("could not read the grid: {error}")));
|
||||
let expected = usize::from(grid.width) * usize::from(grid.height);
|
||||
if grid.cells.len() != expected {
|
||||
fail(&format!(
|
||||
"grid says {}x{} but carries {} cells",
|
||||
grid.width,
|
||||
grid.height,
|
||||
grid.cells.len()
|
||||
));
|
||||
}
|
||||
|
||||
let area = ratatui::layout::Rect::new(0, 0, grid.width, grid.height);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
for (index, cell) in grid.cells.iter().enumerate() {
|
||||
let (x, y) = (index % usize::from(grid.width), index / usize::from(grid.width));
|
||||
let target = &mut buffer[(x as u16, y as u16)];
|
||||
// A wide glyph's trailing cell carries no character of its own; leaving it as a space keeps
|
||||
// the columns after it where the emulator put them.
|
||||
target.set_symbol(if cell.c.is_empty() { " " } else { &cell.c });
|
||||
if let Some(color) = cell.fg.as_deref().and_then(parse_hex) {
|
||||
target.set_fg(color);
|
||||
}
|
||||
if let Some(color) = cell.bg.as_deref().and_then(parse_hex) {
|
||||
target.set_bg(color);
|
||||
}
|
||||
if cell.bold {
|
||||
target.set_style(ratatui::style::Style::default().add_modifier(Modifier::BOLD));
|
||||
}
|
||||
}
|
||||
buffer
|
||||
}
|
||||
|
||||
/// `#rrggbb` to a ratatui color.
|
||||
pub(super) fn parse_hex(value: &str) -> Option<Color> {
|
||||
let digits = value.strip_prefix('#')?;
|
||||
// ASCII first, so the channel slices below always land on character boundaries
|
||||
if digits.len() != 6 || !digits.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let channel = |at: usize| u8::from_str_radix(&digits[at..at + 2], 16).ok();
|
||||
Some(Color::Rgb(channel(0)?, channel(2)?, channel(4)?))
|
||||
}
|
||||
149
crates/luxe-tui/examples/fixture_svg/main.rs
Normal file
149
crates/luxe-tui/examples/fixture_svg/main.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
//! fixture_svg — a production render, exported as vector.
|
||||
//!
|
||||
//! The site needs pictures of Luxe, and a screenshot is the worst way to get one: it is a raster at
|
||||
//! somebody's DPI, its text cannot be selected or searched, it weighs ten times what it should, and
|
||||
//! it puts a terminal and a font in the pipeline where neither belongs. The render is already a
|
||||
//! grid of glyphs and colors, so it can be drawn directly.
|
||||
//!
|
||||
//! A scenario from [`luxe_tui::fixture`] renders through the **production view path** into a
|
||||
//! `TestBackend` buffer, and each cell becomes geometry or text:
|
||||
//!
|
||||
//! - **Block Elements** (full, halves, eighths, quadrants, shades) become rectangles. These are
|
||||
//! defined as exact cell fractions, which is precisely what a font renderer approximates and a
|
||||
//! rectangle does not.
|
||||
//! - **Box drawing** (light lines and rounded corners) becomes stroked paths, for the same reason
|
||||
//! plus one more: a fallback font leaves gaps between border segments, and a panel drawn with
|
||||
//! gaps in it is worse than no panel.
|
||||
//! - **Powerline Extra triangles** become triangles — the range terminals disagree about most.
|
||||
//! - **Everything else** stays real text, one `<text>` per row, so a reader can select a command
|
||||
//! out of the picture and run it.
|
||||
//!
|
||||
//! Every text row carries `textLength`, so the grid holds under whatever monospace font the reader
|
||||
//! actually has rather than only under ours.
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p luxe-tui --example fixture_svg -- --theme luxe --scenario chat-tools > shot.svg
|
||||
//! cargo run -p luxe-tui --example fixture_svg -- --census # what is still drawn as text
|
||||
//! ```
|
||||
|
||||
mod capture;
|
||||
mod color;
|
||||
mod geometry;
|
||||
mod grid;
|
||||
mod palette;
|
||||
mod svg;
|
||||
|
||||
use capture::render;
|
||||
use grid::buffer_from_grid;
|
||||
use luxe_tui::fixture::FixtureScenario;
|
||||
use palette::palette_svg;
|
||||
use svg::{svg, text_census};
|
||||
|
||||
/// Cell size in user units, at the 1:2.2 aspect a terminal draws — the same grid the wordmark's
|
||||
/// vector twin uses, so a logotype exported here lines up with the standalone one.
|
||||
const CELL_W: f64 = 10.0;
|
||||
const CELL_H: f64 = 22.0;
|
||||
|
||||
/// The face's advance width, as a fraction of its type size.
|
||||
///
|
||||
/// This has to be the *real* figure for the first font in the stack below, because every row is
|
||||
/// stretched to `cols × CELL_W` by `textLength`: guess low and every glyph is squeezed, guess high
|
||||
/// and they are pulled apart, in both cases silently and across every capture at once. JetBrains
|
||||
/// Mono advances 0.6em. `scripts/site-smoke.mjs` measures what the website's own face actually
|
||||
/// advances and fails on the difference.
|
||||
const ADVANCE: f64 = 0.6;
|
||||
|
||||
/// Type size that fills the cell at [`ADVANCE`]. `textLength` corrects the rest.
|
||||
const FONT_SIZE: f64 = CELL_W / ADVANCE;
|
||||
/// The face's ascender, as a fraction of its type size.
|
||||
///
|
||||
/// JetBrains Mono's line box is 1.02em up and 0.30em down, 1.32em in all, which at [`FONT_SIZE`]
|
||||
/// is exactly [`CELL_H`] — so the baseline sits where a terminal drawing this face puts it.
|
||||
const ASCENT: f64 = 1.02;
|
||||
/// Baseline as a fraction of cell height.
|
||||
const BASELINE: f64 = ASCENT * FONT_SIZE / CELL_H;
|
||||
/// Stroke width of a light box-drawing line.
|
||||
const HAIRLINE: f64 = CELL_W / 8.0;
|
||||
|
||||
fn main() {
|
||||
let mut theme = "luxe".to_string();
|
||||
let mut scenario = "chat-tools".to_string();
|
||||
let (mut cols, mut rows) = (150_u16, 40_u16);
|
||||
let mut census = false;
|
||||
let mut grid = false;
|
||||
let mut palette: Option<Vec<String>> = None;
|
||||
let mut palette_json: Option<String> = None;
|
||||
let mut overlay: Option<String> = None;
|
||||
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(flag) = args.next() {
|
||||
let mut value = || args.next().unwrap_or_else(|| fail(&format!("{flag} needs a value")));
|
||||
match flag.as_str() {
|
||||
"--theme" => theme = value(),
|
||||
"--scenario" => scenario = value(),
|
||||
"--cols" => cols = value().parse().unwrap_or_else(|_| fail("--cols wants a number")),
|
||||
"--rows" => rows = value().parse().unwrap_or_else(|_| fail("--rows wants a number")),
|
||||
"--census" => census = true,
|
||||
"--grid" => grid = true,
|
||||
"--palette" => {
|
||||
palette = Some(value().split(',').map(str::trim).map(str::to_owned).collect());
|
||||
}
|
||||
"--palette-json" => palette_json = Some(value()),
|
||||
"--overlay" => overlay = Some(value()),
|
||||
"--help" | "-h" => {
|
||||
println!("{USAGE}");
|
||||
return;
|
||||
}
|
||||
other => fail(&format!("unknown flag {other}\n\n{USAGE}")),
|
||||
}
|
||||
}
|
||||
|
||||
// The braille sweep, as the live app draws it wherever a font can: the site's webfonts carry all
|
||||
// ten frames, and a still of a running card in the four-corner fallback reads as broken
|
||||
luxe_tui::glyphs::set_braille(true);
|
||||
|
||||
// A screen somebody else emulated, drawn by the same hand as a fixture.
|
||||
//
|
||||
// `scripts/cast-still.py` replays a recording with a real terminal emulator and sends the
|
||||
// resulting grid here rather than writing its own SVG. Box-drawing and block characters are
|
||||
// *geometry* in this exporter, not glyphs — which is the only way a vertical rule tiles down a
|
||||
// column instead of breaking into dashes at every row boundary — and a second implementation
|
||||
// of that in another language would drift from this one within a release.
|
||||
if grid {
|
||||
print!("{}", svg(&buffer_from_grid()));
|
||||
return;
|
||||
}
|
||||
|
||||
let scenario: FixtureScenario = scenario.parse().unwrap_or_else(|error: String| fail(&error));
|
||||
|
||||
if let Some(themes) = palette {
|
||||
let Some(json) = palette_json else { fail("--palette needs --palette-json FILE") };
|
||||
let (document, values) = palette_svg(&themes, scenario, cols, rows);
|
||||
let written = serde_json::to_string_pretty(&values).expect("a palette is plain strings");
|
||||
std::fs::write(&json, written + "\n")
|
||||
.unwrap_or_else(|error| fail(&format!("could not write {json}: {error}")));
|
||||
print!("{document}");
|
||||
return;
|
||||
}
|
||||
|
||||
let buffer = render(&theme, scenario, overlay.as_deref(), cols, rows).0;
|
||||
|
||||
if census {
|
||||
for (glyph, count) in text_census(&buffer) {
|
||||
println!("U+{:04X} {glyph} {count}", glyph as u32);
|
||||
}
|
||||
return;
|
||||
}
|
||||
print!("{}", svg(&buffer));
|
||||
}
|
||||
|
||||
const USAGE: &str = "usage: fixture_svg [--theme ID] [--scenario NAME] [--cols N] [--rows N] \
|
||||
[--overlay STATE] [--census] [--grid] [--palette ID,ID,... --palette-json FILE]";
|
||||
|
||||
fn fail(message: &str) -> ! {
|
||||
eprintln!("{message}");
|
||||
std::process::exit(2)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
122
crates/luxe-tui/examples/fixture_svg/palette.rs
Normal file
122
crates/luxe-tui/examples/fixture_svg/palette.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
//! Palette pictures — one scenario drawn once for every theme, its colors as CSS variables.
|
||||
|
||||
use super::capture::render;
|
||||
use super::color::hex;
|
||||
use super::fail;
|
||||
use super::svg::{canvas_color, svg};
|
||||
use luxe_tui::fixture::FixtureScenario;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::style::Color;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// The first byte of a placeholder color. Only placeholders are ever in the buffer that gets
|
||||
/// drawn, so nothing real can be mistaken for one.
|
||||
const SENTINEL: u8 = 0x0f;
|
||||
|
||||
/// The scenario drawn once for every theme in `themes`: each color a `var(--pN, first)`, plus what
|
||||
/// every `N` is in every theme.
|
||||
///
|
||||
/// Twelve themes lay the same cells out identically, so what differs between their pictures is
|
||||
/// only which color goes where. Each cell's colors are keyed on what they are across *all* the
|
||||
/// themes at once, and the key becomes a placeholder color in one buffer that the ordinary
|
||||
/// exporter then draws. That is also what keeps the background runs right: two neighbors merge into
|
||||
/// one rectangle only when they match in every theme, where merging per theme and comparing the
|
||||
/// results would have given different shapes to the same picture.
|
||||
pub(super) fn palette_svg(
|
||||
themes: &[String],
|
||||
scenario: FixtureScenario,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
) -> (String, BTreeMap<String, BTreeMap<String, String>>) {
|
||||
if themes.is_empty() {
|
||||
fail("--palette wants at least one theme");
|
||||
}
|
||||
let drawn: Vec<(Buffer, String)> =
|
||||
themes.iter().map(|theme| render(theme, scenario, None, cols, rows)).collect();
|
||||
let (first, _) = &drawn[0];
|
||||
for (theme, (buffer, _)) in themes.iter().zip(&drawn).skip(1) {
|
||||
let same = first.content().iter().zip(buffer.content()).all(|(left, right)| {
|
||||
left.symbol() == right.symbol() && left.modifier == right.modifier
|
||||
});
|
||||
if !same {
|
||||
fail(&format!("{theme} lays {scenario:?} out differently, so no one picture fits it"));
|
||||
}
|
||||
}
|
||||
let canvases: Vec<String> = drawn.iter().map(|(buffer, _)| canvas_color(buffer)).collect();
|
||||
|
||||
// One key per distinct "this color in every theme", numbered in the order the cells meet them
|
||||
let mut keys: BTreeMap<Vec<String>, u16> = BTreeMap::new();
|
||||
let mut order: Vec<Vec<String>> = Vec::new();
|
||||
let mut key_of = |key: Vec<String>| -> u16 {
|
||||
if let Some(index) = keys.get(&key) {
|
||||
return *index;
|
||||
}
|
||||
let index = u16::try_from(order.len()).unwrap_or_else(|_| fail("too many colors"));
|
||||
keys.insert(key.clone(), index);
|
||||
order.push(key);
|
||||
index
|
||||
};
|
||||
let placeholder = |index: u16| {
|
||||
let [high, low] = index.to_be_bytes();
|
||||
Color::Rgb(SENTINEL, high, low)
|
||||
};
|
||||
let mut merged = first.clone();
|
||||
for (position, cell) in merged.content.iter_mut().enumerate() {
|
||||
let fg: Vec<String> = drawn
|
||||
.iter()
|
||||
.map(|(buffer, ink)| hex(buffer.content[position].fg).unwrap_or_else(|| ink.clone()))
|
||||
.collect();
|
||||
let bg: Vec<String> = drawn
|
||||
.iter()
|
||||
.zip(&canvases)
|
||||
.map(|((buffer, _), canvas)| {
|
||||
hex(buffer.content[position].bg).unwrap_or_else(|| canvas.clone())
|
||||
})
|
||||
.collect();
|
||||
cell.set_fg(placeholder(key_of(fg)));
|
||||
cell.set_bg(placeholder(key_of(bg)));
|
||||
}
|
||||
|
||||
let first_values: Vec<&str> = order.iter().map(|key| key[0].as_str()).collect();
|
||||
let document = with_variables(&svg(&merged), &first_values);
|
||||
let mut values = BTreeMap::new();
|
||||
for (column, theme) in themes.iter().enumerate() {
|
||||
let table =
|
||||
order.iter().enumerate().map(|(index, key)| (format!("p{index}"), key[column].clone()));
|
||||
values.insert(theme.clone(), table.collect());
|
||||
}
|
||||
(document, values)
|
||||
}
|
||||
|
||||
/// Every placeholder in an attribute swapped for `var(--pN, #first)`.
|
||||
///
|
||||
/// Only attribute values are touched (`="#0f…"`), because a picture of a terminal can have a hex
|
||||
/// color in its *text*, and that one is somebody's code.
|
||||
pub(super) fn with_variables(document: &str, first: &[&str]) -> String {
|
||||
let marker = format!("=\"#{SENTINEL:02x}");
|
||||
let mut out = String::with_capacity(document.len() + document.len() / 4);
|
||||
let mut rest = document;
|
||||
while let Some(at) = rest.find(&marker) {
|
||||
let (before, tail) = rest.split_at(at);
|
||||
out.push_str(before);
|
||||
let digits = &tail[marker.len()..];
|
||||
let index = digits
|
||||
.get(..4)
|
||||
.filter(|_| digits.as_bytes().get(4) == Some(&b'"'))
|
||||
.and_then(|hex| usize::from_str_radix(hex, 16).ok());
|
||||
match index {
|
||||
Some(index) => {
|
||||
let fallback = first.get(index).copied().unwrap_or("#000000");
|
||||
let _ = write!(out, "=\"var(--p{index}, {fallback})\"");
|
||||
rest = &digits[5..];
|
||||
}
|
||||
None => {
|
||||
out.push_str(&marker);
|
||||
rest = digits;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
156
crates/luxe-tui/examples/fixture_svg/svg.rs
Normal file
156
crates/luxe-tui/examples/fixture_svg/svg.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
//! The SVG document — its backgrounds, the drawn glyphs, and one selectable text row per line.
|
||||
|
||||
use super::color::{attributes, hex};
|
||||
use super::geometry::{geometry, is_drawn, rect};
|
||||
use super::{BASELINE, CELL_H, CELL_W, FONT_SIZE};
|
||||
use ratatui::buffer::Buffer;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// The whole document.
|
||||
pub(super) fn svg(buffer: &Buffer) -> String {
|
||||
let (cols, rows) = (buffer.area.width, buffer.area.height);
|
||||
let (width, height) = (f64::from(cols) * CELL_W, f64::from(rows) * CELL_H);
|
||||
let canvas = canvas_color(buffer);
|
||||
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {width:.0} {height:.0}\" \
|
||||
width=\"{width:.0}\" height=\"{height:.0}\" font-family=\"'JetBrainsMono Nerd Font Mono', \
|
||||
'AdwaitaMono Nerd Font Mono', 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, \
|
||||
Consolas, monospace\" \
|
||||
font-size=\"{FONT_SIZE:.2}\">"
|
||||
);
|
||||
let _ =
|
||||
writeln!(out, " <rect width=\"{width:.0}\" height=\"{height:.0}\" fill=\"{canvas}\"/>");
|
||||
|
||||
out.push_str(" <g shape-rendering=\"crispEdges\">\n");
|
||||
out.push_str(&backgrounds(buffer, &canvas));
|
||||
out.push_str(&geometry(buffer));
|
||||
out.push_str(" </g>\n");
|
||||
|
||||
out.push_str(&text(buffer));
|
||||
out.push_str("</svg>\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// The color behind everything, taken from the cell the app paints most of.
|
||||
///
|
||||
/// Reading it off the render rather than the theme keeps the export honest about surfaces that
|
||||
/// bring their own canvas, and gives `Color::Reset` something real to resolve to.
|
||||
pub(super) fn canvas_color(buffer: &Buffer) -> String {
|
||||
let mut tally: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for cell in buffer.content() {
|
||||
if let Some(hex) = hex(cell.bg) {
|
||||
*tally.entry(hex).or_default() += 1;
|
||||
}
|
||||
}
|
||||
tally.into_iter().max_by_key(|(_, count)| *count).map(|(hex, _)| hex).unwrap_or_else(|| {
|
||||
// Nothing painted a background, so the terminal's own shows through. Dark is the safer
|
||||
// guess: it is what a terminal defaults to, and light text on it stays readable.
|
||||
"#000000".to_string()
|
||||
})
|
||||
}
|
||||
|
||||
/// Merged background rectangles, skipping whatever already matches the canvas.
|
||||
fn backgrounds(buffer: &Buffer, canvas: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for row in 0..buffer.area.height {
|
||||
let mut run: Option<(u16, u16, String)> = None;
|
||||
let flush = |run: &mut Option<(u16, u16, String)>, out: &mut String| {
|
||||
if let Some((start, end, fill)) = run.take() {
|
||||
let _ = writeln!(out, " {}", rect(start, row, end - start + 1, 1, &fill));
|
||||
}
|
||||
};
|
||||
for column in 0..buffer.area.width {
|
||||
let fill = hex(buffer[(column, row)].bg).filter(|fill| fill != canvas);
|
||||
match (&mut run, fill) {
|
||||
(Some((_, end, current)), Some(fill)) if *current == fill && *end + 1 == column => {
|
||||
*end = column;
|
||||
}
|
||||
(_, Some(fill)) => {
|
||||
flush(&mut run, &mut out);
|
||||
run = Some((column, column, fill));
|
||||
}
|
||||
(_, None) => flush(&mut run, &mut out),
|
||||
}
|
||||
}
|
||||
flush(&mut run, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One `<text>` per row, so selecting a line of the picture yields the line.
|
||||
pub(super) fn text(buffer: &Buffer) -> String {
|
||||
let width = f64::from(buffer.area.width) * CELL_W;
|
||||
let mut out = String::new();
|
||||
|
||||
for row in 0..buffer.area.height {
|
||||
let mut spans = String::new();
|
||||
let mut pending = String::new();
|
||||
let mut pending_style: Option<(String, String)> = None;
|
||||
|
||||
for column in 0..buffer.area.width {
|
||||
let cell = &buffer[(column, row)];
|
||||
let symbol = cell.symbol();
|
||||
let glyph = symbol.chars().next().unwrap_or(' ');
|
||||
// A drawn glyph leaves a space behind so the columns after it still line up, and so the
|
||||
// row does not paint the same mark twice. The whole symbol otherwise: an accent or a
|
||||
// joined emoji is several scalars in one cell, and an empty cell still takes a column.
|
||||
let typeset = if is_drawn(glyph) || symbol.is_empty() { " " } else { symbol };
|
||||
let style = (hex(cell.fg).unwrap_or_default(), attributes(cell.modifier));
|
||||
|
||||
if pending_style.as_ref() != Some(&style) {
|
||||
flush_span(&mut spans, &mut pending, &pending_style);
|
||||
pending_style = Some(style);
|
||||
}
|
||||
pending.push_str(typeset);
|
||||
}
|
||||
flush_span(&mut spans, &mut pending, &pending_style);
|
||||
|
||||
if spans.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let baseline = (f64::from(row) + BASELINE) * CELL_H;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" <text x=\"0\" y=\"{baseline:.1}\" textLength=\"{width:.0}\" \
|
||||
lengthAdjust=\"spacingAndGlyphs\" xml:space=\"preserve\">{spans}</text>"
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn flush_span(spans: &mut String, pending: &mut String, style: &Option<(String, String)>) {
|
||||
if pending.is_empty() {
|
||||
return;
|
||||
}
|
||||
let text = std::mem::take(pending);
|
||||
// A run of pure whitespace still has to occupy its columns, but needs no fill or attributes.
|
||||
if text.trim().is_empty() {
|
||||
let _ = write!(spans, "<tspan>{}</tspan>", escape(&text));
|
||||
return;
|
||||
}
|
||||
let (fill, attrs) = style.clone().unwrap_or_default();
|
||||
let fill = if fill.is_empty() { String::new() } else { format!(" fill=\"{fill}\"") };
|
||||
let _ = write!(spans, "<tspan{fill}{attrs}>{}</tspan>", escape(&text));
|
||||
}
|
||||
|
||||
/// Glyphs still reaching the font, most common first — the input to deciding what to draw next.
|
||||
pub(super) fn text_census(buffer: &Buffer) -> Vec<(char, usize)> {
|
||||
let mut tally: BTreeMap<char, usize> = BTreeMap::new();
|
||||
for cell in buffer.content() {
|
||||
let glyph = cell.symbol().chars().next().unwrap_or(' ');
|
||||
if glyph != ' ' && !glyph.is_ascii() && !is_drawn(glyph) {
|
||||
*tally.entry(glyph).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let mut census: Vec<(char, usize)> = tally.into_iter().collect();
|
||||
census.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
|
||||
census
|
||||
}
|
||||
|
||||
fn escape(text: &str) -> String {
|
||||
text.replace('&', "&").replace('<', "<").replace('>', ">")
|
||||
}
|
||||
180
crates/luxe-tui/examples/fixture_svg/tests.rs
Normal file
180
crates/luxe-tui/examples/fixture_svg/tests.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
use super::geometry::{block, is_drawn};
|
||||
use super::grid::parse_hex;
|
||||
use super::palette::with_variables;
|
||||
use super::svg::text;
|
||||
use super::*;
|
||||
use luxe_tui::fixture::FixtureScenario;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::style::Color;
|
||||
|
||||
fn shot() -> Buffer {
|
||||
render("luxe", FixtureScenario::ChatTools, None, 120, 30).0
|
||||
}
|
||||
|
||||
/// One palette picture stands in for every theme: no placeholder survives into the document,
|
||||
/// the fallbacks are the first theme's own colors, and every theme gets a value for every
|
||||
/// variable the picture uses.
|
||||
#[test]
|
||||
fn a_palette_picture_names_every_color_it_draws() {
|
||||
let themes = ["luxe".to_string(), "nord".to_string()];
|
||||
let (document, values) = palette_svg(&themes, FixtureScenario::ChatTools, 120, 30);
|
||||
assert!(!document.contains("=\"#0f"), "a placeholder leaked into the picture");
|
||||
assert!(document.contains("fill=\"var(--p0, #"), "{}", &document[..400]);
|
||||
let used = document.matches("var(--p").count();
|
||||
assert!(used > 20, "the picture is drawn in variables: {used}");
|
||||
let (luxe, nord) = (&values["luxe"], &values["nord"]);
|
||||
assert_eq!(luxe.len(), nord.len());
|
||||
assert!(luxe.iter().any(|(key, value)| nord[key] != *value), "the themes differ");
|
||||
for (key, value) in luxe {
|
||||
assert!(document.contains(&format!("var(--{key}, {value})")), "{key} unused");
|
||||
}
|
||||
}
|
||||
|
||||
/// Only attributes are rewritten: a hex color in the terminal's *text* is somebody's code.
|
||||
#[test]
|
||||
fn a_placeholder_in_the_text_is_left_alone() {
|
||||
let document = "<rect fill=\"#0f0001\"/><text>#0f0001</text>";
|
||||
let out = with_variables(document, &["#aaaaaa", "#bbbbbb"]);
|
||||
assert_eq!(out, "<rect fill=\"var(--p1, #bbbbbb)\"/><text>#0f0001</text>");
|
||||
}
|
||||
|
||||
/// The export is a real render, not a blank grid — the cheapest way to catch a fixture that
|
||||
/// stopped seeding itself.
|
||||
#[test]
|
||||
fn the_export_carries_the_render() {
|
||||
let svg = svg(&shot());
|
||||
assert!(svg.starts_with("<svg xmlns="));
|
||||
assert!(svg.trim_end().ends_with("</svg>"));
|
||||
assert!(svg.contains("<text "), "no typeset rows reached the document");
|
||||
assert!(svg.matches("<text ").count() > 5, "suspiciously few rows");
|
||||
}
|
||||
|
||||
/// Text stays text. The whole reason not to ship a PNG is that a reader can select a command
|
||||
/// out of the picture, so a run of real characters has to survive the trip.
|
||||
#[test]
|
||||
fn commands_in_the_render_are_still_selectable_text() {
|
||||
let svg = svg(&shot());
|
||||
assert!(svg.contains("cargo test"), "a command the fixture renders went missing");
|
||||
assert!(svg.contains("xml:space=\"preserve\""), "leading columns would collapse");
|
||||
assert!(svg.contains("lengthAdjust=\"spacingAndGlyphs\""), "the grid needs pinning");
|
||||
}
|
||||
|
||||
/// Every glyph defined as an exact cell fraction is drawn rather than typeset. These are the
|
||||
/// ones a font approximates, which is what makes a terminal picture look wrong.
|
||||
#[test]
|
||||
fn cell_fraction_glyphs_are_drawn_not_typeset() {
|
||||
for glyph in [
|
||||
'\u{2588}', '\u{2580}', '\u{2584}', '\u{258c}', '\u{2590}', '\u{2581}', '\u{2587}',
|
||||
'\u{258f}', '\u{2589}', '\u{2594}', '\u{2595}', '\u{2596}', '\u{259f}', '\u{2591}',
|
||||
'\u{2593}',
|
||||
] {
|
||||
assert!(is_drawn(glyph), "U+{:04X} should be geometry", glyph as u32);
|
||||
}
|
||||
for glyph in ['\u{2500}', '\u{2502}', '\u{250c}', '\u{253c}', '\u{256d}', '\u{2570}'] {
|
||||
assert!(is_drawn(glyph), "U+{:04X} should be geometry", glyph as u32);
|
||||
}
|
||||
for glyph in ['\u{e0b8}', '\u{e0ba}', '\u{e0bc}', '\u{e0be}'] {
|
||||
assert!(is_drawn(glyph), "U+{:04X} should be geometry", glyph as u32);
|
||||
}
|
||||
// Letters and the geometric shapes Luxe uses as marks stay text: any font has them, and
|
||||
// they carry meaning that should remain selectable.
|
||||
for glyph in ['a', '\u{276f}', '\u{25cf}', '\u{25c6}'] {
|
||||
assert!(!is_drawn(glyph), "U+{:04X} should be typeset", glyph as u32);
|
||||
}
|
||||
}
|
||||
|
||||
/// A drawn glyph leaves a space in its row, so the columns after it still land on the grid and
|
||||
/// the mark is not painted twice.
|
||||
#[test]
|
||||
fn a_drawn_glyph_holds_its_column_in_the_text_layer() {
|
||||
let mut buffer = Buffer::empty(ratatui::layout::Rect::new(0, 0, 3, 1));
|
||||
buffer[(0, 0)].set_symbol("\u{2588}");
|
||||
buffer[(1, 0)].set_symbol("A");
|
||||
buffer[(2, 0)].set_symbol("B");
|
||||
|
||||
let text = text(&buffer);
|
||||
assert!(text.contains("AB"), "typeset glyphs survive: {text}");
|
||||
assert!(!text.contains('\u{2588}'), "the block is drawn, not typeset: {text}");
|
||||
assert!(text.contains(' '), "the block still occupies its column: {text}");
|
||||
}
|
||||
|
||||
/// Quadrant masks are transcribed correctly. Getting one wrong is invisible in review and
|
||||
/// obvious on the page, so it is checked against the halves they must add up to.
|
||||
#[test]
|
||||
fn quadrant_masks_agree_with_the_halves_they_compose() {
|
||||
let area = |glyph: char| {
|
||||
block(glyph).expect("a block").0.iter().map(|(_, _, w, h)| w * h).sum::<f64>()
|
||||
};
|
||||
assert_eq!(area('\u{2596}'), 0.25, "one quadrant");
|
||||
assert_eq!(area('\u{259f}'), 0.75, "three quadrants");
|
||||
// ▘ upper-left plus ▗ lower-right is the same ink as ▚.
|
||||
assert_eq!(area('\u{2598}') + area('\u{2597}'), area('\u{259a}'));
|
||||
// Every eighth block covers the fraction it is named for.
|
||||
assert!((area('\u{2581}') - 0.125).abs() < f64::EPSILON, "one lower eighth");
|
||||
assert!((area('\u{2587}') - 0.875).abs() < f64::EPSILON, "seven lower eighths");
|
||||
assert!((area('\u{258f}') - 0.125).abs() < f64::EPSILON, "one left eighth");
|
||||
assert!((area('\u{2589}') - 0.875).abs() < f64::EPSILON, "seven left eighths");
|
||||
}
|
||||
|
||||
/// Markup that would break a parser is escaped. A diff of HTML is an ordinary thing to render.
|
||||
#[test]
|
||||
fn markup_in_the_render_is_escaped() {
|
||||
let mut buffer = Buffer::empty(ratatui::layout::Rect::new(0, 0, 5, 1));
|
||||
for (index, glyph) in "<a&b".chars().enumerate() {
|
||||
buffer[(index as u16, 0)].set_symbol(&glyph.to_string());
|
||||
}
|
||||
let text = text(&buffer);
|
||||
assert!(text.contains("<a&b"), "unescaped markup would break the document: {text}");
|
||||
}
|
||||
|
||||
/// A cell's whole symbol is typeset, and a wide glyph's trailing cell keeps its column, so the
|
||||
/// marker after each lands where the terminal put it.
|
||||
///
|
||||
/// The break this catches: the text layer kept only a cell's first scalar, so a decomposed
|
||||
/// accent lost its mark and a joined emoji lost everything after its first person.
|
||||
#[test]
|
||||
fn a_cell_keeps_its_whole_symbol_in_the_text_layer() {
|
||||
let mut buffer = Buffer::empty(ratatui::layout::Rect::new(0, 0, 8, 1));
|
||||
for (column, symbol) in
|
||||
["e\u{301}", "X", "\u{1f469}\u{200d}\u{1f4bb}", " ", "Y", "\u{4e2d}", "", "Z"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
buffer[(column as u16, 0)].set_symbol(symbol);
|
||||
}
|
||||
let text = text(&buffer);
|
||||
assert!(
|
||||
text.contains("e\u{301}X\u{1f469}\u{200d}\u{1f4bb} Y\u{4e2d} Z"),
|
||||
"every scalar of every cell, one column each: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A color that is not ASCII hex is refused, not sliced.
|
||||
///
|
||||
/// The break this catches: six bytes passed the length check and the channel slices cut a
|
||||
/// multi-byte character in half, which panics on a grid handed in on stdin.
|
||||
#[test]
|
||||
fn non_ascii_grid_colors_are_rejected_without_panicking() {
|
||||
// six bytes each, with a channel boundary inside a three-byte character
|
||||
assert_eq!(parse_hex("#a\u{20ac}bc"), None);
|
||||
assert_eq!(parse_hex("#\u{e9}\u{20ac}a"), None);
|
||||
assert_eq!(parse_hex("#0a0B0c"), Some(Color::Rgb(0x0a, 0x0b, 0x0c)));
|
||||
}
|
||||
|
||||
/// Each quadrant sits where its name says, not merely with the right amount of ink.
|
||||
#[test]
|
||||
fn quadrants_sit_in_their_own_corners() {
|
||||
let rects = |glyph: char| block(glyph).expect("a block").0;
|
||||
let (upper_left, upper_right) = ((0.0, 0.0, 0.5, 0.5), (0.5, 0.0, 0.5, 0.5));
|
||||
let (lower_left, lower_right) = ((0.0, 0.5, 0.5, 0.5), (0.5, 0.5, 0.5, 0.5));
|
||||
assert_eq!(rects('\u{2598}'), vec![upper_left]);
|
||||
assert_eq!(rects('\u{259d}'), vec![upper_right]);
|
||||
assert_eq!(rects('\u{2596}'), vec![lower_left]);
|
||||
assert_eq!(rects('\u{2597}'), vec![lower_right]);
|
||||
assert_eq!(rects('\u{259a}'), vec![upper_left, lower_right]);
|
||||
assert_eq!(rects('\u{259e}'), vec![upper_right, lower_left]);
|
||||
assert_eq!(rects('\u{2599}'), vec![upper_left, lower_left, lower_right]);
|
||||
assert_eq!(rects('\u{259b}'), vec![upper_left, upper_right, lower_left]);
|
||||
assert_eq!(rects('\u{259c}'), vec![upper_left, upper_right, lower_right]);
|
||||
assert_eq!(rects('\u{259f}'), vec![upper_right, lower_left, lower_right]);
|
||||
}
|
||||
Reference in New Issue
Block a user