Skip to content

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.

thinkterm-web: a browser client on WebGPU and wasm

RoversXb9a29b863042
diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml
index 27bfc685..e92a4fef 100644
--- a/.github/workflows/wasm.yml
+++ b/.github/workflows/wasm.yml
@@ -46,7 +46,9 @@ jobs:
- name: Check the portable core for wasm32
run: |
cargo check -p thinkterm-proto -p codec -p thinkterm-session \
- -p wezterm-term -p termwiz --target wasm32-unknown-unknown
+ -p thinkterm-render -p thinkterm-font-core -p thinkterm-font-web \
+ -p thinkterm-web -p wezterm-term -p termwiz \
+ --target wasm32-unknown-unknown
- name: Run the terminal core in a wasm VM
run: |
cargo build -p wasm-probe --target wasm32-unknown-unknown --release
diff --git a/.gitignore b/.gitignore
index 8f7623af..a2a3bcc5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -97,3 +97,7 @@ __pycache__/
# well...
/.claude
+
+# Built browser bundle (ci/build-web.sh)
+/thinkterm-web/www/pkg/
+/thinkterm-web/www/fonts/
diff --git a/Cargo.lock b/Cargo.lock
index 7643d8d4..02c43eb4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1000,6 +1000,16 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "console_error_panic_hook"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
+dependencies = [
+ "cfg-if",
+ "wasm-bindgen",
+]
+
[[package]]
name = "convert_case"
version = "0.10.0"
@@ -6690,6 +6700,32 @@ dependencies = [
"tempfile",
]
+[[package]]
+name = "thinkterm-web"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytemuck",
+ "codec",
+ "console_error_panic_hook",
+ "euclid",
+ "futures",
+ "js-sys",
+ "log",
+ "termwiz 0.24.0",
+ "thinkterm-font-core",
+ "thinkterm-font-web",
+ "thinkterm-proto",
+ "thinkterm-render",
+ "thinkterm-session",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "wezterm-color-types 0.3.0",
+ "wezterm-term",
+ "wgpu",
+]
+
[[package]]
name = "thiserror"
version = "1.0.69"
diff --git a/Cargo.toml b/Cargo.toml
index 667eb8d3..533f4ea4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,6 +12,7 @@ members = [
"thinkterm-proto",
"thinkterm-render",
"thinkterm-session",
+ "thinkterm-web",
"thinkterm-tui",
"thinkterm-update",
"deps/cairo",
@@ -85,6 +86,7 @@ thinkterm-font-web = { path = "thinkterm-font-web" }
thinkterm-proto = { path = "thinkterm-proto" }
thinkterm-render = { path = "thinkterm-render" }
thinkterm-session = { path = "thinkterm-session" }
+thinkterm-web = { path = "thinkterm-web" }
thinkterm-update = { path = "thinkterm-update" }
core-foundation = "=0.10.0"
core-graphics = "=0.24.0"
@@ -298,6 +300,13 @@ wezterm-toast-notification = { path = "wezterm-toast-notification" }
wezterm-uds = { path = "wezterm-uds" }
wezterm-version = { path = "wezterm-version" }
wgpu = "25.0.2"
+# The browser client. wasm-bindgen is pinned exactly: the CLI that emits
+# the JavaScript glue must match the crate the wasm was built with.
+wasm-bindgen = "=0.2.105"
+wasm-bindgen-futures = "0.4"
+js-sys = "0.3"
+web-sys = "0.3"
+console_error_panic_hook = "0.1"
whoami = "1.5"
winapi = "0.3.9"
window = {path="window"}
diff --git a/ci/build-web.sh b/ci/build-web.sh
new file mode 100755
index 00000000..b244fe16
--- /dev/null
+++ b/ci/build-web.sh
@@ -0,0 +1,34 @@
+#!/bin/sh
+# Build the browser client bundle into thinkterm-web/www:
+# pkg/ the wasm and its wasm-bindgen JavaScript glue
+# fonts/ the faces the page loads
+# Usage: ci/build-web.sh [--debug]
+# Needs the wasm32-unknown-unknown target and the wasm-bindgen CLI at the
+# version the workspace pins (see Cargo.toml). wasm-opt is used if present.
+set -eu
+cd "$(dirname "$0")/.."
+
+PROFILE=release
+CARGO_FLAGS=--release
+if [ "${1:-}" = "--debug" ]; then PROFILE=debug; CARGO_FLAGS=; fi
+
+WANT=$(grep -E '^wasm-bindgen = "=' Cargo.toml | sed -E 's/.*"=([0-9.]+)".*/\1/')
+HAVE=$(wasm-bindgen --version 2>/dev/null | awk '{print $2}')
+if [ "$WANT" != "$HAVE" ]; then
+ echo "wasm-bindgen CLI $HAVE does not match the pinned crate $WANT; run: cargo install wasm-bindgen-cli --version $WANT" >&2
+ exit 1
+fi
+
+TARGET_DIR=${CARGO_TARGET_DIR:-target}
+cargo build -p thinkterm-web --target wasm32-unknown-unknown $CARGO_FLAGS
+WASM="$TARGET_DIR/wasm32-unknown-unknown/$PROFILE/thinkterm_web.wasm"
+OUT=thinkterm-web/www
+rm -rf "$OUT/pkg"
+wasm-bindgen --target web --out-dir "$OUT/pkg" --no-typescript "$WASM"
+if command -v wasm-opt >/dev/null 2>&1 && [ "$PROFILE" = release ]; then
+ wasm-opt -Oz -o "$OUT/pkg/thinkterm_web_bg.wasm" "$OUT/pkg/thinkterm_web_bg.wasm"
+fi
+mkdir -p "$OUT/fonts"
+cp assets/fonts/JetBrainsMono-Regular.ttf assets/fonts/SymbolsNerdFontMono-Regular.ttf "$OUT/fonts/"
+ls -la "$OUT/pkg"
+echo "bundle at $OUT; serve it with web_servers.static_dir = \"$(pwd)/$OUT\" or THINKTERM_WEB_STATIC_DIR"
diff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rs
index ac4a1d9a..731875f4 100644
--- a/thinkterm-session/src/pane.rs
+++ b/thinkterm-session/src/pane.rs
@@ -488,12 +488,22 @@ impl<H: SessionHost> PaneSession<H> {
/// healthy but consistently slow request eventually gets a window long
/// enough to complete instead of losing forever to a fixed watchdog.
pub fn render_looks_stalled(self: &Arc<Self>, viewport_top: Option<StableRowIndex>) -> bool {
+ let st = self.state();
+ let top = viewport_top.unwrap_or(st.dimensions.physical_top);
+ let range = top..top.saturating_add(st.dimensions.viewport_rows as StableRowIndex);
+ drop(st);
+ self.render_looks_stalled_in(range)
+ }
+
+ /// The same check over exactly the rows a client shows. A client whose
+ /// view is shorter than the pane's screen must not ask about rows past
+ /// its bottom: those may not exist, and a row that does not exist
+ /// reads as "repaint" forever.
+ pub fn render_looks_stalled_in(self: &Arc<Self>, range: Range<StableRowIndex>) -> bool {
let mut st = self.state();
if !crate::decide::render_watchdog_should_run(st.dead) {
return false;
}
- let top = viewport_top.unwrap_or(st.dimensions.physical_top);
- let range = top..top.saturating_add(st.dimensions.viewport_rows as StableRowIndex);
let decision = line_watchdog_decision(&mut st.lines, range, self.now());
if decision.repaint {
st.poll_interval = BASE_POLL_INTERVAL;
diff --git a/thinkterm-web/Cargo.toml b/thinkterm-web/Cargo.toml
new file mode 100644
index 00000000..70c63b24
--- /dev/null
+++ b/thinkterm-web/Cargo.toml
@@ -0,0 +1,47 @@
+[package]
+name = "thinkterm-web"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+# The browser client: thinkterm-session's PaneSession over a WebSocket,
+# drawn through thinkterm-render's shader and quads on a WebGPU canvas,
+# with thinkterm-font-web for glyphs. Standards only -- WebGPU, WebSocket,
+# wasm -- so it runs in Safari, Chrome and Firefox alike. The page-facing
+# code is wasm32-only; the pure logic (key mapping, viewport arithmetic)
+# builds and tests natively.
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+
+[dependencies]
+anyhow.workspace = true
+bytemuck.workspace = true
+codec.workspace = true
+euclid.workspace = true
+futures.workspace = true
+log.workspace = true
+termwiz = { workspace = true, features = ["use_serde"] }
+thinkterm-font-core.workspace = true
+thinkterm-font-web.workspace = true
+thinkterm-proto.workspace = true
+thinkterm-render = { workspace = true, features = ["wgpu"] }
+thinkterm-session.workspace = true
+wezterm-color-types.workspace = true
+wezterm-term = { workspace = true, features = ["use_serde"] }
+wgpu.workspace = true
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+console_error_panic_hook.workspace = true
+js-sys.workspace = true
+wasm-bindgen.workspace = true
+wasm-bindgen-futures.workspace = true
+web-sys = { workspace = true, features = [
+ "BinaryType", "Clipboard", "ClipboardEvent", "CloseEvent", "CompositionEvent",
+ "console", "CssStyleDeclaration", "DataTransfer", "Document", "DomRect",
+ "DomRectReadOnly", "Element", "Event", "EventTarget", "FocusEvent", "History",
+ "HtmlCanvasElement", "HtmlElement", "HtmlTextAreaElement", "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.js
new file mode 100644
index 00000000..f846cd44
--- /dev/null
+++ b/thinkterm-web/smoke/cdp.js
@@ -0,0 +1,91 @@
+// Drive headless Chrome over the DevTools protocol for the browser smoke
+// (not part of the served bundle):
+// load a page, wait for its status line to match, optionally type into the
+// terminal through the real keydown path, screenshot, print the console.
+//
+// node cdp.js <url> <out.png> [--wait-status <regex>] [--type <text>] [--timeout <ms>]
+//
+// Needs the `ws` npm package on NODE_PATH and Google Chrome installed.
+const { spawn } = require("child_process");
+const http = require("http");
+const fs = require("fs");
+const WebSocket = require("ws");
+
+const args = process.argv.slice(2);
+const url = args.shift();
+const outPng = args.shift();
+const opt = (name, def) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : def; };
+const waitStatus = opt("--wait-status", null);
+const typeText = opt("--type", null);
+const timeoutMs = Number(opt("--timeout", 15000));
+const chromePath = process.env.CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
+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();
+
+const chrome = spawn(chromePath, [
+ "--headless=new", "--no-first-run", `--remote-debugging-port=${port}`,
+ "--window-size=1240,720", "--hide-scrollbars", "--enable-unsafe-webgpu", "about:blank",
+], { stdio: "ignore" });
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const trace = (m) => { if (process.env.CDP_TRACE) console.error("cdp: " + m); };
+
+async function browserWs() {
+ for (let i = 0; i < 50; i++) {
+ try {
+ return await new Promise((res, rej) => http.get(`http://127.0.0.1:${port}/json/version`, (r) => {
+ let b = ""; r.on("data", (d) => b += d); r.on("end", () => res(JSON.parse(b).webSocketDebuggerUrl));
+ }).on("error", rej));
+ } catch { await sleep(200); }
+ }
+ throw new Error("chrome did not come up");
+}
+
+(async () => {
+ const ws = new WebSocket(await browserWs());
+ await new Promise((r) => ws.on("open", r));
+ trace("browser websocket open");
+ let id = 0; const waiting = new Map(); const logs = [];
+ ws.on("message", (m) => {
+ const msg = JSON.parse(m);
+ if (msg.id && waiting.has(msg.id)) { waiting.get(msg.id)(msg.result || msg.error); waiting.delete(msg.id); }
+ if (msg.method === "Runtime.consoleAPICalled") logs.push(msg.params.args.map((a) => a.value ?? a.description).join(" "));
+ if (msg.method === "Runtime.exceptionThrown") logs.push("EXCEPTION " + JSON.stringify(msg.params.exceptionDetails.exception?.description || msg.params.exceptionDetails.text));
+ });
+ const send = (method, params = {}, sessionId) => new Promise((r) => { const i = ++id; trace(`-> ${method}`); waiting.set(i, (v) => { trace(`<- ${method}`); r(v); }); ws.send(JSON.stringify({ id: i, method, params, sessionId })); });
+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });
+ const session = (await send("Target.attachToTarget", { targetId, flatten: true })).sessionId;
+ await send("Runtime.enable", {}, session);
+ await send("Page.enable", {}, session);
+ await send("Page.navigate", { url }, session);
+
+ const status = async () => (await send("Runtime.evaluate", { expression: "document.getElementById('status')?.textContent || ''", returnByValue: true }, session)).result?.value || "";
+ const deadline = Date.now() + timeoutMs;
+ let text = "";
+ const re = waitStatus ? new RegExp(waitStatus) : null;
+ 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;
+ await sleep(250);
+ }
+ console.log("STATUS " + text);
+
+ if (typeText) {
+ const expr = `(() => {
+ const kbd = document.getElementById('kbd'); kbd.focus();
+ const fire = (key, code) => kbd.dispatchEvent(new KeyboardEvent('keydown', { key, code, bubbles: true, cancelable: true }));
+ for (const ch of ${JSON.stringify(typeText)}) fire(ch, ch === ' ' ? 'Space' : 'Key' + ch.toUpperCase());
+ fire('Enter', 'Enter');
+ return 'typed';
+ })()`;
+ logs.push("harness: " + JSON.stringify((await send("Runtime.evaluate", { expression: expr, returnByValue: true }, session)).result?.value));
+ await sleep(2000);
+ console.log("STATUS " + await status());
+ }
+ const shot = await send("Page.captureScreenshot", { format: "png" }, session);
+ 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);
+})().catch((e) => { console.error(e); chrome.kill(); process.exit(1); });
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
new file mode 100644
index 00000000..af7c6534
--- /dev/null
+++ b/thinkterm-web/src/app.rs
@@ -0,0 +1,793 @@
+//! 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::glyphs::GlyphCache;
+use crate::gpu::Gpu;
+use crate::host::WebHost;
+use crate::link::WsLink;
+use crate::viewport::{cell_at, max_scroll, visible_rows};
+use anyhow::Result;
+use codec::Pdu;
+use std::cell::{Cell, RefCell};
+use std::rc::Rc;
+use std::sync::Arc;
+use termwiz::input::{KeyCode, Modifiers};
+use thinkterm_font_web::FontSet;
+use thinkterm_proto::{PaneId, TabId};
+use thinkterm_render::atlas::OutOfTextureSpace;
+use thinkterm_render::pipeline::GpuTexture;
+use thinkterm_render::quad::HeapQuadAllocator;
+use thinkterm_render::vertex::Vertex;
+use thinkterm_session::pane::PaneSession;
+use wasm_bindgen::prelude::*;
+use wasm_bindgen::JsCast;
+use wezterm_term::color::ColorPalette;
+use wezterm_term::input::{MouseButton, MouseEvent, MouseEventKind};
+use wezterm_term::{KeyModifiers, StableRowIndex, TerminalSize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Pointer {
+ Down,
+ Move,
+ Up,
+}
+
+#[derive(Debug, Clone, Copy)]
+struct Selection {
+ anchor: (StableRowIndex, usize),
+ head: (StableRowIndex, usize),
+ /// 1 = cells, 2 = words, 3 = lines.
+ mode: u8,
+}
+
+impl Selection {
+ fn ordered(&self) -> ((StableRowIndex, usize), (StableRowIndex, usize)) {
+ if self.anchor <= self.head {
+ (self.anchor, self.head)
+ } else {
+ (self.head, self.anchor)
+ }
+ }
+}
+
+/// Everything the page hands the app once it is attached.
+pub struct Setup {
+ pub link: WsLink,
+ pub session: Arc<PaneSession<WebHost>>,
+ pub host: Arc<WebHost>,
+ pub gpu: Gpu,
+ pub glyphs: GlyphCache,
+ pub fonts: Rc<FontSet>,
+ pub canvas: web_sys::HtmlCanvasElement,
+ pub textarea: web_sys::HtmlTextAreaElement,
+ pub status: Option<web_sys::Element>,
+ pub pane_id: PaneId,
+ pub tab_id: TabId,
+ pub dpr: f64,
+ pub cols: usize,
+ pub rows: usize,
+ pub title: String,
+}
+
+pub struct Inner {
+ link: WsLink,
+ session: Arc<PaneSession<WebHost>>,
+ host: Arc<WebHost>,
+ gpu: Gpu,
+ glyphs: GlyphCache,
+ fonts: Rc<FontSet>,
+ canvas: web_sys::HtmlCanvasElement,
+ textarea: web_sys::HtmlTextAreaElement,
+ status: Option<web_sys::Element>,
+ palette: ColorPalette,
+ pane_id: PaneId,
+ tab_id: TabId,
+ dpr: f64,
+ cols: usize,
+ rows: usize,
+ scroll_from_bottom: usize,
+ selection: Option<Selection>,
+ /// Word/line selection extends by units; the pointer is down.
+ selecting: bool,
+ click_count: u8,
+ last_click_ms: f64,
+ focused: bool,
+ composing: bool,
+ disconnected: Option<String>,
+ quads: HeapQuadAllocator,
+ vertices: Vec<Vertex>,
+ title: String,
+}
+
+pub struct App {
+ inner: RefCell<Inner>,
+ frame_requested: Cell<bool>,
+ raf: RefCell<Option<Closure<dyn FnMut()>>>,
+}
+
+fn now_ms() -> f64 {
+ js_sys::Date::now()
+}
+
+impl App {
+ pub fn new(setup: Setup) -> Rc<Self> {
+ let inner = Inner {
+ link: setup.link,
+ session: setup.session,
+ host: setup.host,
+ gpu: setup.gpu,
+ glyphs: setup.glyphs,
+ fonts: setup.fonts,
+ canvas: setup.canvas,
+ textarea: setup.textarea,
+ status: setup.status,
+ palette: ColorPalette::default(),
+ pane_id: setup.pane_id,
+ tab_id: setup.tab_id,
+ dpr: setup.dpr,
+ cols: setup.cols,
+ rows: setup.rows,
+ scroll_from_bottom: 0,
+ selection: None,
+ selecting: false,
+ click_count: 0,
+ last_click_ms: 0.0,
+ focused: true,
+ composing: false,
+ disconnected: None,
+ quads: HeapQuadAllocator::default(),
+ vertices: Vec::new(),
+ title: setup.title,
+ };
+ let app = Rc::new(Self {
+ inner: RefCell::new(inner),
+ frame_requested: Cell::new(false),
+ raf: RefCell::new(None),
+ });
+ let weak = Rc::downgrade(&app);
+ *app.raf.borrow_mut() = Some(Closure::<dyn FnMut()>::new(move || {
+ if let Some(app) = weak.upgrade() {
+ app.frame_requested.set(false);
+ app.frame();
+ }
+ }));
+ app
+ }
+
+ pub fn wake(self: &Rc<Self>) -> Rc<dyn Fn()> {
+ let weak = Rc::downgrade(self);
+ Rc::new(move || {
+ if let Some(app) = weak.upgrade() {
+ app.request_frame();
+ }
+ })
+ }
+
+ pub fn request_frame(&self) {
+ if self.frame_requested.get() {
+ return;
+ }
+ let raf = self.raf.borrow();
+ if let (Some(window), Some(closure)) = (web_sys::window(), raf.as_ref()) {
+ if window
+ .request_animation_frame(closure.as_ref().unchecked_ref())
+ .is_ok()
+ {
+ self.frame_requested.set(true);
+ }
+ }
+ }
+
+ fn set_status(inner: &Inner, text: &str) {
+ if let Some(el) = &inner.status {
+ el.set_text_content(Some(text));
+ }
+ }
+
+ /// The server pushed something for us.
+ pub fn on_push(&self, pdu: Pdu) {
+ let inner = self.inner.borrow();
+ match pdu {
+ Pdu::GetPaneRenderChangesResponse(delta) if delta.pane_id == inner.pane_id => {
+ inner.session.queue_render_delta(delta);
+ }
+ Pdu::PaneRemoved(removed) if removed.pane_id == inner.pane_id => {
+ inner.session.set_dead(true);
+ Self::set_status(&inner, "the pane was closed on the server");
+ }
+ // Sent once per connection, before the first line change: a
+ // program's OSC 4/10/11 colours. Dropping it would leave the
+ // page on the stock palette for good.
+ Pdu::SetApplicationPalette(codec::SetApplicationPalette { pane_id, palette })
+ if pane_id == inner.pane_id =>
+ {
+ drop(inner);
+ let mut inner = self.inner.borrow_mut();
+ let palette = palette.unwrap_or_default();
+ if palette != inner.palette {
+ inner.palette = palette;
+ inner.session.make_all_stale();
+ drop(inner);
+ self.request_frame();
+ }
+ }
+ Pdu::ClientViewportState(_) | Pdu::FrontendAccessState(_) => {
+ drop(inner);
+ self.refresh_status();
+ self.request_frame();
+ }
+ Pdu::SetClipboard(clip) => {
+ if let Some(text) = clip.clipboard {
+ write_clipboard(&text);
+ }
+ }
+ _ => {}
+ }
+ }
+
+ 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."));
+ }
+
+ fn refresh_status(&self) {
+ let inner = self.inner.borrow();
+ if inner.disconnected.is_some() {
+ return;
+ }
+ let owner = inner.link.lease().owns_viewport();
+ let text = if owner {
+ format!("{} · {}x{} · this browser has the terminal", inner.title, inner.cols, inner.rows)
+ } else {
+ format!(
+ "{} · {}x{} · following another device (type or click to take over)",
+ inner.title, inner.cols, inner.rows
+ )
+ };
+ Self::set_status(&inner, &text);
+ }
+
+ fn spawn_drain(inner: &Inner, start: Result<bool, thinkterm_session::input::InputQueueFull>) {
+ match start {
+ Ok(true) => {
+ let session = Arc::clone(&inner.session);
+ wasm_bindgen_futures::spawn_local(session.drain_inputs());
+ inner.session.update_last_send();
+ }
+ Ok(false) => inner.session.update_last_send(),
+ Err(full) => log::warn!("input refused: {full}"),
+ }
+ }
+
+ /// Returns true when the key was consumed (the browser must not act
+ /// on it). `shift` is the key's real Shift state: for printable keys
+ /// it is folded into the character and absent from `mods`, and the
+ /// character's case cannot stand in for it (Caps Lock).
+ pub fn key_down(&self, key: KeyCode, mods: Modifiers, shift: bool) -> bool {
+ let mut inner = self.inner.borrow_mut();
+ if inner.composing || inner.disconnected.is_some() {
+ return false;
+ }
+ // Copy and paste chords belong to the page: Cmd+C/V on a Mac,
+ // Ctrl+Shift+C/V elsewhere. Copy what is selected; let the paste
+ // event carry the clipboard. Every other Cmd chord is the
+ // browser's (reload, address bar, tabs), not the pane's.
+ let cmd = mods == Modifiers::SUPER;
+ let ctrl_shift = mods == Modifiers::CTRL && shift;
+ match key {
+ KeyCode::Char('c') | KeyCode::Char('C') if cmd || ctrl_shift => {
+ if let Some(text) = Self::selection_text(&inner) {
+ write_clipboard(&text);
+ }
+ return true;
+ }
+ KeyCode::Char('v') | KeyCode::Char('V') if cmd || ctrl_shift => return false,
+ _ if mods.contains(Modifiers::SUPER) => return false,
+ _ => {}
+ }
+ // Typing goes back to following the output.
+ inner.scroll_from_bottom = 0;
+ inner.selection = None;
+ let serial = codec::InputSerial::from_millis(
+ thinkterm_session::clock::Clock::wall_millis(&inner.host.clock),
+ );
+ let mods = KeyModifiers::from_bits_truncate(mods.bits());
+ let start = inner.session.key_down(serial, key, mods);
+ Self::spawn_drain(&inner, start);
+ drop(inner);
+ self.request_frame();
+ true
+ }
+
+ pub fn composing(&self, composing: bool) {
+ self.inner.borrow_mut().composing = composing;
+ }
+
+ /// Text the IME composed: bytes, not a paste, so no bracketing.
+ pub fn text(&self, text: &str) {
+ let mut inner = self.inner.borrow_mut();
+ if inner.disconnected.is_some() {
+ return;
+ }
+ inner.scroll_from_bottom = 0;
+ let start = inner.session.write_bytes(text.as_bytes());
+ Self::spawn_drain(&inner, start);
+ drop(inner);
+ self.request_frame();
+ }
+
+ pub fn paste(&self, text: &str) {
+ let mut inner = self.inner.borrow_mut();
+ if inner.disconnected.is_some() {
+ return;
+ }
+ inner.scroll_from_bottom = 0;
+ let start = inner.session.paste(text);
+ Self::spawn_drain(&inner, start);
+ drop(inner);
+ self.request_frame();
+ }
+
+ fn cell_under(inner: &Inner, ev: &web_sys::PointerEvent) -> (usize, usize, isize, isize) {
+ let rect = inner.canvas.get_bounding_client_rect();
+ let px = (ev.client_x() as f64 - rect.left()) * inner.dpr;
+ let py = (ev.client_y() as f64 - rect.top()) * inner.dpr;
+ let (cw, ch) = (
+ inner.glyphs.metrics.cell_size.width as f64,
+ inner.glyphs.metrics.cell_size.height as f64,
+ );
+ let (col, row) = cell_at(px, py, cw, ch);
+ let x_off = (px - col as f64 * cw) as isize;
+ let y_off = (py - row as f64 * ch) as isize;
+ (col, row, x_off, y_off)
+ }
+
+ fn mouse_modifiers(ev: &web_sys::MouseEvent) -> KeyModifiers {
+ let mut m = KeyModifiers::NONE;
+ if ev.shift_key() {
+ m |= KeyModifiers::SHIFT;
+ }
+ if ev.ctrl_key() {
+ m |= KeyModifiers::CTRL;
+ }
+ if ev.alt_key() {
+ m |= KeyModifiers::ALT;
+ }
+ if ev.meta_key() {
+ m |= KeyModifiers::SUPER;
+ }
+ m
+ }
+
+ pub fn pointer(&self, ev: &web_sys::PointerEvent, what: Pointer) {
+ if what == Pointer::Down {
+ // Focus first, outside any borrow: focus() dispatches events
+ // synchronously and a listener may look at the app.
+ let textarea = self.inner.borrow().textarea.clone();
+ let _ = textarea.focus();
+ let canvas = self.inner.borrow().canvas.clone();
+ let _ = canvas.set_pointer_capture(ev.pointer_id());
+ }
+ let mut inner = self.inner.borrow_mut();
+ if inner.disconnected.is_some() {
+ return;
+ }
+ let (col, row, x_off, y_off) = Self::cell_under(&inner, ev);
+ let dims = inner.session.dimensions();
+ let visible = visible_rows(&dims, inner.rows, inner.scroll_from_bottom);
+ let stable_row = visible.start + row as StableRowIndex;
+ let button = match ev.button() {
+ 0 => MouseButton::Left,
+ 1 => MouseButton::Middle,
+ 2 => MouseButton::Right,
+ _ => MouseButton::None,
+ };
+
+ // A program that asked for the mouse gets it, unless Shift holds
+ // the event back for the page's own selection.
+ if inner.session.is_mouse_grabbed() && !ev.shift_key() {
+ let kind = match what {
+ Pointer::Down => MouseEventKind::Press,
+ Pointer::Up => MouseEventKind::Release,
+ Pointer::Move => MouseEventKind::Move,
+ };
+ // A follower taller than the pane shows rows above its top;
+ // those are nowhere for a program, as on the desktop.
+ let event = MouseEvent {
+ kind,
+ x: col,
+ y: (stable_row - dims.physical_top).max(0) as i64,
+ x_pixel_offset: x_off,
+ y_pixel_offset: y_off,
+ button: if what == Pointer::Move && ev.buttons() == 0 { MouseButton::None } else { button },
+ modifiers: Self::mouse_modifiers(ev),
+ };
+ let start = inner.session.mouse_event(event);
+ Self::spawn_drain(&inner, start);
+ return;
+ }
+
+ match what {
+ Pointer::Down if button == MouseButton::Left => {
+ let t = now_ms();
+ inner.click_count = if t - inner.last_click_ms < 400.0 {
+ (inner.click_count % 3) + 1
+ } else {
+ 1
+ };
+ inner.last_click_ms = t;
+ let mode = inner.click_count;
+ inner.selection = Some(Selection {
+ anchor: (stable_row, col),
+ head: (stable_row, col),
+ mode,
+ });
+ inner.selecting = true;
+ // A click is a real interaction: it takes the terminal over.
+ let link = inner.link.clone();
+ let tab_id = inner.tab_id;
+ wasm_bindgen_futures::spawn_local(async move {
+ let _ = link.ensure_owner(tab_id).await;
+ });
+ }
+ Pointer::Move if inner.selecting => {
+ if let Some(sel) = &mut inner.selection {
+ sel.head = (stable_row, col);
+ }
+ }
+ Pointer::Up if inner.selecting => {
+ inner.selecting = false;
+ if let Some(sel) = &mut inner.selection {
+ sel.head = (stable_row, col);
+ }
+ let empty = inner
+ .selection
+ .map(|s| s.mode == 1 && s.anchor == s.head)
+ .unwrap_or(true);
+ if empty {
+ inner.selection = None;
+ } else if let Some(text) = Self::selection_text(&inner) {
+ write_clipboard(&text);
+ }
+ }
+ _ => return,
+ }
+ drop(inner);
+ self.request_frame();
+ }
+
+ /// The selected cells of `row`, from the selection's shape and mode.
+ fn selection_on_row(inner: &Inner, sel: &Selection, row: StableRowIndex, line: &termwiz::surface::Line) -> std::ops::Range<usize> {
+ let ((r0, c0), (r1, c1)) = sel.ordered();
+ if row < r0 || row > r1 {
+ return 0..0;
+ }
+ let cols = inner.cols.max(line.len());
+ match sel.mode {
+ 3 => 0..cols,
+ 2 => {
+ let word = |col: usize| -> std::ops::Range<usize> {
+ match line.compute_double_click_range(col, |s| {
+ s.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-' || c == '.' || c == '/')
+ }) {
+ termwiz::surface::line::DoubleClickRange::Range(r) => r,
+ termwiz::surface::line::DoubleClickRange::RangeWithWrap(r) => r,
+ }
+ };
+ let start = if row == r0 { word(c0).start } else { 0 };
+ let end = if row == r1 { word(c1).end } else { cols };
+ start..end
+ }
+ _ => {
+ let start = if row == r0 { c0 } else { 0 };
+ let end = if row == r1 { c1 + 1 } else { cols };
+ start..end.max(start)
+ }
+ }
+ }
+
+ fn selection_text(inner: &Inner) -> Option<String> {
+ let sel = inner.selection?;
+ let ((r0, _), (r1, _)) = sel.ordered();
+ let (first, lines) = inner.session.get_lines(r0..r1 + 1);
+ let mut out = Vec::new();
+ for (i, line) in lines.iter().enumerate() {
+ let row = first + i as StableRowIndex;
+ let range = Self::selection_on_row(inner, &sel, row, line);
+ let mut text = String::new();
+ for cell in line.visible_cells() {
+ if range.contains(&cell.cell_index()) {
+ text.push_str(cell.str());
+ }
+ }
+ out.push(text.trim_end().to_string());
+ }
+ Some(out.join("\n"))
+ }
+
+ /// Returns true when the page acted on the wheel (the browser must
+ /// not). A program that has the mouse gets every wheel with its real
+ /// modifiers; otherwise Ctrl+wheel and pinch are the browser's zoom.
+ pub fn wheel(&self, ev: &web_sys::WheelEvent) -> bool {
+ let mut inner = self.inner.borrow_mut();
+ if inner.disconnected.is_some() {
+ return false;
+ }
+ let cell_h_css = inner.glyphs.metrics.cell_size.height as f64 / inner.dpr;
+ let lines = match ev.delta_mode() {
+ web_sys::WheelEvent::DOM_DELTA_LINE => ev.delta_y(),
+ web_sys::WheelEvent::DOM_DELTA_PAGE => ev.delta_y() * inner.rows as f64,
+ _ => ev.delta_y() / cell_h_css,
+ };
+ let notches = lines.abs().round().max(if lines == 0.0 { 0.0 } else { 1.0 }) as usize;
+ if notches == 0 {
+ return false;
+ }
+ if inner.session.is_alt_screen() || inner.session.is_mouse_grabbed() {
+ let button = if lines < 0.0 { MouseButton::WheelUp(notches) } else { MouseButton::WheelDown(notches) };
+ let (col, row, x_off, y_off) = {
+ let rect = inner.canvas.get_bounding_client_rect();
+ let px = (ev.client_x() as f64 - rect.left()) * inner.dpr;
+ let py = (ev.client_y() as f64 - rect.top()) * inner.dpr;
+ let (cw, ch) = (
+ inner.glyphs.metrics.cell_size.width as f64,
+ inner.glyphs.metrics.cell_size.height as f64,
+ );
+ let (c, r) = cell_at(px, py, cw, ch);
+ (c, r, (px - c as f64 * cw) as isize, (py - r as f64 * ch) as isize)
+ };
+ let dims = inner.session.dimensions();
+ let visible = visible_rows(&dims, inner.rows, inner.scroll_from_bottom);
+ let event = MouseEvent {
+ kind: MouseEventKind::Press,
+ x: col,
+ y: (visible.start + row as StableRowIndex - dims.physical_top).max(0) as i64,
+ x_pixel_offset: x_off,
+ y_pixel_offset: y_off,
+ button,
+ modifiers: Self::mouse_modifiers(ev),
+ };
+ let start = inner.session.mouse_event(event);
+ Self::spawn_drain(&inner, start);
+ return true;
+ }
+ if ev.ctrl_key() {
+ return false;
+ }
+ let dims = inner.session.dimensions();
+ let max = max_scroll(&dims);
+ inner.scroll_from_bottom = if lines < 0.0 {
+ (inner.scroll_from_bottom + notches).min(max)
+ } else {
+ inner.scroll_from_bottom.saturating_sub(notches)
+ };
+ drop(inner);
+ self.request_frame();
+ true
+ }
+
+ pub fn focus(&self, focused: bool) {
+ self.inner.borrow_mut().focused = focused;
+ self.request_frame();
+ }
+
+ /// Fit the grid to the canvas's CSS box at the device pixel ratio, and
+ /// tell the server if this browser owns the viewport.
+ pub fn resize(&self) {
+ 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);
+ 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)))
+ {
+ Ok(glyphs) => inner.glyphs = glyphs,
+ Err(err) => log::error!("glyph cache for dpr {dpr}: {err:#}"),
+ }
+ }
+ let dev_w = (rect.width() * dpr).floor().max(1.0) as u32;
+ let dev_h = (rect.height() * dpr).floor().max(1.0) as u32;
+ if inner.canvas.width() != dev_w || inner.canvas.height() != dev_h {
+ inner.canvas.set_width(dev_w);
+ inner.canvas.set_height(dev_h);
+ }
+ inner.gpu.resize(dev_w, dev_h);
+ let (cw, ch) = (
+ inner.glyphs.metrics.cell_size.width as u32,
+ inner.glyphs.metrics.cell_size.height as u32,
+ );
+ let Some((cols, rows)) = grid_for(dev_w, dev_h, cw, ch) else {
+ // A box too small for a cell is a hidden or collapsed page,
+ // not a size anyone asked for: keep the last real grid rather
+ // than resize every client's shell to it.
+ return;
+ };
+ let changed = cols != inner.cols || rows != inner.rows;
+ inner.cols = cols;
+ inner.rows = rows;
+ if changed {
+ let size = TerminalSize {
+ rows,
+ cols,
+ pixel_width: cols * cw as usize,
+ pixel_height: rows * ch as usize,
+ dpi: (96.0 * dpr) as u32,
+ };
+ let owner = inner.link.lease().owns_viewport();
+ inner.link.lease_mut().reported = Some(size);
+ let link = inner.link.clone();
+ let (tab_id, pane_id) = (inner.tab_id, inner.pane_id);
+ if owner {
+ inner.session.apply_local_resize(size);
+ wasm_bindgen_futures::spawn_local(async move {
+ let pdu = Pdu::Resize(codec::Resize {
+ containing_tab_id: tab_id,
+ pane_id,
+ size,
+ });
+ if let Err(err) = thinkterm_session::host::request(&link, pdu, |p| match p {
+ Pdu::UnitResponse(_) => Ok(()),
+ other => Err(other),
+ })
+ .await
+ {
+ log::warn!("resize refused: {err:#}");
+ }
+ });
+ } else {
+ wasm_bindgen_futures::spawn_local(async move {
+ let pdu = Pdu::SetClientViewport(codec::SetClientViewport {
+ tab_id,
+ viewport: codec::ClientViewport::CellGrid { size },
+ });
+ if let Ok(state) = thinkterm_session::host::request(&link, pdu, |p| match p {
+ Pdu::ClientViewportState(s) => Ok(s),
+ other => Err(other),
+ })
+ .await
+ {
+ link.lease_mut().apply_viewport(&state);
+ }
+ });
+ }
+ }
+ drop(inner);
+ self.refresh_status();
+ self.request_frame();
+ }
+
+ /// Paint. Lines the session does not have yet come back blank and are
+ /// fetched; their arrival marks the page dirty again.
+ pub fn frame(&self) {
+ let mut inner = self.inner.borrow_mut();
+ let _ = inner.host.events.take_dirty();
+ let title = inner.session.title();
+ if title != inner.title {
+ inner.title = title;
+ if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
+ doc.set_title(&format!("{} — ThinkTerm", inner.title));
+ }
+ drop(inner);
+ 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:#}");
+ break;
+ }
+ }
+ Err(err) => {
+ log::error!("frame failed: {err:#}");
+ break;
+ }
+ }
+ }
+ // Lines still in flight, or a stalled fetch: 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);
+ self.request_frame();
+ }
+ }
+
+ 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");
+ }
+ 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)?;
+ Ok(())
+ }
+
+ fn paint(inner: &mut Inner) -> Result<()> {
+ let dims = inner.session.dimensions();
+ let max = max_scroll(&dims);
+ if inner.scroll_from_bottom > max {
+ inner.scroll_from_bottom = max;
+ }
+ let cursor = inner.session.cursor_position();
+ let visible = visible_rows(&dims, inner.rows, inner.scroll_from_bottom);
+ 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;
+ inner.quads.recycle();
+ let selection = inner.selection;
+ for (i, line) in lines.iter().enumerate() {
+ let row = first + i as StableRowIndex;
+ let sel_range = match &selection {
+ Some(sel) => Self::selection_on_row(inner, sel, row, line),
+ None => 0..0,
+ };
+ let params = crate::emit::LineParams {
+ line,
+ stable_row: row,
+ top_pixel_y: i as f32 * cell_h,
+ cursor: &cursor,
+ palette: &inner.palette,
+ selection: sel_range,
+ focused: inner.focused && inner.link.lease().owns_viewport(),
+ reverse_video: dims.reverse_video,
+ surface: (w as f32, h as f32),
+ };
+ crate::emit::emit_line(&mut inner.glyphs, &mut inner.quads, &params)?;
+ }
+ inner.vertices.clear();
+ inner.quads.extract_vertices(&mut inner.vertices);
+ let bg = inner.palette.background.to_linear().tuple();
+ 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)
+ }
+}
+
+/// The grid a canvas of `w`x`h` device pixels holds, or `None` when it
+/// cannot hold even one cell: a 2x1 shell is never what a 0x0 box means.
+pub fn grid_for(w: u32, h: u32, cell_w: u32, cell_h: u32) -> Option<(usize, usize)> {
+ if cell_w == 0 || cell_h == 0 || w < cell_w || h < cell_h {
+ return None;
+ }
+ Some(((w / cell_w).max(2) as usize, (h / cell_h).max(1) as usize))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::grid_for;
+
+ #[test]
+ fn a_degenerate_box_yields_no_grid() {
+ assert_eq!(grid_for(0, 0, 10, 20), None);
+ assert_eq!(grid_for(1, 1, 10, 20), None);
+ assert_eq!(grid_for(800, 19, 10, 20), None);
+ assert_eq!(grid_for(800, 400, 10, 20), Some((80, 20)));
+ assert_eq!(grid_for(15, 20, 10, 20), Some((2, 1)));
+ }
+}
+
+fn write_clipboard(text: &str) {
+ if let Some(window) = web_sys::window() {
+ let clipboard = window.navigator().clipboard();
+ let promise = clipboard.write_text(text);
+ wasm_bindgen_futures::spawn_local(async move {
+ if let Err(err) = wasm_bindgen_futures::JsFuture::from(promise).await {
+ log::warn!("clipboard write refused: {err:?}");
+ }
+ });
+ }
+}
diff --git a/thinkterm-web/src/attach.rs b/thinkterm-web/src/attach.rs
new file mode 100644
index 00000000..3da8e3b0
--- /dev/null
+++ b/thinkterm-web/src/attach.rs
@@ -0,0 +1,143 @@
+//! The handshake, in the desktop's order, then the lease steps a follower
+//! takes: version, identity, the pane list, a viewport report, and the
+//! render subscription.
+
+use crate::link::WsLink;
+use anyhow::{anyhow, bail, Result};
+use codec::Pdu;
+use thinkterm_proto::layout::{PaneEntry, PaneNode};
+use thinkterm_proto::{ClientId, PaneId, RenderableDimensions, TabId};
+use thinkterm_session::host::request;
+use wezterm_term::TerminalSize;
+
+pub struct Attached {
+ pub pane_id: PaneId,
+ pub tab_id: TabId,
+ pub title: String,
+ pub dims: RenderableDimensions,
+ pub alt_screen: bool,
+ pub server_version: String,
+}
+
+fn active_pane(node: &PaneNode) -> Option<PaneEntry> {
+ match node {
+ PaneNode::Empty => None,
+ PaneNode::Leaf(e) => Some(e.clone()),
+ PaneNode::Stack(s) => s.panes.get(s.active).or(s.panes.first()).cloned(),
+ PaneNode::Split { left, right, .. } => {
+ let (l, r) = (active_pane(left), active_pane(right));
+ match (&l, &r) {
+ (Some(a), _) if a.is_active_pane => l,
+ (_, Some(b)) if b.is_active_pane => r,
+ _ => l.or(r),
+ }
+ }
+ }
+}
+
+/// `size` is the grid this page can show, or `None` when it cannot show
+/// one yet; only a real size is reported, so a later claim never carries
+/// a made-up one.
+pub async fn attach(link: &WsLink, size: Option<TerminalSize>) -> Result<Attached> {
+ 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 = ClientId {
+ hostname: "web".into(),
+ username: "web".into(),
+ pid: 0,
+ epoch: js_sys::Date::now() as u64,
+ id: (js_sys::Math::random() * u32::MAX as f64) as usize,
+ ssh_auth_sock: None,
+ };
+ link.lease_mut().me = Some(me.clone());
+ 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?;
+ // The first tab that has a pane, preferring its active one.
+ let entry = panes
+ .tabs
+ .iter()
+ .find_map(active_pane)
+ .ok_or_else(|| anyhow!("the server has no panes to show"))?;
+
+ link.lease_mut().tab_id = Some(entry.tab_id);
+ if let Some(size) = size {
+ let state = request(
+ link,
+ Pdu::SetClientViewport(codec::SetClientViewport {
+ tab_id: entry.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.reported = Some(size);
+ lease.apply_viewport(&state);
+ }
+
+ request(
+ link,
+ Pdu::GetPaneRenderChanges(codec::GetPaneRenderChanges {
+ pane_id: entry.pane_id,
+ }),
+ |pdu| match pdu {
+ Pdu::LivenessResponse(_) | Pdu::UnitResponse(_) => Ok(()),
+ other => Err(other),
+ },
+ )
+ .await?;
+
+ let rows = entry.size.rows;
+ Ok(Attached {
+ pane_id: entry.pane_id,
+ tab_id: entry.tab_id,
+ title: entry.title.clone(),
+ dims: RenderableDimensions {
+ cols: entry.size.cols,
+ viewport_rows: rows,
+ scrollback_rows: rows,
+ physical_top: entry.physical_top,
+ scrollback_top: entry.physical_top,
+ dpi: entry.size.dpi,
+ pixel_width: entry.size.pixel_width,
+ pixel_height: entry.size.pixel_height,
+ reverse_video: false,
+ },
+ alt_screen: entry.alt_screen,
+ server_version: version.version_string,
+ })
+}
diff --git a/thinkterm-web/src/emit.rs b/thinkterm-web/src/emit.rs
new file mode 100644
index 00000000..78ebd226
--- /dev/null
+++ b/thinkterm-web/src/emit.rs
@@ -0,0 +1,327 @@
+//! One row of cells to quads: the phase-one cut of the desktop's
+//! `render_screen_line` (wezterm-gui/src/termwindow/render/screen_line.rs):
+//! backgrounds, underlines, the selection, the cursor, then glyphs sliced
+//! 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 anyhow::{Context, Result};
+use std::ops::Range;
+use termwiz::cell::{Intensity, Underline};
+use termwiz::surface::{CursorShape, CursorVisibility, Line};
+use thinkterm_font_core::PresentationWidth;
+use thinkterm_proto::StableCursorPosition;
+use thinkterm_render::quad::{HeapQuadAllocator, QuadTrait, TripleLayerQuadAllocatorTrait};
+use wezterm_color_types::LinearRgba;
+use wezterm_term::color::{ColorAttribute, ColorPalette};
+use wezterm_term::{CellAttributes, StableRowIndex};
+
+pub struct LineParams<'a> {
+ pub line: &'a Line,
+ pub stable_row: StableRowIndex,
+ /// Top edge of the row in device pixels from the canvas top.
+ pub top_pixel_y: f32,
+ pub cursor: &'a StableCursorPosition,
+ pub palette: &'a ColorPalette,
+ /// Selected cells on this row.
+ pub selection: Range<usize>,
+ pub focused: bool,
+ pub reverse_video: bool,
+ /// The canvas, in device pixels.
+ pub surface: (f32, f32),
+}
+
+/// The desktop's default `bold_brightens_ansi_colors`: bold lifts the
+/// first eight palette colours to their bright twins.
+fn resolve_fg(attrs: &CellAttributes, fg: ColorAttribute, palette: &ColorPalette) -> LinearRgba {
+ match fg {
+ ColorAttribute::PaletteIndex(idx) if idx < 8 => {
+ let idx = if attrs.intensity() == Intensity::Bold {
+ idx + 8
+ } else {
+ idx
+ };
+ palette.resolve_fg(ColorAttribute::PaletteIndex(idx))
+ }
+ other => palette.resolve_fg(other),
+ }
+ .to_linear()
+}
+
+fn intersection(r1: &Range<f32>, r2: &Range<f32>) -> Range<f32> {
+ let start = r1.start.max(r2.start);
+ let end = r1.end.min(r2.end);
+ if end > start {
+ start..end
+ } else {
+ start..start
+ }
+}
+
+/// `r` split into the parts left of, inside and right of `within`.
+fn range3(r: &Range<f32>, within: &Range<f32>) -> (Range<f32>, Range<f32>, Range<f32>) {
+ if r.is_empty() {
+ return (r.clone(), r.clone(), r.clone());
+ }
+ let i = intersection(r, within);
+ if i.is_empty() {
+ return (r.clone(), i.clone(), i.clone());
+ }
+ let left = if i.start > r.start {
+ r.start..i.start
+ } else {
+ r.start..r.start
+ };
+ let right = if i.end < r.end {
+ i.end..r.end
+ } else {
+ r.end..r.end
+ };
+ (left, i, right)
+}
+
+fn is_block(shape: CursorShape) -> bool {
+ matches!(
+ shape,
+ CursorShape::Default | CursorShape::BlinkingBlock | CursorShape::SteadyBlock
+ )
+}
+
+pub fn emit_line(
+ cache: &mut GlyphCache,
+ layers: &mut HeapQuadAllocator,
+ p: &LineParams<'_>,
+) -> Result<()> {
+ if p.line.is_double_height_bottom() {
+ return Ok(());
+ }
+ let metrics = cache.metrics;
+ let width_scale: f32 = if p.line.is_single_width() { 1.0 } else { 2.0 };
+ let height_scale: f32 = if p.line.is_double_height_top() { 2.0 } else { 1.0 };
+ let cell_width = metrics.cell_size.width as f32 * width_scale;
+ let cell_height = metrics.cell_size.height as f32 * height_scale;
+ let gl_x = -p.surface.0 / 2.0;
+ let pos_y = -p.surface.1 / 2.0 + p.top_pixel_y;
+ let pixel_width = p.surface.0;
+
+ let cursor_on_row = p.stable_row == p.cursor.y;
+ let cursor_cell = if cursor_on_row {
+ p.line.get_cell(p.cursor.x)
+ } else {
+ None
+ };
+ let cursor_range = if cursor_on_row {
+ p.cursor.x..p.cursor.x + cursor_cell.as_ref().map(|c| c.width()).unwrap_or(1)
+ } else {
+ 0..0
+ };
+ let cursor_range_pixels =
+ cursor_range.start as f32 * cell_width..cursor_range.end as f32 * cell_width;
+ let selection_pixels = if p.selection.is_empty() {
+ 0.0..0.0
+ } else {
+ p.selection.start as f32 * cell_width..p.selection.end as f32 * cell_width
+ };
+ let cursor_visible = cursor_on_row && p.cursor.visibility == CursorVisibility::Visible;
+ let filled_cursor = cursor_visible && p.focused && is_block(p.cursor.shape);
+
+ let selection_fg = p.palette.selection_fg.to_linear();
+ let selection_bg = p.palette.selection_bg.to_linear();
+ let cursor_fg = p.palette.cursor_fg.to_linear();
+ let cursor_bg = p.palette.cursor_bg.to_linear();
+ let cursor_border = p.palette.cursor_border.to_linear();
+ let default_fg = p.palette.foreground.to_linear();
+ let filled_box = cache.filled_box.texture_coords();
+
+ let filled_rectangle =
+ |layers: &mut HeapQuadAllocator, layer: usize, x: f32, w: f32, color: LinearRgba| -> Result<()> {
+ let mut quad = layers.allocate(layer).context("allocate")?;
+ quad.set_position(gl_x + x, pos_y, gl_x + x + w, pos_y + cell_height);
+ quad.set_texture(filled_box);
+ quad.set_is_background();
+ quad.set_fg_color(color);
+ quad.set_hsv(None);
+ Ok(())
+ };
+
+ if p.reverse_video {
+ filled_rectangle(layers, 0, 0.0, pixel_width, default_fg)?;
+ }
+
+ // Shape and resolve every cluster first: colours and glyphs.
+ struct Shaped {
+ first_cell: usize,
+ width: usize,
+ fg: LinearRgba,
+ bg: LinearRgba,
+ bg_is_default: bool,
+ invisible: bool,
+ underline: Option<(thinkterm_render::bitmaps::TextureRect, LinearRgba)>,
+ glyphs: Vec<(u8, std::rc::Rc<crate::glyphs::CachedGlyph>)>,
+ }
+ let clusters = p.line.cluster(None);
+ let mut shaped: Vec<Shaped> = Vec::with_capacity(clusters.len());
+ for cluster in &clusters {
+ let attrs = &cluster.attrs;
+ let bg_is_default = attrs.background() == ColorAttribute::Default;
+ let bg = p.palette.resolve_bg(attrs.background()).to_linear();
+ let fg = resolve_fg(attrs, attrs.foreground(), p.palette);
+ let (fg, bg, bg_is_default) = if attrs.reverse() == !p.reverse_video {
+ (bg, fg, false)
+ } else {
+ (fg, bg, bg_is_default)
+ };
+ let underline = if attrs.underline() != Underline::None
+ || attrs.strikethrough()
+ || attrs.overline()
+ {
+ let sprite = cache.line_sprite(attrs.strikethrough(), attrs.underline(), attrs.overline())?;
+ let color = match attrs.underline_color() {
+ ColorAttribute::Default => fg,
+ other => p.palette.resolve_fg(other).to_linear(),
+ };
+ Some((sprite.texture_coords(), color))
+ } else {
+ None
+ };
+ let infos = cache.shape(
+ &cluster.text,
+ Some(cluster.presentation),
+ Some(&PresentationWidth::with_cluster(cluster)),
+ )?;
+ 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));
+ }
+ shaped.push(Shaped {
+ first_cell: cluster.first_cell_idx,
+ width: cluster.width,
+ fg,
+ bg,
+ bg_is_default,
+ invisible: attrs.invisible(),
+ underline,
+ glyphs,
+ });
+ }
+
+ // Backgrounds and underlines.
+ for item in &shaped {
+ if !item.bg_is_default {
+ let x = item.first_cell as f32 * cell_width;
+ let w = item.width as f32 * cell_width;
+ if x < pixel_width {
+ filled_rectangle(layers, 0, x, w.min(pixel_width - x), item.bg)?;
+ }
+ }
+ if let Some((tex, color)) = &item.underline {
+ for i in 0..item.width {
+ let x = gl_x + (item.first_cell + i) as f32 * cell_width;
+ let mut quad = layers.allocate(0).context("allocate")?;
+ quad.set_position(x, pos_y, x + cell_width, pos_y + cell_height);
+ quad.set_hsv(None);
+ quad.set_has_color(false);
+ quad.set_texture(*tex);
+ quad.set_fg_color(*color);
+ }
+ }
+ }
+
+ if !p.selection.is_empty() && selection_pixels.start < pixel_width {
+ filled_rectangle(
+ layers,
+ 0,
+ selection_pixels.start,
+ (selection_pixels.end - selection_pixels.start).min(pixel_width - selection_pixels.start),
+ selection_bg,
+ )?;
+ }
+
+ // The cursor: filled when this page has focus and the shape is a
+ // block, an outline when it does not, bar and underline as themselves.
+ if cursor_visible {
+ let (shape, color) = if !p.focused {
+ (CursorShape::SteadyBlock, cursor_border)
+ } else if is_block(p.cursor.shape) {
+ (CursorShape::Default, cursor_bg)
+ } else {
+ (p.cursor.shape, cursor_bg)
+ };
+ let layer = match shape {
+ CursorShape::BlinkingBar | CursorShape::SteadyBar => 2,
+ _ => 0,
+ };
+ let width_cells = (cursor_range.end - cursor_range.start).max(1) as u8;
+ let sprite = cache.cursor_sprite(Some(shape), width_cells)?;
+ let x = gl_x + cursor_range_pixels.start;
+ let mut quad = layers.allocate(layer).context("allocate")?;
+ quad.set_hsv(None);
+ quad.set_has_color(false);
+ quad.set_position(x, pos_y, x + width_cells as f32 * cell_width, pos_y + cell_height);
+ quad.set_texture(sprite.texture_coords());
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ }
+
+ // Glyphs, in strips.
+ let descender = metrics.descender.get() as f32;
+ for item in &shaped {
+ let mut cluster_x = item.first_cell as f32 * cell_width;
+ for (num_cells, glyph) in &item.glyphs {
+ if let Some(texture) = &glyph.texture {
+ let top = cell_height
+ + (descender - (glyph.y_offset + glyph.bearing_y).get() as f32) * height_scale;
+ let pos_x = cluster_x;
+ if pos_x > pixel_width {
+ break;
+ }
+ let adjust = (glyph.x_offset + glyph.bearing_x).get() as f32;
+ let texture_range = pos_x + adjust
+ ..pos_x + adjust + texture.coords.size.width as f32 * width_scale;
+ let (left, mid, right) = range3(&texture_range, &cursor_range_pixels);
+ let (la, lb, lc) = range3(&left, &selection_pixels);
+ let (ra, rb, rc) = range3(&right, &selection_pixels);
+ for range in [la, lb, lc, mid, ra, rb, rc] {
+ if range.is_empty() {
+ continue;
+ }
+ let is_cursor = cursor_range_pixels.contains(&range.start);
+ let selected = !is_cursor && selection_pixels.contains(&range.start);
+ let (glyph_color, bg_color) = if is_cursor && filled_cursor {
+ (cursor_fg.when_fully_transparent(item.fg), cursor_bg)
+ } else if selected {
+ (selection_fg.when_fully_transparent(item.fg), selection_bg)
+ } else {
+ (item.fg, item.bg)
+ };
+ if glyph_color == bg_color || item.invisible {
+ continue;
+ }
+ let pixel_rect = euclid::rect(
+ texture.coords.origin.x + (range.start - (pos_x + adjust)) as isize,
+ texture.coords.origin.y,
+ ((range.end - range.start) / width_scale) as isize,
+ texture.coords.size.height,
+ );
+ let texture_rect = texture.texture.to_texture_coords(pixel_rect);
+ let mut quad = layers.allocate(1).context("allocate")?;
+ quad.set_position(
+ gl_x + range.start,
+ pos_y + top,
+ gl_x + range.end,
+ pos_y + top + texture.coords.size.height as f32 * height_scale,
+ );
+ quad.set_fg_color(glyph_color);
+ quad.set_alt_color_and_mix_value(glyph_color, 0.0);
+ quad.set_texture(texture_rect);
+ quad.set_hsv(None);
+ quad.set_has_color(glyph.has_color);
+ }
+ }
+ cluster_x += *num_cells as f32 * cell_width;
+ }
+ }
+ Ok(())
+}
diff --git a/thinkterm-web/src/glyphs.rs b/thinkterm-web/src/glyphs.rs
new file mode 100644
index 00000000..d67ef78f
--- /dev/null
+++ b/thinkterm-web/src/glyphs.rs
@@ -0,0 +1,487 @@
+//! The browser's glyph cache: the desktop's glyph key and `load_glyph`
+//! arithmetic (wezterm-gui/src/glyphcache.rs), its cell metrics
+//! (utilsprites.rs) and its underline and cursor sprites, over the shared
+//! 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 anyhow::{Context, Result};
+use std::collections::HashMap;
+use std::rc::Rc;
+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_render::atlas::{Atlas, AtlasTag, OutOfTextureSpace, Sprite};
+use thinkterm_render::bitmaps::{BitmapImage, Image, Texture2d};
+use thinkterm_render::geom::{Point, Rect, Size};
+use thinkterm_render::pipeline::GpuTexture;
+use wezterm_color_types::SrgbaPixel;
+
+/// utilsprites.rs `RenderMetrics`, the config-free constructor.
+#[derive(Copy, Clone, Debug)]
+pub struct RenderMetrics {
+ pub descender: PixelLength,
+ pub descender_row: isize,
+ pub descender_plus_two: isize,
+ pub underline_height: isize,
+ pub strike_row: isize,
+ pub cell_size: Size,
+}
+
+impl RenderMetrics {
+ pub fn with_font_metrics(metrics: &FontMetrics) -> Self {
+ let (cell_height, cell_width) = (
+ metrics.cell_height.get().ceil() as usize,
+ metrics.cell_width.get().ceil() as usize,
+ );
+ let underline_height = metrics.underline_thickness.get().round().max(1.) as isize;
+ let descender_row =
+ (cell_height as f64 + (metrics.descender - metrics.underline_position).get()) as isize;
+ let descender_plus_two =
+ (2 * underline_height + descender_row).min(cell_height as isize - underline_height);
+ let strike_row = descender_row / 2;
+ Self {
+ descender: metrics.descender,
+ descender_row,
+ descender_plus_two,
+ strike_row,
+ cell_size: Size::new(cell_width as isize, cell_height as isize),
+ underline_height,
+ }
+ }
+
+ pub fn scale_cell_width(&self, scale: f64) -> Self {
+ let mut scaled = *self;
+ scaled.cell_size.width = (self.cell_size.width as f64 * scale) as isize;
+ scaled
+ }
+}
+
+/// glyphcache.rs `CachedGlyph`, fields and all: the emitter reads what it
+/// needs today and the rest is the desktop's record.
+#[derive(Debug)]
+#[allow(dead_code)]
+pub struct CachedGlyph {
+ pub has_color: bool,
+ pub brightness_adjust: f32,
+ pub x_offset: PixelLength,
+ pub y_offset: PixelLength,
+ pub x_advance: PixelLength,
+ pub bearing_x: PixelLength,
+ pub bearing_y: PixelLength,
+ pub texture: Option<Sprite>,
+ pub scale: f64,
+}
+
+/// glyphcache.rs `GlyphKey` without the style: one style in the browser.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct GlyphKey {
+ font_idx: usize,
+ glyph_pos: u32,
+ num_cells: u8,
+ followed_by_space: bool,
+ cell_width: u16,
+ cell_height: u16,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct LineKey {
+ strike_through: bool,
+ underline: Underline,
+ overline: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct ShapeKey {
+ text: String,
+ /// `Presentation` has no `Hash`; Text is 0, Emoji is 1.
+ presentation: Option<u8>,
+}
+
+pub struct GlyphCache {
+ fonts: Rc<FontSet>,
+ pub size_pt: f64,
+ pub dpi: u32,
+ pub base_metrics: FontMetrics,
+ pub metrics: RenderMetrics,
+ texture: Rc<GpuTexture>,
+ pub atlas: Atlas,
+ glyphs: HashMap<GlyphKey, Rc<CachedGlyph>>,
+ lines: HashMap<LineKey, Sprite>,
+ cursors: HashMap<(Option<CursorShape>, u8), Sprite>,
+ shapes: HashMap<ShapeKey, Rc<Vec<GlyphInfo>>>,
+ #[allow(dead_code)]
+ pub white_space: Sprite,
+ pub filled_box: Sprite,
+}
+
+impl GlyphCache {
+ pub fn new(
+ fonts: Rc<FontSet>,
+ size_pt: f64,
+ dpi: u32,
+ texture: Rc<GpuTexture>,
+ ) -> Result<Self> {
+ let base_metrics = fonts.metrics(size_pt, dpi)?;
+ let metrics = RenderMetrics::with_font_metrics(&base_metrics);
+ let surface: Rc<dyn Texture2d> = texture.clone();
+ let mut atlas = Atlas::new(&surface)?;
+ // utilsprites.rs `UtilSprites`: a white cell and a blank cell.
+ let mut buffer = Image::new(
+ metrics.cell_size.width as usize,
+ metrics.cell_size.height as usize,
+ );
+ let cell_rect = Rect::new(Point::new(0, 0), metrics.cell_size);
+ buffer.clear_rect(cell_rect, SrgbaPixel::rgba(0xff, 0xff, 0xff, 0xff));
+ let filled_box = atlas.allocate(&buffer)?;
+ buffer.clear_rect(cell_rect, SrgbaPixel::rgba(0, 0, 0, 0));
+ let white_space = atlas.allocate(&buffer)?;
+ Ok(Self {
+ fonts,
+ size_pt,
+ dpi,
+ base_metrics,
+ metrics,
+ texture,
+ atlas,
+ glyphs: HashMap::new(),
+ lines: HashMap::new(),
+ cursors: HashMap::new(),
+ shapes: HashMap::new(),
+ white_space,
+ filled_box,
+ })
+ }
+
+ pub fn texture(&self) -> &GpuTexture {
+ &self.texture
+ }
+
+ /// Shape one cluster's text, memoised: the same text with the same
+ /// attributes shapes the same every frame.
+ pub fn shape(
+ &mut self,
+ text: &str,
+ presentation: Option<termwiz::cell::Presentation>,
+ presentation_width: Option<&thinkterm_font_core::PresentationWidth>,
+ ) -> Result<Rc<Vec<GlyphInfo>>> {
+ let key = ShapeKey {
+ text: text.to_string(),
+ presentation: presentation.map(|p| match p {
+ termwiz::cell::Presentation::Text => 0,
+ termwiz::cell::Presentation::Emoji => 1,
+ }),
+ };
+ 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(
+ text,
+ self.size_pt,
+ self.dpi,
+ &mut no_glyphs,
+ presentation,
+ thinkterm_font_core::Direction::LeftToRight,
+ None,
+ presentation_width,
+ )?);
+ if !no_glyphs.is_empty() {
+ log::debug!("no bundled face has {no_glyphs:?}");
+ }
+ if self.shapes.len() > 4096 {
+ self.shapes.clear();
+ }
+ self.shapes.insert(key, Rc::clone(&shaped));
+ Ok(shaped)
+ }
+
+ pub fn cached_glyph(
+ &mut self,
+ info: &GlyphInfo,
+ followed_by_space: bool,
+ num_cells: u8,
+ ) -> Result<Rc<CachedGlyph>> {
+ let key = GlyphKey {
+ font_idx: info.font_idx,
+ glyph_pos: info.glyph_pos,
+ num_cells,
+ followed_by_space,
+ cell_width: self.metrics.cell_size.width as u16,
+ cell_height: self.metrics.cell_size.height as u16,
+ };
+ if let Some(entry) = self.glyphs.get(&key) {
+ return Ok(Rc::clone(entry));
+ }
+ let glyph = match self.load_glyph(info, followed_by_space, num_cells) {
+ Ok(g) => g,
+ Err(err) => {
+ if err.root_cause().downcast_ref::<OutOfTextureSpace>().is_some() {
+ return Err(err);
+ }
+ 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,
+ })
+ }
+ };
+ self.glyphs.insert(key, 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)]
+ fn load_glyph(
+ &mut self,
+ info: &GlyphInfo,
+ followed_by_space: bool,
+ num_cells: u8,
+ ) -> Result<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)?;
+ let idx_metrics = self.fonts.metrics_for_idx(info.font_idx, self.size_pt, self.dpi)?;
+ let brightness_adjust = 1.0;
+
+ let aspect = (idx_metrics.cell_width / idx_metrics.cell_height).get();
+ let is_square_or_wide = aspect >= 0.7;
+ let allow_width_overflow = is_square_or_wide && followed_by_space;
+ let num_cells = num_cells.max(1) as f64;
+ let max_pixel_width = base_metrics.cell_width.get() * (num_cells + 0.25);
+
+ let scale;
+ let mut metrics_only_scale = 1.0;
+ if info.font_idx == 0 {
+ scale = if allow_width_overflow || glyph.width as f64 <= max_pixel_width {
+ 1.0
+ } else {
+ 1.0 / num_cells
+ };
+ } else if !glyph.is_scaled {
+ let y_scale = base_metrics.cell_height.get() / idx_metrics.cell_height.get();
+ let y_scaled_width = y_scale * glyph.width as f64;
+ if allow_width_overflow || y_scaled_width <= max_pixel_width {
+ scale = y_scale;
+ } else {
+ scale = max_pixel_width / glyph.width as f64;
+ }
+ } else {
+ let f_width = glyph.width as f64;
+ if allow_width_overflow || f_width <= max_pixel_width {
+ scale = 1.0;
+ } else {
+ scale = max_pixel_width / f_width;
+ }
+ if !idx_metrics.is_scaled {
+ metrics_only_scale =
+ base_metrics.cell_height.get() / idx_metrics.cell_height.get();
+ }
+ }
+
+ let descender_adjust = if info.font_idx == 0 {
+ PixelLength::new(0.0)
+ } else {
+ idx_metrics.force_y_adjust
+ };
+
+ let glyph = if glyph.width == 0 || glyph.height == 0 {
+ CachedGlyph {
+ brightness_adjust: 1.0,
+ has_color: glyph.has_color,
+ texture: None,
+ x_offset: info.x_offset * scale,
+ y_offset: info.y_offset * scale,
+ x_advance: info.x_advance * scale,
+ bearing_x: PixelLength::new(0.0),
+ bearing_y: descender_adjust,
+ scale,
+ }
+ } else {
+ let raw_im = Image::with_rgba32(
+ glyph.width,
+ glyph.height,
+ 4 * glyph.width,
+ &glyph.data,
+ );
+ let bearing_x = glyph.bearing_x * scale * metrics_only_scale;
+ let bearing_y = descender_adjust + (glyph.bearing_y * scale);
+ 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;
+ 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)?;
+ CachedGlyph {
+ brightness_adjust,
+ has_color: glyph.has_color,
+ texture: Some(tex),
+ x_offset,
+ y_offset,
+ x_advance,
+ bearing_x,
+ bearing_y,
+ scale,
+ }
+ };
+ Ok(Rc::new(glyph))
+ }
+
+ /// glyphcache.rs `cached_line_sprite`: underline, strike and overline
+ /// drawn into one cell-sized sprite.
+ pub fn line_sprite(
+ &mut self,
+ strike_through: bool,
+ underline: Underline,
+ overline: bool,
+ ) -> Result<Sprite> {
+ let key = LineKey {
+ strike_through,
+ underline,
+ overline,
+ };
+ if let Some(s) = self.lines.get(&key) {
+ return Ok(s.clone());
+ }
+ let metrics = self.metrics;
+ let mut buffer = Image::new(
+ metrics.cell_size.width as usize,
+ metrics.cell_size.height as usize,
+ );
+ let black = SrgbaPixel::rgba(0, 0, 0, 0);
+ let white = SrgbaPixel::rgba(0xff, 0xff, 0xff, 0xff);
+ let cell_rect = Rect::new(Point::new(0, 0), metrics.cell_size);
+ let width = metrics.cell_size.width;
+
+ let draw_rows = |buffer: &mut Image, first_row: isize| {
+ for row in 0..metrics.underline_height {
+ buffer.draw_line(
+ Point::new(0, first_row + row),
+ Point::new(width, first_row + row),
+ white,
+ );
+ }
+ };
+ let draw_pattern = |buffer: &mut Image, segment: usize| {
+ for row in 0..metrics.underline_height {
+ let y = (metrics.descender_row + row) as usize;
+ if y >= metrics.cell_size.height as usize {
+ break;
+ }
+ let mut color = white;
+ let mut count = segment;
+ let range = buffer.horizontal_pixel_range_mut(0, width as usize, y);
+ for c in range.iter_mut() {
+ *c = color.as_srgba32();
+ count -= 1;
+ if count == 0 {
+ color = if color == white { black } else { white };
+ count = segment;
+ }
+ }
+ }
+ };
+
+ buffer.clear_rect(cell_rect, black);
+ if overline {
+ draw_rows(&mut buffer, 0);
+ }
+ match underline {
+ Underline::None => {}
+ Underline::Single => draw_rows(&mut buffer, metrics.descender_row),
+ Underline::Dotted => draw_pattern(&mut buffer, (width / 4).max(1) as usize),
+ Underline::Dashed => draw_pattern(&mut buffer, (width / 3) as usize + 1),
+ Underline::Double => {
+ let first_line = metrics
+ .descender_row
+ .min(metrics.descender_plus_two - 2 * metrics.underline_height);
+ draw_rows(&mut buffer, first_line);
+ draw_rows(&mut buffer, metrics.descender_plus_two);
+ }
+ Underline::Curly => {
+ let max_y = metrics.cell_size.height as usize - 1;
+ let x_factor = (2. * std::f32::consts::PI) / width as f32;
+ let wave_height = metrics.cell_size.height - metrics.descender_row;
+ let half_height = (wave_height as f32 / 4.).max(1.);
+ let y = (metrics.descender_row as usize).saturating_sub(half_height as usize);
+ fn add(x: usize, y: usize, val: u8, max_y: usize, buffer: &mut Image) {
+ let y = y.min(max_y);
+ let pixel = buffer.pixel_mut(x, y);
+ let (current, _, _, _) = SrgbaPixel::with_srgba_u32(*pixel).as_rgba();
+ let value = current.saturating_add(val);
+ *pixel = SrgbaPixel::rgba(value, value, value, value).as_srgba32();
+ }
+ for x in 0..width as usize {
+ let vertical = -half_height * (x as f32 * x_factor).sin() + half_height;
+ let v1 = vertical.floor();
+ let v2 = vertical.ceil();
+ for row in 0..metrics.underline_height as usize {
+ let value = (255. * (vertical - v1).abs()) as u8;
+ add(x, row + y + v1 as usize, 255u8.saturating_sub(value), max_y, &mut buffer);
+ add(x, row + y + v2 as usize, value, max_y, &mut buffer);
+ }
+ }
+ }
+ }
+ if strike_through {
+ draw_rows(&mut buffer, metrics.strike_row);
+ }
+ let sprite = self.atlas.allocate(&buffer)?;
+ self.lines.insert(key, sprite.clone());
+ Ok(sprite)
+ }
+
+ /// The cursor's sprite for a shape and a width in cells. Filled block,
+ /// outlined block, bar and underline as flat pixels: the desktop draws
+ /// these through its custom-glyph poly rasteriser, which is not shared
+ /// yet.
+ pub fn cursor_sprite(&mut self, shape: Option<CursorShape>, width: u8) -> Result<Sprite> {
+ if let Some(sprite) = self.cursors.get(&(shape, width)) {
+ return Ok(sprite.clone());
+ }
+ let metrics = self.metrics.scale_cell_width(width.max(1) as f64);
+ let (w, h) = (metrics.cell_size.width, metrics.cell_size.height);
+ let thickness = metrics.underline_height.max(1);
+ let mut buffer = Image::new(w as usize, h as usize);
+ let black = SrgbaPixel::rgba(0, 0, 0, 0);
+ let white = SrgbaPixel::rgba(0xff, 0xff, 0xff, 0xff);
+ let cell_rect = Rect::new(Point::new(0, 0), metrics.cell_size);
+ buffer.clear_rect(cell_rect, black);
+ let fill = |buffer: &mut Image, x: isize, y: isize, rw: isize, rh: isize| {
+ buffer.clear_rect(Rect::new(Point::new(x, y), Size::new(rw, rh)), white);
+ };
+ match shape {
+ None => {}
+ Some(CursorShape::Default) => buffer.clear_rect(cell_rect, white),
+ Some(CursorShape::BlinkingBlock | CursorShape::SteadyBlock) => {
+ fill(&mut buffer, 0, 0, w, thickness);
+ fill(&mut buffer, 0, h - thickness, w, thickness);
+ fill(&mut buffer, 0, 0, thickness, h);
+ fill(&mut buffer, w - thickness, 0, thickness, h);
+ }
+ Some(CursorShape::BlinkingBar | CursorShape::SteadyBar) => {
+ fill(&mut buffer, 0, 0, thickness, h);
+ }
+ Some(CursorShape::BlinkingUnderline | CursorShape::SteadyUnderline) => {
+ fill(&mut buffer, 0, h - thickness, w, thickness);
+ }
+ }
+ let sprite = self.atlas.allocate(&buffer).context("cursor sprite")?;
+ self.cursors.insert((shape, width), sprite.clone());
+ Ok(sprite)
+ }
+}
diff --git a/thinkterm-web/src/gpu.rs b/thinkterm-web/src/gpu.rs
new file mode 100644
index 00000000..690237b5
--- /dev/null
+++ b/thinkterm-web/src/gpu.rs
@@ -0,0 +1,354 @@
+//! The canvas surface and one frame's worth of drawing through the shared
+//! pipeline. Colour: the canvas is configured with the linear name of its
+//! format and drawn through an sRGB view, so the hardware encodes on write
+//! exactly as it does for the desktop's already-sRGB surface.
+
+use anyhow::{anyhow, Result};
+use std::sync::Arc;
+use thinkterm_render::pipeline::{
+ centred_projection, quad_indices, srgb_format, view_as, AtlasBindGroups, GpuTexture, Pipeline,
+ ShaderUniform,
+};
+use thinkterm_render::vertex::Vertex;
+
+pub struct Gpu {
+ pub device: wgpu::Device,
+ pub queue: Arc<wgpu::Queue>,
+ surface: wgpu::Surface<'static>,
+ config: wgpu::SurfaceConfiguration,
+ view_format: wgpu::TextureFormat,
+ pub pipeline: Pipeline,
+ uniform_buffer: wgpu::Buffer,
+ uniform_bind_group: wgpu::BindGroup,
+ vertex_buffer: wgpu::Buffer,
+ vertex_capacity: usize,
+ index_buffer: wgpu::Buffer,
+ index_quads: usize,
+ atlas_bind_groups: Option<(usize, AtlasBindGroups)>,
+ pub adapter_info: wgpu::AdapterInfo,
+}
+
+impl Gpu {
+ pub async fn new(canvas: web_sys::HtmlCanvasElement, width: u32, height: u32) -> Result<Self> {
+ let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
+ backends: wgpu::Backends::BROWSER_WEBGPU,
+ ..Default::default()
+ });
+ let surface = instance
+ .create_surface(wgpu::SurfaceTarget::Canvas(canvas))
+ .map_err(|e| anyhow!("creating the canvas surface: {e}"))?;
+ let adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ compatible_surface: Some(&surface),
+ force_fallback_adapter: false,
+ })
+ .await
+ .map_err(|e| anyhow!("no WebGPU adapter: {e}"))?;
+ let adapter_info = adapter.get_info();
+ let (device, queue) = adapter
+ .request_device(&wgpu::DeviceDescriptor {
+ required_features: wgpu::Features::empty(),
+ // Never the WebGL2 downlevel limits: they cap textures at
+ // 2048 where the desktop atlas may reach 8192.
+ required_limits: wgpu::Limits::downlevel_defaults()
+ .using_resolution(adapter.limits()),
+ label: None,
+ memory_hints: Default::default(),
+ trace: wgpu::Trace::Off,
+ })
+ .await
+ .map_err(|e| anyhow!("requesting the device: {e}"))?;
+ let queue = Arc::new(queue);
+
+ let caps = surface.get_capabilities(&adapter);
+ let format = caps
+ .formats
+ .first()
+ .copied()
+ .ok_or_else(|| anyhow!("the canvas offers no texture format"))?;
+ let view_format = srgb_format(format);
+ let config = wgpu::SurfaceConfiguration {
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ format,
+ width: width.max(1),
+ height: height.max(1),
+ present_mode: wgpu::PresentMode::Fifo,
+ alpha_mode: wgpu::CompositeAlphaMode::Opaque,
+ view_formats: if view_format != format { vec![view_format] } else { vec![] },
+ desired_maximum_frame_latency: 2,
+ };
+ surface.configure(&device, &config);
+
+ let pipeline = Pipeline::new(&device, view_format);
+ let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ShaderUniform"),
+ size: std::mem::size_of::<ShaderUniform>() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let uniform_bind_group = pipeline.uniform_bind_group(&device, &uniform_buffer);
+ let vertex_capacity = 4096;
+ let vertex_buffer = Self::make_vertex_buffer(&device, vertex_capacity);
+ let index_quads = vertex_capacity / 4;
+ let index_buffer = Self::make_index_buffer(&device, &queue, index_quads);
+ Ok(Self {
+ device,
+ queue,
+ surface,
+ config,
+ view_format,
+ pipeline,
+ uniform_buffer,
+ uniform_bind_group,
+ vertex_buffer,
+ vertex_capacity,
+ index_buffer,
+ index_quads,
+ atlas_bind_groups: None,
+ adapter_info,
+ })
+ }
+
+ fn make_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("vertices"),
+ size: (capacity * std::mem::size_of::<Vertex>()) as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ })
+ }
+
+ fn make_index_buffer(device: &wgpu::Device, queue: &wgpu::Queue, quads: usize) -> wgpu::Buffer {
+ let indices = quad_indices(quads);
+ let buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("indices"),
+ size: (indices.len() * 4) as u64,
+ usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&indices));
+ buffer
+ }
+
+ pub fn size(&self) -> (u32, u32) {
+ (self.config.width, self.config.height)
+ }
+
+ /// Grow both buffers as needed and upload; returns the quad count.
+ fn upload_vertices(&mut self, vertices: &[Vertex]) -> usize {
+ let quads = vertices.len() / 4;
+ if vertices.len() > self.vertex_capacity {
+ self.vertex_capacity = vertices.len().next_power_of_two();
+ self.vertex_buffer = Self::make_vertex_buffer(&self.device, self.vertex_capacity);
+ }
+ if quads > self.index_quads {
+ self.index_quads = quads.next_power_of_two();
+ self.index_buffer = Self::make_index_buffer(&self.device, &self.queue, self.index_quads);
+ }
+ if !vertices.is_empty() {
+ self.queue
+ .write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(vertices));
+ }
+ quads
+ }
+
+ pub fn resize(&mut self, width: u32, height: u32) {
+ let (width, height) = (width.max(1), height.max(1));
+ if (width, height) == (self.config.width, self.config.height) {
+ return;
+ }
+ self.config.width = width;
+ self.config.height = height;
+ self.surface.configure(&self.device, &self.config);
+ }
+
+ pub fn max_texture_dimension(&self) -> u32 {
+ self.device.limits().max_texture_dimension_2d
+ }
+
+ fn atlas_groups(&mut self, atlas: &GpuTexture) -> &AtlasBindGroups {
+ let identity = atlas.id();
+ if self.atlas_bind_groups.as_ref().map(|(id, _)| *id) != Some(identity) {
+ let groups = self.pipeline.atlas_bind_groups(&self.device, &atlas.view());
+ self.atlas_bind_groups = Some((identity, groups));
+ }
+ &self.atlas_bind_groups.as_ref().expect("just set").1
+ }
+
+ /// Draw `vertices` (four per quad, TL TR BL BR) over a cleared frame.
+ /// `background` is the pane's default background, painted as the
+ /// clear colour so letterboxed margins match it.
+ pub fn draw(
+ &mut self,
+ vertices: &[Vertex],
+ atlas: &GpuTexture,
+ background: [f32; 4],
+ millis: u32,
+ ) -> Result<()> {
+ let (w, h) = self.size();
+ let uniforms = ShaderUniform {
+ foreground_text_hsb: [1.0, 1.0, 1.0],
+ milliseconds: millis,
+ viewport_and_corner: [w as f32, h as f32, 0.0, 0.0],
+ window_border: [0.0; 4],
+ projection: centred_projection(w as f32, h as f32),
+ };
+ self.queue
+ .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniforms));
+
+ let quads = self.upload_vertices(vertices);
+ self.atlas_groups(atlas);
+
+ let frame = self
+ .surface
+ .get_current_texture()
+ .map_err(|e| anyhow!("acquiring the canvas frame: {e}"))?;
+ let view = view_as(&frame.texture, self.view_format);
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") });
+ {
+ let groups = &self.atlas_bind_groups.as_ref().expect("set above").1;
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("pane"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color {
+ r: background[0] as f64,
+ g: background[1] as f64,
+ b: background[2] as f64,
+ a: 1.0,
+ }),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ if quads > 0 {
+ pass.set_pipeline(&self.pipeline.render_pipeline);
+ pass.set_bind_group(0, &self.uniform_bind_group, &[]);
+ pass.set_bind_group(1, &groups.linear, &[]);
+ pass.set_bind_group(2, &groups.nearest, &[]);
+ pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+ pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
+ pass.draw_indexed(0..(quads * 6) as u32, 0, 0..1);
+ }
+ }
+ self.queue.submit(Some(encoder.finish()));
+ frame.present();
+ Ok(())
+ }
+
+ /// Render one frame of `vertices` and read back the pixel at (x, y) as
+ /// the 8-bit value the canvas holds. The check the smoke test runs:
+ /// a known linear colour must come back sRGB-encoded.
+ pub async fn draw_and_read_pixel(
+ &mut self,
+ vertices: &[Vertex],
+ atlas: &GpuTexture,
+ x: u32,
+ y: u32,
+ ) -> Result<[u8; 4]> {
+ let (w, h) = self.size();
+ let uniforms = ShaderUniform {
+ foreground_text_hsb: [1.0, 1.0, 1.0],
+ milliseconds: 0,
+ viewport_and_corner: [w as f32, h as f32, 0.0, 0.0],
+ window_border: [0.0; 4],
+ projection: centred_projection(w as f32, h as f32),
+ };
+ self.queue
+ .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniforms));
+ let quads = self.upload_vertices(vertices);
+ self.atlas_groups(atlas);
+
+ let frame = self
+ .surface
+ .get_current_texture()
+ .map_err(|e| anyhow!("acquiring the canvas frame: {e}"))?;
+ let view = view_as(&frame.texture, self.view_format);
+ let readback = self.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("readback"),
+ size: 256,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("check") });
+ {
+ let groups = &self.atlas_bind_groups.as_ref().expect("set above").1;
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("check"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ pass.set_pipeline(&self.pipeline.render_pipeline);
+ pass.set_bind_group(0, &self.uniform_bind_group, &[]);
+ pass.set_bind_group(1, &groups.linear, &[]);
+ pass.set_bind_group(2, &groups.nearest, &[]);
+ pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+ pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
+ pass.draw_indexed(0..(quads * 6) as u32, 0, 0..1);
+ }
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture: &frame.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d { x, y, z: 0 },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: &readback,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(256),
+ rows_per_image: Some(1),
+ },
+ },
+ wgpu::Extent3d {
+ width: 1,
+ height: 1,
+ depth_or_array_layers: 1,
+ },
+ );
+ self.queue.submit(Some(encoder.finish()));
+ frame.present();
+
+ let slice = readback.slice(..);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ slice.map_async(wgpu::MapMode::Read, move |r| {
+ let _ = tx.send(r);
+ });
+ let _ = self.device.poll(wgpu::PollType::Poll);
+ rx.await
+ .map_err(|_| anyhow!("readback dropped"))?
+ .map_err(|e| anyhow!("mapping the readback: {e}"))?;
+ let bytes = slice.get_mapped_range();
+ let mut pixel = [bytes[0], bytes[1], bytes[2], bytes[3]];
+ // Byte order follows the canvas format.
+ if matches!(
+ self.config.format,
+ wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
+ ) {
+ pixel.swap(0, 2);
+ }
+ drop(bytes);
+ readback.unmap();
+ Ok(pixel)
+ }
+}
diff --git a/thinkterm-web/src/host.rs b/thinkterm-web/src/host.rs
new file mode 100644
index 00000000..06e8e1f4
--- /dev/null
+++ b/thinkterm-web/src/host.rs
@@ -0,0 +1,143 @@
+//! What the session takes from the page: a clock, a spawner, an event
+//! sink and its settings.
+
+use crate::link::WsLink;
+use std::cell::{Cell, RefCell};
+use std::future::Future;
+use std::pin::Pin;
+use std::rc::Rc;
+use std::sync::Arc;
+use thinkterm_session::clock::{Clock, Timestamp};
+use thinkterm_session::host::{
+ DetachedFuture, HostConfig, HostPaneId, ImageDomainKey, SessionEvents, SessionHost, Spawner,
+};
+
+pub type LocalFuture<T> = Pin<Box<dyn Future<Output = T> + 'static>>;
+
+pub struct WebClock {
+ performance: web_sys::Performance,
+}
+
+impl WebClock {
+ pub fn new() -> Self {
+ let performance = web_sys::window()
+ .and_then(|w| w.performance())
+ .expect("performance.now is a web standard");
+ Self { performance }
+ }
+}
+
+impl Clock for WebClock {
+ fn now(&self) -> Timestamp {
+ Timestamp::from_micros((self.performance.now() * 1000.0) as u64)
+ }
+ fn wall_millis(&self) -> u64 {
+ js_sys::Date::now() as u64
+ }
+}
+
+pub struct LocalSpawner;
+
+impl Spawner for LocalSpawner {
+ fn spawn_detached(&self, fut: DetachedFuture) {
+ wasm_bindgen_futures::spawn_local(fut);
+ }
+}
+
+/// The session's notifications, folded into "the page needs a paint" plus
+/// the few facts the page shows.
+#[derive(Default)]
+pub struct WebEvents {
+ dirty: Cell<bool>,
+ wake: RefCell<Option<Rc<dyn Fn()>>>,
+}
+
+impl WebEvents {
+ /// `wake` runs on every event that changes what the page should show;
+ /// it schedules a frame.
+ pub fn set_wake(&self, wake: Rc<dyn Fn()>) {
+ *self.wake.borrow_mut() = Some(wake);
+ }
+
+ pub fn take_dirty(&self) -> bool {
+ self.dirty.replace(false)
+ }
+
+ fn mark(&self) {
+ self.dirty.set(true);
+ if let Some(wake) = self.wake.borrow().clone() {
+ wake();
+ }
+ }
+}
+
+impl SessionEvents for WebEvents {
+ fn pane_output(&self, _pane: HostPaneId) {
+ self.mark();
+ }
+ fn alert(&self, _pane: HostPaneId, _alert: wezterm_term::Alert) {}
+ fn agent_status_changed(&self, _pane: HostPaneId) {}
+ fn pane_removed(&self, _pane: HostPaneId) {
+ self.mark();
+ }
+ fn pane_focused(&self, _pane: HostPaneId) {}
+ fn input_recorded(&self) {}
+}
+
+pub struct WebConfig {
+ rules: Arc<Vec<termwiz::hyperlink::Rule>>,
+}
+
+impl Default for WebConfig {
+ fn default() -> Self {
+ Self {
+ rules: Arc::new(Vec::new()),
+ }
+ }
+}
+
+impl HostConfig for WebConfig {
+ fn hyperlink_rules(&self) -> Arc<Vec<termwiz::hyperlink::Rule>> {
+ Arc::clone(&self.rules)
+ }
+ fn fetch_rate_per_second(&self) -> u32 {
+ // The desktop's default mux_output_parser... no: its default
+ // ratelimit for line fetches is 10 per second per pane.
+ 10
+ }
+}
+
+pub struct WebHost {
+ pub clock: WebClock,
+ pub spawner: LocalSpawner,
+ pub events: WebEvents,
+ pub link: WsLink,
+ pub config: WebConfig,
+}
+
+impl SessionHost for WebHost {
+ type Clock = WebClock;
+ type Spawner = LocalSpawner;
+ type Events = WebEvents;
+ type Link = WsLink;
+ type Config = WebConfig;
+
+ fn clock(&self) -> &WebClock {
+ &self.clock
+ }
+ fn spawner(&self) -> &LocalSpawner {
+ &self.spawner
+ }
+ fn events(&self) -> &WebEvents {
+ &self.events
+ }
+ fn link(&self) -> &WsLink {
+ &self.link
+ }
+ fn config(&self) -> &WebConfig {
+ &self.config
+ }
+ fn image_domain(&self) -> ImageDomainKey {
+ 1
+ }
+}
diff --git a/thinkterm-web/src/input.rs b/thinkterm-web/src/input.rs
new file mode 100644
index 00000000..b372fc7d
--- /dev/null
+++ b/thinkterm-web/src/input.rs
@@ -0,0 +1,164 @@
+//! DOM events to the app. A hidden textarea owns keyboard focus so the
+//! IME composes into it; keys the IME is not handling go to the pane as
+//! key events, composed text goes as bytes, and paste arrives as paste.
+
+use crate::app::App;
+use crate::keymap::{map_key, DomKey};
+use std::rc::Rc;
+use wasm_bindgen::prelude::*;
+use wasm_bindgen::JsCast;
+use web_sys::{
+ ClipboardEvent, CompositionEvent, Event, HtmlCanvasElement, HtmlTextAreaElement, InputEvent,
+ KeyboardEvent, PointerEvent, WheelEvent,
+};
+
+fn listen<E: JsCast + 'static>(
+ target: &web_sys::EventTarget,
+ name: &str,
+ handler: impl FnMut(E) + 'static,
+) {
+ let mut handler = handler;
+ let closure = Closure::<dyn FnMut(Event)>::new(move |ev: Event| {
+ if let Ok(ev) = ev.dyn_into::<E>() {
+ handler(ev);
+ }
+ });
+ target
+ .add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())
+ .expect("addEventListener");
+ // The listeners live as long as the page.
+ closure.forget();
+}
+
+pub fn install(app: Rc<App>, canvas: &HtmlCanvasElement, textarea: &HtmlTextAreaElement) {
+ let window = web_sys::window().expect("window");
+
+ {
+ let app = app.clone();
+ listen::<KeyboardEvent>(textarea, "keydown", move |ev| {
+ let key = ev.key();
+ let code = ev.code();
+ let dom = DomKey {
+ key: &key,
+ code: &code,
+ ctrl: ev.ctrl_key(),
+ alt: ev.alt_key(),
+ shift: ev.shift_key(),
+ meta: ev.meta_key(),
+ composing: ev.is_composing(),
+ };
+ match map_key(&dom) {
+ Some((key, mods)) => {
+ if app.key_down(key, mods, ev.shift_key()) {
+ ev.prevent_default();
+ }
+ }
+ None => {}
+ }
+ });
+ }
+ {
+ let app = app.clone();
+ listen::<CompositionEvent>(textarea, "compositionstart", move |_| app.composing(true));
+ }
+ {
+ let app = app.clone();
+ let textarea = textarea.clone();
+ listen::<CompositionEvent>(&textarea.clone(), "compositionend", move |ev| {
+ app.composing(false);
+ if let Some(text) = ev.data() {
+ if !text.is_empty() {
+ app.text(&text);
+ }
+ }
+ textarea.set_value("");
+ });
+ }
+ {
+ let app = app.clone();
+ let textarea = textarea.clone();
+ listen::<InputEvent>(&textarea.clone(), "input", move |ev| {
+ // Composition text arrives through compositionend; anything
+ // else typed straight into the textarea (a virtual keyboard,
+ // autocorrect) is sent as bytes.
+ if ev.is_composing() {
+ return;
+ }
+ let value = textarea.value();
+ if !value.is_empty() {
+ app.text(&value);
+ textarea.set_value("");
+ }
+ });
+ }
+ {
+ let app = app.clone();
+ listen::<ClipboardEvent>(textarea, "paste", move |ev| {
+ ev.prevent_default();
+ if let Some(data) = ev.clipboard_data() {
+ if let Ok(text) = data.get_data("text/plain") {
+ if !text.is_empty() {
+ app.paste(&text);
+ }
+ }
+ }
+ });
+ }
+ {
+ let app = app.clone();
+ listen::<PointerEvent>(canvas, "pointerdown", move |ev| {
+ app.pointer(&ev, crate::app::Pointer::Down);
+ ev.prevent_default();
+ });
+ }
+ {
+ let app = app.clone();
+ listen::<PointerEvent>(canvas, "pointermove", move |ev| {
+ app.pointer(&ev, crate::app::Pointer::Move);
+ });
+ }
+ {
+ let app = app.clone();
+ listen::<PointerEvent>(canvas, "pointerup", move |ev| {
+ app.pointer(&ev, crate::app::Pointer::Up);
+ });
+ }
+ {
+ let app = app.clone();
+ listen::<PointerEvent>(canvas, "pointercancel", move |ev| {
+ app.pointer(&ev, crate::app::Pointer::Up);
+ });
+ }
+ {
+ let app = app.clone();
+ listen::<WheelEvent>(canvas, "wheel", move |ev| {
+ if app.wheel(&ev) {
+ ev.prevent_default();
+ }
+ });
+ }
+ {
+ listen::<Event>(canvas, "contextmenu", move |ev| ev.prevent_default());
+ }
+ {
+ let app = app.clone();
+ listen::<Event>(&window, "focus", move |_| app.focus(true));
+ }
+ {
+ let app = app.clone();
+ listen::<Event>(&window, "blur", move |_| app.focus(false));
+ }
+ {
+ let app = app.clone();
+ listen::<Event>(&window, "resize", move |_| app.resize());
+ }
+ {
+ // The canvas's own box, not just the window: CSS can resize it.
+ let app = app.clone();
+ let closure = Closure::<dyn FnMut(js_sys::Array)>::new(move |_entries: js_sys::Array| app.resize());
+ if let Ok(observer) = web_sys::ResizeObserver::new(closure.as_ref().unchecked_ref()) {
+ observer.observe(canvas);
+ closure.forget();
+ }
+ }
+}
diff --git a/thinkterm-web/src/keymap.rs b/thinkterm-web/src/keymap.rs
new file mode 100644
index 00000000..4911d5d6
--- /dev/null
+++ b/thinkterm-web/src/keymap.rs
@@ -0,0 +1,162 @@
+//! DOM keyboard events to the terminal's key model. The browser already
+//! applied the layout and Shift to `key`, so a printable key becomes
+//! `KeyCode::Char` as typed and Shift is not reported for it, which is
+//! what the desktop does after `normalize_shift_to_upper_case`.
+
+use termwiz::input::{KeyCode, Modifiers};
+
+/// What a `keydown` event carries that matters here.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DomKey<'a> {
+ pub key: &'a str,
+ pub code: &'a str,
+ pub ctrl: bool,
+ pub alt: bool,
+ pub shift: bool,
+ pub meta: bool,
+ /// `KeyboardEvent.isComposing`: the IME owns this key.
+ pub composing: bool,
+}
+
+pub fn map_key(k: &DomKey<'_>) -> Option<(KeyCode, Modifiers)> {
+ if k.composing {
+ return None;
+ }
+ let mut mods = Modifiers::NONE;
+ if k.ctrl {
+ mods |= Modifiers::CTRL;
+ }
+ if k.alt {
+ mods |= Modifiers::ALT;
+ }
+ if k.meta {
+ mods |= Modifiers::SUPER;
+ }
+ let with_shift = |code: KeyCode, mods: Modifiers| {
+ Some((code, if k.shift { mods | Modifiers::SHIFT } else { mods }))
+ };
+ let code = match k.key {
+ "Enter" => KeyCode::Enter,
+ "Backspace" => KeyCode::Backspace,
+ "Tab" => KeyCode::Tab,
+ "Escape" => KeyCode::Escape,
+ "ArrowUp" => KeyCode::UpArrow,
+ "ArrowDown" => KeyCode::DownArrow,
+ "ArrowLeft" => KeyCode::LeftArrow,
+ "ArrowRight" => KeyCode::RightArrow,
+ "Home" => KeyCode::Home,
+ "End" => KeyCode::End,
+ "PageUp" => KeyCode::PageUp,
+ "PageDown" => KeyCode::PageDown,
+ "Insert" => KeyCode::Insert,
+ "Delete" => KeyCode::Delete,
+ "Clear" => KeyCode::Clear,
+ "Pause" => KeyCode::Pause,
+ "PrintScreen" => KeyCode::PrintScreen,
+ "ContextMenu" => KeyCode::Applications,
+ // Modifier keys on their own, dead keys, and keys the IME is
+ // handling do not reach the terminal.
+ "Shift" | "Control" | "Alt" | "Meta" | "CapsLock" | "NumLock" | "ScrollLock" | "Dead"
+ | "Process" | "Unidentified" | "AltGraph" | "Fn" | "Hyper" | "Super" | "OS" => {
+ return None
+ }
+ other => {
+ if let Some(n) = other.strip_prefix('F').and_then(|n| n.parse::<u8>().ok()) {
+ if (1..=24).contains(&n) && other.len() <= 3 {
+ return with_shift(KeyCode::Function(n), mods);
+ }
+ }
+ let mut chars = other.chars();
+ match (chars.next(), chars.next()) {
+ (Some(c), None) => {
+ if let Some(digit) = k.code.strip_prefix("Numpad") {
+ if let Ok(d) = digit.parse::<u8>() {
+ if d < 10 {
+ let numpad = match d {
+ 0 => KeyCode::Numpad0,
+ 1 => KeyCode::Numpad1,
+ 2 => KeyCode::Numpad2,
+ 3 => KeyCode::Numpad3,
+ 4 => KeyCode::Numpad4,
+ 5 => KeyCode::Numpad5,
+ 6 => KeyCode::Numpad6,
+ 7 => KeyCode::Numpad7,
+ 8 => KeyCode::Numpad8,
+ _ => KeyCode::Numpad9,
+ };
+ return with_shift(numpad, mods);
+ }
+ }
+ }
+ // Shift is already folded into the character. Ctrl+Alt
+ // together with a non-alphanumeric character is AltGr
+ // on Windows: the character is what was typed.
+ if k.ctrl && k.alt && !c.is_ascii_alphanumeric() {
+ return Some((KeyCode::Char(c), mods - Modifiers::CTRL - Modifiers::ALT));
+ }
+ return Some((KeyCode::Char(c), mods));
+ }
+ _ => return None,
+ }
+ }
+ };
+ with_shift(code, mods)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn key(key: &str, code: &str) -> DomKey<'static> {
+ DomKey {
+ key: Box::leak(key.to_string().into_boxed_str()),
+ code: Box::leak(code.to_string().into_boxed_str()),
+ ctrl: false,
+ alt: false,
+ shift: false,
+ meta: false,
+ composing: false,
+ }
+ }
+
+ #[test]
+ fn printable_keys_carry_their_character_without_shift() {
+ let mut k = key("A", "KeyA");
+ k.shift = true;
+ assert_eq!(map_key(&k), Some((KeyCode::Char('A'), Modifiers::NONE)));
+ let mut k = key("c", "KeyC");
+ k.ctrl = true;
+ assert_eq!(map_key(&k), Some((KeyCode::Char('c'), Modifiers::CTRL)));
+ }
+
+ #[test]
+ fn special_keys_keep_shift_and_the_function_row_is_numbered() {
+ let mut k = key("ArrowUp", "ArrowUp");
+ k.shift = true;
+ assert_eq!(map_key(&k), Some((KeyCode::UpArrow, Modifiers::SHIFT)));
+ assert_eq!(map_key(&key("F12", "F12")), Some((KeyCode::Function(12), Modifiers::NONE)));
+ assert_eq!(map_key(&key("Enter", "NumpadEnter")), Some((KeyCode::Enter, Modifiers::NONE)));
+ assert_eq!(map_key(&key("7", "Numpad7")), Some((KeyCode::Numpad7, Modifiers::NONE)));
+ }
+
+ #[test]
+ fn altgr_characters_arrive_as_typed() {
+ let mut k = key("@", "KeyQ");
+ k.ctrl = true;
+ k.alt = true;
+ assert_eq!(map_key(&k), Some((KeyCode::Char('@'), Modifiers::NONE)));
+ let mut k = key("x", "KeyX");
+ k.ctrl = true;
+ k.alt = true;
+ assert_eq!(map_key(&k), Some((KeyCode::Char('x'), Modifiers::CTRL | Modifiers::ALT)));
+ }
+
+ #[test]
+ fn modifiers_dead_keys_and_ime_keys_do_not_reach_the_terminal() {
+ assert_eq!(map_key(&key("Shift", "ShiftLeft")), None);
+ assert_eq!(map_key(&key("Dead", "Quote")), None);
+ let mut k = key("a", "KeyA");
+ k.composing = true;
+ assert_eq!(map_key(&k), None);
+ }
+}
diff --git a/thinkterm-web/src/lease.rs b/thinkterm-web/src/lease.rs
new file mode 100644
index 00000000..73778492
--- /dev/null
+++ b/thinkterm-web/src/lease.rs
@@ -0,0 +1,125 @@
+//! Who owns the tab this browser mirrors, as the server has told us. Pure,
+//! so it is tested natively; the WebSocket link keeps one and feeds it.
+
+use thinkterm_proto::{ClientId, TabId};
+use wezterm_term::TerminalSize;
+
+/// What the server has told us about who owns the tab we mirror.
+#[derive(Debug, Default, Clone)]
+pub struct Lease {
+ pub tab_id: Option<TabId>,
+ pub me: Option<ClientId>,
+ pub mode: Option<codec::FrontendAccessMode>,
+ /// Connection-wide owner (Handoff mode).
+ pub owner: Option<ClientId>,
+ /// Per-tab owner (TmuxLatest mode).
+ pub tab_owner: Option<ClientId>,
+ pub canonical_size: Option<TerminalSize>,
+ /// The grid this browser last reported.
+ pub reported: Option<TerminalSize>,
+}
+
+fn same_client(a: &ClientId, b: &ClientId) -> bool {
+ // The server stamps a web client's hostname and username with the
+ // token it came in on, so only the parts we chose identify us.
+ a.pid == b.pid && a.epoch == b.epoch && a.id == b.id
+}
+
+impl Lease {
+ pub fn owns_viewport(&self) -> bool {
+ let Some(me) = &self.me else {
+ return false;
+ };
+ match self.mode {
+ Some(codec::FrontendAccessMode::TmuxLatest) => {
+ self.tab_owner.as_ref().is_some_and(|o| same_client(o, me))
+ }
+ Some(codec::FrontendAccessMode::Handoff) => {
+ self.owner.as_ref().is_some_and(|o| same_client(o, me))
+ }
+ None => false,
+ }
+ }
+
+ pub fn apply_access(&mut self, access: &codec::FrontendAccessState) {
+ self.mode = Some(access.mode);
+ self.owner = access.owner.clone();
+ }
+
+ pub fn apply_viewport(&mut self, state: &codec::ClientViewportState) {
+ if Some(state.tab_id) != self.tab_id {
+ return;
+ }
+ self.tab_owner = state.owner.clone();
+ self.canonical_size = Some(state.canonical_size);
+ self.apply_access(&state.access);
+ }
+}
+
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn id(n: usize) -> ClientId {
+ ClientId {
+ hostname: "h".into(),
+ username: "u".into(),
+ pid: 0,
+ epoch: 1,
+ id: n,
+ ssh_auth_sock: None,
+ }
+ }
+
+ #[test]
+ fn ownership_follows_the_mode() {
+ let mut lease = Lease {
+ me: Some(id(1)),
+ tab_id: Some(7),
+ ..Lease::default()
+ };
+ assert!(!lease.owns_viewport(), "unknown mode owns nothing");
+ lease.apply_access(&codec::FrontendAccessState {
+ mode: codec::FrontendAccessMode::Handoff,
+ owner: Some(id(1)),
+ generation: 1,
+ });
+ assert!(lease.owns_viewport());
+ // The server stamps hostname and username on web clients; the rest
+ // still identifies us.
+ let mut stamped = id(1);
+ stamped.hostname = "web:laptop".into();
+ stamped.username = "server-user".into();
+ lease.owner = Some(stamped);
+ assert!(lease.owns_viewport());
+ lease.owner = Some(id(2));
+ assert!(!lease.owns_viewport());
+ }
+
+ #[test]
+ fn viewport_state_for_another_tab_is_ignored() {
+ let mut lease = Lease {
+ me: Some(id(1)),
+ tab_id: Some(7),
+ ..Lease::default()
+ };
+ let access = codec::FrontendAccessState {
+ mode: codec::FrontendAccessMode::TmuxLatest,
+ owner: None,
+ generation: 1,
+ };
+ let state = |tab_id, owner| codec::ClientViewportState {
+ tab_id,
+ owner,
+ canonical_size: TerminalSize::default(),
+ view: None,
+ generation: 1,
+ access: access.clone(),
+ };
+ lease.apply_viewport(&state(8, Some(id(1))));
+ assert!(!lease.owns_viewport(), "another tab's owner is not ours");
+ lease.apply_viewport(&state(7, Some(id(1))));
+ assert!(lease.owns_viewport());
+ }
+}
diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rs
new file mode 100644
index 00000000..049f12c6
--- /dev/null
+++ b/thinkterm-web/src/lib.rs
@@ -0,0 +1,30 @@
+//! The ThinkTerm browser client. See Cargo.toml for the charter.
+//!
+//! `keymap` and `viewport` are pure and build everywhere; everything that
+//! touches the page is `wasm32` only.
+
+pub mod keymap;
+pub mod lease;
+pub mod viewport;
+
+#[cfg(target_arch = "wasm32")]
+mod app;
+#[cfg(target_arch = "wasm32")]
+mod attach;
+#[cfg(target_arch = "wasm32")]
+mod emit;
+#[cfg(target_arch = "wasm32")]
+mod glyphs;
+#[cfg(target_arch = "wasm32")]
+mod gpu;
+#[cfg(target_arch = "wasm32")]
+mod host;
+#[cfg(target_arch = "wasm32")]
+mod input;
+#[cfg(target_arch = "wasm32")]
+mod link;
+#[cfg(target_arch = "wasm32")]
+mod page;
+
+#[cfg(target_arch = "wasm32")]
+pub use page::{color_check, start};
diff --git a/thinkterm-web/src/link.rs b/thinkterm-web/src/link.rs
new file mode 100644
index 00000000..fac6e06a
--- /dev/null
+++ b/thinkterm-web/src/link.rs
@@ -0,0 +1,410 @@
+//! The WebSocket as the session's `PduLink`: one connection, requests
+//! matched to answers by serial, server pushes handed to the app, and the
+//! lease bookkeeping that decides whether this browser may type.
+
+use crate::host::LocalFuture;
+use thinkterm_proto::TabId;
+use anyhow::{anyhow, Result};
+use codec::{DecodedPdu, Pdu};
+use futures::channel::oneshot;
+use futures::io::{AsyncRead, AsyncWrite};
+use std::cell::{Cell, RefCell};
+use std::collections::VecDeque;
+use std::pin::Pin;
+use std::rc::Rc;
+use std::task::{Context, Poll, Waker};
+use thinkterm_session::connection::{Answer, SerialTable};
+use thinkterm_session::host::{LinkError, PduLink};
+use thinkterm_session::input::PaneLink;
+use wasm_bindgen::prelude::*;
+use wasm_bindgen::JsCast;
+use web_sys::{BinaryType, MessageEvent, WebSocket};
+
+pub const SUBPROTOCOL: &str = "thinkterm.v1";
+pub const TOKEN_PROTOCOL_PREFIX: &str = "tt-token.";
+
+/// The socket's bytes, in order, as the codec's async reader wants them.
+struct Socket {
+ ws: WebSocket,
+ incoming: RefCell<VecDeque<u8>>,
+ waker: RefCell<Option<Waker>>,
+ open: Cell<bool>,
+ closed: Cell<bool>,
+ close_reason: RefCell<String>,
+ _closures: RefCell<Vec<Closure<dyn FnMut(JsValue)>>>,
+}
+
+#[derive(Clone)]
+struct SocketReader(Rc<Socket>);
+
+impl std::fmt::Debug for SocketReader {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SocketReader")
+ .field("buffered", &self.0.incoming.borrow().len())
+ .field("closed", &self.0.closed.get())
+ .finish()
+ }
+}
+
+impl AsyncRead for SocketReader {
+ fn poll_read(
+ self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &mut [u8],
+ ) -> Poll<std::io::Result<usize>> {
+ let mut queue = self.0.incoming.borrow_mut();
+ if queue.is_empty() {
+ if self.0.closed.get() {
+ return Poll::Ready(Ok(0));
+ }
+ *self.0.waker.borrow_mut() = Some(cx.waker().clone());
+ return Poll::Pending;
+ }
+ let n = queue.len().min(buf.len());
+ for (dst, src) in buf.iter_mut().zip(queue.drain(..n)) {
+ *dst = src;
+ }
+ Poll::Ready(Ok(n))
+ }
+}
+
+impl AsyncWrite for SocketReader {
+ fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
+ match self.0.ws.send_with_u8_array(buf) {
+ Ok(()) => Poll::Ready(Ok(buf.len())),
+ Err(e) => Poll::Ready(Err(std::io::Error::new(
+ std::io::ErrorKind::BrokenPipe,
+ format!("{e:?}"),
+ ))),
+ }
+ }
+ fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+ fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
+ let _ = self.0.ws.close();
+ Poll::Ready(Ok(()))
+ }
+}
+
+use crate::lease::Lease;
+
+struct Inner {
+ socket: 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
+ /// pushes from the first subscription on, while the page is still
+ /// 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)>>>,
+ /// The close that happened before a handler was installed.
+ closed_early: RefCell<Option<String>>,
+ pub lease: RefCell<Lease>,
+}
+
+/// A handle on the connection; clone freely.
+#[derive(Clone)]
+pub struct WsLink(Rc<Inner>);
+
+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 protocols = js_sys::Array::new();
+ protocols.push(&JsValue::from_str(SUBPROTOCOL));
+ protocols.push(&JsValue::from_str(&format!("{TOKEN_PROTOCOL_PREFIX}{token}")));
+ let ws = WebSocket::new_with_str_sequence(url, &protocols)
+ .map_err(|e| anyhow!("WebSocket::new: {e:?}"))?;
+ ws.set_binary_type(BinaryType::Arraybuffer);
+ let socket = Rc::new(Socket {
+ ws,
+ incoming: RefCell::new(VecDeque::new()),
+ waker: RefCell::new(None),
+ open: Cell::new(false),
+ closed: Cell::new(false),
+ close_reason: RefCell::new(String::new()),
+ _closures: RefCell::new(Vec::new()),
+ });
+ let wake = |s: &Rc<Socket>| {
+ if let Some(w) = s.waker.borrow_mut().take() {
+ w.wake();
+ }
+ };
+ let mut closures = Vec::new();
+ {
+ let s = socket.clone();
+ let c = Closure::<dyn FnMut(JsValue)>::new(move |ev: JsValue| {
+ let ev: MessageEvent = ev.unchecked_into();
+ if let Ok(buf) = ev.data().dyn_into::<js_sys::ArrayBuffer>() {
+ let bytes = js_sys::Uint8Array::new(&buf).to_vec();
+ s.incoming.borrow_mut().extend(bytes);
+ wake(&s);
+ }
+ });
+ socket.ws.set_onmessage(Some(c.as_ref().unchecked_ref()));
+ closures.push(c);
+ }
+ {
+ let s = socket.clone();
+ let c = Closure::<dyn FnMut(JsValue)>::new(move |_| {
+ s.open.set(true);
+ wake(&s);
+ });
+ socket.ws.set_onopen(Some(c.as_ref().unchecked_ref()));
+ closures.push(c);
+ }
+ {
+ let s = socket.clone();
+ let c = Closure::<dyn FnMut(JsValue)>::new(move |ev: JsValue| {
+ let reason = match ev.dyn_into::<web_sys::CloseEvent>() {
+ Ok(close) => format!("closed ({}{})", close.code(), {
+ let r = close.reason();
+ if r.is_empty() { String::new() } else { format!(": {r}") }
+ }),
+ Err(_) => "closed".to_string(),
+ };
+ *s.close_reason.borrow_mut() = reason;
+ s.closed.set(true);
+ wake(&s);
+ });
+ socket.ws.set_onclose(Some(c.as_ref().unchecked_ref()));
+ closures.push(c);
+ }
+ {
+ let s = socket.clone();
+ let c = Closure::<dyn FnMut(JsValue)>::new(move |_| {
+ if s.close_reason.borrow().is_empty() {
+ *s.close_reason.borrow_mut() = "connection error".to_string();
+ }
+ s.closed.set(true);
+ wake(&s);
+ });
+ socket.ws.set_onerror(Some(c.as_ref().unchecked_ref()));
+ closures.push(c);
+ }
+ *socket._closures.borrow_mut() = closures;
+
+ futures::future::poll_fn(|cx| {
+ if socket.open.get() {
+ Poll::Ready(Ok(()))
+ } else if socket.closed.get() {
+ Poll::Ready(Err(anyhow!(
+ "the server refused the connection ({}); the token may be wrong or expired",
+ socket.close_reason.borrow()
+ )))
+ } else {
+ *socket.waker.borrow_mut() = Some(cx.waker().clone());
+ Poll::Pending
+ }
+ })
+ .await?;
+ if socket.ws.protocol() != SUBPROTOCOL {
+ 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)
+ }
+
+ pub fn lease(&self) -> std::cell::Ref<'_, Lease> {
+ self.0.lease.borrow()
+ }
+
+ pub fn lease_mut(&self) -> std::cell::RefMut<'_, Lease> {
+ self.0.lease.borrow_mut()
+ }
+
+ /// Server-initiated PDUs (serial 0) go here, starting with whatever
+ /// arrived before the handler did.
+ pub fn set_push_handler(&self, handler: impl FnMut(Pdu) + 'static) {
+ *self.0.pushes.borrow_mut() = Some(Box::new(handler));
+ let pending = std::mem::take(&mut *self.0.pending_pushes.borrow_mut());
+ for pdu in pending {
+ self.push(pdu);
+ }
+ }
+
+ /// Told once, when the socket ends -- at once, if it already has.
+ pub fn set_close_handler(&self, handler: impl FnOnce(String) + 'static) {
+ if let Some(reason) = self.0.closed_early.borrow_mut().take() {
+ handler(reason);
+ return;
+ }
+ *self.0.on_close.borrow_mut() = Some(Box::new(handler));
+ }
+
+ fn send(&self, pdu: &Pdu, serial: u64) -> Result<(), LinkError> {
+ let mut bytes = Vec::new();
+ pdu.encode(&mut bytes, serial).map_err(|e| LinkError {
+ 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,
+ })
+ }
+
+ fn spawn_reader(&self) {
+ let link = self.clone();
+ wasm_bindgen_futures::spawn_local(async move {
+ let mut reader = SocketReader(link.0.socket.clone());
+ loop {
+ 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();
+ if r.is_empty() { format!("{err:#}") } else { r }
+ };
+ link.0.socket.closed.set(true);
+ // 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),
+ None => *link.0.closed_early.borrow_mut() = Some(reason),
+ }
+ return;
+ }
+ };
+ if serial == 0 {
+ match pdu {
+ Pdu::Ping(_) => {
+ let _ = link.send(&Pdu::Pong(codec::Pong {}), 0);
+ }
+ Pdu::FrontendAccessState(access) => {
+ link.0.lease.borrow_mut().apply_access(&access);
+ link.push(Pdu::FrontendAccessState(access));
+ }
+ Pdu::ClientViewportState(state) => {
+ link.0.lease.borrow_mut().apply_viewport(&state);
+ link.push(Pdu::ClientViewportState(state));
+ }
+ other => link.push(other),
+ }
+ continue;
+ }
+ let answer = link
+ .0
+ .serials
+ .borrow_mut()
+ .answer(serial, pdu, |tx, pdu| tx.send(pdu).is_ok());
+ if answer == Answer::Unmatched {
+ log::error!("the server answered serial {serial}, which nothing asked for");
+ }
+ }
+ });
+ }
+
+ fn push(&self, pdu: Pdu) {
+ // Taken out for the call so a handler that requests something (and
+ // so re-enters this link) never finds the slot borrowed. While it
+ // is out, or before one exists, pushes queue.
+ let handler = self.0.pushes.borrow_mut().take();
+ match handler {
+ Some(mut handler) => {
+ handler(pdu);
+ let mut slot = self.0.pushes.borrow_mut();
+ if slot.is_none() {
+ *slot = Some(handler);
+ }
+ drop(slot);
+ // Anything that queued while the handler was out.
+ let pending = std::mem::take(&mut *self.0.pending_pushes.borrow_mut());
+ for pdu in pending {
+ self.push(pdu);
+ }
+ }
+ None => self.0.pending_pushes.borrow_mut().push(pdu),
+ }
+ }
+
+ /// Become the tab's viewport owner, if this browser is not already.
+ /// Called before input goes out, and answered from what the server
+ /// says about ownership afterwards.
+ pub async fn ensure_owner(&self, tab_id: TabId) -> Result<bool> {
+ if self.0.lease.borrow().owns_viewport() {
+ return Ok(true);
+ }
+ let size = {
+ let lease = self.0.lease.borrow();
+ lease.reported.or(lease.canonical_size)
+ }
+ .ok_or_else(|| anyhow!("no viewport has been reported yet"))?;
+ let state = thinkterm_session::host::request(
+ self,
+ Pdu::ClaimClientViewport(codec::ClaimClientViewport {
+ tab_id,
+ viewport: codec::ClientViewport::CellGrid { size },
+ }),
+ |pdu| match pdu {
+ Pdu::ClientViewportState(state) => Ok(state),
+ other => Err(other),
+ },
+ )
+ .await?;
+ let mut lease = self.0.lease.borrow_mut();
+ lease.apply_viewport(&state);
+ Ok(lease.owns_viewport())
+ }
+}
+
+impl PduLink for WsLink {
+ type Request = LocalFuture<Result<Pdu, LinkError>>;
+
+ fn request(&self, pdu: Pdu) -> Self::Request {
+ let (tx, rx) = oneshot::channel();
+ let serial = self.0.serials.borrow_mut().register(tx);
+ let sent = self.send(&pdu, serial);
+ if sent.is_err() {
+ // Nothing went out, so nothing will answer: do not leave a
+ // waiter for a serial the server never saw.
+ self.0
+ .serials
+ .borrow_mut()
+ .answer(serial, Pdu::Invalid { ident: 0 }, |_, _| false);
+ }
+ Box::pin(async move {
+ sent?;
+ rx.await.map_err(|_| LinkError {
+ message: "the connection closed before the server answered".to_string(),
+ retryable: false,
+ })
+ })
+ }
+
+ fn is_reconnectable(&self) -> bool {
+ false
+ }
+
+ fn connection_generation(&self) -> u64 {
+ 1
+ }
+}
+
+impl PaneLink for WsLink {
+ type Prepare = LocalFuture<Result<bool>>;
+
+ fn prepare(&self, remote_tab_id: TabId) -> Self::Prepare {
+ let link = self.clone();
+ Box::pin(async move { link.ensure_owner(remote_tab_id).await })
+ }
+}
+
diff --git a/thinkterm-web/src/page.rs b/thinkterm-web/src/page.rs
new file mode 100644
index 00000000..20543138
--- /dev/null
+++ b/thinkterm-web/src/page.rs
@@ -0,0 +1,264 @@
+//! What the page calls: `start` brings a pane up on a canvas, and
+//! `color_check` is the smoke test's numeric colour assertion.
+
+use crate::app::{App, Setup};
+use crate::attach::attach;
+use crate::glyphs::GlyphCache;
+use crate::gpu::Gpu;
+use crate::host::{LocalSpawner, WebClock, WebConfig, WebEvents, WebHost};
+use crate::link::WsLink;
+use anyhow::{anyhow, Context, Result};
+use std::rc::Rc;
+use std::sync::atomic::AtomicUsize;
+use std::sync::Arc;
+use thinkterm_font_web::{Face, FontSet};
+use thinkterm_render::bitmaps::BitmapImage;
+use thinkterm_render::pipeline::GpuTexture;
+use thinkterm_render::quad::HeapQuadAllocator;
+use thinkterm_session::pane::PaneSession;
+use thinkterm_session::{Lock, SessionConfig};
+use wasm_bindgen::prelude::*;
+use wasm_bindgen::JsCast;
+
+fn js_err(e: anyhow::Error) -> JsValue {
+ JsValue::from_str(&format!("{e:#}"))
+}
+
+fn element<T: JsCast>(id: &str) -> Result<T> {
+ web_sys::window()
+ .and_then(|w| w.document())
+ .and_then(|d| d.get_element_by_id(id))
+ .ok_or_else(|| anyhow!("no element #{id}"))?
+ .dyn_into::<T>()
+ .map_err(|_| anyhow!("#{id} is not the expected element"))
+}
+
+struct ConsoleLog;
+impl log::Log for ConsoleLog {
+ fn enabled(&self, m: &log::Metadata) -> bool {
+ m.level() <= log::Level::Info
+ }
+ fn log(&self, record: &log::Record) {
+ if self.enabled(record.metadata()) {
+ web_sys::console::log_1(&JsValue::from_str(&format!(
+ "{} {}",
+ record.level(),
+ record.args()
+ )));
+ }
+ }
+ fn flush(&self) {}
+}
+static LOGGER: ConsoleLog = ConsoleLog;
+
+#[wasm_bindgen(start)]
+pub fn init() {
+ console_error_panic_hook::set_once();
+ let _ = log::set_logger(&LOGGER).map(|()| log::set_max_level(log::LevelFilter::Info));
+}
+
+/// Bring the server's active pane up on `canvas_id`. `fonts` are the face
+/// files the page fetched, base face first.
+#[wasm_bindgen]
+pub async fn start(
+ canvas_id: String,
+ textarea_id: String,
+ status_id: String,
+ url: String,
+ token: String,
+ font_names: Vec<String>,
+ fonts: Vec<js_sys::Uint8Array>,
+ size_pt: f64,
+) -> Result<(), JsValue> {
+ run(canvas_id, textarea_id, status_id, url, token, font_names, fonts, size_pt)
+ .await
+ .map_err(js_err)
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn run(
+ canvas_id: String,
+ textarea_id: String,
+ status_id: String,
+ url: String,
+ token: String,
+ font_names: Vec<String>,
+ fonts: Vec<js_sys::Uint8Array>,
+ size_pt: f64,
+) -> Result<()> {
+ let canvas: web_sys::HtmlCanvasElement = element(&canvas_id)?;
+ let textarea: web_sys::HtmlTextAreaElement = element(&textarea_id)?;
+ let status: Option<web_sys::Element> = element(&status_id).ok();
+ let set_status = |text: &str| {
+ if let Some(s) = &status {
+ s.set_text_content(Some(text));
+ }
+ };
+ let window = web_sys::window().ok_or_else(|| anyhow!("no window"))?;
+ if js_sys::Reflect::get(&window.navigator(), &JsValue::from_str("gpu"))
+ .map(|v| v.is_undefined())
+ .unwrap_or(true)
+ {
+ anyhow::bail!(
+ "this browser exposes no WebGPU here. It needs a secure context (https, or \
+ http://localhost) and a browser with WebGPU enabled"
+ );
+ }
+
+ set_status("loading fonts…");
+ 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 fonts = Rc::new(FontSet::new(faces)?);
+ let dpr = window.device_pixel_ratio();
+ let dpi = (96.0 * dpr) as u32;
+
+ set_status("connecting…");
+ let link = WsLink::connect(&url, &token).await?;
+
+ set_status("starting WebGPU…");
+ let rect = canvas.get_bounding_client_rect();
+ let dev_w = (rect.width() * dpr).floor().max(1.0) as u32;
+ let dev_h = (rect.height() * dpr).floor().max(1.0) as u32;
+ canvas.set_width(dev_w);
+ canvas.set_height(dev_h);
+ 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 (cw, ch) = (
+ glyphs.metrics.cell_size.width as u32,
+ glyphs.metrics.cell_size.height as u32,
+ );
+ // A page too small for a cell (hidden, collapsed, mid-layout) reports
+ // no viewport: it follows the pane's own size until it has a real one.
+ let size = crate::app::grid_for(dev_w, dev_h, cw, ch).map(|(cols, rows)| {
+ wezterm_term::TerminalSize {
+ rows,
+ cols,
+ pixel_width: cols * cw as usize,
+ pixel_height: rows * ch as usize,
+ dpi,
+ }
+ });
+
+ set_status("attaching…");
+ let attached = attach(&link, size).await?;
+ let (cols, rows) = match size {
+ Some(size) => (size.cols, size.rows),
+ None => (attached.dims.cols, attached.dims.viewport_rows),
+ };
+ log::info!(
+ "attached to pane {} in tab {} on {} ({}x{})",
+ attached.pane_id,
+ attached.tab_id,
+ attached.server_version,
+ cols,
+ rows
+ );
+
+ let host = Arc::new(WebHost {
+ clock: WebClock::new(),
+ spawner: LocalSpawner,
+ events: WebEvents::default(),
+ link: link.clone(),
+ config: WebConfig::default(),
+ });
+ let session = PaneSession::new(
+ Arc::clone(&host),
+ Arc::new(Lock::new(thinkterm_session::images::ImageStore::default())),
+ SessionConfig {
+ scrollback_lines: 3500,
+ local_echo_threshold_ms: Some(100),
+ overlay_lag_indicator: false,
+ },
+ attached.pane_id,
+ Arc::new(AtomicUsize::new(attached.tab_id)),
+ 0,
+ attached.dims,
+ &attached.title,
+ attached.alt_screen,
+ );
+
+ let app = App::new(Setup {
+ link: link.clone(),
+ session,
+ host: Arc::clone(&host),
+ gpu,
+ glyphs,
+ fonts,
+ canvas: canvas.clone(),
+ textarea: textarea.clone(),
+ status,
+ pane_id: attached.pane_id,
+ tab_id: attached.tab_id,
+ dpr,
+ cols,
+ rows,
+ title: attached.title.clone(),
+ });
+ host.events.set_wake(app.wake());
+ {
+ let app = Rc::clone(&app);
+ link.set_push_handler(move |pdu| app.on_push(pdu));
+ }
+ {
+ let app = Rc::clone(&app);
+ link.set_close_handler(move |reason| app.on_close(reason));
+ }
+ crate::input::install(Rc::clone(&app), &canvas, &textarea);
+ let _ = textarea.focus();
+ app.resize();
+ app.request_frame();
+ // The push and close handlers and every DOM listener hold the app.
+ Ok(())
+}
+
+/// Render a mid-grey quad and read the pixel back: linear 0.5 must come
+/// out as sRGB 188 (±1), which proves the surface is being encoded.
+#[wasm_bindgen]
+pub async fn color_check(canvas_id: String) -> Result<String, JsValue> {
+ async fn run(canvas_id: String) -> Result<String> {
+ let canvas: web_sys::HtmlCanvasElement = element(&canvas_id)?;
+ canvas.set_width(64);
+ canvas.set_height(64);
+ let mut gpu = Gpu::new(canvas, 64, 64).await?;
+ let texture = GpuTexture::new(&gpu.device, Arc::clone(&gpu.queue), 64, 64)?;
+ // A white filled box in the atlas, like UtilSprites::filled_box.
+ let mut image = thinkterm_render::bitmaps::Image::new(8, 8);
+ image.clear_rect(
+ thinkterm_render::geom::Rect::new(
+ thinkterm_render::geom::Point::new(0, 0),
+ thinkterm_render::geom::Size::new(8, 8),
+ ),
+ wezterm_color_types::SrgbaPixel::rgba(0xff, 0xff, 0xff, 0xff),
+ );
+ let surface: Rc<dyn thinkterm_render::bitmaps::Texture2d> = Rc::new(texture);
+ let mut atlas = thinkterm_render::atlas::Atlas::new(&surface)?;
+ let sprite = atlas.allocate(&image)?;
+ let mut quads = HeapQuadAllocator::default();
+ {
+ use thinkterm_render::quad::{QuadTrait, TripleLayerQuadAllocatorTrait};
+ let mut quad = quads.allocate(0)?;
+ quad.set_position(-32.0, -32.0, 32.0, 32.0);
+ quad.set_texture(sprite.texture_coords());
+ quad.set_is_background();
+ quad.set_fg_color(wezterm_color_types::LinearRgba::with_components(0.5, 0.5, 0.5, 1.0));
+ quad.set_hsv(None);
+ }
+ let mut vertices = Vec::new();
+ quads.extract_vertices(&mut vertices);
+ let gpu_texture = surface
+ .downcast_ref::<GpuTexture>()
+ .ok_or_else(|| anyhow!("atlas texture type"))?;
+ let pixel = gpu.draw_and_read_pixel(&vertices, gpu_texture, 32, 32).await?;
+ let expected = 188u8;
+ let ok = pixel[..3].iter().all(|c| (*c as i32 - expected as i32).abs() <= 1);
+ Ok(format!(
+ "{{\"pixel\":[{},{},{},{}],\"expected\":{expected},\"ok\":{ok},\"adapter\":\"{}\",\"format\":\"{:?}\"}}",
+ pixel[0], pixel[1], pixel[2], pixel[3], gpu.adapter_info.name, gpu.pipeline.target_format
+ ))
+ }
+ run(canvas_id).await.map_err(js_err)
+}
diff --git a/thinkterm-web/src/viewport.rs b/thinkterm-web/src/viewport.rs
new file mode 100644
index 00000000..695bc727
--- /dev/null
+++ b/thinkterm-web/src/viewport.rs
@@ -0,0 +1,67 @@
+//! Where the browser is looking in the pane, and the cell under a pixel.
+
+use std::ops::Range;
+use thinkterm_proto::RenderableDimensions;
+use wezterm_term::StableRowIndex;
+
+/// Rows the page shows: the last `rows` of the screen, moved up into the
+/// scrollback by `scroll_from_bottom` lines.
+pub fn visible_rows(
+ dims: &RenderableDimensions,
+ rows: usize,
+ scroll_from_bottom: usize,
+) -> Range<StableRowIndex> {
+ let bottom = dims.physical_top + dims.viewport_rows as StableRowIndex;
+ let lowest_top = dims.scrollback_top;
+ let top = (bottom - rows as StableRowIndex - scroll_from_bottom as StableRowIndex).max(lowest_top);
+ top..top + rows as StableRowIndex
+}
+
+/// How far up the view may go: everything above the screen that the
+/// server remembers.
+pub fn max_scroll(dims: &RenderableDimensions) -> usize {
+ (dims.physical_top - dims.scrollback_top).max(0) as usize
+}
+
+/// The cell under a canvas pixel (device pixels, origin top-left).
+pub fn cell_at(px: f64, py: f64, cell_width: f64, cell_height: f64) -> (usize, usize) {
+ let col = (px / cell_width).floor().max(0.0) as usize;
+ let row = (py / cell_height).floor().max(0.0) as usize;
+ (col, row)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn dims(physical_top: StableRowIndex, scrollback_top: StableRowIndex, rows: usize) -> RenderableDimensions {
+ RenderableDimensions {
+ cols: 80,
+ viewport_rows: rows,
+ scrollback_rows: (physical_top - scrollback_top) as usize + rows,
+ physical_top,
+ scrollback_top,
+ dpi: 96,
+ pixel_width: 0,
+ pixel_height: 0,
+ reverse_video: false,
+ }
+ }
+
+ #[test]
+ fn following_the_tail_shows_the_screen() {
+ assert_eq!(visible_rows(&dims(100, 0, 24), 24, 0), 100..124);
+ }
+
+ #[test]
+ fn scrolling_moves_up_and_stops_at_the_oldest_row() {
+ assert_eq!(visible_rows(&dims(100, 0, 24), 24, 10), 90..114);
+ assert_eq!(visible_rows(&dims(100, 95, 24), 24, 10), 95..119);
+ assert_eq!(max_scroll(&dims(100, 95, 24)), 5);
+ }
+
+ #[test]
+ fn a_shorter_page_still_shows_the_bottom_of_the_screen() {
+ assert_eq!(visible_rows(&dims(100, 0, 24), 10, 0), 114..124);
+ }
+}
diff --git a/thinkterm-web/www/app.js b/thinkterm-web/www/app.js
new file mode 100644
index 00000000..027bdda6
--- /dev/null
+++ b/thinkterm-web/www/app.js
@@ -0,0 +1,55 @@
+// The page: pick up the token, fetch the fonts, start the wasm client.
+import init, { start, color_check } from "./pkg/thinkterm_web.js";
+
+const status = document.getElementById("status");
+const fail = (msg) => { status.textContent = msg; status.classList.add("error"); console.error(msg); };
+
+// The token arrives once in the URL fragment -- never sent to the server,
+// never in a Referer -- and is kept for this tab only; the address bar is
+// cleaned so it is not copied or bookmarked by accident.
+const params = new URLSearchParams(location.search);
+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");
+try {
+ if (token) {
+ sessionStorage.setItem("thinkterm.token", token);
+ history.replaceState(null, "", location.pathname + location.search);
+ } else {
+ token = sessionStorage.getItem("thinkterm.token");
+ }
+} catch (e) {
+ console.warn("session storage unavailable; the token is kept for this load only", e);
+}
+const requested = Number(params.get("font"));
+const fontSize = Number.isFinite(requested) && requested >= 6 && requested <= 72 ? requested : 12;
+
+const FONTS = [
+ ["JetBrains Mono", "./fonts/JetBrainsMono-Regular.ttf"],
+ ["Symbols Nerd Font Mono", "./fonts/SymbolsNerdFontMono-Regular.ttf"],
+];
+
+async function fetchFont(url) {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`${url}: ${res.status}`);
+ return new Uint8Array(await res.arrayBuffer());
+}
+
+try {
+ await init();
+ 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") {
+ status.textContent = "COLOR " + await color_check("term");
+ } 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);
+ }
+} catch (e) {
+ fail(String(e && e.message ? e.message : e));
+}
diff --git a/thinkterm-web/www/index.html b/thinkterm-web/www/index.html
new file mode 100644
index 00000000..cb7c67ab
--- /dev/null
+++ b/thinkterm-web/www/index.html
@@ -0,0 +1,23 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>ThinkTerm</title>
+<style>
+ html, body { margin: 0; height: 100%; background: #000; color: #ccc; font: 12px system-ui, sans-serif; overflow: hidden; }
+ #term { position: absolute; inset: 0 0 22px 0; width: 100%; height: calc(100% - 22px); display: block; outline: none; }
+ #status { position: absolute; left: 0; right: 0; bottom: 0; height: 22px; line-height: 22px; padding: 0 8px; background: #111; color: #9a9a9a; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ #status.error { color: #f66; }
+ /* Focus lives here so the IME composes into a real text field; the
+ field 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; }
+</style>
+</head>
+<body>
+<canvas id="term"></canvas>
+<textarea id="kbd" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea>
+<div id="status">loading…</div>
+<script type="module" src="./app.js"></script>
+</body>
+</html>