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
thinkterm-web: fallback glyphs, an anchored IME field, and reconnect
RoversX8d908eb02d24
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.mdindex 3325025a..44d4f22f 100644--- a/docs/thinkterm/web-access.md+++ b/docs/thinkterm/web-access.md@@ -92,9 +92,47 @@ for instance at a development checkout.## What the first version does not do-Images (kitty, sixel, iTerm2) and colour emoji are not drawn; tabs, splits and-the ThinkTerm tree are not shown -- the page mirrors one pane; there is no-reconnect after the socket drops (reload the page); the cursor does not blink;-box-drawing comes from the font rather than the desktop's custom block glyphs;-font fallback is the bundled list (JetBrains Mono, Symbols Nerd Font Mono), so-scripts outside it show as missing-glyph boxes.+Images (kitty, sixel, iTerm2) are not drawn; tabs, splits and the ThinkTerm+tree are not shown -- the page mirrors one pane, chosen when it connects,+and does not follow the desktop to another; the cursor does not blink. The input+method's hidden field follows the terminal cursor, including scrolling and+resizing, so the browser can place its candidate window there; pre-edit+text and its underline are not yet drawn in the grid.++A dropped socket is reopened by the page itself, with a backoff, on the same+pane; the status line says so while it is down. It gives up only when there+is nothing to come back to -- the pane was closed, or the server speaks a+different protocol version -- and says which.++## Fonts++The page ships two faces (JetBrains Mono, Symbols Nerd Font Mono) and shapes+with them. Anything they do not cover -- CJK, Hangul, emoji, a scattering of+symbols -- is drawn with **your own machine's fonts**, on a 2D canvas, and+kept in the same glyph atlas as everything else. Braille is drawn from the+dot pattern rather than from a font, as the desktop does.++Blocks, fractions, shades and box-drawing use the desktop's shared geometric+glyph renderer instead of font outlines, so adjacent cells meet at their+edges. These glyphs are cached in the same atlas and obey its allocation+freeze and recovery rules. They do not use the Canvas font fallback budget.++`?glyphfont=` sets the CSS font stack used for that, which is also how the+regional shape of a Han character is chosen: pass a Japanese face to get+Japanese forms. A grapheme your machine has no font for either is still a+missing-glyph box, the same as it would be in a native terminal there.++Right-to-left scripts stay as boxes on purpose: the page does not do bidi,+so drawing them would put correct glyphs in the wrong order, which is harder+to notice than a box.++`?check=fallback` draws a sample of every kind and prints what it measured,+as JSON, in the status line. It needs no server, no token and no WebGPU, so+it is the way to check a browser or a machine before relying on it.++`?check=graphics` checks the real WebGPU line renderer for block seams,+cache reuse, recovery of a frozen cache miss, and the input field's DOM+position. It needs WebGPU but no token or pane. It reports CPU emission+timings for its sample, not end-to-end terminal latency. Use a real input+method to verify the native candidate window; the DOM check cannot inspect+that operating-system UI.diff --git a/thinkterm-web/Cargo.toml b/thinkterm-web/Cargo.tomlindex 70c63b24..78ee4496 100644--- a/thinkterm-web/Cargo.toml+++ b/thinkterm-web/Cargo.toml@@ -36,11 +36,18 @@ console_error_panic_hook.workspace = truejs-sys.workspace = truewasm-bindgen.workspace = truewasm-bindgen-futures.workspace = true+# CanvasRenderingContext2d and ImageData are what the glyph fallback draws+# missing graphemes with (see canvas.rs). TextMetrics is deliberately absent:+# `measureText` only offers an advance, and using an advance as a column+# count would put fallback glyphs on the wrong grid -- leaving the feature+# off makes that mistake unavailable rather than merely discouraged.web-sys = { workspace = true, features = [- "BinaryType", "Clipboard", "ClipboardEvent", "CloseEvent", "CompositionEvent",+ "BinaryType", "CanvasRenderingContext2d", "Clipboard", "ClipboardEvent",+ "CloseEvent", "CompositionEvent","console", "CssStyleDeclaration", "DataTransfer", "Document", "DomRect","DomRectReadOnly", "Element", "Event", "EventTarget", "FocusEvent", "History",- "HtmlCanvasElement", "HtmlElement", "HtmlTextAreaElement", "InputEvent",+ "HtmlCanvasElement", "HtmlElement", "HtmlTextAreaElement", "ImageData",+ "InputEvent","KeyboardEvent", "Location", "MessageEvent", "MouseEvent", "Navigator","Performance", "PointerEvent", "ResizeObserver", "ResizeObserverEntry", "Storage","WebSocket", "WheelEvent", "Window",diff --git a/thinkterm-web/smoke/cdp.js b/thinkterm-web/smoke/cdp.jsindex f846cd44..51f7a21c 100644--- a/thinkterm-web/smoke/cdp.js+++ b/thinkterm-web/smoke/cdp.js@@ -9,6 +9,7 @@const { spawn } = require("child_process");const http = require("http");const fs = require("fs");+const os = require("os");const WebSocket = require("ws");const args = process.argv.slice(2);@@ -23,8 +24,13 @@ const port = 9333 + Math.floor(Math.random() * 500);// Whatever happens, this process ends.setTimeout(() => { console.error("cdp: watchdog"); try { chrome.kill(); } catch {} process.exit(4); }, timeoutMs + 30000).unref();+// A profile of our own. Without one, launching the app bundle hands the+// request to the Chrome the user already has open and exits, so this script+// would drive their tabs -- or nothing at all -- instead of the page.+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-cdp-`);const chrome = spawn(chromePath, ["--headless=new", "--no-first-run", `--remote-debugging-port=${port}`,+ `--user-data-dir=${profile}`,"--window-size=1240,720", "--hide-scrollbars", "--enable-unsafe-webgpu", "about:blank",], { stdio: "ignore" });const sleep = (ms) => new Promise((r) => setTimeout(r, ms));@@ -63,10 +69,15 @@ async function browserWs() {const deadline = Date.now() + timeoutMs;let text = "";const re = waitStatus ? new RegExp(waitStatus) : null;+ // The probes (?check=graphics, ?check=fallback, the colour check) end in+ // a JSON line whose `ok` says whether they passed; a probe line that says+ // false is a failure whatever else the status looks like.+ const probeFailed = (t) => /^(FALLBACK|GRAPHICS|COLOR)\b/.test(t) && !/"ok"\s*:\s*true\b/.test(t);+ const hardFailed = (t) => /^(disconnected|no token|WebGPU|error)/i.test(t) || /^FAIL/.test(t) || probeFailed(t);while (Date.now() < deadline) {text = await status();if (re ? re.test(text) : text && !/…$/.test(text)) break;- if (/^(disconnected|no token|WebGPU|error)/i.test(text) || /^FAIL/.test(text)) break;+ if (hardFailed(text)) break;await sleep(250);}console.log("STATUS " + text);@@ -87,5 +98,10 @@ async function browserWs() {fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));console.log(logs.join("\n"));ws.close(); chrome.kill();- process.exit(re && !re.test(text) ? 3 : 0);+ // Without --wait-status this used to exit 0 no matter what the page said,+ // so a smoke run that reported an error still passed CI.+ // A probe that reports ok:false fails even when --wait-status matched it:+ // the pattern says the probe finished, the JSON says how.+ const failed = (re ? !re.test(text) : !text) || hardFailed(text);+ process.exit(failed ? 3 : 0);})().catch((e) => { console.error(e); chrome.kill(); process.exit(1); });diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex af7c6534..fa72b98e 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -1,6 +1,7 @@//! The page's state: one pane session, the canvas it is drawn on, where//! the user is looking, what they selected, and who owns the tab.+use crate::fallback::{Capacity, FallbackBudget, Next, MIN_RETRY_MS};use crate::glyphs::GlyphCache;use crate::gpu::Gpu;use crate::host::WebHost;@@ -51,6 +52,20 @@ impl Selection {}/// Everything the page hands the app once it is attached.+/// Reconnect backoff. The first attempt is immediate -- a socket that+/// dropped because a laptop's wifi blinked is usually back at once -- and+/// the wait doubles from there so a server that is down for an hour is not+/// hammered.+const RECONNECT_MIN_MS: f64 = 500.0;+const RECONNECT_MAX_MS: f64 = 15_000.0;+/// After this many failed attempts the status line stops saying+/// "reconnecting" and admits it may never work.+const RECONNECT_DOUBT_AFTER: u32 = 6;+/// How long a new connection has to last before the backoff is forgiven.+/// Shorter than the shortest useful outage and longer than the time a+/// server that is restarting in a loop stays up.+const RECONNECT_STABLE_MS: f64 = 5_000.0;+pub struct Setup {pub link: WsLink,pub session: Arc<PaneSession<WebHost>>,@@ -61,6 +76,9 @@ pub struct Setup {pub canvas: web_sys::HtmlCanvasElement,pub textarea: web_sys::HtmlTextAreaElement,pub status: Option<web_sys::Element>,+ /// Kept so the page can reopen the socket by itself.+ pub url: String,+ pub token: String,pub pane_id: PaneId,pub tab_id: TabId,pub dpr: f64,@@ -93,22 +111,79 @@ pub struct Inner {last_click_ms: f64,focused: bool,composing: bool,+ /// Refreshed on layout/scroll changes, avoiding layout reads per glyph+ /// or per frame. The IME field itself uses fixed CSS positioning.+ canvas_rect: [f64; 4],+ ime_anchor: Option<crate::ime::Anchor>,+ /// Set while there is no live socket. Cleared by a reconnect, which is+ /// why it is no longer the end of the page's life.disconnected: Option<String>,+ url: String,+ token: String,+ /// How long to wait before the next attempt, and whether one is already+ /// scheduled. Attempts are counted only to change what the status line+ /// says after enough of them.+ reconnect_delay: f64,+ reconnect_pending: bool,+ reconnect_attempts: u32,+ /// When the current connection came up, until it has lasted long enough+ /// to be called good. `None` once the backoff has been forgiven.+ connected_since: Option<f64>,quads: HeapQuadAllocator,vertices: Vec<Vertex>,title: String,+ /// What to do about an atlas that has run out of room for good.+ capacity: Capacity,}pub struct App {inner: RefCell<Inner>,frame_requested: Cell<bool>,raf: RefCell<Option<Closure<dyn FnMut()>>>,+ /// The atlas backoff's own wake-up. Everything else here is driven by+ /// input or by output; this is the one thing that has to happen on a+ /// still screen.+ retry: RefCell<Option<Closure<dyn FnMut()>>>,+ retry_pending: Cell<bool>,+ /// When the pending timer is due, so a nearer one can replace it.+ retry_due: Cell<f64>,+}++/// How large the glyph atlas is allowed to get.+///+/// Not the GPU's maximum, which is commonly 8192: that is 268 MB of video+/// memory for glyphs alone, which is not a trade a terminal should make+/// silently. At this size it holds several screens' worth of distinct CJK,+/// and beyond it `Capacity` clears and reuses rather than growing -- which+/// is the whole reason that path exists.+const MAX_ATLAS_SIDE: usize = 4096;++/// What `grow_atlas` managed.+enum Grown {+ /// A bigger texture; try again.+ Larger,+ /// Already at the GPU's largest, and it is full. Only a clear frees+ /// space now, and `Capacity` decides when that is worth doing.+ AtCapacity,}fn now_ms() -> f64 {js_sys::Date::now()}+/// Milliseconds from a clock that does not step.+///+/// `Date::now` is wall time, and the atlas backoff stores an absolute+/// deadline: an NTP correction or a VM host resync that moves the clock+/// backwards would park the terminal in its degraded mode for as long as+/// the correction, with every frame answering "not yet".+pub(crate) fn monotonic_ms() -> f64 {+ web_sys::window()+ .and_then(|w| w.performance())+ .map(|p| p.now())+ .unwrap_or_else(now_ms)+}+impl App {pub fn new(setup: Setup) -> Rc<Self> {let inner = Inner {@@ -134,7 +209,16 @@ impl App {last_click_ms: 0.0,focused: true,composing: false,+ canvas_rect: [0.0; 4],+ ime_anchor: None,disconnected: None,+ url: setup.url,+ token: setup.token,+ reconnect_delay: RECONNECT_MIN_MS,+ reconnect_pending: false,+ reconnect_attempts: 0,+ connected_since: None,+ capacity: Capacity::new(),quads: HeapQuadAllocator::default(),vertices: Vec::new(),title: setup.title,@@ -143,6 +227,9 @@ impl App {inner: RefCell::new(inner),frame_requested: Cell::new(false),raf: RefCell::new(None),+ retry: RefCell::new(None),+ retry_pending: Cell::new(false),+ retry_due: Cell::new(0.0),});let weak = Rc::downgrade(&app);*app.raf.borrow_mut() = Some(Closure::<dyn FnMut()>::new(move || {@@ -151,9 +238,46 @@ impl App {app.frame();}}));+ let weak = Rc::downgrade(&app);+ *app.retry.borrow_mut() = Some(Closure::<dyn FnMut()>::new(move || {+ if let Some(app) = weak.upgrade() {+ app.retry_pending.set(false);+ app.request_frame();+ }+ }));app}+ /// Come back after `delay_ms` whether or not anything else asks for a+ /// frame.+ ///+ /// The atlas backoff is the only thing here that cannot wait to be+ /// asked: once the terminal goes quiet nothing requests another frame,+ /// so a retry that counted frames would never arrive -- and repainting a+ /// still screen thousands of times to reach a count would be waste.+ fn schedule_retry(&self, delay_ms: f64) {+ // A timer already set for sooner will do. One set for later will+ // not: dropping a nearer deadline on the floor is how a recovery+ // that should have taken a second takes eight.+ let due = monotonic_ms() + delay_ms;+ if self.retry_pending.get() && self.retry_due.get() <= due {+ return;+ }+ let retry = self.retry.borrow();+ if let (Some(window), Some(closure)) = (web_sys::window(), retry.as_ref()) {+ if window+ .set_timeout_with_callback_and_timeout_and_arguments_0(+ closure.as_ref().unchecked_ref(),+ delay_ms.clamp(0.0, i32::MAX as f64) as i32,+ )+ .is_ok()+ {+ self.retry_pending.set(true);+ self.retry_due.set(due);+ }+ }+ }+pub fn wake(self: &Rc<Self>) -> Rc<dyn Fn()> {let weak = Rc::downgrade(self);Rc::new(move || {@@ -225,13 +349,164 @@ impl App {}}- pub fn on_close(&self, reason: String) {- let mut inner = self.inner.borrow_mut();- inner.disconnected = Some(reason.clone());- // Nothing more will arrive: the watchdog must stop asking, or the- // page keeps requesting frames for lines that never come.- inner.session.set_dead(true);- Self::set_status(&inner, &format!("disconnected: {reason}. Reload to reconnect."));+ pub fn on_close(self: &Rc<Self>, reason: String) {+ {+ let mut inner = self.inner.borrow_mut();+ if inner.disconnected.is_some() {+ return;+ }+ inner.disconnected = Some(reason.clone());+ // The connection that just died settles its own backoff here:+ // one that held for a while earns the short delay back, one+ // that did not keeps the long one. Left set, a frame drawn+ // during the outage would forgive a connection that is gone.+ if let Some(at) = inner.connected_since.take() {+ if monotonic_ms() - at >= RECONNECT_STABLE_MS {+ inner.reconnect_delay = RECONNECT_MIN_MS;+ }+ }+ // Nothing more will arrive on this socket: the watchdog must+ // stop asking, or the page keeps requesting lines that never+ // come. `reconnected` turns it back on.+ inner.session.set_dead(true);+ log::warn!("connection lost: {reason}");+ }+ self.show_reconnect_status();+ self.schedule_reconnect(0.0);+ }++ /// What the status line says while there is no connection.+ ///+ /// The reason is shown as well as the count, because the page cannot+ /// tell the interesting cases apart: a browser is not told why an+ /// upgrade was refused, so a revoked link, an expired one and a server+ /// that is simply not running all arrive here as the same closed+ /// socket. After a while the message says so rather than counting up+ /// for ever in silence.+ fn show_reconnect_status(&self) {+ let inner = self.inner.borrow();+ let Some(reason) = inner.disconnected.clone() else {+ return;+ };+ let text = if inner.reconnect_attempts >= RECONNECT_DOUBT_AFTER {+ format!(+ "still trying to reconnect after {} attempts ({reason}). \+ The link may have expired, or the server may be down.",+ inner.reconnect_attempts+ )+ } else {+ format!("connection lost ({reason}); reconnecting…")+ };+ Self::set_status(&inner, &text);+ }++ /// Come back and try again. `0.0` means as soon as the browser will.+ fn schedule_reconnect(self: &Rc<Self>, delay_ms: f64) {+ {+ let mut inner = self.inner.borrow_mut();+ if inner.reconnect_pending || inner.disconnected.is_none() {+ return;+ }+ inner.reconnect_pending = true;+ }+ let app = Rc::clone(self);+ let closure = Closure::once_into_js(move || {+ app.inner.borrow_mut().reconnect_pending = false;+ wasm_bindgen_futures::spawn_local(app.try_reconnect());+ });+ let armed = web_sys::window().is_some_and(|window| {+ window+ .set_timeout_with_callback_and_timeout_and_arguments_0(+ closure.as_ref().unchecked_ref(),+ delay_ms.max(0.0) as i32,+ )+ .is_ok()+ });+ if !armed {+ // Nothing will clear the flag, and nothing else in the page+ // schedules an attempt: leaving it set would make this the last+ // reconnect the page ever tries.+ self.inner.borrow_mut().reconnect_pending = false;+ log::error!("could not arm the reconnect timer");+ }+ }++ /// One attempt: reopen the socket, redo the handshake on the same pane,+ /// and refetch everything on screen.+ async fn try_reconnect(self: Rc<Self>) {+ let (link, url, token, pane_id, tab_id, size) = {+ let inner = self.inner.borrow();+ if inner.disconnected.is_none() {+ return;+ }+ let size = inner.link.lease().reported;+ (+ inner.link.clone(),+ inner.url.clone(),+ inner.token.clone(),+ inner.pane_id,+ inner.tab_id,+ size,+ )+ };+ let outcome = async {+ link.reconnect(&url, &token).await?;+ crate::attach::reattach(&link, pane_id, tab_id, size).await+ }+ .await;+ match outcome {+ Ok(()) => self.reconnected(),+ Err(err) => {+ // A pane that is gone will not come back, and neither will a+ // server whose protocol this bundle cannot speak. Retrying+ // either one for ever would only hide the reason.+ let permanent = err.downcast_ref::<crate::attach::PaneGone>().is_some()+ || err.to_string().contains("update the server or the bundle");+ if permanent {+ // Nothing will read this socket again, and the server+ // keeps a registered client and a TCP session for as+ // long as one is open. Hand it back.+ link.shutdown();+ let inner = self.inner.borrow();+ Self::set_status(&inner, &format!("{err:#}"));+ log::error!("not reconnecting: {err:#}");+ return;+ }+ let delay = {+ let mut inner = self.inner.borrow_mut();+ inner.reconnect_attempts += 1;+ inner.reconnect_delay =+ (inner.reconnect_delay * 2.0).clamp(RECONNECT_MIN_MS, RECONNECT_MAX_MS);+ inner.reconnect_delay+ };+ log::warn!("reconnect failed, retrying in {delay:.0} ms: {err:#}");+ self.show_reconnect_status();+ self.schedule_reconnect(delay);+ }+ }+ }++ /// The socket is back. Everything on screen was fetched from a server+ /// that has since forgotten us, so none of it may be trusted: the rows+ /// go stale and are asked for again.+ fn reconnected(&self) {+ {+ let mut inner = self.inner.borrow_mut();+ inner.disconnected = None;+ inner.reconnect_attempts = 0;+ // The backoff is *not* reset here. A server that accepts and+ // then drops -- one restarting in a loop, a proxy closing idle+ // sockets -- would otherwise be hammered at the minimum delay+ // for ever, because every attempt "succeeds" for the moment it+ // takes to hand back a socket. `frame` clears it once the+ // connection has proved it can carry a frame.+ inner.connected_since = Some(monotonic_ms());+ inner.session.set_dead(false);+ inner.session.make_all_stale();+ log::info!("reconnected to pane {}", inner.pane_id);+ }+ self.refresh_status();+ self.request_frame();}fn refresh_status(&self) {@@ -581,17 +856,30 @@ impl App {let mut inner = self.inner.borrow_mut();let rect = inner.canvas.get_bounding_client_rect();let dpr = web_sys::window().map(|w| w.device_pixel_ratio()).unwrap_or(1.0);+ inner.canvas_rect = [rect.left(), rect.top(), rect.width(), rect.height()];if (dpr - inner.dpr).abs() > f64::EPSILON {// Another monitor: glyphs are rasterised for the new density.inner.dpr = dpr;let dpi = (96.0 * dpr) as u32;let side = inner.glyphs.atlas.size() as u32;match GpuTexture::new(&inner.gpu.device, Arc::clone(&inner.gpu.queue), side, side)- .and_then(|t| GlyphCache::new(Rc::clone(&inner.fonts), inner.glyphs.size_pt, dpi, Rc::new(t)))+ .and_then(|t| {+ GlyphCache::new(+ Rc::clone(&inner.fonts),+ inner.glyphs.size_pt,+ dpi,+ Rc::new(t),+ Rc::clone(&inner.glyphs.families),+ )+ }){Ok(glyphs) => inner.glyphs = glyphs,Err(err) => log::error!("glyph cache for dpr {dpr}: {err:#}"),}+ // A new cell size makes "what fits" a different question, so+ // the atlas backoff starts over rather than carrying a grudge+ // from the old one.+ inner.capacity.reset();}let dev_w = (rect.width() * dpr).floor().max(1.0) as u32;let dev_h = (rect.height() * dpr).floor().max(1.0) as u32;@@ -668,6 +956,16 @@ impl App {/// fetched; their arrival marks the page dirty again.pub fn frame(&self) {let mut inner = self.inner.borrow_mut();+ // A connection that has carried frames for a while has earned the+ // short delay back. Done here rather than on connect, because+ // "the socket opened" is not evidence a server is healthy.+ if inner+ .connected_since+ .is_some_and(|at| monotonic_ms() - at >= RECONNECT_STABLE_MS)+ {+ inner.connected_since = None;+ inner.reconnect_delay = RECONNECT_MIN_MS;+ }let _ = inner.host.events.take_dirty();let title = inner.session.title();if title != inner.title {@@ -679,13 +977,67 @@ impl App {self.refresh_status();inner = self.inner.borrow_mut();}- for attempt in 0..2 {- match Self::paint(&mut inner) {- Ok(()) => break,- Err(err) if err.root_cause().downcast_ref::<OutOfTextureSpace>().is_some() && attempt == 0 => {- if let Err(err) = Self::grow_atlas(&mut inner) {- log::error!("atlas could not grow: {err:#}");+ // One budget for the whole frame, not one per attempt. The loop+ // below calls `paint` more than once, so a fresh budget each time+ // would let a single browser callback draw several times the cap --+ // which is the thing the cap is for. The deadline inside it is set+ // once, here, for the same reason.+ let mut budget = FallbackBudget::new(monotonic_ms());+ let (mut owed, mut declined, mut painted) = (0u32, 0u32, false);+ // Whether the atlas is what has been failing, and whether the budget+ // has already been given back once this frame.+ let (mut atlas_failed, mut refunded) = (false, false);+ const ATTEMPTS: usize = 4;+ for attempt in 0..ATTEMPTS {+ // The last attempt always declines allocations, so it cannot+ // fail on the atlas and the frame reaches the screen. Leaving+ // that to `grow_atlas` saying `AtCapacity` was not enough: two+ // growths that both succeed and still do not fit left the last+ // attempt allocating normally, and its failure fell out of the+ // loop with nothing painted, no repaint requested and no timer+ // armed -- the last frame stayed up until unrelated input+ // arrived, which looks exactly like a hang.+ if attempt + 1 == ATTEMPTS && atlas_failed && !inner.capacity.frozen() {+ inner.capacity.at_capacity(monotonic_ms());+ }+ match Self::paint(&mut inner, &mut budget) {+ Ok((deferred, refused)) => {+ owed = deferred;+ declined = refused;+ painted = true;+ break;+ }+ Err(err) if attempt + 1 < ATTEMPTS => {+ let Some(full) = err.root_cause().downcast_ref::<OutOfTextureSpace>() else {+ log::error!("frame failed: {err:#}");break;+ };+ atlas_failed = true;+ match Self::grow_atlas(&mut inner, full.size) {+ // The cache was rebuilt, so every glyph this frame+ // has already drawn is gone with it. The retry gets+ // the count back: charging it twice for the same+ // graphemes left the rows at the bottom of the+ // screen -- where a terminal's action is -- as+ // boxes, and made `owed` a sum over attempts rather+ // than what this frame still owes.+ Ok(Grown::Larger) => {+ // Once only, and the deadline is never given+ // back -- see `refund`. The rebuild honestly+ // threw away what the earlier attempt drew, but+ // three refunds would let one frame do four+ // times the work, which is the opposite of what+ // the budget is for.+ if !refunded {+ refunded = true;+ budget.refund();+ }+ }+ Ok(Grown::AtCapacity) => inner.capacity.at_capacity(monotonic_ms()),+ Err(err) => {+ log::error!("atlas could not grow: {err:#}");+ break;+ }}}Err(err) => {@@ -694,28 +1046,118 @@ impl App {}}}- // Lines still in flight, or a stalled fetch: come back for them.++ // Lines still in flight, a stalled fetch, or glyphs the budget put+ // off: come back for them.let dims = inner.session.dimensions();- let visible = visible_rows(&dims, inner.rows, inner.scroll_from_bottom);// Exactly the rows shown: asking about rows past a shorter page's// bottom, which may not exist, would repaint forever.- if inner.session.render_looks_stalled_in(visible) {- drop(inner);+ let visible = visible_rows(&dims, inner.rows, inner.scroll_from_bottom);+ // Called first, and never behind a `||`. This is not a predicate:+ // it re-issues line fetches that timed out and resets the poll+ // interval. Short-circuiting it on a frame that deferred a glyph+ // meant a dropped `GetLines` was never retried, and those rows+ // stayed blank for the rest of the stream.+ let stalled = inner.session.render_looks_stalled_in(visible);+ let mut again = owed > 0 || stalled;++ let mut retry_in = None;+ if !painted {+ // Nothing reached the screen. Come back on the backoff's own+ // timer rather than waiting to be asked.+ retry_in = Some(MIN_RETRY_MS);+ } else if inner.capacity.frozen() {+ match inner.capacity.submitted_frozen(monotonic_ms(), owed, declined) {+ Next::Recovered => {}+ Next::Clear => match Self::clear_atlas(&mut inner) {+ Ok(()) => again = true,+ Err(err) => {+ // `submitted_frozen` unfroze on the promise of a+ // clear that did not happen. Put it back, or the+ // frame stands still against a full atlas with+ // nothing scheduled to try again.+ log::error!("the atlas could not be cleared: {err:#}");+ inner.capacity.at_capacity(monotonic_ms());+ retry_in = Some(MIN_RETRY_MS);+ }+ },+ Next::RetryAt(at) => retry_in = Some((at - monotonic_ms()).max(0.0)),+ }+ } else if owed == 0 && declined == 0 {+ // Owing nothing is the whole condition. A frame whose budget+ // ran out returns successfully too, and taking that for "the+ // demand is satisfied" would end the emergency after refilling+ // only part of the screen.+ inner.capacity.drew_everything();+ }++ drop(inner);+ if again {self.request_frame();}+ if let Some(delay) = retry_in {+ self.schedule_retry(delay);+ }}- fn grow_atlas(inner: &mut Inner) -> Result<()> {- let side = (inner.glyphs.atlas.size() * 2).min(inner.gpu.max_texture_dimension() as usize);- if side <= inner.glyphs.atlas.size() {- anyhow::bail!("the atlas is already at the GPU's largest texture");+ /// Grow the atlas past what would not fit.+ ///+ /// `wanted` is the size the allocator says would hold the sprite, which+ /// is not always twice the current side: one sprite larger than that+ /// does not fit after a single doubling, and the frame only retries so+ /// many times.+ fn grow_atlas(inner: &mut Inner, wanted: Option<usize>) -> Result<Grown> {+ let current = inner.glyphs.atlas.size();+ let side = wanted+ .unwrap_or(current * 2)+ .max(current * 2)+ .next_power_of_two()+ .min(MAX_ATLAS_SIDE)+ .min(inner.gpu.max_texture_dimension() as usize);+ if side <= current {+ return Ok(Grown::AtCapacity);}- let texture = Rc::new(GpuTexture::new(&inner.gpu.device, Arc::clone(&inner.gpu.queue), side as u32, side as u32)?);- inner.glyphs = GlyphCache::new(Rc::clone(&inner.fonts), inner.glyphs.size_pt, inner.glyphs.dpi, texture)?;+ let texture = Rc::new(GpuTexture::new(+ &inner.gpu.device,+ Arc::clone(&inner.gpu.queue),+ side as u32,+ side as u32,+ )?);+ Self::rebuild_glyphs(inner, texture)?;+ Ok(Grown::Larger)+ }++ /// Empty the atlas by rebuilding the cache over the same texture:+ /// `Atlas::new` zeroes it and resets the allocator.+ ///+ /// Everything drawn so far is lost, which is the point. There is no+ /// per-sprite eviction, so this is the only way to get space back, and+ /// the flicker it causes is a great deal better than the alternative --+ /// which, before this existed, was a terminal that never drew again.+ fn clear_atlas(inner: &mut Inner) -> Result<()> {+ log::warn!(+ "the atlas is at the GPU's largest texture ({}) and still full; clearing it",+ inner.glyphs.atlas.size()+ );+ let texture = inner.glyphs.texture_rc();+ Self::rebuild_glyphs(inner, texture)+ }++ fn rebuild_glyphs(inner: &mut Inner, texture: Rc<GpuTexture>) -> Result<()> {+ inner.glyphs = GlyphCache::new(+ Rc::clone(&inner.fonts),+ inner.glyphs.size_pt,+ inner.glyphs.dpi,+ texture,+ Rc::clone(&inner.glyphs.families),+ )?;Ok(())}- fn paint(inner: &mut Inner) -> Result<()> {+ /// Returns what this frame owes: glyphs the budget put off, and sprites+ /// a full atlas declined.+ fn paint(inner: &mut Inner, budget: &mut FallbackBudget) -> Result<(u32, u32)> {+ inner.glyphs.begin_frame(inner.capacity.frozen());let dims = inner.session.dimensions();let max = max_scroll(&dims);if inner.scroll_from_bottom > max {@@ -726,6 +1168,20 @@ impl App {let (first, lines) = inner.session.get_lines(visible);let (w, h) = inner.gpu.size();let cell_h = inner.glyphs.metrics.cell_size.height as f32;+ let cursor_line = cursor.y.checked_sub(first)+ .and_then(|row| usize::try_from(row).ok())+ .and_then(|row| lines.get(row));+ let width_scale = if cursor_line.is_some_and(|line| !line.is_single_width()) { 2.0 } else { 1.0 };+ let height_scale = if cursor_line.is_some_and(|line| line.is_double_height_top()) { 2.0 } else { 1.0 };+ let cell_w = inner.glyphs.metrics.cell_size.width as f64 * width_scale;+ let anchor = crate::ime::anchor(+ inner.canvas_rect,+ (w, h),+ (cursor.x as f64 * cell_w, cursor.y.saturating_sub(first) as f64 * cell_h as f64),+ (cell_w, cell_h as f64 * height_scale),+ );+ crate::ime::update_field(&inner.textarea, &mut inner.ime_anchor, anchor)+ .map_err(|e| anyhow::anyhow!("IME anchor: {e:?}"))?;inner.quads.recycle();let selection = inner.selection;for (i, line) in lines.iter().enumerate() {@@ -745,7 +1201,7 @@ impl App {reverse_video: dims.reverse_video,surface: (w as f32, h as f32),};- crate::emit::emit_line(&mut inner.glyphs, &mut inner.quads, ¶ms)?;+ crate::emit::emit_line(&mut inner.glyphs, &mut inner.quads, budget, ¶ms)?;}inner.vertices.clear();inner.quads.extract_vertices(&mut inner.vertices);@@ -753,7 +1209,8 @@ impl App {let millis = (js_sys::Date::now() % (u32::MAX as f64)) as u32;inner.gpu- .draw(&inner.vertices, inner.glyphs.texture(), [bg.0, bg.1, bg.2, bg.3], millis)+ .draw(&inner.vertices, inner.glyphs.texture(), [bg.0, bg.1, bg.2, bg.3], millis)?;+ Ok((budget.deferred(), inner.glyphs.declined()))}}diff --git a/thinkterm-web/src/attach.rs b/thinkterm-web/src/attach.rsindex 3da8e3b0..c59f3900 100644--- a/thinkterm-web/src/attach.rs+++ b/thinkterm-web/src/attach.rs@@ -141,3 +141,122 @@ pub async fn attach(link: &WsLink, size: Option<TerminalSize>) -> Result<Attacheserver_version: version.version_string,})}++/// The pane this page was showing is not on the server any more.+///+/// Its own type so the reconnect loop can tell "come back later" from+/// "there is nothing to come back to" and stop retrying.+#[derive(Debug)]+pub struct PaneGone(pub PaneId);++impl std::fmt::Display for PaneGone {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "pane {} is no longer on the server", self.0)+ }+}++impl std::error::Error for PaneGone {}++/// The handshake again, on a socket that has just been reopened.+///+/// Not `attach`: that picks a pane, and picking again after a reconnect+/// would silently move the page to whatever is active now. This one insists+/// on the pane it was already showing and fails with [`PaneGone`] if the+/// server no longer has it.+///+/// The identity is the one from the first connection. The server tracks the+/// frontend lease by `ClientId`, so coming back under a new one would hand+/// this page a different seat than the one it left.+pub async fn reattach(+ link: &WsLink,+ pane_id: PaneId,+ tab_id: TabId,+ size: Option<TerminalSize>,+) -> Result<()> {+ let version = request(+ link,+ Pdu::GetCodecVersion(codec::GetCodecVersion {}),+ |pdu| match pdu {+ Pdu::GetCodecVersionResponse(v) => Ok(v),+ other => Err(other),+ },+ )+ .await?;+ if version.codec_vers != codec::CODEC_VERSION {+ bail!(+ "this page speaks protocol {} but the server speaks {}; update the server or the bundle",+ codec::CODEC_VERSION,+ version.codec_vers+ );+ }++ let me = link+ .lease()+ .me+ .clone()+ .ok_or_else(|| anyhow!("reconnecting without an identity"))?;+ request(+ link,+ Pdu::SetClientId(codec::SetClientId {+ client_id: me,+ is_proxy: false,+ }),+ |pdu| match pdu {+ Pdu::UnitResponse(_) => Ok(()),+ other => Err(other),+ },+ )+ .await?;++ let panes = request(link, Pdu::ListPanes(codec::ListPanes {}), |pdu| match pdu {+ Pdu::ListPanesResponse(p) => Ok(p),+ other => Err(other),+ })+ .await?;+ if !panes.tabs.iter().any(|tab| contains_pane(tab, pane_id)) {+ return Err(PaneGone(pane_id).into());+ }++ if let Some(size) = size {+ let state = request(+ link,+ Pdu::SetClientViewport(codec::SetClientViewport {+ tab_id,+ viewport: codec::ClientViewport::CellGrid { size },+ }),+ |pdu| match pdu {+ Pdu::ClientViewportState(s) => Ok(s),+ other => Err(other),+ },+ )+ .await?;+ let mut lease = link.lease_mut();+ lease.tab_id = Some(tab_id);+ lease.reported = Some(size);+ lease.apply_viewport(&state);+ }++ // Re-subscribes: the server forgot this page along with the socket.+ request(+ link,+ Pdu::GetPaneRenderChanges(codec::GetPaneRenderChanges { pane_id }),+ |pdu| match pdu {+ Pdu::LivenessResponse(_) | Pdu::UnitResponse(_) => Ok(()),+ other => Err(other),+ },+ )+ .await?;+ Ok(())+}++/// Whether a tab's layout still holds this pane.+fn contains_pane(node: &PaneNode, pane_id: PaneId) -> bool {+ match node {+ PaneNode::Empty => false,+ PaneNode::Leaf(entry) => entry.pane_id == pane_id,+ PaneNode::Stack(stack) => stack.panes.iter().any(|e| e.pane_id == pane_id),+ PaneNode::Split { left, right, .. } => {+ contains_pane(left, pane_id) || contains_pane(right, pane_id)+ }+ }+}diff --git a/thinkterm-web/src/canvas.rs b/thinkterm-web/src/canvas.rsnew file mode 100644index 00000000..5c042a97--- /dev/null+++ b/thinkterm-web/src/canvas.rs@@ -0,0 +1,282 @@+//! 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.++use crate::fallback::{self, Ink, Placement};+use anyhow::{anyhow, Result};+use thinkterm_render::bitmaps::Image;+use thinkterm_render::geom::Size;+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+/// bare canvas, and the two names in `app.js` identify the files we parse+/// ourselves, not CSS families -- so this is it, and `?glyphfont=`+/// replaces it.+///+/// This is also how the regional shape of a Han character is chosen. Not+/// `ctx.lang`: on this browser, switching it between Chinese and Japanese+/// moved not one pixel, while switching the face moved several hundred.+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";++/// 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,+}++/// The off-screen canvas the fallback glyphs are drawn on.+pub struct Scratch {+ 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,+}++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> {+ let document = web_sys::window()+ .and_then(|w| w.document())+ .ok_or_else(|| anyhow!("no document"))?;+ let canvas: web_sys::HtmlCanvasElement = document+ .create_element("canvas")+ .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);++ let options = js_sys::Object::new();+ let set = |key: &str, value: bool| {+ js_sys::Reflect::set(&options, &JsValue::from_str(key), &JsValue::from_bool(value))+ .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)+ .map_err(|e| anyhow!("2d context: {e:?}"))?+ .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");+ ctx.set_font(&format!("{size} {families}"));+ if !ctx.font().starts_with(&size) {+ log::warn!(+ "the browser would not take the font {families:?} (it kept {:?}); \+ using the built-in stack",+ ctx.font()+ );+ 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",+ ctx.font()+ );+ }+ 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,+ })+ }++ fn clear(&self) {+ 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);+ 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>> {+ Ok(self+ .ctx+ .get_image_data(x, y, w, h)+ .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/emit.rs b/thinkterm-web/src/emit.rsindex 78ebd226..587bdcc4 100644--- a/thinkterm-web/src/emit.rs+++ b/thinkterm-web/src/emit.rs@@ -4,12 +4,15 @@//! into strips wherever the cursor or the selection changes their colour.//! No images, no bidi, no hyperlink hover, no blink.-use crate::glyphs::GlyphCache;+use crate::fallback::FallbackBudget;+use crate::glyphs::{CachedGlyph, GlyphCache};use anyhow::{Context, Result};use std::ops::Range;+use std::rc::Rc;use termwiz::cell::{Intensity, Underline};use termwiz::surface::{CursorShape, CursorVisibility, Line};use thinkterm_font_core::PresentationWidth;+use thinkterm_font_web::GlyphRole;use thinkterm_proto::StableCursorPosition;use thinkterm_render::quad::{HeapQuadAllocator, QuadTrait, TripleLayerQuadAllocatorTrait};use wezterm_color_types::LinearRgba;@@ -90,6 +93,7 @@ fn is_block(shape: CursorShape) -> bool {pub fn emit_line(cache: &mut GlyphCache,layers: &mut HeapQuadAllocator,+ budget: &mut FallbackBudget,p: &LineParams<'_>,) -> Result<()> {if p.line.is_double_height_bottom() {@@ -157,7 +161,7 @@ pub fn emit_line(bg_is_default: bool,invisible: bool,underline: Option<(thinkterm_render::bitmaps::TextureRect, LinearRgba)>,- glyphs: Vec<(u8, std::rc::Rc<crate::glyphs::CachedGlyph>)>,+ glyphs: Vec<(u8, Rc<CachedGlyph>)>,}let clusters = p.line.cluster(None);let mut shaped: Vec<Shaped> = Vec::with_capacity(clusters.len());@@ -184,16 +188,71 @@ pub fn emit_line(} else {None};- let infos = cache.shape(+ let widths = PresentationWidth::with_cluster(cluster);+ let run = cache.shape(&cluster.text,Some(cluster.presentation),- Some(&PresentationWidth::with_cluster(cluster)),+ Some(&widths),+ cluster.width,)?;- let mut glyphs = Vec::with_capacity(infos.len());- for (idx, info) in infos.iter().enumerate() {- let followed_by_space = infos.get(idx + 1).map(|n| n.is_space).unwrap_or(false);- let glyph = cache.cached_glyph(info, followed_by_space, info.num_cells)?;- glyphs.push((info.num_cells, glyph));+ // Nothing off the right edge gets a fallback. The stand-in used to+ // be one shared `.notdef` and cost nothing; a fallback is a canvas+ // draw and an atlas slot each, out of a budget the whole frame+ // shares.+ //+ // Asked per gap, not per cluster. `CellCluster` breaks only on an+ // attribute change or whitespace, and Chinese prose has no+ // whitespace, so a 150-column row of Han is one cluster starting at+ // column 0: a test on where the cluster starts called all 150+ // visible in an 80-column viewport and paid for 70 draws the strip+ // loop below then threw away.+ let mut fallbacks: Vec<Option<Rc<CachedGlyph>>> = vec![None; run.gaps.len()];+ let mut columns: Vec<u8> = vec![0; run.gaps.len()];+ if !attrs.invisible() {+ for (g, gap) in run.gaps.iter().enumerate() {+ // Already absolute: `CellCluster::byte_to_cell_idx` adds+ // `first_cell_idx` itself (cellcluster.rs:34, :295). Adding+ // it again put every cluster but the first too far right,+ // so its gaps were taken for off-screen and left as boxes.+ let cell = widths.byte_to_cell_idx(gap.bytes.start);+ if (cell as f32) * cell_width >= pixel_width {+ break;+ }+ // Counted from the row in hand, not read back from the+ // shape cache. `ShapeKey` holds the cluster's *total*+ // columns, so two rows that spend the same total+ // differently -- `[1,2,1]` and `[2,1,1]` for the same text,+ // which explicit cell widths allow -- share an entry, and+ // the second would inherit the first's per-gap count and+ // shift everything after it.+ columns[g] = widths.num_cells(gap.bytes.clone());+ fallbacks[g] = cache.fallback_glyph(gap, columns[g], budget)?;+ }+ }+ let mut glyphs = Vec::with_capacity(run.infos.len());+ for (idx, info) in run.infos.iter().enumerate() {+ // Read from the list as it was shaped: whether a space follows+ // decides if this glyph may overflow its cell, and that must not+ // change because the gap after it got replaced.+ let followed_by_space =+ run.infos.get(idx + 1).map(|n| n.is_space).unwrap_or(false);+ match run.roles[idx] {+ GlyphRole::GapLead(g) if fallbacks[g as usize].is_some() => {+ // The whole grapheme, in the columns the row's own width+ // data gave it. No `.max(1)`: a zero-column gap was+ // refused before it got here, and inventing a column+ // shifts the rest of the line with nothing to report it.+ let glyph = Rc::clone(fallbacks[g as usize].as_ref().expect("just checked"));+ glyphs.push((columns[g as usize], glyph));+ }+ // The gap's other stand-ins. Keeping one draws the cell+ // twice and advances the column twice.+ GlyphRole::GapTail(g) if fallbacks[g as usize].is_some() => {}+ _ => glyphs.push((+ info.num_cells,+ cache.cached_glyph(info, followed_by_space, info.num_cells)?,+ )),+ }}shaped.push(Shaped {first_cell: cluster.first_cell_idx,@@ -296,7 +355,11 @@ pub fn emit_line(} else {(item.fg, item.bg)};- if glyph_color == bg_color || item.invisible {+ // A colour glyph takes its colour from the texture, not+ // from the foreground, so a foreground that happens to+ // equal the background says nothing about whether it+ // would be visible. `invisible` still hides everything.+ if item.invisible || (!glyph.has_color && glyph_color == bg_color) {continue;}let pixel_rect = euclid::rect(diff --git a/thinkterm-web/src/fallback.rs b/thinkterm-web/src/fallback.rsnew file mode 100644index 00000000..9365c2fe--- /dev/null+++ b/thinkterm-web/src/fallback.rs@@ -0,0 +1,750 @@+//! The arithmetic behind drawing a glyph with the browser's own fonts:+//! where the ink is, whether it carries its own colour, where it sits+//! relative to the baseline, how much of it one frame may do, and what an+//! atlas that cannot grow any further does next.+//!+//! All of it is pure, and none of it is `wasm32`-only, because `emit.rs`+//! and `glyphs.rs` are -- and this crate has no wasm test runner, so an+//! assertion written in either of those files never runs. `braille.rs` was+//! split the same way and for the same reason.++/// The tightest box around the non-transparent pixels of a drawing.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Ink {+ pub left: usize,+ pub top: usize,+ pub width: usize,+ pub height: usize,+ /// The ink reaches an edge of the buffer, so the glyph may have been+ /// cut off rather than merely being large.+ pub clipped: bool,+}++/// The ink in an RGBA buffer, or `None` when the browser drew nothing.+///+/// Alpha only: the fill colour is ours, and a glyph that carries its own+/// colour still has an alpha channel.+pub fn ink_box(rgba: &[u8], width: usize, height: usize) -> Option<Ink> {+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);+ for y in 0..height {+ let row = &rgba[y * width * 4..(y + 1) * width * 4];+ for x in 0..width {+ if row[x * 4 + 3] != 0 {+ x0 = x0.min(x);+ y0 = y0.min(y);+ x1 = x1.max(x);+ y1 = y1.max(y);+ }+ }+ }+ (x0 != usize::MAX).then(|| Ink {+ left: x0,+ top: y0,+ width: x1 - x0 + 1,+ height: y1 - y0 + 1,+ clipped: x0 == 0 || y0 == 0 || x1 + 1 == width || y1 + 1 == height,+ })+}++/// Whether a glyph brought its own colour, from the same ink drawn twice in+/// two different fills.+///+/// Identical pixels mean the browser ignored the colour we asked for, which+/// only a glyph carrying its own does. The two fills must differ in **every**+/// channel: white and red share a red channel, and comparing that one+/// channel is what silently called five hundred Chinese characters coloured+/// in the first round of measurements.+///+/// Both buffers are the ink and nothing else -- outside it the drawings are+/// transparent and would agree whatever the glyph is.+pub fn carries_own_colour(first: &[u8], second: &[u8]) -> bool {+ first == second+}++/// The ink cut out of the buffer as its own tightly packed RGBA8.+///+/// A row at a time and nothing per pixel. The bytes are copied exactly as+/// `getImageData` gave them, **not** premultiplied: the pipeline blends+/// with `ALPHA_BLENDING` and the shader does not undo a premultiply, so+/// straight alpha is what it wants.+pub fn crop(rgba: &[u8], stride: usize, ink: &Ink) -> Vec<u8> {+ let mut out = Vec::with_capacity(ink.width * ink.height * 4);+ for row in 0..ink.height {+ let at = ((ink.top + row) * stride + ink.left) * 4;+ out.extend_from_slice(&rgba[at..at + ink.width * 4]);+ }+ out+}++/// Where a drawn glyph goes, in the terms `CachedGlyph` uses.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Placement {+ pub bearing_x: f64,+ pub bearing_y: f64,+ pub scale: f64,+}++/// Turn an ink box into a bearing, given where we put the pen and the+/// baseline.+///+/// `bearing_y` is read off the emitter's own arithmetic rather than+/// guessed. `emit.rs` puts a sprite's top edge at+///+/// ```text+/// cell_height + descender - (y_offset + bearing_y)+/// ```+///+/// and `cell_height + descender` *is* the baseline, so `bearing_y` is the+/// distance from the baseline up to the top of the ink. It goes negative+/// for a glyph that sits entirely below the baseline, such as a comma.+///+/// This is not `braille.rs`'s `cell_height + descender`: that is this same+/// expression for the one case where the sprite is the whole cell, so the+/// ink starts at the top of the row.+///+/// A glyph whose ink is wider than the columns it was given is scaled about+/// the baseline, which is the arithmetic `load_glyph` already uses.+pub fn place(ink: &Ink, pen_x: f64, baseline: f64, max_width: f64) -> Placement {+ let scale = if ink.width as f64 > max_width && max_width > 0.0 {+ max_width / ink.width as f64+ } else {+ 1.0+ };+ // Never small enough to round the height away. `Image::scale_by`+ // truncates without a floor, so a one-pixel-tall rule -- U+203E, U+2015,+ // U+FF3F, which a system font draws full width -- becomes a zero-height+ // sprite: no panic, no error, an invisible glyph cached as a good one,+ // in a cell whose missing-glyph box has already been dropped.+ // Overflowing is the lesser evil, and is already allowed for wide ink.+ //+ // Only the height needs it. `max_width` is at least one and a quarter+ // cells, so the width can never be scaled below a pixel.+ let scale = scale.max(1.0 / ink.height.max(1) as f64).min(1.0);+ Placement {+ bearing_x: (ink.left as f64 - pen_x) * scale,+ bearing_y: (baseline - ink.top as f64) * scale,+ scale,+ }+}++/// Graphemes the caller draws itself, and would rather have the+/// missing-glyph box for than a substitute.+///+/// **Braille**, because `braille.rs` draws it: no bundled face covers a+/// single one of U+2800..=U+28FF, so every Braille character is a gap, and+/// routing them to a canvas would quietly turn that module into dead code+/// and take btop's graphs from a pixel-exact dot matrix to something slower+/// and off the grid.+/// Other terminal graphics (blocks, shades, borders and the desktop's+/// custom symbols) also bypass fonts and use the shared cell geometry.+///+/// **Right-to-left scripts**, because the emitter cannot lay them out. It+/// does no bidi and the shaper is hard-coded left to right, so a run of+/// them would come out as correct-looking glyphs in the wrong order --+/// harder for a reader to catch than a row of boxes, which at least says+/// plainly that this is not rendered. Joining scripts have a second reason+/// on top: joining crosses grapheme boundaries, so drawing one grapheme at+/// a time yields isolated forms.+///+/// The test is by script rather than by joining class deliberately. Hebrew+/// does not join at all, and would still be reversed.+pub fn keeps_notdef(text: &str) -> bool {+ let mut chars = text.chars();+ let (first, rest) = (chars.next(), chars.next());+ if rest.is_none()+ && first.and_then(thinkterm_render::customglyph::BlockKey::from_char).is_some()+ {+ return true;+ }+ text.chars().any(is_right_to_left)+}++/// The right-to-left blocks, contiguous so nothing between two of them is+/// left out: an earlier version of this list jumped from Mandaic straight+/// to Arabic Extended-A and silently routed Syriac Supplement and Arabic+/// Extended-B, both of which join.+fn is_right_to_left(c: char) -> bool {+ matches!(c as u32,+ // Hebrew, Arabic, Syriac, Thaana, N'Ko, Samaritan, Mandaic, and the+ // Syriac and Arabic extensions that sit between them.+ 0x0590..=0x08ff+ // Hebrew and Arabic presentation forms.+ | 0xfb1d..=0xfdff | 0xfe70..=0xfeff+ // Mongolian, which is vertical as well as joining.+ | 0x1800..=0x18af+ // The historic right-to-left scripts of the supplementary plane --+ // Cypriot through Chorasmian -- and Mende Kikakui.+ | 0x10800..=0x10fff | 0x1e800..=0x1e8df+ // Adlam, and the Arabic mathematical alphabets.+ | 0x1e900..=0x1e95f | 0x1ee00..=0x1eeff)+}++/// How long a frame may spend drawing glyphs it has never drawn before.+///+/// The budget a frame actually runs on. A count bounds work, not time, and+/// the difference was measurable: at 512 glyphs a screen of fresh CJK+/// hitched for 124 ms, and a CPU profile put 89 ms of that in `fillText`+/// and `getImageData` against 0.6 ms in this crate's own code. Eight+/// milliseconds leaves the rest of a 60 Hz frame to the rest of the frame.+///+/// **Built in `frame`, shared by both `paint` attempts**: the retry loop+/// calls `paint` more than once, and a fresh deadline per attempt would let+/// one browser callback take several times this long -- which is the thing+/// the budget exists to prevent.+pub const NEW_GLYPH_MS_PER_FRAME: f64 = 8.0;++/// A backstop, not the budget.+///+/// The deadline above is what stops a frame. This catches a clock that does+/// not advance -- `performance.now()` is deliberately coarsened, and some+/// privacy settings pin it -- which would otherwise leave the deadline+/// permanently in the future and the cap gone altogether.+pub const NEW_GLYPHS_PER_FRAME: u32 = 512;++#[derive(Debug)]+pub struct FallbackBudget {+ remaining: u32,+ deferred: u32,+ deadline: f64,+ drawn: u32,+}++impl FallbackBudget {+ /// `now` here and the `now` passed to `take` must be the same clock.+ pub fn new(now: f64) -> Self {+ Self {+ remaining: NEW_GLYPHS_PER_FRAME,+ deferred: 0,+ deadline: now + NEW_GLYPH_MS_PER_FRAME,+ drawn: 0,+ }+ }++ /// Whether this frame may draw one more. A refusal is counted, and the+ /// caller leaves the missing-glyph box in place and asks again next+ /// frame; nothing is written down, so nothing has to be invalidated.+ pub fn take(&mut self, now: f64) -> bool {+ // The first is always allowed. A device slow enough to spend the+ // whole budget on a single glyph would otherwise refuse every glyph+ // of every frame, and the screen would stay boxes for ever.+ if self.remaining == 0 || (self.drawn > 0 && now >= self.deadline) {+ self.deferred += 1;+ return false;+ }+ self.remaining -= 1;+ self.drawn += 1;+ true+ }++ /// The atlas was rebuilt, so everything this frame drew went with it.+ ///+ /// Gives back the count and what the frame owes, but **not the time**:+ /// the deadline belongs to the frame, not to the attempt, and moving it+ /// would let one browser callback run a second full budget -- which is+ /// the thing the budget is for.+ pub fn refund(&mut self) {+ self.remaining = NEW_GLYPHS_PER_FRAME;+ self.deferred = 0;+ self.drawn = 0;+ }++ /// Glyphs this frame put off until the next one.+ pub fn deferred(&self) -> u32 {+ self.deferred+ }+}++/// The shortest and longest a screen waits for the atlas to be tried again.+///+/// The cap is the recovery bound: once the content will fit, it is on+/// screen within this. Not longer, because "the screen got simple and is+/// still blank" becomes something a person reports; not shorter, because a+/// clear rewrites the whole texture and a screen that genuinely never fits+/// would pay that over and over.+pub const MIN_RETRY_MS: f64 = 1000.0;+pub const MAX_RETRY_MS: f64 = 8000.0;++/// What the next frame does about an atlas that cannot grow any further.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum Next {+ /// Everything the frame wanted, it got. Stop declining.+ Recovered,+ /// Clear the atlas and stop declining.+ Clear,+ /// Keep declining, and wake up at this time (same clock as `now`) to+ /// try again.+ RetryAt(f64),+}++/// An atlas that has grown as far as the GPU allows and still cannot fit+/// what is on screen.+///+/// There is no per-sprite eviction, so the only thing that frees space is+/// clearing the whole texture, and whether that will help is not knowable:+/// the content changes, and which glyphs win the race for space afterwards+/// depends on allocation order, so even "the set we had to decline" is not+/// a stable fingerprint of demand. So this does not try to know. It retries+/// on a backoff -- at once, then after 1 s, 2 s, 4 s, capped at 8 s.+///+/// The clock, not a frame count: once the terminal stops producing output+/// nothing asks for another frame, so a frame-counted deadline on a still+/// screen would never arrive -- and repainting a still screen thousands of+/// times to reach one would be pure waste. The caller schedules a timer.+#[derive(Debug)]+pub struct Capacity {+ frozen: bool,+ next_retry: f64,+ backoff: f64,+}++impl Default for Capacity {+ fn default() -> Self {+ Self::new()+ }+}++impl Capacity {+ pub fn new() -> Self {+ Self {+ frozen: false,+ next_retry: 0.0,+ backoff: 0.0,+ }+ }++ /// Whether this frame must be drawn without allocating anything.+ pub fn frozen(&self) -> bool {+ self.frozen+ }++ /// A frame reached the GPU owing nothing: no glyph put off by the+ /// budget, none declined by a full atlas.+ ///+ /// Both counts have to be zero. A frame whose budget ran out returns+ /// successfully too, and taking that for "the demand is satisfied"+ /// gives "clear, refill part of it, hit the ceiling again".+ ///+ /// **This does not touch the backoff.** The backoff is a limit on how+ /// often the whole texture may be rewritten, and it has to hold across+ /// a recovery, because "the screen fits for one frame and then fills up+ /// again" is the ordinary shape of scrolling through CJK. Resetting it+ /// here made a scroll clear the atlas every few frames -- 48 ms apart+ /// in simulation, which is the storm this whole mechanism exists to+ /// prevent. A terminal that stays healthy is not held back by it: the+ /// deadline is an absolute time, so by the time trouble comes round+ /// again it has long passed and the next clear happens at once.+ pub fn drew_everything(&mut self) {+ self.frozen = false;+ }++ /// The atlas can neither grow nor take another sprite.+ pub fn at_capacity(&mut self, now: f64) {+ self.frozen = true;+ // Never cleared: the atlas is most likely full of glyphs that+ // scrolled off the screen long ago, so try at once. Otherwise the+ // deadline the last clear set stands.+ if self.backoff == 0.0 {+ self.next_retry = now;+ }+ }++ /// Forget the history. For a `GlyphCache` rebuilt for a reason that has+ /// nothing to do with capacity -- a font size or device pixel ratio+ /// change -- where what fits is a different question entirely.+ pub fn reset(&mut self) {+ *self = Self::new();+ }++ /// A frame was submitted while declining allocations, having put off+ /// `deferred` glyphs and declined `declined` sprites.+ pub fn submitted_frozen(&mut self, now: f64, deferred: u32, declined: u32) -> Next {+ if deferred == 0 && declined == 0 {+ self.drew_everything();+ return Next::Recovered;+ }+ if now < self.next_retry {+ return Next::RetryAt(self.next_retry);+ }+ self.backoff = (self.backoff * 2.0).clamp(MIN_RETRY_MS, MAX_RETRY_MS);+ self.next_retry = now + self.backoff;+ self.frozen = false;+ Next::Clear+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A `w`x`h` RGBA buffer with an opaque rectangle in it.+ fn drawn(w: usize, h: usize, rect: (usize, usize, usize, usize), rgb: [u8; 3]) -> Vec<u8> {+ let mut buf = vec![0u8; w * h * 4];+ let (x, y, rw, rh) = rect;+ for row in y..y + rh {+ for col in x..x + rw {+ let at = (row * w + col) * 4;+ buf[at..at + 3].copy_from_slice(&rgb);+ buf[at + 3] = 0xff;+ }+ }+ buf+ }++ #[test]+ fn a_blank_drawing_has_no_ink() {+ assert_eq!(ink_box(&vec![0u8; 8 * 8 * 4], 8, 8), None);+ }++ #[test]+ fn the_ink_box_is_the_tightest_one() {+ let buf = drawn(10, 10, (2, 3, 4, 5), [0xff, 0, 0]);+ let ink = ink_box(&buf, 10, 10).expect("ink");+ assert_eq!((ink.left, ink.top, ink.width, ink.height), (2, 3, 4, 5));+ assert!(!ink.clipped);+ }++ #[test]+ fn ink_that_reaches_an_edge_is_marked_clipped() {+ for rect in [(0, 3, 4, 4), (3, 0, 4, 4), (6, 3, 4, 4), (3, 6, 4, 4)] {+ assert!(ink_box(&drawn(10, 10, rect, [1, 2, 3]), 10, 10).unwrap().clipped, "{rect:?}");+ }+ }++ #[test]+ fn two_fills_that_agree_mean_the_glyph_brought_its_own_colour() {+ let ink = Ink { left: 2, top: 2, width: 4, height: 4, clipped: false };+ // A glyph that ignored us: the same pixels both times.+ let own = crop(&drawn(10, 10, (2, 2, 4, 4), [0x33, 0x66, 0x99]), 10, &ink);+ assert!(carries_own_colour(&own, &own.clone()));+ // A mask: it took each fill we asked for, so the two drawings+ // differ and it is not a colour glyph.+ let red = crop(&drawn(10, 10, (2, 2, 4, 4), [0xff, 0x00, 0x00]), 10, &ink);+ let cyan = crop(&drawn(10, 10, (2, 2, 4, 4), [0x00, 0xff, 0xff]), 10, &ink);+ assert!(!carries_own_colour(&red, &cyan));+ // The trap this pair of fills exists to avoid: white and red are+ // equal on the red channel, so the first round of measurements --+ // which compared that channel alone -- called every Chinese+ // character a colour glyph. Comparing all four bytes tells them+ // apart, and the fills we use differ in every channel anyway.+ let white = crop(&drawn(10, 10, (2, 2, 4, 4), [0xff, 0xff, 0xff]), 10, &ink);+ assert_eq!(white[0], red[0], "premise: they agree on the red channel");+ assert!(!carries_own_colour(&white, &red));+ }++ #[test]+ fn only_the_ink_is_compared() {+ // What lies outside the ink box never reaches the comparison, so a+ // stray pixel from an earlier draw cannot decide the question.+ let ink = Ink { left: 2, top: 2, width: 2, height: 2, clipped: false };+ let a = drawn(8, 8, (2, 2, 2, 2), [9, 9, 9]);+ let mut b = a.clone();+ let at = (6 * 8 + 6) * 4;+ b[at..at + 4].copy_from_slice(&[1, 2, 3, 4]);+ assert!(carries_own_colour(&crop(&a, 8, &ink), &crop(&b, 8, &ink)));+ }++ #[test]+ fn cropping_copies_the_ink_byte_for_byte() {+ let buf = drawn(10, 10, (3, 1, 2, 3), [0x12, 0x34, 0x56]);+ let ink = ink_box(&buf, 10, 10).unwrap();+ let out = crop(&buf, 10, &ink);+ assert_eq!(out.len(), ink.width * ink.height * 4);+ assert!(out.chunks(4).all(|px| px == [0x12, 0x34, 0x56, 0xff]));+ }++ #[test]+ fn the_bearing_is_the_one_the_emitter_subtracts() {+ // The derivation, not a restatement of it: build ink whose top edge+ // is exactly the top of the row, and the bearing must come out as+ // the constant `braille_glyph` hard-codes for a full-cell sprite.+ // Get a sign or a term order wrong and this goes red.+ let (cell_h, descender, row_top) = (32.0, -6.0, 10.0);+ let baseline = row_top + cell_h + descender;+ let ink = Ink { left: 0, top: row_top as usize, width: 10, height: 20, clipped: false };+ let p = place(&ink, 0.0, baseline, 100.0);+ assert_eq!(p.bearing_y, cell_h + descender);+ assert_eq!(p.scale, 1.0);+ }++ #[test]+ fn a_glyph_below_the_baseline_has_a_negative_bearing() {+ let ink = Ink { left: 0, top: 30, width: 4, height: 4, clipped: false };+ assert!(place(&ink, 0.0, 20.0, 100.0).bearing_y < 0.0);+ }++ #[test]+ fn ink_wider_than_its_columns_is_scaled_about_the_baseline() {+ let ink = Ink { left: 4, top: 10, width: 30, height: 10, clipped: false };+ let plain = place(&ink, 2.0, 40.0, 100.0);+ let squeezed = place(&ink, 2.0, 40.0, 10.0);+ assert_eq!(squeezed.scale, 10.0 / 30.0);+ assert_eq!(squeezed.bearing_x, plain.bearing_x * squeezed.scale);+ assert_eq!(squeezed.bearing_y, plain.bearing_y * squeezed.scale);+ }++ #[test]+ fn what_the_caller_draws_itself_keeps_its_box() {+ assert!(keeps_notdef("\u{2801}"), "braille is drawn by braille.rs");+ assert!(keeps_notdef("\u{28ff}"));+ for c in ["█", "▀", "▄", "░", "▒", "▓", "─", "│", "┌", "\u{1fb00}"] {+ assert!(keeps_notdef(c), "{c} must use cell geometry, not Canvas");+ }+ assert!(!keeps_notdef("█\u{301}"), "a combining sequence is not a single block");+ assert!(keeps_notdef("\u{0628}"), "Arabic joins across graphemes");+ assert!(!keeps_notdef("\u{4e2d}"));+ assert!(!keeps_notdef("\u{d55c}"));+ assert!(!keeps_notdef("\u{1f600}"));+ // Two Braille characters are two graphemes; one grapheme holding+ // two of them is not something `braille.rs` can draw.+ assert!(!keeps_notdef("\u{2801}\u{2802}"));+ }++ #[test]+ fn the_budget_defers_rather_than_dropping() {+ // A clock that never moves, so this is the count backstop alone.+ let mut budget = FallbackBudget::new(0.0);+ for _ in 0..NEW_GLYPHS_PER_FRAME {+ assert!(budget.take(0.0));+ }+ assert_eq!(budget.deferred(), 0);+ for n in 1..=5 {+ assert!(!budget.take(0.0));+ assert_eq!(budget.deferred(), n);+ }+ }++ #[test]+ fn a_frame_stops_at_its_deadline_long_before_the_count() {+ // A tenth of a millisecond a glyph: what a headless software+ // backend measured. The count alone would have allowed all 512 --+ // 51 ms in one frame, which is the hitch this replaced.+ let mut budget = FallbackBudget::new(1000.0);+ let (mut now, mut drawn) = (1000.0, 0u32);+ while budget.take(now) {+ drawn += 1;+ now += 0.1;+ assert!(drawn <= NEW_GLYPHS_PER_FRAME, "the deadline never fired");+ }+ assert_eq!(drawn, (NEW_GLYPH_MS_PER_FRAME / 0.1) as u32);+ assert!(drawn < NEW_GLYPHS_PER_FRAME);+ }++ #[test]+ fn the_first_glyph_is_drawn_even_when_the_frame_is_already_late() {+ // Pins the deadlock: a device that spends the whole budget on one+ // glyph must still make progress. Refusing here defers every glyph+ // of every frame, and the screen stays boxes for good.+ let mut budget = FallbackBudget::new(0.0);+ assert!(budget.take(1_000_000.0));+ assert!(!budget.take(1_000_000.0));+ assert_eq!(budget.deferred(), 1);+ }++ #[test]+ fn a_refund_gives_back_the_count_but_not_the_deadline() {+ let mut budget = FallbackBudget::new(0.0);+ assert!(budget.take(0.0));+ assert!(!budget.take(NEW_GLYPH_MS_PER_FRAME));+ assert_eq!(budget.deferred(), 1);+ budget.refund();+ assert_eq!(budget.deferred(), 0);+ // One more, because the rebuilt atlas threw away what was drawn,+ // and then the deadline stops it again. A refund that moved the+ // deadline would let this one frame run a second full budget.+ assert!(budget.take(NEW_GLYPH_MS_PER_FRAME));+ assert!(!budget.take(NEW_GLYPH_MS_PER_FRAME));+ }++ // --- the atlas recovery state machine ---------------------------------+ //+ // Every one of these pins a way an earlier version of this logic locked+ // the terminal up or thrashed it.++ #[test]+ fn the_first_time_at_capacity_clears_at_once() {+ let mut cap = Capacity::new();+ cap.at_capacity(1000.0);+ assert!(cap.frozen());+ assert_eq!(cap.submitted_frozen(1000.0, 0, 7), Next::Clear);+ assert!(!cap.frozen(), "a clear is followed by a normal frame");+ }++ #[test]+ fn a_screen_that_never_fits_backs_off_and_caps() {+ let mut cap = Capacity::new();+ let mut now = 0.0f64;+ let mut clears = vec![];+ // One frame every 16 ms, forever declining something.+ for _ in 0..4000 {+ if !cap.frozen() {+ cap.at_capacity(now);+ }+ if let Next::Clear = cap.submitted_frozen(now, 0, 3) {+ clears.push(now);+ }+ now += 16.0;+ }+ let gaps: Vec<f64> = clears.windows(2).map(|w| w[1] - w[0]).collect();+ assert!(clears.len() > 4, "it has to keep trying: {clears:?}");+ assert!(+ gaps.iter().all(|g| *g >= MIN_RETRY_MS),+ "never once per frame: {gaps:?}"+ );+ assert!(+ gaps.iter().all(|g| *g <= MAX_RETRY_MS + 16.0),+ "and never longer than the cap: {gaps:?}"+ );+ // Doubling, then flat at the cap.+ assert!(gaps[1] > gaps[0] && gaps[2] > gaps[1], "{gaps:?}");+ assert_eq!(gaps.last(), gaps.iter().max_by(|a, b| a.total_cmp(b)));+ }++ #[test]+ fn a_frozen_frame_that_owes_nothing_ends_the_emergency() {+ let mut cap = Capacity::new();+ cap.at_capacity(0.0);+ assert_eq!(cap.submitted_frozen(0.0, 0, 0), Next::Recovered);+ assert!(!cap.frozen());+ }++ #[test]+ fn a_new_glyph_after_the_screen_got_simple_still_gets_drawn() {+ // The self-lock. The screen is cleared down to one character that+ // was never cached, so the frozen frame declines it and keeps+ // declining it. "Unfreeze when nothing was declined" never fires+ // here and the character is never drawn.+ let mut cap = Capacity::new();+ cap.at_capacity(0.0);+ assert_eq!(cap.submitted_frozen(0.0, 0, 9), Next::Clear);+ // ... and the clear did not help, so we are frozen again, at the+ // cap, with exactly one thing outstanding for ever after.+ let mut now = 16.0;+ let mut cleared = None;+ for _ in 0..2000 {+ if !cap.frozen() {+ cap.at_capacity(now);+ }+ if let Next::Clear = cap.submitted_frozen(now, 0, 1) {+ cleared = Some(now);+ break;+ }+ now += 16.0;+ }+ let at = cleared.expect("it must try again rather than stay frozen for ever");+ assert!(at <= MAX_RETRY_MS + 16.0, "recovery took {at} ms");+ }++ #[test]+ fn a_deferred_frame_does_not_end_the_emergency() {+ // A frame whose budget ran out returns successfully. Treating that+ // as "the demand is satisfied" resets the backoff, and the next+ // ceiling starts from scratch.+ let mut cap = Capacity::new();+ cap.at_capacity(0.0);+ assert_ne!(cap.submitted_frozen(0.0, 4, 0), Next::Recovered);+ }++ #[test]+ fn a_recovery_does_not_reset_the_backoff() {+ // Scrolling through CJK: after each clear the screen fits for a+ // frame, then fills up again. Treating that satisfied frame as the+ // end of the emergency reset the backoff, so the next capacity hit+ // cleared at once -- clears 48 ms apart in simulation, which is the+ // storm the backoff exists to prevent.+ let mut cap = Capacity::new();+ let mut now = 0.0f64;+ let mut clears = vec![];+ for _ in 0..3000 {+ if cap.frozen() {+ if let Next::Clear = cap.submitted_frozen(now, 0, 4) {+ clears.push(now);+ }+ } else {+ cap.drew_everything();+ cap.at_capacity(now);+ }+ now += 16.0;+ }+ assert!(clears.len() > 2, "it has to keep trying: {clears:?}");+ for pair in clears.windows(2) {+ assert!(+ pair[1] - pair[0] >= MIN_RETRY_MS,+ "two clears {} ms apart: {clears:?}",+ pair[1] - pair[0]+ );+ }+ }++ #[test]+ fn a_long_healthy_stretch_still_clears_at_once() {+ // The other side of the same rule: the deadline is an absolute+ // time, so a terminal that has been fine for a minute does not have+ // to wait out an old backoff.+ let mut cap = Capacity::new();+ cap.at_capacity(0.0);+ assert_eq!(cap.submitted_frozen(0.0, 0, 1), Next::Clear);+ for _ in 0..600 {+ cap.drew_everything();+ }+ cap.at_capacity(60_000.0);+ assert_eq!(cap.submitted_frozen(60_000.0, 0, 1), Next::Clear);+ }++ #[test]+ fn a_thin_glyph_is_never_scaled_out_of_existence() {+ // A full-width rule -- U+203E, U+2015, U+FF3F -- is a pixel or two+ // tall and far wider than its cell. Each case asserts its own+ // premise first: without the clamp the height really would truncate+ // to zero, so the test cannot quietly pass on inputs that never+ // needed it.+ for (w, h, max) in [(24usize, 1usize, 10.0f64), (40, 2, 12.5), (30, 2, 10.0)] {+ let unclamped = max / w as f64;+ assert_eq!(+ (h as f64 * unclamped) as usize,+ 0,+ "premise: {w}x{h} at {max} would round the height away"+ );+ let ink = Ink { left: 0, top: 10, width: w, height: h, clipped: false };+ let p = place(&ink, 0.0, 20.0, max);+ assert!(+ (h as f64 * p.scale) as usize >= 1,+ "{w}x{h}: scale {} rounds the height away",+ p.scale+ );+ assert!((w as f64 * p.scale) as usize >= 1, "{w}x{h}: scale {}", p.scale);+ assert!(p.scale <= 1.0, "a glyph is never enlarged: {}", p.scale);+ }+ }++ #[test]+ fn right_to_left_scripts_keep_their_boxes() {+ // Not just the joining ones: the emitter does no bidi, so Hebrew+ // would render as legible-but-reversed text, which a reader is far+ // less likely to notice than a row of boxes.+ for text in ["\u{628}", "\u{5d0}", "\u{780}", "\u{710}", "\u{870}", "\u{8a0}", "\u{fb2a}"] {+ assert!(keeps_notdef(text), "{text:?} would be laid out backwards");+ }+ for text in ["\u{4e2d}", "\u{d55c}", "\u{3042}", "\u{1f600}", "e\u{301}", "\u{e01}"] {+ assert!(!keeps_notdef(text), "{text:?} should reach the canvas");+ }+ }++ #[test]+ fn the_retry_deadline_is_a_time_not_a_frame_count() {+ // Output stopped, so the clock is the only thing that moves. Any+ // number of frames at the same instant must not bring the retry+ // forward, and the retry must arrive once the clock passes it.+ let mut cap = Capacity::new();+ cap.at_capacity(0.0);+ assert_eq!(cap.submitted_frozen(0.0, 0, 1), Next::Clear);+ cap.at_capacity(0.0);+ let deadline = match cap.submitted_frozen(0.0, 0, 1) {+ Next::RetryAt(t) => t,+ other => panic!("expected a deadline, got {other:?}"),+ };+ for _ in 0..500 {+ assert_eq!(cap.submitted_frozen(0.0, 0, 1), Next::RetryAt(deadline));+ }+ assert_eq!(cap.submitted_frozen(deadline, 0, 1), Next::Clear);+ }+}diff --git a/thinkterm-web/src/glyphs.rs b/thinkterm-web/src/glyphs.rsindex a3e5f464..5b88dd44 100644--- a/thinkterm-web/src/glyphs.rs+++ b/thinkterm-web/src/glyphs.rs@@ -4,6 +4,7 @@//! atlas and the pure-Rust font set. Moved, not re-derived, so the only//! placement differences left are the shaper's (see thinkterm-font-web).+use crate::fallback::FallbackBudget;use anyhow::{Context, Result};use std::collections::HashMap;use std::rc::Rc;@@ -11,9 +12,10 @@ use termwiz::cell::Underline;use termwiz::surface::CursorShape;use thinkterm_font_core::units::PixelLength;use thinkterm_font_core::{FontMetrics, FontRasterizer, FontShaper, GlyphInfo};-use thinkterm_font_web::FontSet;+use thinkterm_font_web::{FontSet, Gap, WebShaped};use thinkterm_render::atlas::{Atlas, AtlasTag, OutOfTextureSpace, Sprite};use thinkterm_render::bitmaps::{BitmapImage, Image, Texture2d};+use thinkterm_render::customglyph::{block_image, BlockKey, BlockMetrics, PolyAA};use thinkterm_render::geom::{Point, Rect, Size};use thinkterm_render::pipeline::GpuTexture;use wezterm_color_types::SrgbaPixel;@@ -58,6 +60,11 @@ impl RenderMetrics {}}+/// How many drawn-glyph verdicts to keep. Large enough for several screens+/// of distinct CJK, small enough that a stream of junk code points cannot+/// grow the heap without end.+const MAX_FALLBACK_ENTRIES: usize = 8192;+/// glyphcache.rs `CachedGlyph`, fields and all: the emitter reads what it/// needs today and the rest is the desktop's record.#[derive(Debug)]@@ -97,6 +104,15 @@ struct ShapeKey {text: String,/// `Presentation` has no `Hash`; Text is 0, Emoji is 1.presentation: Option<u8>,+ /// The columns the row says this cluster occupies.+ ///+ /// The same text really is a different number of columns either side of+ /// an `ambiguous_are_wide` or `cell_widths` change, and a character can+ /// be both ambiguous-width and a gap -- U+2605 is in neither bundled+ /// face. This used to only get `num_cells` wrong; now `Gap.cells` comes+ /// out of this cache entry and decides how far a fallback glyph+ /// advances the column.+ cells: u16,}pub struct GlyphCache {@@ -114,18 +130,69 @@ pub struct GlyphCache {/// pattern: every one of the 256 shapes to the same .notdef, and/// `glyphs` would collide them onto a single entry.braille: HashMap<u8, Rc<CachedGlyph>>,- shapes: HashMap<ShapeKey, Rc<Vec<GlyphInfo>>>,- #[allow(dead_code)]+ blocks: HashMap<(BlockKey, u8), Rc<CachedGlyph>>,+ shapes: HashMap<ShapeKey, Rc<WebShaped>>,+ /// Glyphs the browser drew for us, by columns and then by grapheme.+ /// `None` remembers that it could not draw one either, so a machine+ /// without the font does not redraw the same nothing every frame.+ ///+ /// Not keyed on `GlyphKey`: every uncovered grapheme shapes to font 0's+ /// glyph 0, so CJK, Hangul, emoji and arrows would all collide onto one+ /// entry -- the Braille bug, at the scale of Unicode. Not on+ /// `only_char` either: that is `None` for every ZWJ, combining and+ /// variation-selector cluster.+ ///+ /// Cell size, dpi and the font chain are deliberately absent from the+ /// key: none of them can change without rebuilding this whole cache,+ /// and this table goes with it. So is presentation -- one font string,+ /// one drawing procedure, no difference in the pixels.+ fallback: HashMap<u8, HashMap<String, Option<Rc<CachedGlyph>>>>,+ scratch: Renderer,+ /// The CSS font stack the fallback draws with.+ pub families: Rc<str>,+ /// Handed back wherever a glyph cannot be made right now. Shared, so+ /// the frozen path allocates nothing at all.+ blank: Rc<CachedGlyph>,+ /// No sprite may be allocated this frame; see `reserve`.+ frozen: bool,+ declined: u32,pub white_space: Sprite,pub filled_box: Sprite,}+/// The scratch canvas is made on first use: a session that never meets a+/// missing glyph never touches the DOM for one, and a browser that will not+/// give us a 2D context is asked exactly once.+enum Renderer {+ Untried,+ Ready(crate::canvas::Scratch),+ Unavailable,+}++/// A glyph with nothing to draw. The emitter skips a `texture: None` glyph+/// but still advances the column, so a cell left out this way keeps the+/// line aligned.+fn blank_glyph() -> CachedGlyph {+ CachedGlyph {+ brightness_adjust: 1.0,+ has_color: false,+ texture: None,+ x_offset: PixelLength::new(0.0),+ y_offset: PixelLength::new(0.0),+ x_advance: PixelLength::new(0.0),+ bearing_x: PixelLength::new(0.0),+ bearing_y: PixelLength::new(0.0),+ scale: 1.0,+ }+}+impl GlyphCache {pub fn new(fonts: Rc<FontSet>,size_pt: f64,dpi: u32,texture: Rc<GpuTexture>,+ families: Rc<str>,) -> Result<Self> {let base_metrics = fonts.metrics(size_pt, dpi)?;let metrics = RenderMetrics::with_font_metrics(&base_metrics);@@ -153,7 +220,14 @@ impl GlyphCache {lines: HashMap::new(),cursors: HashMap::new(),braille: HashMap::new(),+ blocks: HashMap::new(),shapes: HashMap::new(),+ fallback: HashMap::new(),+ scratch: Renderer::Untried,+ families,+ blank: Rc::new(blank_glyph()),+ frozen: false,+ declined: 0,white_space,filled_box,})@@ -163,38 +237,85 @@ impl GlyphCache {&self.texture}+ /// The atlas texture, so this cache can be rebuilt over the same one --+ /// which is how the atlas gets cleared.+ pub fn texture_rc(&self) -> Rc<GpuTexture> {+ Rc::clone(&self.texture)+ }++ /// Start a frame. While `frozen`, nothing new is allocated and nothing+ /// is remembered; see `reserve`.+ pub fn begin_frame(&mut self, frozen: bool) {+ self.frozen = frozen;+ self.declined = 0;+ }++ /// Sprites this frame asked for and did not get.+ pub fn declined(&self) -> u32 {+ self.declined+ }++ /// Sprite allocation, and the one place that gives up.+ ///+ /// Once the atlas has grown to the GPU's largest texture and still has+ /// no room, the frame must reach `gpu.draw` anyway, so allocation stops+ /// failing and starts declining. Every caller has to say what it draws+ /// instead, which is why this returns an `Option` rather than taking a+ /// flag: a new kind of sprite that forgot the frozen case would not+ /// compile.+ ///+ /// Nothing declined is written to any cache. There is no invalidation+ /// to get wrong -- the glyph is simply drawn once there is room.+ ///+ /// (`filled_box` and `white_space` are allocated in `new`, before there+ /// is a `self` to freeze, and are the two sprites this always has.)+ fn reserve(&mut self, im: &dyn BitmapImage, tag: AtlasTag) -> Result<Option<Sprite>> {+ if self.frozen {+ self.declined += 1;+ return Ok(None);+ }+ Ok(Some(self.atlas.allocate_tagged(im, None, None, tag)?))+ }+/// Shape one cluster's text, memoised: the same text with the same/// attributes shapes the same every frame.+ ///+ /// The gaps come back cached with the glyphs, which is the whole point:+ /// held separately, the second frame would hit this cache and no longer+ /// know which graphemes need drawing.pub fn shape(&mut self,text: &str,presentation: Option<termwiz::cell::Presentation>,presentation_width: Option<&thinkterm_font_core::PresentationWidth>,- ) -> Result<Rc<Vec<GlyphInfo>>> {+ cells: usize,+ ) -> Result<Rc<WebShaped>> {let key = ShapeKey {text: text.to_string(),presentation: presentation.map(|p| match p {termwiz::cell::Presentation::Text => 0,termwiz::cell::Presentation::Emoji => 1,}),+ cells: cells.min(u16::MAX as usize) as u16,};if let Some(shaped) = self.shapes.get(&key) {return Ok(Rc::clone(shaped));}- let mut no_glyphs = Vec::new();- let shaped = Rc::new(self.fonts.shape(+ let shaped = Rc::new(self.fonts.shape_web(text,self.size_pt,self.dpi,- &mut no_glyphs,presentation,thinkterm_font_core::Direction::LeftToRight,None,presentation_width,+ &crate::fallback::keeps_notdef,)?);- if !no_glyphs.is_empty() {- log::debug!("no bundled face has {no_glyphs:?}");- }+ // Flushing this is safe and cheap: `shape_web` is pure, so the next+ // frame derives the same answer again. The drawn fallbacks live in+ // their own table and are deliberately *not* flushed with it --+ // sharing one would make an ordinary scroll redraw a screenful of+ // CJK, at the moment that costs the most.if self.shapes.len() > 4096 {self.shapes.clear();}@@ -202,6 +323,196 @@ impl GlyphCache {Ok(shaped)}+ /// The scratch canvas, made on first use.+ ///+ /// A session that never meets a missing glyph never creates a DOM+ /// element for one. A browser that will not give us a 2D context is+ /// 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> {+ 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.metrics.cell_size,+ self.metrics.descender.get(),+ px,+ &self.families,+ ) {+ Ok(scratch) => Renderer::Ready(scratch),+ Err(err) => {+ log::warn!("no canvas for fallback glyphs: {err:#}");+ Renderer::Unavailable+ }+ };+ }+ match &self.scratch {+ Renderer::Ready(scratch) => Some(scratch),+ _ => None,+ }+ }++ /// Keep what the canvas produced, including that it produced nothing.+ fn remember(+ &mut self,+ gap: &Gap,+ cells: u8,+ glyph: Option<Rc<CachedGlyph>>,+ ) -> Option<Rc<CachedGlyph>> {+ // Every other table here is bounded by the atlas: fill it and the+ // whole cache is rebuilt. The `None` entries are not -- they hold no+ // sprite, so they never push the atlas towards that -- and a pane+ // spewing unassigned or private-use code points would grow this+ // without limit. Flushed wholesale rather than by LRU, like+ // `shapes`: what is lost is redrawn, at worst once.+ if self.fallback.values().map(HashMap::len).sum::<usize>() > MAX_FALLBACK_ENTRIES {+ self.fallback.clear();+ }+ self.fallback+ .entry(cells)+ .or_default()+ .insert(gap.text.clone(), glyph.clone());+ glyph+ }++ /// The glyph for a gap, drawn with the platform's own fonts.+ ///+ /// `Ok(None)` means **leave the missing-glyph box** -- which is what+ /// this machine's native terminal would show anyway, and is never worse+ /// than what the page does today.+ ///+ /// The order of the first four steps is the design:+ ///+ /// 1. A gap with no columns is refused. The `.notdef` it would replace+ /// advances no columns; a fallback advances one, and the rest of the+ /// line shifts with nothing to report it.+ /// 2. The cache is consulted before the budget, so scrolling back over+ /// CJK already drawn costs nothing at all.+ /// 3. **The freeze is checked before the budget and before the canvas.**+ /// Leaving it to `reserve` would draw the glyph and throw it away,+ /// and -- worse -- would spend budget, producing a `deferred` that+ /// asks for another frame and undoes the atlas backoff.+ /// 4. Only then is a glyph drawn.+ /// `cells` is the column count taken from the row being drawn, not+ /// `gap.cells`. The shape cache is keyed on a cluster's *total* width,+ /// so two rows that spend the same total differently -- `[1,2,1]` and+ /// `[2,1,1]` for the same text, which explicit cell widths allow --+ /// share an entry, and the second would inherit the first's per-gap+ /// count and shift everything after it.+ pub fn fallback_glyph(+ &mut self,+ gap: &Gap,+ cells: u8,+ budget: &mut FallbackBudget,+ ) -> Result<Option<Rc<CachedGlyph>>> {+ if cells == 0 {+ return Ok(None);+ }+ // Wider than the scratch canvas was built for: its ink would be cut+ // off at the edge and the bearing measured from the truncated box,+ // 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 {+ return Ok(self.remember(gap, cells, None));+ }+ if let Some(known) = self+ .fallback+ .get(&cells)+ .and_then(|by_text| by_text.get(&gap.text))+ {+ return Ok(known.clone());+ }+ if self.frozen {+ self.declined += 1;+ return Ok(None);+ }+ // The canvas is checked before the budget. Spending budget on a+ // browser that will not give us a 2D context produced `deferred`,+ // `deferred` asked for another frame, and the next frame was+ // byte-identical: a repaint loop at the display's refresh rate,+ // drawing nothing, on a device already constrained enough that+ // `getContext` failed.+ //+ // The verdict is latched for the life of this cache, so a context+ // refused under transient pressure is retried only when the cache is+ // next rebuilt -- a font size or dpr change, or an atlas growth. A+ // page that never gets one shows boxes until it is reloaded.+ let drawn = match self.scratch() {+ None => return Ok(None),+ Some(scratch) => {+ if !budget.take(crate::app::monotonic_ms()) {+ return Ok(None);+ }+ scratch.glyph(&gap.text, cells)+ }+ };+ let drawn = match drawn {+ Ok(Some(drawn)) => drawn,+ // The browser has no font for it either, or it threw. Either+ // way this machine will not start being able to draw it, and+ // retrying every frame would redraw the same nothing for ever.+ Ok(None) => return Ok(self.remember(gap, cells, None)),+ Err(err) => {+ // Not remembered. `Ok(None)` above is a fact about this+ // machine -- no font has the glyph -- and is worth caching+ // for ever. A thrown exception is not: `getImageData` can+ // fail for reasons that pass, and writing "undrawable" here+ // left the grapheme a box for the life of the cache. The+ // budget already stops this from being redrawn more than a+ // few times a frame.+ log::warn!("the canvas could not draw {:?}: {err:#}", gap.text);+ return Ok(None);+ }+ };+ if drawn.clipped {+ // The ink ran into the edge of the scratch canvas, so its+ // bounding box -- and every bearing derived from it -- describes+ // whatever fitted rather than the glyph. Caching that would put a+ // permanently mis-placed, half-drawn glyph on screen; the box is+ // the honest answer. The canvas has a full cell of margin on each+ // side, so this means genuinely enormous ink.+ log::warn!(+ "the fallback glyph for {:?} did not fit the scratch canvas; keeping the box",+ gap.text+ );+ return Ok(self.remember(gap, cells, None));+ }+ // Scaled here rather than at draw time, the way `load_glyph` does+ // it: the bearings were already scaled with it.+ // A colour glyph never arrives scaled; see `Scratch::glyph`.+ let image = if drawn.placement.scale != 1.0 {+ drawn.image.scale_by(drawn.placement.scale)+ } else {+ drawn.image+ };+ // `.context`, never `format!`: the downcast in `cached_glyph` and in+ // `frame` walks the root cause, and hiding an `OutOfTextureSpace`+ // behind a string turns a recoverable full atlas into a terminal+ // that never draws again.+ let Some(texture) = self+ .reserve(&image, AtlasTag::Glyph)+ .context("canvas fallback sprite")?+ else {+ return Ok(None);+ };+ let glyph = Rc::new(CachedGlyph {+ brightness_adjust: 1.0,+ has_color: drawn.has_color,+ texture: Some(texture),+ x_offset: PixelLength::new(0.0),+ y_offset: PixelLength::new(0.0),+ // The columns the row gave it, not what the canvas measured.+ x_advance: PixelLength::new(+ cells as f64 * self.metrics.cell_size.width as f64,+ ),+ bearing_x: PixelLength::new(drawn.placement.bearing_x),+ bearing_y: PixelLength::new(drawn.placement.bearing_y),+ scale: 1.0,+ });+ Ok(self.remember(gap, cells, Some(glyph)))+ }+pub fn cached_glyph(&mut self,info: &GlyphInfo,@@ -214,6 +525,9 @@ impl GlyphCache {if let Some(dots) = info.only_char.and_then(crate::braille::dots) {return self.braille_glyph(dots);}+ if let Some(block) = info.only_char.and_then(BlockKey::from_char) {+ return self.block_glyph(block, num_cells);+ }let key = GlyphKey {font_idx: info.font_idx,glyph_pos: info.glyph_pos,@@ -225,30 +539,69 @@ impl GlyphCache {if let Some(entry) = self.glyphs.get(&key) {return Ok(Rc::clone(entry));}+ // Checked before rasterising, not just before allocating: a frozen+ // frame that rendered the outline and then threw it away would burn+ // the work for nothing.+ if self.frozen {+ self.declined += 1;+ return Ok(Rc::clone(&self.blank));+ }let glyph = match self.load_glyph(info, followed_by_space, num_cells) {- Ok(g) => g,+ Ok(Some(glyph)) => glyph,+ // The atlas declined it. Hand back a blank without remembering:+ // storing it here would turn "no room just now" into a cell+ // that stays empty until the whole cache is rebuilt.+ Ok(None) => return Ok(Rc::clone(&self.blank)),Err(err) => {if err.root_cause().downcast_ref::<OutOfTextureSpace>().is_some() {return Err(err);}+ // A glyph that genuinely will not rasterise, on the other+ // hand, is worth remembering: it will not start working.log::error!("load_glyph failed; using blank instead: {err:#} {info:?}");- Rc::new(CachedGlyph {- brightness_adjust: 1.0,- has_color: false,- texture: None,- x_advance: PixelLength::new(0.0),- x_offset: PixelLength::new(0.0),- y_offset: PixelLength::new(0.0),- bearing_x: PixelLength::new(0.0),- bearing_y: PixelLength::new(0.0),- scale: 1.0,- })+ Rc::new(blank_glyph())}};self.glyphs.insert(key, Rc::clone(&glyph));Ok(glyph)}+ /// Cell geometry has no font bearing or baseline padding. Cache it by+ /// shape and column count; atlas/DPR rebuilds discard this table too.+ fn block_glyph(&mut self, block: BlockKey, cells: u8) -> Result<Rc<CachedGlyph>> {+ if cells == 0 {+ return Ok(Rc::clone(&self.blank));+ }+ if let Some(glyph) = self.blocks.get(&(block, cells)) {+ return Ok(Rc::clone(glyph));+ }+ if self.frozen {+ self.declined += 1;+ return Ok(Rc::clone(&self.blank));+ }+ let metrics = BlockMetrics {+ cell_size: Size::new(+ self.metrics.cell_size.width * cells as isize,+ self.metrics.cell_size.height,+ ),+ underline_height: self.metrics.underline_height,+ };+ let buffer = block_image(block, &metrics, PolyAA::AntiAlias);+ let Some(texture) = self.reserve(&buffer, AtlasTag::Glyph).context("block sprite")? else {+ return Ok(Rc::clone(&self.blank));+ };+ let glyph = Rc::new(CachedGlyph {+ texture: Some(texture),+ x_advance: PixelLength::new(metrics.cell_size.width as f64),+ // Cancels the emitter's baseline to anchor at the cell top.+ bearing_y: self.metrics.descender+ + PixelLength::new(metrics.cell_size.height as f64),+ ..blank_glyph()+ });+ self.blocks.insert((block, cells), Rc::clone(&glyph));+ Ok(glyph)+ }+/// glyphcache.rs `load_glyph`, with the desktop's default of letting/// square glyphs overflow when a space follows.#[allow(clippy::float_cmp)]@@ -257,7 +610,7 @@ impl GlyphCache {info: &GlyphInfo,followed_by_space: bool,num_cells: u8,- ) -> Result<Rc<CachedGlyph>> {+ ) -> Result<Option<Rc<CachedGlyph>>> {let base_metrics = self.base_metrics;let face = self.fonts.face(info.font_idx)?;let glyph = face.rasterize_glyph(info.glyph_pos, self.size_pt, self.dpi)?;@@ -329,14 +682,21 @@ impl GlyphCache {let x_offset = info.x_offset * scale * metrics_only_scale;let y_offset = info.y_offset * scale * metrics_only_scale;let x_advance = info.x_advance * scale * metrics_only_scale;+ // `Image::scale_by` truncates without a floor, so a glyph one+ // pixel tall scales away to nothing; the same clamp+ // `fallback::place` applies to the canvas path.+ let scale = scale+ .max(1.0 / raw_im.image_dimensions().0.max(1) as f64)+ .max(1.0 / raw_im.image_dimensions().1.max(1) as f64)+ .min(1.0);let (scale, raw_im) = if scale != 1.0 {(1.0, raw_im.scale_by(scale))} else {(scale, raw_im)};- let tex = self- .atlas- .allocate_tagged(&raw_im, None, None, AtlasTag::Glyph)?;+ let Some(tex) = self.reserve(&raw_im, AtlasTag::Glyph)? else {+ return Ok(None);+ };CachedGlyph {brightness_adjust,has_color: glyph.has_color,@@ -349,7 +709,7 @@ impl GlyphCache {scale,}};- Ok(Rc::new(glyph))+ Ok(Some(Rc::new(glyph)))}/// glyphcache.rs `cached_line_sprite`: underline, strike and overline@@ -451,7 +811,12 @@ impl GlyphCache {if strike_through {draw_rows(&mut buffer, metrics.strike_row);}- let sprite = self.atlas.allocate(&buffer)?;+ // No underline this frame rather than no frame at all. After a+ // clear these are gone along with everything else, so re-allocating+ // them is exactly the moment the atlas is most likely to refuse.+ let Some(sprite) = self.reserve(&buffer, AtlasTag::Other)? else {+ return Ok(self.white_space.clone());+ };self.lines.insert(key, sprite.clone());Ok(sprite)}@@ -473,7 +838,15 @@ impl GlyphCache {}let cell = self.metrics.cell_size;let buffer = crate::braille::image(dots, cell);- let sprite = self.atlas.allocate(&buffer).context("braille sprite")?;+ // Its own allocation, so it needs its own frozen branch -- this is+ // the entry point an earlier design missed, because `cached_glyph`+ // returns here before it reaches any of its own error handling.+ let Some(sprite) = self+ .reserve(&buffer, AtlasTag::Glyph)+ .context("braille sprite")?+ else {+ return Ok(Rc::clone(&self.blank));+ };let glyph = Rc::new(CachedGlyph {brightness_adjust: 1.0,has_color: false,@@ -520,7 +893,14 @@ impl GlyphCache {fill(&mut buffer, 0, h - thickness, w, thickness);}}- let sprite = self.atlas.allocate(&buffer).context("cursor sprite")?;+ // Same again: a missing cursor for a frame or two is survivable in+ // an emergency; a black screen is not.+ let Some(sprite) = self+ .reserve(&buffer, AtlasTag::Other)+ .context("cursor sprite")?+ else {+ return Ok(self.white_space.clone());+ };self.cursors.insert((shape, width), sprite.clone());Ok(sprite)}diff --git a/thinkterm-web/src/graphics_check.rs b/thinkterm-web/src/graphics_check.rsnew file mode 100644index 00000000..c3fdb6f2--- /dev/null+++ b/thinkterm-web/src/graphics_check.rs@@ -0,0 +1,203 @@+//! Token-free WebGPU regression probe using the real line emitter/cache.+use crate::{emit, fallback::FallbackBudget, glyphs::GlyphCache, gpu::Gpu, ime};+use anyhow::{anyhow, ensure, Result};+use std::{rc::Rc, sync::Arc};+use termwiz::surface::{CursorVisibility, Line};+use thinkterm_font_web::{Face, FontSet};+use thinkterm_proto::StableCursorPosition;+use thinkterm_render::{pipeline::GpuTexture, quad::HeapQuadAllocator};+use wasm_bindgen::{prelude::*, JsCast};+use wezterm_term::{color::ColorPalette, CellAttributes};++#[wasm_bindgen]+pub async fn graphics_check(+ font_names: Vec<String>,+ fonts: Vec<js_sys::Uint8Array>,+ size_pt: f64,+) -> Result<String, JsValue> {+ run(font_names, fonts, size_pt)+ .await+ .map_err(|e| JsValue::from_str(&format!("{e:#}")))+}++async fn run(names: Vec<String>, fonts: Vec<js_sys::Uint8Array>, size: f64) -> Result<String> {+ let window = web_sys::window().ok_or_else(|| anyhow!("no window"))?;+ let document = window.document().ok_or_else(|| anyhow!("no document"))?;+ let canvas: web_sys::HtmlCanvasElement = document+ .get_element_by_id("term")+ .unwrap()+ .dyn_into()+ .unwrap();+ let field: web_sys::HtmlTextAreaElement = document+ .get_element_by_id("kbd")+ .unwrap()+ .dyn_into()+ .unwrap();+ let clock = window.performance().unwrap();+ let rect = canvas.get_bounding_client_rect();+ let dpr = window.device_pixel_ratio();+ let (w, h) = ((rect.width() * dpr) as u32, (rect.height() * dpr) as u32);+ canvas.set_width(w);+ canvas.set_height(h);+ let mut gpu = Gpu::new(canvas.clone(), w, h).await?;+ let faces = names+ .iter()+ .zip(fonts.iter())+ .map(|(n, f)| Face::new(n, f.to_vec(), 0))+ .collect::<Result<Vec<_>>>()?;+ let texture = Rc::new(GpuTexture::new(+ &gpu.device,+ Arc::clone(&gpu.queue),+ 1024,+ 1024,+ )?);+ let mut cache = GlyphCache::new(+ Rc::new(FontSet::new(faces)?),+ size,+ (96.0 * dpr) as u32,+ texture,+ crate::canvas::DEFAULT_FAMILIES.into(),+ )?;+ let (cw, ch) = (+ cache.metrics.cell_size.width as u32,+ cache.metrics.cell_size.height as u32,+ );+ ensure!(+ w >= 4 * cw && h >= 2 * ch,+ "the probe needs at least four columns and two rows"+ );+ let cols = (w / cw).min(40) as usize;+ let samples = [+ "█".repeat(cols),+ "█".repeat(cols),+ "▀".repeat(cols),+ "▄".repeat(cols),+ "▌▐".repeat(cols / 2),+ "░".repeat(cols),+ "▒".repeat(cols),+ "▓".repeat(cols),+ format!("┌{}┐", "─".repeat(cols - 2)),+ format!("│{}│", " ".repeat(cols - 2)),+ format!("└{}┘", "─".repeat(cols - 2)),+ "╔══╦══╗ ╭──╮ ┣━╋━┫".into(),+ "▁▂▃▄▅▆▇█ ▏▎▍▌▋▊▉ ▖▗▘▙▚▛▜▝▞▟".into(),+ "⠁⠃⠇⡇⣇⣧⣷⣿".into(),+ ];+ let palette = ColorPalette::default();+ let cursor = StableCursorPosition {+ visibility: CursorVisibility::Hidden,+ ..Default::default()+ };+ let mut quads = HeapQuadAllocator::default();+ let mut vertices = Vec::new();+ let emit = |cache: &mut GlyphCache,+ quads: &mut HeapQuadAllocator,+ texts: &[String],+ frozen|+ -> Result<()> {+ cache.begin_frame(frozen);+ quads.recycle();+ let mut budget = FallbackBudget::new(clock.now());+ for (i, text) in texts.iter().enumerate() {+ let line = Line::from_text(text, &CellAttributes::default(), 0, None);+ emit::emit_line(+ cache,+ quads,+ &mut budget,+ &emit::LineParams {+ line: &line,+ stable_row: i as isize,+ top_pixel_y: (i as u32 * ch) as f32,+ cursor: &cursor,+ palette: &palette,+ selection: 0..0,+ focused: false,+ reverse_video: false,+ surface: (w as f32, h as f32),+ },+ )?;+ }+ ensure!(budget.deferred() == 0, "geometry spent Canvas budget");+ Ok(())+ };+ let t = clock.now();+ emit(&mut cache, &mut quads, &samples, false)?;+ let cold_ms = clock.now() - t;+ let usage = cache.atlas.usage();+ let t = clock.now();+ for _ in 0..20 {+ emit(&mut cache, &mut quads, &samples, false)?;+ }+ let warm_ms = (clock.now() - t) / 20.0;+ ensure!(+ cache.atlas.usage() == usage,+ "warm frames allocated more atlas space"+ );+ // An uncached shape declined while frozen must work once unfrozen.+ let missed = ["╬".to_string()];+ emit(&mut cache, &mut quads, &missed, true)?;+ ensure!(+ cache.declined() > 0 && cache.atlas.usage() == usage,+ "frozen miss allocated or was not declined"+ );+ emit(&mut cache, &mut quads, &missed, false)?;+ ensure!(+ cache.declined() == 0 && cache.atlas.usage().allocations > usage.allocations,+ "frozen miss stayed blank"+ );+ emit(&mut cache, &mut quads, &samples, false)?;+ quads.extract_vertices(&mut vertices);+ let reference = gpu+ .draw_and_read_pixel(&vertices, cache.texture(), cw / 2, ch / 2)+ .await?;+ ensure!(reference[0] > 32, "full block is blank");+ for (x, y) in [+ (0, 0),+ (cw - 1, ch / 2),+ (cw, ch / 2),+ (cw + 1, ch / 2),+ (cw / 2, ch - 1),+ (cw / 2, ch),+ (cw / 2, ch + 1),+ (cw - 1, ch - 1),+ (cw, ch),+ ] {+ let pixel = gpu+ .draw_and_read_pixel(&vertices, cache.texture(), x, y)+ .await?;+ ensure!(+ pixel == reference,+ "seam at ({x},{y}): {pixel:?}, expected {reference:?}"+ );+ }+ // Check the real DOM update path, including the no-op and preservation+ // of composition text. Native IME candidate UI still needs manual QA.+ let bounds = [rect.left(), rect.top(), rect.width(), rect.height()];+ let mut previous = None;+ field.set_value("pinyin");+ for point in [+ (0.0, 0.0),+ (cw as f64 * 3.0, ch as f64 * 4.0),+ (w as f64, h as f64),+ ] {+ let anchor = ime::anchor(bounds, (w, h), point, (cw as f64, ch as f64)).unwrap();+ ime::update_field(&field, &mut previous, Some(anchor))+ .map_err(|e| anyhow!("IME: {e:?}"))?;+ let actual = field.get_bounding_client_rect();+ ensure!(+ (actual.left() - anchor.left).abs() < 0.1 && (actual.top() - anchor.top).abs() < 0.1,+ "IME field differs from cursor anchor"+ );+ ensure!(+ !ime::update_field(&field, &mut previous, Some(anchor))+ .map_err(|e| anyhow!("IME: {e:?}"))?,+ "unchanged anchor writes DOM"+ );+ ensure!(+ field.value() == "pinyin",+ "position update changed composition text"+ );+ }+ field.set_value("");+ Ok(format!("{{\"ok\":true,\"seams\":0,\"warm_allocations\":0,\"frozen_recovered\":true,\"ime_anchor\":true,\"cell\":[{cw},{ch}],\"dpr\":{dpr},\"cold_emit_ms\":{cold_ms:.2},\"warm_emit_ms\":{warm_ms:.2}}}"))+}diff --git a/thinkterm-web/src/ime.rs b/thinkterm-web/src/ime.rsnew file mode 100644index 00000000..16e2295f--- /dev/null+++ b/thinkterm-web/src/ime.rs@@ -0,0 +1,118 @@+//! Position of the browser's IME input field, in viewport CSS pixels.+//! The terminal uses device pixels and stable scrollback rows instead.++#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Anchor {+ pub left: f64,+ pub top: f64,+ pub width: f64,+ pub height: f64,+}++/// Keep the input field inside the visible canvas even when the terminal+/// cursor is in a row scrolled out of view or just past the right margin.+/// `cursor` and `cell` are device pixels, relative to the canvas.+pub fn anchor(+ rect: [f64; 4],+ surface: (u32, u32),+ cursor: (f64, f64),+ cell: (f64, f64),+) -> Option<Anchor> {+ let [left, top, width, height] = rect;+ if surface.0 == 0 || surface.1 == 0 || width <= 0.0 || height <= 0.0 {+ return None;+ }+ let sx = width / surface.0 as f64;+ let sy = height / surface.1 as f64;+ let w = (cell.0 * sx).max(1.0).min(width);+ let h = (cell.1 * sy).max(1.0).min(height);+ Some(Anchor {+ left: left + (cursor.0 * sx).clamp(0.0, width - w),+ top: top + (cursor.1 * sy).clamp(0.0, height - h),+ width: w,+ height: h,+ })+}++/// Update only changed geometry, without touching focus, composition,+/// value or selection. Returns whether anything changed for the smoke probe.+#[cfg(target_arch = "wasm32")]+pub fn update_field(+ field: &web_sys::HtmlTextAreaElement,+ previous: &mut Option<Anchor>,+ next: Option<Anchor>,+) -> Result<bool, wasm_bindgen::JsValue> {+ let Some(next) = next.filter(|a| Some(*a) != *previous) else {+ return Ok(false);+ };+ let style = field.style();+ if previous.is_none_or(|old| old.left != next.left) {+ style.set_property("left", &format!("{}px", next.left))?;+ }+ if previous.is_none_or(|old| old.top != next.top) {+ style.set_property("top", &format!("{}px", next.top))?;+ }+ if previous.is_none_or(|old| old.width != next.width || old.height != next.height) {+ style.set_property("width", &format!("{}px", next.width))?;+ style.set_property("height", &format!("{}px", next.height))?;+ style.set_property("line-height", &format!("{}px", next.height))?;+ style.set_property("font-size", &format!("{}px", next.height * 0.75))?;+ }+ *previous = Some(next);+ Ok(true)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn device_pixels_become_css_pixels_at_the_canvas_origin() {+ assert_eq!(+ anchor(+ [30.0, 40.0, 800.0, 600.0],+ (1600, 1200),+ (200.0, 172.0),+ (20.0, 43.0)+ ),+ Some(Anchor {+ left: 130.0,+ top: 126.0,+ width: 10.0,+ height: 21.5+ })+ );+ }++ #[test]+ fn fractional_zoom_and_double_width_rows_use_actual_surface_scale() {+ let a = anchor(+ [0.0, 0.0, 803.0, 601.0],+ (1003, 751),+ (40.0, 86.0),+ (40.0, 86.0),+ )+ .unwrap();+ assert!((a.left - 40.0 * 803.0 / 1003.0).abs() < 1e-9);+ assert!((a.height - 86.0 * 601.0 / 751.0).abs() < 1e-9);+ }++ #[test]+ fn scrollback_and_right_margin_do_not_move_the_ime_outside_the_canvas() {+ let rect = [10.0, 20.0, 800.0, 600.0];+ let bottom = anchor(rect, (800, 600), (900.0, 9000.0), (10.0, 22.0)).unwrap();+ assert_eq!(+ bottom,+ Anchor {+ left: 800.0,+ top: 598.0,+ width: 10.0,+ height: 22.0+ }+ );+ let top = anchor(rect, (800, 600), (0.0, -22.0), (10.0, 22.0)).unwrap();+ assert_eq!(top.top, 20.0);+ assert_eq!(anchor(rect, (0, 600), (0.0, 0.0), (10.0, 22.0)), None);+ assert_eq!(anchor([0.0; 4], (800, 600), (0.0, 0.0), (10.0, 22.0)), None);+ }+}diff --git a/thinkterm-web/src/input.rs b/thinkterm-web/src/input.rsindex b372fc7d..990c639d 100644--- a/thinkterm-web/src/input.rs+++ b/thinkterm-web/src/input.rs@@ -152,6 +152,10 @@ pub fn install(app: Rc<App>, canvas: &HtmlCanvasElement, textarea: &HtmlTextArealet app = app.clone();listen::<Event>(&window, "resize", move |_| app.resize());}+ {+ let app = app.clone();+ listen::<Event>(&window, "scroll", move |_| app.resize());+ }{// The canvas's own box, not just the window: CSS can resize it.let app = app.clone();diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rsindex 3fd11601..74d55aa0 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -1,9 +1,11 @@//! The ThinkTerm browser client. See Cargo.toml for the charter.//!-//! `braille`, `keymap`, `lease` and `viewport` are pure and build-//! everywhere; everything that touches the page is `wasm32` only.+//! `braille`, `fallback`, `keymap`, `lease` and `viewport` are pure and+//! build everywhere; everything that touches the page is `wasm32` only.pub mod braille;+pub mod fallback;+pub mod ime;pub mod keymap;pub mod lease;pub mod viewport;@@ -13,12 +15,16 @@ mod app;#[cfg(target_arch = "wasm32")]mod attach;#[cfg(target_arch = "wasm32")]+mod canvas;+#[cfg(target_arch = "wasm32")]mod emit;#[cfg(target_arch = "wasm32")]mod glyphs;#[cfg(target_arch = "wasm32")]mod gpu;#[cfg(target_arch = "wasm32")]+mod graphics_check;+#[cfg(target_arch = "wasm32")]mod host;#[cfg(target_arch = "wasm32")]mod input;diff --git a/thinkterm-web/src/link.rs b/thinkterm-web/src/link.rsindex fac6e06a..226d8130 100644--- a/thinkterm-web/src/link.rs+++ b/thinkterm-web/src/link.rs@@ -34,6 +34,32 @@ struct Socket {_closures: RefCell<Vec<Closure<dyn FnMut(JsValue)>>>,}+impl Socket {+ /// Let go of a socket this link is done with.+ ///+ /// The four event closures each hold an `Rc` to the very Socket that+ /// owns them, so its strong count never falls below four and neither+ /// it nor its `WebSocket` is ever dropped. That was harmless while+ /// exactly one existed per page; a link that reconnects makes a new one+ /// per attempt, and an overnight outage is thousands of them. Clearing+ /// the handlers first is what makes emptying the vector actually free+ /// anything.+ fn retire(&self) {+ self.ws.set_onmessage(None);+ self.ws.set_onopen(None);+ self.ws.set_onclose(None);+ self.ws.set_onerror(None);+ self._closures.borrow_mut().clear();+ self.closed.set(true);+ // Nothing is listening any more, so a socket still open is a socket+ // the server is holding a session for. 1000 is a normal close.+ let _ = self.ws.close_with_code(1000);+ if let Some(waker) = self.waker.borrow_mut().take() {+ waker.wake();+ }+ }+}+#[derive(Clone)]struct SocketReader(Rc<Socket>);@@ -90,7 +116,10 @@ impl AsyncWrite for SocketReader {use crate::lease::Lease;struct Inner {- socket: Rc<Socket>,+ /// Replaced wholesale by `reconnect`, so the handle every other part of+ /// the page holds survives a dropped connection. Read it into a local+ /// before awaiting: the borrow must not be held across a reconnect.+ socket: RefCell<Rc<Socket>>,serials: RefCell<SerialTable<oneshot::Sender<Pdu>>>,pushes: RefCell<Option<Box<dyn FnMut(Pdu)>>>,/// Pushes that arrived before a handler was installed (the server@@ -98,7 +127,10 @@ struct Inner {/// setting up), replayed in order once one is. The server never/// resends a push, so none may be dropped.pending_pushes: RefCell<Vec<Pdu>>,- on_close: RefCell<Option<Box<dyn FnOnce(String)>>>,+ /// `FnMut`, not `FnOnce`: a link that reconnects can close more than+ /// once, and the second close has to reach the page as well as the+ /// first.+ on_close: RefCell<Option<Box<dyn FnMut(String)>>>,/// The close that happened before a handler was installed.closed_early: RefCell<Option<String>>,pub lease: RefCell<Lease>,@@ -112,6 +144,22 @@ impl WsLink {/// Open the socket with the token in the subprotocol list, and wait for/// the server to accept it.pub async fn connect(url: &str, token: &str) -> Result<Self> {+ let socket = Self::open(url, token).await?;+ let link = Self(Rc::new(Inner {+ socket: RefCell::new(socket),+ serials: RefCell::new(SerialTable::new()),+ pushes: RefCell::new(None),+ pending_pushes: RefCell::new(Vec::new()),+ on_close: RefCell::new(None),+ closed_early: RefCell::new(None),+ lease: RefCell::new(Lease::default()),+ }));+ link.spawn_reader();+ Ok(link)+ }++ /// Open a socket and wait for the server to accept the token.+ async fn open(url: &str, token: &str) -> Result<Rc<Socket>> {let protocols = js_sys::Array::new();protocols.push(&JsValue::from_str(SUBPROTOCOL));protocols.push(&JsValue::from_str(&format!("{TOKEN_PROTOCOL_PREFIX}{token}")));@@ -186,12 +234,18 @@ impl WsLink {}*socket._closures.borrow_mut() = closures;- futures::future::poll_fn(|cx| {+ let opened = futures::future::poll_fn(|cx| {if socket.open.get() {Poll::Ready(Ok(()))} else if socket.closed.get() {+ // Which of the two it was is not knowable from here: a+ // browser is not told why a WebSocket upgrade failed, so a+ // refused token and a server that is not running arrive+ // as the same closed socket. Saying "the token expired"+ // was wrong every time the server was simply down.Poll::Ready(Err(anyhow!(- "the server refused the connection ({}); the token may be wrong or expired",+ "the connection was not accepted ({}); the server may be down, \+ or the link may have expired",socket.close_reason.borrow())))} else {@@ -199,22 +253,50 @@ impl WsLink {Poll::Pending}})- .await?;+ .await;+ // A socket that never made it is still a Socket with four closures+ // pointing back at it: every failed attempt during an outage would+ // otherwise leak one, which is exactly the case `retire` exists for.+ if let Err(err) = opened {+ socket.retire();+ return Err(err);+ }if socket.ws.protocol() != SUBPROTOCOL {+ socket.retire();anyhow::bail!("the server did not select the {SUBPROTOCOL} subprotocol");}- let link = Self(Rc::new(Inner {- socket,- serials: RefCell::new(SerialTable::new()),- pushes: RefCell::new(None),- pending_pushes: RefCell::new(Vec::new()),- on_close: RefCell::new(None),- closed_early: RefCell::new(None),- lease: RefCell::new(Lease::default()),- }));- link.spawn_reader();- Ok(link)+ Ok(socket)+ }++ /// Put a fresh socket under this handle.+ ///+ /// The point of doing it here rather than building a new `WsLink` is+ /// that the session, the host and the app all hold clones of this one:+ /// swapping the socket underneath them is what makes a reconnect+ /// invisible to everything above.+ pub async fn reconnect(&self, url: &str, token: &str) -> Result<()> {+ let socket = Self::open(url, token).await?;+ // Anything still waiting was waiting on the old socket and will+ // never be answered; the new server has never heard of those+ // serials.+ self.0.serials.borrow_mut().drain();+ self.0.closed_early.borrow_mut().take();+ let old = std::mem::replace(&mut *self.0.socket.borrow_mut(), socket);+ old.retire();+ self.spawn_reader();+ Ok(())+ }++ /// Give up on this link: close the socket and stop reading.+ ///+ /// The page calls this when it has decided not to reconnect. Without+ /// it the socket stays open, its reader keeps answering pings, and the+ /// server keeps the registered client and the TCP session for as long+ /// as the tab is open -- a session nobody is watching.+ pub fn shutdown(&self) {+ self.0.serials.borrow_mut().drain();+ self.0.socket.borrow().retire();}pub fn lease(&self) -> std::cell::Ref<'_, Lease> {@@ -235,13 +317,13 @@ impl WsLink {}}- /// Told once, when the socket ends -- at once, if it already has.- pub fn set_close_handler(&self, handler: impl FnOnce(String) + 'static) {+ /// Told whenever the socket ends -- at once, if it already has.+ pub fn set_close_handler(&self, handler: impl FnMut(String) + 'static) {+ let mut handler = Box::new(handler) as Box<dyn FnMut(String)>;if let Some(reason) = self.0.closed_early.borrow_mut().take() {handler(reason);- return;}- *self.0.on_close.borrow_mut() = Some(Box::new(handler));+ *self.0.on_close.borrow_mut() = Some(handler);}fn send(&self, pdu: &Pdu, serial: u64) -> Result<(), LinkError> {@@ -250,35 +332,71 @@ impl WsLink {message: format!("encoding {}: {e:#}", pdu.pdu_name()),retryable: false,})?;- self.0- .socket- .ws- .send_with_u8_array(&bytes)- .map_err(|e| LinkError {- message: format!("sending {}: {e:?}", pdu.pdu_name()),- retryable: false,- })+ let socket = self.0.socket.borrow();+ // `WebSocket.send` throws only while CONNECTING; on a CLOSING or+ // CLOSED socket it quietly buffers and returns. Without this check+ // `request` registers a serial, gets `Ok`, and waits on an answer+ // that can never come -- there is no timeout on this link, so the+ // page hangs where it stood. It is reachable at startup: the socket+ // can die during the WebGPU init that runs between `connect` and+ // the first handshake request.+ if socket.closed.get() || socket.ws.ready_state() != web_sys::WebSocket::OPEN {+ return Err(LinkError {+ message: format!("sending {}: the connection is not open", pdu.pdu_name()),+ retryable: true,+ });+ }+ socket.ws.send_with_u8_array(&bytes).map_err(|e| LinkError {+ message: format!("sending {}: {e:?}", pdu.pdu_name()),+ retryable: false,+ })}fn spawn_reader(&self) {let link = self.clone();wasm_bindgen_futures::spawn_local(async move {- let mut reader = SocketReader(link.0.socket.clone());+ // The socket this reader owns. A later reconnect installs a+ // different one and spawns its own reader; this one ends when+ // its own socket does.+ let socket = link.0.socket.borrow().clone();+ let mut reader = SocketReader(socket.clone());loop {+ // Checked every time round: a reconnect may have replaced+ // this socket while the read was parked, and a retiring+ // reader must not answer pings or hand pushes to the page+ // through the *new* socket. The error arm below repeats the+ // check for the same reason.+ if !Rc::ptr_eq(&socket, &link.0.socket.borrow()) {+ return;+ }let DecodedPdu { serial, pdu } = match Pdu::decode_async(&mut reader, None).await {Ok(d) => d,Err(err) => {let reason = {- let r = link.0.socket.close_reason.borrow().clone();+ let r = socket.close_reason.borrow().clone();if r.is_empty() { format!("{err:#}") } else { r }};- link.0.socket.closed.set(true);+ socket.closed.set(true);+ // A reconnect already replaced this socket: its+ // reader is live and this one is just retiring, so+ // it must not drain the new socket's serials or+ // report a close that has already been handled.+ if !Rc::ptr_eq(&socket, &link.0.socket.borrow()) {+ return;+ }// Every request still waiting fails now; the// senders drop and the receivers see Canceled.link.0.serials.borrow_mut().drain();- let on_close = link.0.on_close.borrow_mut().take();- match on_close {- Some(on_close) => on_close(reason),+ // Taken out before it is called and put back+ // after: the handler reaches straight back into+ // this link to start reconnecting, so the borrow+ // must not be held across it.+ let taken = link.0.on_close.borrow_mut().take();+ match taken {+ Some(mut on_close) => {+ on_close(reason);+ *link.0.on_close.borrow_mut() = Some(on_close);+ }None => *link.0.closed_early.borrow_mut() = Some(reason),}return;@@ -391,7 +509,9 @@ impl PduLink for WsLink {}fn is_reconnectable(&self) -> bool {- false+ // The page reopens the socket on its own, so a request that timed+ // out is a connection that went away, not a pane that died.+ true}fn connection_generation(&self) -> u64 {diff --git a/thinkterm-web/src/page.rs b/thinkterm-web/src/page.rsindex 20543138..41040c6c 100644--- a/thinkterm-web/src/page.rs+++ b/thinkterm-web/src/page.rs@@ -11,6 +11,7 @@ use anyhow::{anyhow, Context, Result};use std::rc::Rc;use std::sync::atomic::AtomicUsize;use std::sync::Arc;+use thinkterm_font_core::FontShaper;use thinkterm_font_web::{Face, FontSet};use thinkterm_render::bitmaps::BitmapImage;use thinkterm_render::pipeline::GpuTexture;@@ -69,10 +70,23 @@ pub async fn start(font_names: Vec<String>,fonts: Vec<js_sys::Uint8Array>,size_pt: f64,+ // `glyph_font` is the CSS font stack the glyph fallback draws with,+ // from `?glyphfont=`; empty means the built-in list.+ glyph_font: String,) -> Result<(), JsValue> {- run(canvas_id, textarea_id, status_id, url, token, font_names, fonts, size_pt)- .await- .map_err(js_err)+ run(+ canvas_id, textarea_id, status_id, url, token, font_names, fonts, size_pt, glyph_font,+ )+ .await+ .map_err(js_err)+}++/// The stack to hand the fallback canvas.+fn families(requested: &str) -> Rc<str> {+ match requested.trim() {+ "" => crate::canvas::DEFAULT_FAMILIES.into(),+ given => given.into(),+ }}#[allow(clippy::too_many_arguments)]@@ -85,6 +99,7 @@ async fn run(font_names: Vec<String>,fonts: Vec<js_sys::Uint8Array>,size_pt: f64,+ glyph_font: String,) -> Result<()> {let canvas: web_sys::HtmlCanvasElement = element(&canvas_id)?;let textarea: web_sys::HtmlTextAreaElement = element(&textarea_id)?;@@ -116,7 +131,38 @@ async fn run(set_status("connecting…");let link = WsLink::connect(&url, &token).await?;+ // From here on a failure must hand the socket back: without this the+ // server keeps a registered client and a TCP session for a page that+ // gave up, and the reader keeps answering its pings.+ let outcome = start_attached(+ &link, &canvas, &textarea, status.clone(), &url, &token, fonts, size_pt, &glyph_font, dpr,+ dpi,+ )+ .await;+ if outcome.is_err() {+ link.shutdown();+ }+ outcome+}+async fn start_attached(+ link: &WsLink,+ canvas: &web_sys::HtmlCanvasElement,+ textarea: &web_sys::HtmlTextAreaElement,+ status: Option<web_sys::Element>,+ url: &str,+ token: &str,+ fonts: Rc<FontSet>,+ size_pt: f64,+ glyph_font: &str,+ dpr: f64,+ dpi: u32,+) -> Result<()> {+ let set_status = |text: &str| {+ if let Some(s) = &status {+ s.set_text_content(Some(text));+ }+ };set_status("starting WebGPU…");let rect = canvas.get_bounding_client_rect();let dev_w = (rect.width() * dpr).floor().max(1.0) as u32;@@ -126,7 +172,7 @@ async fn run(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)?;+ let glyphs = GlyphCache::new(Rc::clone(&fonts), size_pt, dpi, texture, families(glyph_font))?;let (cw, ch) = (glyphs.metrics.cell_size.width as u32,glyphs.metrics.cell_size.height as u32,@@ -191,6 +237,8 @@ async fn run(canvas: canvas.clone(),textarea: textarea.clone(),status,+ url: url.to_string(),+ token: token.to_string(),pane_id: attached.pane_id,tab_id: attached.tab_id,dpr,@@ -207,7 +255,7 @@ async fn run(let app = Rc::clone(&app);link.set_close_handler(move |reason| app.on_close(reason));}- crate::input::install(Rc::clone(&app), &canvas, &textarea);+ crate::input::install(Rc::clone(&app), canvas, textarea);let _ = textarea.focus();app.resize();app.request_frame();@@ -262,3 +310,180 @@ pub async fn color_check(canvas_id: String) -> Result<String, JsValue> {}run(canvas_id).await.map_err(js_err)}++/// Every kind of glyph the fallback has to get right, and whether it should+/// come back carrying its own colour.+///+/// `\u{2713}` and `\u{2714}` sit together on purpose: JetBrains Mono has the+/// first and not the second, so they come from different fonts while looking+/// almost the same. That is the mismatch most likely to be reported.+const SAMPLES: &[(&str, &str, u8, bool)] = &[+ ("latin", "A", 1, false),+ ("braille", "\u{2801}", 1, false),+ ("han", "\u{4e2d}", 2, false),+ ("han-punct", "\u{3002}", 2, false),+ ("han-bracket", "\u{300c}", 2, false),+ ("kana", "\u{3042}", 2, false),+ ("han-shared-1", "\u{76f4}", 2, false),+ ("han-shared-2", "\u{9aa8}", 2, false),+ ("hangul", "\u{d55c}", 2, false),+ ("combining", "e\u{301}", 1, false),+ // rustybuzz clusters this Burmese syllable as one where UAX#29 sees+ // three graphemes -- the case that used to make the vowel signs vanish.+ ("burmese", "\u{1005}\u{102c}\u{1038}", 1, false),+ ("arabic", "\u{628}", 1, false),+ ("hebrew", "\u{5d0}", 1, false),+ ("thai", "\u{e01}", 1, false),+ ("devanagari", "\u{915}", 1, false),+ ("check-present", "\u{2713}", 1, false),+ ("check-missing", "\u{2714}", 1, false),+ ("cross", "\u{2718}", 1, false),+ ("star", "\u{2605}", 1, false),+ ("info", "\u{2139}", 1, false),+ ("arrow", "\u{27a4}", 1, false),+ ("return", "\u{21b5}", 1, false),+ ("circle", "\u{25d0}", 1, false),+ ("gear-text", "\u{2699}\u{fe0e}", 1, false),+ ("gear-emoji", "\u{2699}\u{fe0f}", 2, true),+ ("emoji", "\u{1f600}", 2, true),+ ("emoji-zwj", "\u{1f468}\u{200d}\u{1f4bb}", 2, true),+ ("emoji-flag", "\u{1f3f3}\u{fe0f}\u{200d}\u{1f308}", 2, true),+ ("emoji-heart", "\u{2764}\u{fe0f}", 2, true),+];++/// Draw the sample matrix on a scratch canvas and report what happened, as+/// JSON, with the assertions already evaluated.+///+/// This needs no server, no token, no pane and **no WebGPU**, which makes it+/// the only automatic check that can run on Safari, on Firefox, and on a+/// machine with hardly any fonts installed. It reports the geometry it used+/// as well as the results: an early round of measurements was done at a cell+/// size the product never uses, and nothing in the output said so.+#[wasm_bindgen]+pub fn fallback_check(+ font_names: Vec<String>,+ fonts: Vec<js_sys::Uint8Array>,+ size_pt: f64,+ glyph_font: String,+) -> Result<String, JsValue> {+ fn run(+ font_names: Vec<String>,+ fonts: Vec<js_sys::Uint8Array>,+ size_pt: f64,+ glyph_font: String,+ ) -> Result<String> {+ let mut faces = Vec::new();+ for (name, data) in font_names.iter().zip(fonts.iter()) {+ faces.push(Face::new(name, data.to_vec(), 0).with_context(|| name.clone())?);+ }+ let set = FontSet::new(faces)?;+ let dpr = web_sys::window().map(|w| w.device_pixel_ratio()).unwrap_or(1.0);+ let dpi = (96.0 * dpr) as u32;+ 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 mut rows = Vec::new();+ let (mut drawn, mut wrong_colour, mut clipped, mut blank) = (0, 0, 0, 0);+ for (name, text, cells, expect_color) in SAMPLES {+ let points: Vec<String> =+ text.chars().map(|c| format!("\"U+{:04X}\"", c as u32)).collect();+ // Whether the terminal would actually use the canvas here --+ // asked of the real thing, not of half of it. Production routes+ // a grapheme to the canvas only when the bundled faces cannot+ // draw it AND `keeps_notdef` lets it through; consulting only+ // the second half marked `A` and the check mark U+2713 as+ // routed, so on a machine whose default monospace lacks U+2713+ // the probe failed over a character JetBrains Mono draws and the+ // canvas is never asked for. It also meant the U+2713/U+2714+ // pair -- there precisely because they look alike and come from+ // different fonts -- was measured from the canvas on both sides+ // and could never show the mismatch it exists to show.+ let routed = !set+ .shape_web(+ text,+ size_pt,+ dpi,+ None,+ thinkterm_font_core::Direction::LeftToRight,+ None,+ None,+ &crate::fallback::keeps_notdef,+ )?+ .gaps+ .is_empty();+ let row = match scratch.measure(text, *cells)? {+ None => {+ if routed {+ blank += 1;+ }+ format!(+ "{{\"name\":\"{name}\",\"cp\":[{}],\"routed\":{routed},\+ \"ink\":null,\"ok\":{}}}",+ points.join(","),+ !routed+ )+ }+ Some((ink, placement, has_color)) => {+ drawn += 1;+ let mut ok = true;+ if routed {+ if has_color != *expect_color {+ wrong_colour += 1;+ ok = false;+ }+ if ink.clipped {+ clipped += 1;+ ok = false;+ }+ }+ format!(+ "{{\"name\":\"{name}\",\"cp\":[{}],\"routed\":{routed},\+ \"ink\":{{\"left\":{},\"top\":{},\"width\":{},\"height\":{}}},\+ \"clipped\":{},\"has_color\":{},\"expect_color\":{},\+ \"bearing_x\":{:.2},\"bearing_y\":{:.2},\"scale\":{:.3},\"ok\":{ok}}}",+ points.join(","),+ ink.left,+ ink.top,+ ink.width,+ ink.height,+ ink.clipped,+ has_color,+ expect_color,+ placement.bearing_x,+ placement.bearing_y,+ placement.scale,+ )+ }+ };+ rows.push(row);+ }+ // The counts are the assertions. The first round of measurements had+ // a silent bug in exactly this place -- both branches produced+ // plausible numbers, and only printing "how many were judged+ // coloured" exposed it -- so they are printed whether or not anyone+ // is looking at them.+ let ok = blank == 0 && wrong_colour == 0 && clipped == 0;+ Ok(format!(+ "{{\"ok\":{ok},\"drawn\":{drawn},\"blank\":{blank},\"wrong_colour\":{wrong_colour},\+ \"clipped\":{clipped},\"samples\":{},\+ \"cell\":[{},{}],\"descender\":{:.2},\"px\":{:.2},\"dpr\":{dpr},\+ \"canvas\":[{canvas_w},{canvas_h}],\"pen_x\":{pen_x:.2},\"baseline\":{baseline:.2},\+ \"families\":\"{}\",\"results\":[{}]}}",+ SAMPLES.len(),+ metrics.cell_size.width,+ metrics.cell_size.height,+ metrics.descender.get(),+ px,+ // The stack comes from the query string, so it is data: a+ // stray quote or backslash would produce JSON the harness+ // cannot parse, and the harness is the point of this.+ stack.replace(['"', '\\'], "'"),+ rows.join(",")+ ))+ }+ run(font_names, fonts, size_pt, glyph_font).map_err(js_err)+}diff --git a/thinkterm-web/www/app.js b/thinkterm-web/www/app.jsindex 027bdda6..278c6e41 100644--- a/thinkterm-web/www/app.js+++ b/thinkterm-web/www/app.js@@ -1,5 +1,5 @@// The page: pick up the token, fetch the fonts, start the wasm client.-import init, { start, color_check } from "./pkg/thinkterm_web.js";+import init, { start, color_check, fallback_check, graphics_check } from "./pkg/thinkterm_web.js";const status = document.getElementById("status");const fail = (msg) => { status.textContent = msg; status.classList.add("error"); console.error(msg); };@@ -12,10 +12,17 @@ const fragment = new URLSearchParams(location.hash.replace(/^#/, ""));// A browser that blocks storage throws on the first touch; the token then// lives only in this page load, and the failure is reported, not silent.let token = fragment.get("token");+if (token) {+ // Out of the address bar first, and outside the try: a browser that+ // blocks storage throws on setItem, and doing this after it meant the+ // token stayed in the URL -- visible in the bar, in a screenshot, and in+ // whatever the user pastes next -- in exactly the case the comment said+ // it would not.+ history.replaceState(null, "", location.pathname + location.search);+}try {if (token) {sessionStorage.setItem("thinkterm.token", token);- history.replaceState(null, "", location.pathname + location.search);} else {token = sessionStorage.getItem("thinkterm.token");}@@ -24,6 +31,9 @@ try {}const requested = Number(params.get("font"));const fontSize = Number.isFinite(requested) && requested >= 6 && requested <= 72 ? requested : 12;+// The CSS font stack the glyph fallback draws with. This is also how the+// regional shape of a Han character is chosen; see canvas.rs.+const glyphFont = params.get("glyphfont") || "";const FONTS = [["JetBrains Mono", "./fonts/JetBrainsMono-Regular.ttf"],@@ -38,17 +48,29 @@ async function fetchFont(url) {try {await init();- if (!navigator.gpu) {+ const check = params.get("check");+ if (check === "fallback") {+ // Deliberately before the WebGPU check: this one draws on a 2D canvas+ // and needs no GPU, no token and no pane, which is what lets it run on+ // Safari, on Firefox, and on a machine with hardly any fonts installed+ // -- the place the glyph fallback is most likely to fail.+ const names = FONTS.map(([n]) => n);+ const data = await Promise.all(FONTS.map(([, u]) => fetchFont(u)));+ status.textContent = "FALLBACK " + fallback_check(names, data, fontSize, glyphFont);+ } else if (!navigator.gpu) {throw new Error("WebGPU is not available: open the page over https or http://localhost in a browser with WebGPU enabled");- }- if (params.get("check") === "color") {+ } else if (check === "color") {status.textContent = "COLOR " + await color_check("term");+ } else if (check === "graphics") {+ const names = FONTS.map(([n]) => n);+ const data = await Promise.all(FONTS.map(([, u]) => fetchFont(u)));+ status.textContent = "GRAPHICS " + await graphics_check(names, data, fontSize);} else {if (!token) throw new Error("no token: open the URL that `thinkterm cli web-token mint` printed");const names = FONTS.map(([n]) => n);const data = await Promise.all(FONTS.map(([, u]) => fetchFont(u)));const scheme = location.protocol === "https:" ? "wss" : "ws";- await start("term", "kbd", "status", `${scheme}://${location.host}/ws`, token, names, data, fontSize);+ await start("term", "kbd", "status", `${scheme}://${location.host}/ws`, token, names, data, fontSize, glyphFont);}} catch (e) {fail(String(e && e.message ? e.message : e));diff --git a/thinkterm-web/www/index.html b/thinkterm-web/www/index.htmlindex cb7c67ab..32a45b6e 100644--- a/thinkterm-web/www/index.html+++ b/thinkterm-web/www/index.html@@ -11,12 +11,12 @@#status.error { color: #f66; }/* Focus lives here so the IME composes into a real text field; thefield itself stays out of sight. */- #kbd { position: absolute; left: 0; top: 0; width: 1px; height: 1px; opacity: 0; border: 0; padding: 0; resize: none; overflow: hidden; }+ #kbd { position: fixed; left: 0; top: 0; width: 1px; height: 1px; opacity: 0; border: 0; padding: 0; margin: 0; resize: none; overflow: hidden; pointer-events: none; }</style></head><body><canvas id="term"></canvas>-<textarea id="kbd" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea>+<textarea id="kbd" wrap="off" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea><div id="status">loading…</div><script type="module" src="./app.js"></script></body>