A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
web: split glyph fallback into a platform painter and a shared procedure
RoversXbf54e5ebf50c
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 87255b1f..160d61f9 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -4132,6 +4132,7 @@ impl App {dpi,Rc::new(t),Rc::clone(&inner.glyphs.families),+ Rc::clone(&inner.glyphs.platform),)},) {@@ -4157,6 +4158,7 @@ impl App {dpi,Rc::new(t),Rc::clone(&inner.glyphs.families),+ Rc::clone(&inner.glyphs.platform),)});match built {@@ -4266,7 +4268,7 @@ impl App {let side = inner.glyphs.atlas.size() as u32;let (size_pt, dpi) = (inner.glyphs.size_pt, inner.glyphs.dpi);let built = GpuTexture::new(&inner.gpu.device, Arc::clone(&inner.gpu.queue), side, side).and_then(|t| {- GlyphCache::new(Rc::clone(&inner.fonts), size_pt * scale, dpi, Rc::new(t), Rc::clone(&inner.glyphs.families))+ GlyphCache::new(Rc::clone(&inner.fonts), size_pt * scale, dpi, Rc::new(t), Rc::clone(&inner.glyphs.families), Rc::clone(&inner.glyphs.platform))});match built {Ok(glyphs) => {@@ -4683,6 +4685,7 @@ impl App {inner.glyphs.dpi,texture,Rc::clone(&inner.glyphs.families),+ Rc::clone(&inner.glyphs.platform),)?;Ok(())}diff --git a/thinkterm-web/src/canvas.rs b/thinkterm-web/src/canvas.rsindex 3dfcb076..2c0df082 100644--- a/thinkterm-web/src/canvas.rs+++ b/thinkterm-web/src/canvas.rs@@ -1,27 +1,13 @@-//! A 2D canvas kept aside for drawing the glyphs the bundled faces cannot.-//!-//! The page ships two font files and does its own shaping, so it has no-//! system fallback chain: CJK, Hangul, emoji and a scattering of symbols-//! have no glyph at all. The browser, however, has every font the machine-//! has installed, and `fillText` will use them. So the missing graphemes-//! are drawn here, read back with `getImageData` and put into the same-//! atlas as everything else; WebGPU then draws them like any other glyph.-//! This is what xterm.js's WebGL renderer does.-//!-//! Only the DOM lives here. The arithmetic -- ink bounds, the colour-//! decision, the bearing -- is in `fallback.rs`, where it can be tested.+//! The browser's side of glyph fallback: a 2D canvas as the painter and+//! `performance.now` as the clock. The procedure that uses them is in+//! `raster.rs`; the arithmetic in `fallback.rs`. This is what xterm.js's+//! WebGL renderer does too.-use crate::fallback::{self, Ink, Placement};+use crate::raster::{GlyphPlatform, Platform, ScratchGeometry, TextPainter};use anyhow::{anyhow, Result};-use thinkterm_render::bitmaps::Image;-use thinkterm_render::geom::Size;+use std::rc::Rc;use wasm_bindgen::{JsCast, JsValue};-/// The widest glyph we will draw. Wider than any terminal cluster we expect-/// and cheap to be generous about: the scratch canvas is a few hundred-/// kilobytes at the largest cell size.-pub const MAX_FALLBACK_CELLS: u8 = 4;-/// The fonts the canvas draws with, in CSS order.////// The page gives the terminal no font stack of its own -- `#term` is a@@ -35,48 +21,31 @@ pub const MAX_FALLBACK_CELLS: u8 = 4;pub const DEFAULT_FAMILIES: &str ="ui-monospace, SFMono-Regular, Menlo, Consolas, \"DejaVu Sans Mono\", monospace";-/// Two fills that differ in **every** channel.-///-/// A glyph that takes our colour looks different under the two; one that-/// carries its own looks the same. Sharing a channel between them -- white-/// and red both have full red -- is what made the first measurements call-/// every Chinese character a colour glyph.-const FILL_A: &str = "#ff0000";-const FILL_B: &str = "#00ffff";+pub struct WebPlatform;++impl GlyphPlatform for WebPlatform {+ fn now_ms(&self) -> f64 {+ crate::app::monotonic_ms()+ }-/// A glyph the browser drew for us.-pub struct Drawn {- /// The ink, cropped, as straight (not premultiplied) RGBA.- pub image: Image,- pub placement: Placement,- pub has_color: bool,- /// The ink reached the edge of the scratch canvas, so it may have been- /// cut off. Reported rather than corrected: growing the canvas per- /// glyph would defeat the fixed geometry below.- pub clipped: bool,+ fn painter(&self, geometry: &ScratchGeometry, families: &str) -> Result<Box<dyn TextPainter>> {+ Ok(Box::new(CanvasPainter::new(geometry, families)?))+ }+}++pub fn platform() -> Platform {+ Rc::new(WebPlatform)}-/// The off-screen canvas the fallback glyphs are drawn on.-pub struct Scratch {+/// A canvas kept aside, sized to the scratch geometry, drawing with the+/// requested font stack.+pub struct CanvasPainter {ctx: web_sys::CanvasRenderingContext2d,- width: usize,- height: usize,- /// Where `fillText` is told to start, and the baseline it sits on --- /// both inside the scratch canvas, not the terminal.- pen_x: f64,- baseline: f64,- cell_width: f64,+ geometry: ScratchGeometry,}-impl Scratch {- /// A canvas sized once, for a cell of this size.- ///- /// The size never changes afterwards. Setting either dimension of a- /// canvas resets every attribute of its 2D context -- font, fill,- /// baseline, the lot -- so a canvas that resized would have to reinstate- /// all of them, and forgetting one would show up as glyphs drawn at the- /// wrong size with nothing to say why.- pub fn new(cell: Size, descender: f64, px: f64, families: &str) -> Result<Self> {+impl CanvasPainter {+ pub fn new(geometry: &ScratchGeometry, families: &str) -> Result<Self> {let document = web_sys::window().and_then(|w| w.document()).ok_or_else(|| anyhow!("no document"))?;@@ -85,15 +54,8 @@ impl Scratch {.map_err(|e| anyhow!("canvas: {e:?}"))?.dyn_into().map_err(|_| anyhow!("created element is not a canvas"))?;- // Never added to the document. `getContext`, `fillText` and- // `getImageData` all work on a detached element, and the page has no- // styling that would find a stray canvas anyway.- let (width, height) = (- (MAX_FALLBACK_CELLS as usize + 2) * cell.width.max(1) as usize,- 2 * cell.height.max(1) as usize,- );- canvas.set_width(width as u32);- canvas.set_height(height as u32);+ canvas.set_width(geometry.width as u32);+ canvas.set_height(geometry.height as u32);let options = js_sys::Object::new();let set = |key: &str, value: bool| {@@ -101,9 +63,6 @@ impl Scratch {.map_err(|e| anyhow!("context option {key}: {e:?}"))};set("alpha", true)?;- // Every draw here is followed by a read. Without this the browser- // keeps the canvas on the GPU and each `getImageData` stalls on a- // readback: measured at 1053 us per glyph rather than 54.set("willReadFrequently", true)?;let ctx: web_sys::CanvasRenderingContext2d = canvas.get_context_with_context_options("2d", &options)@@ -111,20 +70,7 @@ impl Scratch {.ok_or_else(|| anyhow!("no 2d context"))?.dyn_into().map_err(|_| anyhow!("2d context has the wrong type"))?;- // The canvas `font` setter silently ignores anything that is not- // a valid CSS `font` shorthand and keeps what it had, which on a- // fresh context is the spec default `10px sans-serif`. `families`- // comes straight from `?glyphfont=`, so one stray comma -- or a- // family whose name starts with a digit, which CSS will not take- // unquoted -- would draw every glyph at 10px into a cell several- // times that size, with nothing anywhere saying so. Read it back.- //- // Whole pixels, because the browser hands the string back in its own- // serialised form: it turns `17.333333333333332px` into- // `17.3333px`, and comparing those two is how the first version of- // this check decided every font had been refused.- let px = px.max(1.0).round();- let size = format!("{px}px");+ let size = format!("{}px", geometry.px);ctx.set_font(&format!("{size} {families}"));if !ctx.font().starts_with(&size) {log::warn!(@@ -134,10 +80,6 @@ impl Scratch {);ctx.set_font(&format!("{size} {DEFAULT_FAMILIES}"));}- // Reported, never fatal. Refusing here leaves every fallback- // grapheme a box for the life of this cache -- far worse than glyphs- // drawn at the wrong size, which is all this check was ever meant to- // catch.if !ctx.font().starts_with(&size) {log::warn!("the canvas font is {:?} rather than {size}; fallback glyphs may be mis-sized",@@ -145,138 +87,27 @@ impl Scratch {);}ctx.set_text_baseline("alphabetic");-- // A cell of margin on the left and half a cell above, so a glyph- // that overhangs its cell is measured rather than clipped.- let pen_x = cell.width as f64;- let row_top = cell.height as f64 / 2.0;- // The same baseline the emitter uses: it puts a sprite's top at- // `cell_height + descender - bearing_y`, and `cell_height +- // descender` is the baseline. Kept in floating point, because the- // emitter subtracts exactly this number.- let baseline = row_top + cell.height as f64 + descender;Ok(Self {ctx,- width,- height,- pen_x,- baseline,- cell_width: cell.width as f64,+ geometry: *geometry,})}+}- fn clear(&self) {+impl TextPainter for CanvasPainter {+ fn paint(&self, text: &str, fill: [u8; 3]) -> Result<Vec<u8>> {+ let g = &self.geometry;+ self.ctx.clear_rect(0.0, 0.0, g.width as f64, g.height as f64);self.ctx- .clear_rect(0.0, 0.0, self.width as f64, self.height as f64);- }-- fn draw(&self, text: &str, fill: &str) -> Result<()> {- self.clear();- self.ctx.set_fill_style_str(fill);+ .set_fill_style_str(&format!("#{:02x}{:02x}{:02x}", fill[0], fill[1], fill[2]));self.ctx- .fill_text(text, self.pen_x, self.baseline)- .map_err(|e| anyhow!("fillText: {e:?}"))- }-- fn read(&self, x: f64, y: f64, w: f64, h: f64) -> Result<Vec<u8>> {+ .fill_text(text, g.pen_x, g.baseline)+ .map_err(|e| anyhow!("fillText: {e:?}"))?;Ok(self.ctx- .get_image_data(x, y, w, h)+ .get_image_data(0.0, 0.0, g.width as f64, g.height as f64).map_err(|e| anyhow!("getImageData: {e:?}"))?.data().0)}-- /// Draw one grapheme twice and read back what happened.- ///- /// The first draw says where the ink is; the second says whether the- /// glyph took the colour we asked for or brought its own. The second is- /// read back over the ink alone -- strictly less work, and it comes out- /// packed the same way as the first crop, so the two compare directly.- ///- /// `Ok(None)` means the browser drew nothing, which is what a machine- /// with no font for this grapheme does.- fn render(&self, text: &str) -> Result<Option<(Ink, Vec<u8>, bool)>> {- self.draw(text, FILL_A)?;- let first = self.read(0.0, 0.0, self.width as f64, self.height as f64)?;- let Some(ink) = fallback::ink_box(&first, self.width, self.height) else {- return Ok(None);- };- let cropped = fallback::crop(&first, self.width, &ink);- self.draw(text, FILL_B)?;- let second = self.read(- ink.left as f64,- ink.top as f64,- ink.width as f64,- ink.height as f64,- )?;- let has_color = fallback::carries_own_colour(&cropped, &second);- Ok(Some((ink, cropped, has_color)))- }-- /// How wide the ink may be before it is scaled down, in the same terms- /// `load_glyph` uses: the columns the row gave it, plus a quarter.- ///- /// The columns come from the row and never from the canvas.- /// `measureText` would offer an advance, and an advance is not a column- /// count -- Hangul measured 1.73 cells and the arrows 1.2 -- which is- /// why its web-sys feature is deliberately not enabled.- fn max_width(&self, cells: u8) -> f64 {- self.cell_width * (cells.max(1) as f64 + 0.25)- }-- /// The width limit a glyph is placed against. A colour glyph gets none:- /// see `glyph`.- fn limit(&self, cells: u8, has_color: bool) -> f64 {- if has_color {- f64::INFINITY- } else {- self.max_width(cells)- }- }-- /// One grapheme, ready for the atlas.- pub fn glyph(&self, text: &str, cells: u8) -> Result<Option<Drawn>> {- let Some((ink, cropped, has_color)) = self.render(text)? else {- return Ok(None);- };- // A colour glyph is given no width limit, so it is never scaled.- // `getImageData` returns straight RGBA, in which a fully transparent- // pixel is (0,0,0,0), and the resampler mixes channels without- // regard to alpha -- so every partly transparent pixel is dragged- // towards black and a scaled emoji picks up a dark halo. Letting it- // overflow its cells is what wide glyphs already do, and it costs- // almost nothing here: the browser draws emoji at the cell size, so- // their ink fits inside the quarter-cell of slack anyway. Ink that- // overflows so far that it hits the edge of this canvas is refused- // by the caller rather than placed from a truncated box.- Ok(Some(Drawn {- image: Image::from_raw(ink.width, ink.height, cropped),- placement: fallback::place(- &ink,- self.pen_x,- self.baseline,- self.limit(cells, has_color),- ),- has_color,- clipped: ink.clipped,- }))- }-- /// One grapheme, reported rather than drawn. Only the probe uses this.- pub fn measure(&self, text: &str, cells: u8) -> Result<Option<(Ink, Placement, bool)>> {- let Some((ink, _, has_color)) = self.render(text)? else {- return Ok(None);- };- // The same limit `glyph` uses, or the probe would report a scale- // the terminal never applies.- let placement =- fallback::place(&ink, self.pen_x, self.baseline, self.limit(cells, has_color));- Ok(Some((ink, placement, has_color)))- }-- /// What this canvas is doing, for the `?check=fallback` probe.- pub fn geometry(&self) -> (usize, usize, f64, f64) {- (self.width, self.height, self.pen_x, self.baseline)- }}diff --git a/thinkterm-web/src/glyphs.rs b/thinkterm-web/src/glyphs.rsindex 046af13e..ad0fb7d2 100644--- a/thinkterm-web/src/glyphs.rs+++ b/thinkterm-web/src/glyphs.rs@@ -155,6 +155,8 @@ pub struct GlyphCache {scratch: Renderer,/// The CSS font stack the fallback draws with.pub families: Rc<str>,+ /// The clock and the painter for glyphs the faces lack.+ pub platform: crate::raster::Platform,/// Handed back wherever a glyph cannot be made right now. Shared, so/// the frozen path allocates nothing at all.blank: Rc<CachedGlyph>,@@ -170,7 +172,7 @@ pub struct GlyphCache {/// give us a 2D context is asked exactly once.enum Renderer {Untried,- Ready(crate::canvas::Scratch),+ Ready(crate::raster::Scratch),Unavailable,}@@ -198,6 +200,7 @@ impl GlyphCache {dpi: u32,texture: Rc<GpuTexture>,families: Rc<str>,+ platform: crate::raster::Platform,) -> Result<Self> {let base_metrics = fonts.metrics(size_pt, dpi)?;let metrics = RenderMetrics::with_font_metrics(&base_metrics);@@ -231,6 +234,7 @@ impl GlyphCache {failed: HashMap::new(),scratch: Renderer::Untried,families,+ platform,blank: Rc::new(blank_glyph()),frozen: false,declined: 0,@@ -336,10 +340,11 @@ impl GlyphCache {/// asked once per cache -- this is a field, so an atlas growth or clear/// rebuilds it along with everything else, which is what keeps it in/// step with the cell size.- fn scratch(&mut self) -> Option<&crate::canvas::Scratch> {+ fn scratch(&mut self) -> Option<&crate::raster::Scratch> {if matches!(self.scratch, Renderer::Untried) {let px = self.size_pt * self.dpi as f64 / 72.0;- self.scratch = match crate::canvas::Scratch::new(+ self.scratch = match crate::raster::Scratch::new(+ &*self.platform,self.metrics.cell_size,self.metrics.descender.get(),px,@@ -433,7 +438,7 @@ impl GlyphCache {// so the box is the honest answer. Nothing in a terminal is this// wide -- the widest cluster the shaper produces is two columns --// but `cells` comes from the row, and the row is data.- if cells > crate::canvas::MAX_FALLBACK_CELLS {+ if cells > crate::raster::MAX_FALLBACK_CELLS {return Ok(self.remember(gap, cells, None));}if let Some(known) = self@@ -447,7 +452,7 @@ impl GlyphCache {self.declined += 1;return Ok(None);}- let now = crate::app::monotonic_ms();+ let now = self.platform.now_ms();if let Some((retry_at, _)) = self.failed.get(&(cells, gap.text.clone())) {if now < *retry_at {return Ok(None);@@ -467,7 +472,7 @@ impl GlyphCache {let drawn = match self.scratch() {None => return Ok(None),Some(scratch) => {- if !budget.take(crate::app::monotonic_ms()) {+ if !budget.take(now) {return Ok(None);}scratch.glyph(&gap.text, cells)diff --git a/thinkterm-web/src/graphics_check.rs b/thinkterm-web/src/graphics_check.rsindex 859987b7..5d2a6227 100644--- a/thinkterm-web/src/graphics_check.rs+++ b/thinkterm-web/src/graphics_check.rs@@ -57,6 +57,7 @@ async fn run(names: Vec<String>, fonts: Vec<js_sys::Uint8Array>, size: f64) -> R(96.0 * dpr) as u32,texture,crate::canvas::DEFAULT_FAMILIES.into(),+ crate::canvas::platform(),)?;let (cw, ch) = (cache.metrics.cell_size.width as u32,diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rsindex a9bea2dd..ebc7e4b3 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -1,7 +1,9 @@//! The ThinkTerm browser client. See Cargo.toml for the charter.//!-//! `braille`, `fallback`, `keymap`, `lease` and `viewport` are pure and-//! build everywhere; everything that touches the page is `wasm32` only.+//! `braille`, `fallback`, `keymap`, `lease`, `raster` and `viewport` are pure+//! and build everywhere, and so do `emit` and `glyphs` -- the drawing of a+//! line and the glyph atlas -- which the mobile client shares; everything+//! that touches the page is `wasm32` only.pub mod agents;pub mod braille;@@ -15,6 +17,7 @@ pub mod lease;pub mod menu;pub mod navbar;pub mod palette;+pub mod raster;pub mod settings;pub mod sidebar;pub mod tree;@@ -29,10 +32,8 @@ mod attach;mod bridge;#[cfg(target_arch = "wasm32")]mod canvas;-#[cfg(target_arch = "wasm32")]-mod emit;-#[cfg(target_arch = "wasm32")]-mod glyphs;+pub mod emit;+pub mod glyphs;#[cfg(target_arch = "wasm32")]mod gpu;#[cfg(target_arch = "wasm32")]diff --git a/thinkterm-web/src/page.rs b/thinkterm-web/src/page.rsindex 692d5817..4182c624 100644--- a/thinkterm-web/src/page.rs+++ b/thinkterm-web/src/page.rs@@ -170,7 +170,7 @@ async fn start_attached(let gpu = Gpu::new(canvas.clone(), dev_w, dev_h).await?;let atlas_side = 1024u32.min(gpu.max_texture_dimension());let texture = Rc::new(GpuTexture::new(&gpu.device, Arc::clone(&gpu.queue), atlas_side, atlas_side)?);- let glyphs = GlyphCache::new(Rc::clone(&fonts), size_pt, dpi, texture, families(glyph_font))?;+ let glyphs = GlyphCache::new(Rc::clone(&fonts), size_pt, dpi, texture, families(glyph_font), crate::canvas::platform())?;let (cw, ch) = (glyphs.metrics.cell_size.width as u32,glyphs.metrics.cell_size.height as u32,@@ -406,9 +406,16 @@ pub fn fallback_check(let metrics = crate::glyphs::RenderMetrics::with_font_metrics(&set.metrics(size_pt, dpi)?);let stack = families(&glyph_font);let px = size_pt * dpi as f64 / 72.0;- let scratch =- crate::canvas::Scratch::new(metrics.cell_size, metrics.descender.get(), px, &stack)?;- let (canvas_w, canvas_h, pen_x, baseline) = scratch.geometry();+ let scratch = crate::raster::Scratch::new(+ &crate::canvas::WebPlatform,+ metrics.cell_size,+ metrics.descender.get(),+ px,+ &stack,+ )?;+ let geometry = scratch.geometry();+ let (canvas_w, canvas_h, pen_x, baseline) =+ (geometry.width, geometry.height, geometry.pen_x, geometry.baseline);let mut rows = Vec::new();let (mut drawn, mut wrong_colour, mut clipped, mut blank) = (0, 0, 0, 0);diff --git a/thinkterm-web/src/raster.rs b/thinkterm-web/src/raster.rsnew file mode 100644index 00000000..2fd96aaf--- /dev/null+++ b/thinkterm-web/src/raster.rs@@ -0,0 +1,245 @@+//! Drawing the glyphs the bundled faces cannot, on any platform.+//!+//! The page ships two font files and does its own shaping, so it has no+//! system fallback chain: CJK, Hangul, emoji and a scattering of symbols+//! have no glyph at all. The platform, however, has every font the machine+//! has installed. So the missing graphemes are painted by it -- a 2D canvas+//! in the browser, CoreText on iOS, `android.graphics` on Android -- read+//! back as pixels and put into the same atlas as everything else.+//!+//! Only the painting primitive is platform code ([`TextPainter`]). The+//! procedure around it -- paint twice in fills that differ in every+//! channel to learn whether the glyph carries its own colour, find the+//! ink, crop it, decide the bearing -- is here, and the arithmetic it+//! leans on is in `fallback.rs`, where it is tested.++use crate::fallback::{self, Ink, Placement};+use anyhow::Result;+use std::rc::Rc;+use thinkterm_render::bitmaps::Image;+use thinkterm_render::geom::Size;++/// The widest glyph we will draw. Wider than any terminal cluster we expect+/// and cheap to be generous about: the scratch is a few hundred kilobytes+/// at the largest cell size.+pub const MAX_FALLBACK_CELLS: u8 = 4;++/// Two fills that differ in **every** channel.+///+/// A glyph that takes our colour looks different under the two; one that+/// carries its own looks the same. Sharing a channel between them -- white+/// and red both have full red -- is what made the first measurements call+/// every Chinese character a colour glyph.+pub const FILL_A: [u8; 3] = [0xff, 0x00, 0x00];+pub const FILL_B: [u8; 3] = [0x00, 0xff, 0xff];++/// The scratch surface a painter draws into: its size in pixels, where+/// the pen starts and where the baseline sits, and the font size.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct ScratchGeometry {+ pub width: usize,+ pub height: usize,+ pub pen_x: f64,+ pub baseline: f64,+ /// Font size in pixels, already rounded.+ pub px: f64,+}++impl ScratchGeometry {+ /// Room for `MAX_FALLBACK_CELLS` cells with a cell of margin on either+ /// side and half a row above and below, so ink that overhangs is kept+ /// rather than cut.+ pub fn for_cell(cell: Size, descender: f64, px: f64) -> Self {+ let cell_w = cell.width.max(1) as usize;+ let cell_h = cell.height.max(1) as usize;+ let row_top = cell_h as f64 / 2.0;+ Self {+ width: (MAX_FALLBACK_CELLS as usize + 2) * cell_w,+ height: 2 * cell_h,+ pen_x: cell_w as f64,+ baseline: row_top + cell_h as f64 + descender,+ px: px.max(1.0).round(),+ }+ }+}++/// What the platform must do: paint `text` in one solid colour at the+/// geometry it was built for and hand back the whole scratch as RGBA,+/// `width * height * 4` bytes, non-premultiplied, transparent where nothing+/// was painted.+pub trait TextPainter {+ fn paint(&self, text: &str, fill: [u8; 3]) -> Result<Vec<u8>>;+}++/// What a glyph cache needs from its platform: a clock that does not step+/// (for the per-frame budget and the retry backoff) and painters.+pub trait GlyphPlatform {+ /// Milliseconds from a monotonic clock.+ fn now_ms(&self) -> f64;+ /// A painter for one scratch geometry, drawing with `families` (a CSS+ /// font stack on the web; other platforms may ignore it).+ fn painter(&self, geometry: &ScratchGeometry, families: &str) -> Result<Box<dyn TextPainter>>;+}++pub type Platform = Rc<dyn GlyphPlatform>;++/// A glyph the platform drew for us.+pub struct Drawn {+ /// The ink, cropped, in the cell's coordinate space.+ pub image: Image,+ pub placement: Placement,+ /// Whether it carries its own colour (an emoji) or takes the cell's.+ pub has_color: bool,+ /// The ink touched the edge of the scratch: it was cut, and the caller+ /// should not trust its width.+ pub clipped: bool,+}++/// The scratch and the procedure; the painter is the only platform part.+pub struct Scratch {+ painter: Box<dyn TextPainter>,+ geometry: ScratchGeometry,+ cell_width: f64,+}++impl Scratch {+ pub fn new(+ platform: &dyn GlyphPlatform,+ cell: Size,+ descender: f64,+ px: f64,+ families: &str,+ ) -> Result<Self> {+ let geometry = ScratchGeometry::for_cell(cell, descender, px);+ let painter = platform.painter(&geometry, families)?;+ Ok(Self {+ painter,+ geometry,+ cell_width: cell.width.max(1) as f64,+ })+ }++ fn render(&self, text: &str) -> Result<Option<(Ink, Vec<u8>, bool)>> {+ let (width, height) = (self.geometry.width, self.geometry.height);+ let first = self.painter.paint(text, FILL_A)?;+ anyhow::ensure!(+ first.len() == width * height * 4,+ "the painter returned {} bytes for a {width}x{height} scratch",+ first.len()+ );+ let Some(ink) = fallback::ink_box(&first, width, height) else {+ return Ok(None);+ };+ let cropped = fallback::crop(&first, width, &ink);+ let second_full = self.painter.paint(text, FILL_B)?;+ anyhow::ensure!(+ second_full.len() == width * height * 4,+ "the painter returned {} bytes for a {width}x{height} scratch",+ second_full.len()+ );+ let second = fallback::crop(&second_full, width, &ink);+ let has_color = fallback::carries_own_colour(&cropped, &second);+ Ok(Some((ink, cropped, has_color)))+ }++ fn max_width(&self, cells: u8) -> f64 {+ self.cell_width * (cells.max(1) as f64 + 0.25)+ }++ fn limit(&self, cells: u8, has_color: bool) -> f64 {+ if has_color {+ f64::INFINITY+ } else {+ self.max_width(cells)+ }+ }++ pub fn glyph(&self, text: &str, cells: u8) -> Result<Option<Drawn>> {+ let Some((ink, cropped, has_color)) = self.render(text)? else {+ return Ok(None);+ };+ Ok(Some(Drawn {+ image: Image::from_raw(ink.width, ink.height, cropped),+ placement: fallback::place(+ &ink,+ self.geometry.pen_x,+ self.geometry.baseline,+ self.limit(cells, has_color),+ ),+ has_color,+ clipped: ink.clipped,+ }))+ }++ pub fn measure(&self, text: &str, cells: u8) -> Result<Option<(Ink, Placement, bool)>> {+ let Some((ink, _, has_color)) = self.render(text)? else {+ return Ok(None);+ };+ let placement = fallback::place(+ &ink,+ self.geometry.pen_x,+ self.geometry.baseline,+ self.limit(cells, has_color),+ );+ Ok(Some((ink, placement, has_color)))+ }++ pub fn geometry(&self) -> ScratchGeometry {+ self.geometry+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use thinkterm_render::bitmaps::BitmapImage;++ /// A painter that draws a filled box for any text, in the fill it is+ /// given, so the colour test sees a glyph that takes our colour.+ struct BoxPainter(ScratchGeometry);++ impl TextPainter for BoxPainter {+ fn paint(&self, text: &str, fill: [u8; 3]) -> Result<Vec<u8>> {+ let g = self.0;+ let mut out = vec![0u8; g.width * g.height * 4];+ if text.is_empty() {+ return Ok(out);+ }+ let (x0, y0, w, h) = (g.pen_x as usize, g.baseline as usize - 10, 8usize, 10usize);+ for y in y0..y0 + h {+ for x in x0..x0 + w {+ let i = (y * g.width + x) * 4;+ out[i..i + 3].copy_from_slice(&fill);+ out[i + 3] = 255;+ }+ }+ Ok(out)+ }+ }++ struct Fake;+ impl GlyphPlatform for Fake {+ fn now_ms(&self) -> f64 {+ 0.0+ }+ fn painter(&self, geometry: &ScratchGeometry, _: &str) -> Result<Box<dyn TextPainter>> {+ Ok(Box::new(BoxPainter(*geometry)))+ }+ }++ #[test]+ fn a_box_is_a_monochrome_glyph_at_the_pen() {+ let scratch = Scratch::new(&Fake, Size::new(9, 20), -4.0, 16.0, "").unwrap();+ let drawn = scratch.glyph("x", 1).unwrap().expect("ink");+ assert!(!drawn.has_color);+ assert!(!drawn.clipped);+ assert_eq!(drawn.image.image_dimensions(), (8, 10));+ assert_eq!(drawn.placement.bearing_x, 0.0);+ }++ #[test]+ fn nothing_painted_is_no_glyph() {+ let scratch = Scratch::new(&Fake, Size::new(9, 20), -4.0, 16.0, "").unwrap();+ assert!(scratch.glyph("", 1).unwrap().is_none());+ }+}