From d619bfbcda6eb722fae386a87bccace2c49a18eb Mon Sep 17 00:00:00 2001 From: DarkSky Date: Wed, 25 Nov 2026 09:50:24 +0900 Subject: [PATCH] feat(preview): add pure-Rust offline preview kernel crate --- .github/workflows/native-playground.yml | 4 + blocksuite/crates/AGENTS.md | 3 +- blocksuite/crates/preview/AGENTS.md | 33 + blocksuite/crates/preview/BENCHMARK.md | 75 + blocksuite/crates/preview/CLAUDE.md | 1 + blocksuite/crates/preview/Cargo.toml | 66 + .../preview/scripts/gen-katex-fixture.mjs | 218 ++ blocksuite/crates/preview/src/cache.rs | 415 +++ blocksuite/crates/preview/src/engine.rs | 601 ++++ blocksuite/crates/preview/src/error.rs | 49 + blocksuite/crates/preview/src/font_pool.rs | 329 ++ blocksuite/crates/preview/src/lib.rs | 73 + blocksuite/crates/preview/src/math.rs | 1055 ++++++ blocksuite/crates/preview/src/mermaid.rs | 326 ++ blocksuite/crates/preview/src/pdf.rs | 329 ++ blocksuite/crates/preview/src/svg_raster.rs | 846 +++++ blocksuite/crates/preview/src/test_support.rs | 399 +++ blocksuite/crates/preview/src/typst_world.rs | 345 ++ blocksuite/crates/preview/src/wasm.rs | 510 +++ .../tests/fixtures/katex_v0275_metrics.json | 474 +++ packages/frontend/AGENTS.md | 2 +- packages/frontend/Cargo.lock | 2880 ++++++++++++++++- packages/frontend/Cargo.toml | 1 + packages/frontend/scripts/check-invariants.sh | 5 + 24 files changed, 8975 insertions(+), 64 deletions(-) create mode 100644 blocksuite/crates/preview/AGENTS.md create mode 100644 blocksuite/crates/preview/BENCHMARK.md create mode 100644 blocksuite/crates/preview/CLAUDE.md create mode 100644 blocksuite/crates/preview/Cargo.toml create mode 100755 blocksuite/crates/preview/scripts/gen-katex-fixture.mjs create mode 100644 blocksuite/crates/preview/src/cache.rs create mode 100644 blocksuite/crates/preview/src/engine.rs create mode 100644 blocksuite/crates/preview/src/error.rs create mode 100644 blocksuite/crates/preview/src/font_pool.rs create mode 100644 blocksuite/crates/preview/src/lib.rs create mode 100644 blocksuite/crates/preview/src/math.rs create mode 100644 blocksuite/crates/preview/src/mermaid.rs create mode 100644 blocksuite/crates/preview/src/pdf.rs create mode 100644 blocksuite/crates/preview/src/svg_raster.rs create mode 100644 blocksuite/crates/preview/src/test_support.rs create mode 100644 blocksuite/crates/preview/src/typst_world.rs create mode 100644 blocksuite/crates/preview/src/wasm.rs create mode 100644 blocksuite/crates/preview/tests/fixtures/katex_v0275_metrics.json diff --git a/.github/workflows/native-playground.yml b/.github/workflows/native-playground.yml index 9337e39342..fa620cf5ea 100644 --- a/.github/workflows/native-playground.yml +++ b/.github/workflows/native-playground.yml @@ -278,6 +278,10 @@ jobs: cargo check --locked -p ui -p playground --target wasm32-unknown-unknown cargo check --locked -p blocksuite-playground-doc --no-default-features --target wasm32-unknown-unknown cargo check --locked -p affine-store --no-default-features --target wasm32-unknown-unknown + cargo check --locked -p blocksuite-preview --no-default-features --features mermaid,wasm-worker --target wasm32-unknown-unknown + cargo check --locked -p blocksuite-preview --no-default-features --features math,wasm-worker --target wasm32-unknown-unknown + cargo check --locked -p blocksuite-preview --no-default-features --features typst,wasm-worker --target wasm32-unknown-unknown + cargo check --locked -p blocksuite-preview --no-default-features --features pdf,wasm-worker --target wasm32-unknown-unknown headless-linux-and-perf: name: Headless Linux, Web Smoke & Perf diff --git a/blocksuite/crates/AGENTS.md b/blocksuite/crates/AGENTS.md index e5ccc5a7ac..59e19be798 100644 --- a/blocksuite/crates/AGENTS.md +++ b/blocksuite/crates/AGENTS.md @@ -1,12 +1,13 @@ # Working in `blocksuite/crates/` (for agents) -`blocksuite/crates/` holds the pure BlockSuite CRDT document engine (`doc/`), the standalone playground application (`playground/`), and browser geometry/style oracle fixtures (`oracle/`). +`blocksuite/crates/` holds the pure BlockSuite CRDT document engine (`doc/`), the pure-Rust offline block preview kernel (`preview/`), the standalone playground application (`playground/`), and browser geometry/style oracle fixtures (`oracle/`). These crates belong to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`. ## Active Invariants (enforced now) ### Workspace boundaries - `blocksuite/crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies, `packages/frontend/scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `blocksuite/blocksuite/crates/doc/Cargo.toml`) built on `y-octo 0.4.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (`schema/`, 0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks (`session/`), WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:`), awareness refcounting across connections that forwards a removal (including the equal-clock live-to-`null` form `y-protocols` uses to expire a peer) once the last owner releases a client, `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. `read/` (`PageDocSession::read_page_snapshot`) is the typed read side: an ordered `PageSnapshot` tree of `BlockNode`s whose `BlockContent` covers every supported block flavour, keeps the normalized JSON of every `prop:*`, numbers `numbered` list runs, reads `prop:textAlign` and the note display modes by their BlockSuite wire values (`both` / `doc` / `edgeless`), reports blocks outside the root tree as `detached`, and reads any other flavour as `Unknown` instead of dropping it. +- `blocksuite/crates/preview` (`blocksuite-preview`): Pure-Rust offline preview kernel (`#![forbid(unsafe_code)]`, zero GUI/network/OS blocking I/O, zero host system font discovery or wall-clock calls). Provides `FontPool`, `SvgRasterizer`, `PinnedPixelCache`, `MermaidRenderer` (`merman` `resvg_safe`), pure in-memory RaTeX outline math rendering, `InMemoryTypstWorld`, `HayroPdfRenderer`, `PreviewEngine`, and `WasmPreviewEngine`. All four worker features (`mermaid`, `math`, `typst`, `pdf`) compile independently on `wasm32-unknown-unknown` with `wasm-worker`. - `blocksuite/crates/playground`: Application layer owning the shipping `PlaygroundView` (`lib.rs`, `chrome.rs`, `view_room.rs`), the tracked repository font registration (`Inter` and the four `IBM Plex Mono` faces), the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`), and the deterministic headless verification CLI (`src/bin/bs_harness/`). `theme.rs` resolves colors, typography and icons from the generated `packages/ui/tokens/tokens.rs` / `packages/ui/tokens/icons.rs` (pulled in with `include!`, never copied and never reformatted) for `PlaygroundTheme::{Light, Dark}`; `block_flow/` is the Page-mode renderer; `rich_text/` is the rich paragraph engine; `editor_session/` and `clipboard/` are the page editor; `overlays/` holds the popovers and the interactive block controls; `room_client/` is live room sync; `showcase.rs` seeds the deterministic `seed_showcase_doc` workspace shown without a room (every Page-mode block, one image blob, one remote collaborator). - `unexpected_cfgs = "deny"` is enforced workspace-wide in `Cargo.toml`; dead upstream feature gates are forbidden. - `blocksuite/crates/oracle/`: Browser-captured style and surface geometry fixtures (`style-oracle.json`, `surface-oracle.json`, `surface-baselines.json`, `surface-metrics-test.ttf`), `surface-baselines.mjs`, `surface-oracle.spec.mjs`, `extract-style-oracle.spec.ts`, and browser-mode `vitest.config.ts` (`browser.enabled: true` so `scripts/ci/vitest-node-projects.mjs` skips it). diff --git a/blocksuite/crates/preview/AGENTS.md b/blocksuite/crates/preview/AGENTS.md new file mode 100644 index 0000000000..ffba52d4fe --- /dev/null +++ b/blocksuite/crates/preview/AGENTS.md @@ -0,0 +1,33 @@ +# Working in `blocksuite/crates/preview` (for agents) + +This crate implements the pure-Rust offline block preview kernel (`blocksuite-preview`). + +## Scope and isolation + +- Keep `blocksuite-preview` free of GUI, network, and OS blocking I/O dependencies. `math`, `mermaid`, and `pdf` stay pure safe Rust with zero `cc` build scripts; on native targets only, `typst` pulls `stacker -> psm` (a small stack-probe assembly stub via `cc`, unused on `wasm32-unknown-unknown`). +- Keep `#![forbid(unsafe_code)]` enabled in `src/lib.rs`. +- Never call `load_system_fonts()`, `Instant::now()`, `SystemTime::now()`, or local wall-clock APIs in crate code. +- Pass calendar dates and timezone offsets through explicit parameters (`PreviewDate` and `timezone_offset_minutes`). +- Keep `mermaid`, `math`, `typst`, `pdf`, and `wasm-worker` Cargo features independently buildable for native and `wasm32-unknown-unknown`. + +## Module layout and limits + +- Keep every `.rs` file at or below 800 non-test lines. +- Do not use `super::super::` outside `#[cfg(test)] mod tests`. +- Do not keep `.rs` beside a `/` directory. +- Declare every `.rs` file under `src/` with a `mod` statement so no orphan file exists. +- Keep unit tests table-driven and deterministic without host system fonts. + +## Verification commands + +Always clear inherited root rustflags before running Cargo commands: + +```sh +CARGO_ENCODED_RUSTFLAGS="" cargo fmt --all -- --check +CARGO_ENCODED_RUSTFLAGS="" cargo clippy --locked --all-targets --all-features -- -D warnings +CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --all-features +CARGO_ENCODED_RUSTFLAGS="" cargo build --locked --target wasm32-unknown-unknown --release --no-default-features --features mermaid,wasm-worker +CARGO_ENCODED_RUSTFLAGS="" cargo build --locked --target wasm32-unknown-unknown --release --no-default-features --features math,wasm-worker +CARGO_ENCODED_RUSTFLAGS="" cargo build --locked --target wasm32-unknown-unknown --release --no-default-features --features typst,wasm-worker +CARGO_ENCODED_RUSTFLAGS="" cargo build --locked --target wasm32-unknown-unknown --release --no-default-features --features pdf,wasm-worker +``` diff --git a/blocksuite/crates/preview/BENCHMARK.md b/blocksuite/crates/preview/BENCHMARK.md new file mode 100644 index 0000000000..a96f209dce --- /dev/null +++ b/blocksuite/crates/preview/BENCHMARK.md @@ -0,0 +1,75 @@ +# Preview Kernel Benchmark and Engine Selection + +This document records empirical measurements for `blocksuite-preview` inside the unified client Cargo workspace (`packages/frontend/Cargo.toml`, Rust 1.98.1, `[profile.release]` with `debug = "limited"`, `lto = "thin"`, `codegen-units = 1`). + +## 1. LaTeX Math Engine Selection + +We evaluated two Rust math pipelines against `tests/fixtures/katex_v0275_metrics.json`, a 52-formula corpus captured from `katex@0.18.10` (the exact `0.27.5` `yarn.lock` version). The corpus contains 48 main formulas (subscripts, fractions, roots, matrices, sums, integrals, limits, Greek symbols, math alphabets, `\text{CJK}`, `aligned`, `cases`, `array`, `\left...\right`, accents, logic operators, and boxed color expressions) plus four AFFiNE edge cases. + +### Summary Comparison + +| Metric | RaTeX (`0.1.16`, pure `` outlines via `ratex-katex-fonts` + `FontPool`) | `mitex 0.2.4` + `InMemoryTypstWorld` (`0.15.1`) | +| --- | --- | --- | +| 48-formula main corpus pass rate | **48 / 48 (100.0%)** with registered CJK font (`45 / 48` with empty `FontPool`; 3 CJK formulas return `MissingGlyphFont`) | 40 / 48 (83.3%) with custom Typst prelude (8 formulas fail on missing Typst helpers or symbol modifiers) | +| 52-formula full corpus pass rate | **51 / 52 (98.1%)** with registered CJK font | 42 / 52 (80.8%) with custom Typst prelude | +| `katex@0.18.10` vertical metric agreement (`height_em` and `depth_em`) | **48 / 48 (100.0%)** non-CJK formulas: **43 / 48 within `<= 0.005 em`** and **5 / 48 named large-operator/accent/delimiter cases within `<= 0.085 em`** | Outer Typst page frame reports `descent_pt = 0.00` on inline fractions | +| `katex@0.18.10` horizontal width agreement (`width_em`, 48 non-CJK formulas, headless Chromium CSS + `.woff2` fonts) | **`p50 = 0.01%`**, **`p90 = 1.95%`**, **48 / 48 (100.0%) within `<= 10%`** (max `8.01%` on `nth_root`) | Not comparable to KaTeX DOM box widths | +| Release batch throughput (3 runs, `>= 300 ms` per run, AMD Ryzen 7 PRO 8845HS) | 3,072 renders (`48 x 64`) in **`421 / 443 / 419 ms`** (`~0.14 ms` per formula) | Requires Typst page layout per formula (`~0.3` to `0.4 ms` per formula in R1) | +| Host font isolation (`cargo tree -p blocksuite-preview --no-default-features --features math,wasm-worker`) | **Zero** `ratex-svg`, `ratex-font-loader`, `ratex-unicode-font`, `system-fonts`, `sys-locale`, or `fontconfig-parser` on both native and `wasm32-unknown-unknown` | Zero host font loading (`InMemoryTypstWorld` rejects empty `FontPool` with `no font could be found`) | + +### Baseline Metric Samples (`16 pt` base size) + +| Sample | RaTeX (`width / ascent / descent pt`) | `katex@0.18.10` (`height / depth em` at `16 pt`) | +| --- | --- | --- | +| `E = mc^2` | `61.44 / 13.03 / 0.00` | `0.814 / 0.000 em` (`13.03 / 0.00 pt`) | +| `x_{i,j}^{n+1} + y_k^{(2)}` | `74.06 / 16.72 / 6.61` | `1.045 / 0.413 em` (`16.72 / 6.61 pt`) | +| `\frac{a+b}{c+d}` | `23.28 / 14.08 / 6.45` | `0.880 / 0.403 em` (`14.08 / 6.45 pt`) | + +### Selection Decision and Edge-Case Ledger + +RaTeX wins on corpus coverage, tight KaTeX box-metric parity (`<= 0.005 em` on 43 of 48 non-CJK formulas and `<= 0.085 em` on all 48), pure `` outline determinism (zero `` elements), latency, and Wasm bundle size. We ship RaTeX directly from `ratex-layout::to_display_list` plus `ratex-katex-fonts` and explicit `FontPool` outlines as the production `math` backend, and keep `InMemoryTypstWorld` under the separate `typst` feature for native Typst code blocks. + +| Edge Case | RaTeX | `mitex` + Typst | Notes | +| --- | --- | --- | --- | +| `\def\arraystretch{1.5}` + `\hdashline` array | Pass | Fail (`unknown command: \arraystretch`) | Matches AFFiNE `inline.spec.ts` fixture. | +| `\vcenter{\hbox{...}}` | Pass | Fail (`unknown command: \vcenter`) | Matches AFFiNE `inline.spec.ts` highlight fixture. | +| `\newcommand{\myvec}[1]{\mathbf{#1}}\myvec{v}` | Pass | Pass | Custom macro definitions work in RaTeX. | +| `\newcommand{\R}{\mathbb{R}}\R^n` | Error (`redefine \R`) | Pass | Fails because `\R` is a built-in RaTeX macro. Authors must use `\renewcommand{\R}` or a distinct macro name. | + +## 2. Mermaid 2x RGBA Footprint and Cache Calibration + +All nine diagram families ran through `merman 0.11.0` with `SvgPipeline::resvg_safe()` (zero `` elements) and explicit `PreviewDate` plus timezone offset injection (`try_with_fixed_local_offset_minutes` and `try_with_fixed_today_at_local_midnight`), then rasterized at `2.0x` scale via `SvgRasterizer`. + +| Diagram Family | 2x Pixel Dimensions | RGBA8 Bytes | Size (KiB) | +| --- | --- | --- | --- | +| `flowchart` | `720 x 836` | 2,407,680 | 2,351.2 | +| `flowchart_cjk` | `1104 x 122` | 538,752 | 526.1 | +| `sequence` (CJK) | `900 x 562` | 2,023,200 | 1,975.8 | +| `class` | `384 x 622` | 955,392 | 933.0 | +| `state` | `304 x 874` | 1,062,784 | 1,037.9 | +| `er` | `270 x 922` | 995,760 | 972.4 | +| `gantt` (CJK) | `1600 x 296` | 1,894,400 | 1,850.0 | +| `pie` (CJK) | `1160 x 900` | 4,176,000 | 4,078.1 | +| `gitgraph` | `541 x 329` | 711,956 | 695.3 | + +The nine-family mean is 1,602 KiB (1.56 MiB) and the peak is 4,078 KiB (3.98 MiB). Setting `CacheLimits::MOBILE_DEFAULT` to `max_entries = 64` and `max_bytes = 32 MiB` holds about 20 full-size 2x Mermaid diagrams or 64 smaller formula tiles while `PinnedPixelCache` protects all visible on-screen entries from eviction and skips oversized unpinned entries without wiping live cache contents. + +## 3. Standalone WebAssembly Worker Sizes + +Each preview capability builds independently under the unified `packages/frontend/Cargo.toml` workspace for `wasm32-unknown-unknown --release` with `--no-default-features --features ,wasm-worker` so the main Web application pays zero upfront preview bundle cost. + +The unified workspace `[profile.release]` sets `debug = "limited"`, `lto = "thin"`, and `codegen-units = 1`, which preserves DWARF custom sections in raw `.wasm` output. Production web packaging strips custom debug sections via `wasm-bindgen` and `wasm-opt` (in R1 stripped standalone builds with `opt-level = "s"` and `strip = true`, `gzip -9` sizes were 1.15 MiB for `math`, 1.77 MiB for `pdf`, 5.05 MiB for `mermaid`, and 7.70 MiB for `typst`). + +| Worker Feature | Unified Workspace Raw `.wasm` Bytes | Raw Size (`debug = "limited"`) | Unified Workspace `gzip -9` Bytes | `gzip -9` Size | +| --- | --- | --- | --- | --- | +| `math,wasm-worker` (RaTeX + outlines) | 30,270,736 | 28.87 MiB | 7,760,539 | 7.40 MiB | +| `pdf,wasm-worker` (`hayro 0.9.0`) | 51,300,697 | 48.92 MiB | 11,484,798 | 10.95 MiB | +| `typst,wasm-worker` (`typst 0.15.1`) | 175,521,113 | 167.39 MiB | 37,523,574 | 35.79 MiB | +| `mermaid,wasm-worker` (`merman 0.11.0`) | 188,055,986 | 179.34 MiB | 40,001,096 | 38.15 MiB | + +## 4. Native Build and Toolchain Audit + +- `math`, `mermaid`, and `pdf` are pure safe Rust with zero `cc` build scripts and zero native C or C++ libraries. +- `typst` depends on `stacker` -> `psm`, which compiles a small stack-probe assembly stub via `cc` on native targets (`wasm32-unknown-unknown` builds do not invoke `psm`). +- `blocksuite-preview` itself enforces `#![forbid(unsafe_code)]`, zero wall-clock calls, zero host font discovery, strict CSS color validation with XML attribute escaping, and zero external SVG `` filesystem or network resolution. +- Across the Wasm Worker boundary, Mermaid and Typst copy cached RGBA pixels once from the shared `Arc` (or move them via `Arc::try_unwrap` when unshared), while `take_pixels(&mut self)` eliminates a second clone on JS property access. diff --git a/blocksuite/crates/preview/CLAUDE.md b/blocksuite/crates/preview/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/blocksuite/crates/preview/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/blocksuite/crates/preview/Cargo.toml b/blocksuite/crates/preview/Cargo.toml new file mode 100644 index 0000000000..349d31409a --- /dev/null +++ b/blocksuite/crates/preview/Cargo.toml @@ -0,0 +1,66 @@ +[package] +name = "blocksuite-preview" +version.workspace = true +edition.workspace = true +publish.workspace = true +license.workspace = true +workspace = "../../../packages/frontend" + +[lib] +crate-type = ["rlib", "cdylib"] + +[features] +default = ["mermaid", "math", "typst", "pdf"] +mermaid = ["dep:merman"] +math = [ + "dep:ratex-parser", + "dep:ratex-layout", + "dep:ratex-katex-fonts", + "dep:ratex-types", +] +typst = [ + "dep:comemo", + "dep:typst", + "dep:typst-layout", + "dep:typst-svg", +] +pdf = ["dep:hayro"] +wasm-worker = ["dep:wasm-bindgen"] + +[dependencies] +resvg = { version = "0.46.0", default-features = false, features = ["text", "raster-images"] } +usvg = { version = "0.46.0", default-features = false, features = ["text"] } +sha2 = "0.10" +thiserror.workspace = true +ttf-parser.workspace = true + +# Mermaid +merman = { version = "0.11.0", optional = true } + +# LaTeX Math (pure in-memory RaTeX parser/layout + embedded KaTeX TTF bytes, zero ratex-unicode-font) +ratex-parser = { version = "0.1.16", optional = true } +ratex-layout = { version = "0.1.16", optional = true } +ratex-katex-fonts = { version = "0.1.16", optional = true } +ratex-types = { version = "0.1.16", optional = true } + +# Typst native block compiler +comemo = { version = "0.5", optional = true } +typst = { version = "0.15.1", optional = true } +typst-layout = { version = "0.15.1", optional = true } +typst-svg = { version = "0.15.1", optional = true } + +# PDF +hayro = { version = "0.9.0", optional = true } + +# Wasm worker entry points +wasm-bindgen = { workspace = true, optional = true } + +[dev-dependencies] +mitex = "0.2.4" +roxmltree = "0.21" +serde.workspace = true +serde_json.workspace = true +typst-assets = { version = "0.15.1", features = ["fonts"] } + +[lints] +workspace = true diff --git a/blocksuite/crates/preview/scripts/gen-katex-fixture.mjs b/blocksuite/crates/preview/scripts/gen-katex-fixture.mjs new file mode 100755 index 0000000000..f39875b107 --- /dev/null +++ b/blocksuite/crates/preview/scripts/gen-katex-fixture.mjs @@ -0,0 +1,218 @@ +#!/usr/bin/env node +/** + * Regenerates `tests/fixtures/katex_v0275_metrics.json` from the repository's + * pinned `katex` package (0.18.10 in 0.27.5 yarn.lock) using real headless + * Chromium with `katex.min.css` and bundled `.woff2` fonts for `width_em` + * measurements alongside `katex.__renderToDomTree` vertical box metrics. + * + * Usage: + * node blocksuite/crates/preview/scripts/gen-katex-fixture.mjs + * + * Optional env vars: + * KATEX_MODULE_PATH Path to a `katex` package directory + * PLAYWRIGHT_MODULE_PATH Path to `playwright` or `playwright-core` + * CHROMIUM_EXECUTABLE_PATH Path to an existing Chrome/Chromium binary + */ +import fs from 'node:fs'; +import http from 'node:http'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const fixturePath = path.resolve( + __dirname, + '../tests/fixtures/katex_v0275_metrics.json' +); +const require = createRequire(import.meta.url); + +const katexPkgPath = process.env.KATEX_MODULE_PATH + ? path.resolve(process.env.KATEX_MODULE_PATH) + : path.dirname(require.resolve('katex/package.json')); +const katex = require(katexPkgPath); +const katexDistDir = path.join(katexPkgPath, 'dist'); + +function loadPlaywright() { + if (process.env.PLAYWRIGHT_MODULE_PATH) { + return require(process.env.PLAYWRIGHT_MODULE_PATH); + } + for (const mod of ['playwright', 'playwright-core']) { + try { + return require(mod); + } catch { + // Try next candidate. + } + } + throw new Error( + 'Playwright is required (set PLAYWRIGHT_MODULE_PATH or install in workspace).' + ); +} + +function resolveChromiumExecutable() { + const candidates = [ + process.env.CHROMIUM_EXECUTABLE_PATH, + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/Applications/Chromium.app/Contents/MacOS/Chromium', + '/usr/bin/chromium', + '/usr/bin/chromium-browser', + '/usr/bin/google-chrome', + ].filter(Boolean); + for (const candidate of candidates) { + if (fs.existsSync(candidate)) { + return candidate; + } + } + return undefined; +} + +function contentTypeFor(filePath) { + if (filePath.endsWith('.css')) return 'text/css; charset=utf-8'; + if (filePath.endsWith('.js')) return 'application/javascript; charset=utf-8'; + if (filePath.endsWith('.woff2')) return 'font/woff2'; + if (filePath.endsWith('.woff')) return 'font/woff'; + if (filePath.endsWith('.ttf')) return 'font/ttf'; + return 'text/html; charset=utf-8'; +} + +function startStaticServer(rootDir) { + return new Promise(resolve => { + const server = http.createServer((req, res) => { + const reqPath = (req.url || '/').split('?')[0]; + if (reqPath === '/' || reqPath === '/index.html') { + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(` + + + + + + + +
+`); + return; + } + const safeRel = path.normalize(reqPath).replace(/^(\.\.[/\\])+/, ''); + const absPath = path.join(rootDir, safeRel); + if (!absPath.startsWith(rootDir) || !fs.existsSync(absPath)) { + res.writeHead(404); + res.end('Not found'); + return; + } + res.writeHead(200, { 'Content-Type': contentTypeFor(absPath) }); + fs.createReadStream(absPath).pipe(res); + }); + server.listen(0, '127.0.0.1', () => { + const addr = server.address(); + resolve({ server, port: addr.port }); + }); + }); +} + +const existing = JSON.parse(fs.readFileSync(fixturePath, 'utf8')); +const { chromium } = loadPlaywright(); +const { server, port } = await startStaticServer(katexDistDir); +const executablePath = resolveChromiumExecutable(); +const browser = await chromium.launch({ + headless: true, + ...(executablePath ? { executablePath } : {}), +}); + +try { + const page = await browser.newPage({ + viewport: { width: 4200, height: 1200 }, + }); + await page.goto(`http://127.0.0.1:${port}/`, { waitUntil: 'networkidle' }); + + // Measure every formula in real Chromium with KaTeX CSS + .woff2 fonts at 64px. + const browserWidths = await page.evaluate(async items => { + const stage = document.getElementById('stage'); + const nodes = []; + for (const item of items) { + const wrapper = document.createElement('div'); + wrapper.className = item.display_mode ? 'probe-display' : 'probe-inline'; + stage.appendChild(wrapper); + try { + window.katex.render(item.latex, wrapper, { + displayMode: item.display_mode, + strict: false, + throwOnError: true, + }); + nodes.push({ name: item.name, wrapper, ok: true }); + } catch { + nodes.push({ name: item.name, wrapper, ok: false }); + } + } + await document.fonts.ready; + const loadedFamilies = [...document.fonts] + .filter(f => f.status === 'loaded') + .map(f => f.family); + if (!loadedFamilies.some(f => f.includes('KaTeX_Main'))) { + throw new Error( + `KaTeX_Main font did not load in Chromium: ${JSON.stringify(loadedFamilies)}` + ); + } + + const widths = {}; + for (const entry of nodes) { + if (!entry.ok) { + widths[entry.name] = 0; + continue; + } + const katexEl = entry.wrapper.querySelector('.katex') || entry.wrapper; + const target = entry.wrapper.querySelector('.katex-html') || katexEl; + const fontSizePx = parseFloat(getComputedStyle(katexEl).fontSize) || 64; + const rect = target.getBoundingClientRect(); + widths[entry.name] = Number((rect.width / fontSizePx).toFixed(6)); + } + return widths; + }, existing.formulas); + + const formulas = existing.formulas.map(item => { + try { + const dom = katex.__renderToDomTree(item.latex, { + displayMode: item.display_mode, + strict: false, + throwOnError: true, + }); + return { + name: item.name, + latex: item.latex, + display_mode: item.display_mode, + katex_ok: true, + height_em: Number(dom.height.toFixed(6)), + depth_em: Number(dom.depth.toFixed(6)), + width_em: browserWidths[item.name] ?? 0, + }; + } catch { + return { + name: item.name, + latex: item.latex, + display_mode: item.display_mode, + katex_ok: false, + height_em: 0, + depth_em: 0, + width_em: 0, + }; + } + }); + + const out = { + katex_version: katex.version, + count: formulas.length, + formulas, + }; + fs.writeFileSync(fixturePath, `${JSON.stringify(out, null, 2)}\n`); + console.log( + `Wrote ${formulas.length} Chromium-measured formulas from katex@${katex.version} to ${fixturePath}` + ); +} finally { + await browser.close(); + server.close(); +} diff --git a/blocksuite/crates/preview/src/cache.rs b/blocksuite/crates/preview/src/cache.rs new file mode 100644 index 0000000000..39441d9ae1 --- /dev/null +++ b/blocksuite/crates/preview/src/cache.rs @@ -0,0 +1,415 @@ +use std::collections::HashMap; +use std::hash::Hash; +use std::sync::Arc; + +use crate::svg_raster::RgbaImageBuffer; + +/// Dual-threshold cache limits for rasterized preview images. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CacheLimits { + /// Maximum number of unpinned-evictable entries retained in cache. + pub max_entries: usize, + /// Maximum total RGBA pixel bytes (`width * height * 4`) retained in cache. + pub max_bytes: usize, +} + +impl CacheLimits { + /// Default mobile preview cache budget calibrated from 2x Mermaid and formula measurements. + /// + /// Allows up to 64 preview tiles or 32 MiB of RGBA8 pixels before evicting + /// off-screen (`pin_count == 0`) entries. + pub const MOBILE_DEFAULT: Self = Self { + max_entries: 64, + max_bytes: 32 * 1024 * 1024, + }; +} + +impl Default for CacheLimits { + fn default() -> Self { + Self::MOBILE_DEFAULT + } +} + +/// Summary of entries evicted during a cache insertion or pin release. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct EvictionReport { + /// Number of entries removed from the cache. + pub evicted_entries: usize, + /// Total pixel bytes freed by the eviction pass. + pub evicted_bytes: usize, +} + +struct CacheEntry { + image: Arc, + bytes: usize, + pin_count: usize, + last_touch: u64, +} + +/// Dual-limit (entry count + pixel bytes) LRU cache with on-screen pin protection. +/// +/// Entries with `pin_count > 0` are never evicted, preventing visible preview +/// flicker during scrolling when many diagrams share a viewport. When limits +/// are exceeded, the cache evicts the least-recently-used entry with +/// `pin_count == 0`. +pub struct PinnedPixelCache { + limits: CacheLimits, + entries: HashMap, + total_bytes: usize, + pinned_entries: usize, + pinned_bytes: usize, + clock: u64, +} + +impl PinnedPixelCache { + /// Creates an empty cache with the given entry and byte limits. + pub fn new(limits: CacheLimits) -> Self { + Self { + limits, + entries: HashMap::new(), + total_bytes: 0, + pinned_entries: 0, + pinned_bytes: 0, + clock: 0, + } + } + + /// Returns the configured cache limits. + pub fn limits(&self) -> CacheLimits { + self.limits + } + + /// Returns the number of cached entries (pinned and unpinned). + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Returns true when the cache contains no entries. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Returns the total pixel bytes stored across all entries. + pub fn total_bytes(&self) -> usize { + self.total_bytes + } + + /// Returns the number of currently pinned entries. + pub fn pinned_count(&self) -> usize { + self.pinned_entries + } + + /// Returns the total pixel bytes held by currently pinned entries. + pub fn pinned_bytes(&self) -> usize { + self.pinned_bytes + } + + /// Returns the current pin count for `key`. + pub fn pin_count(&self, key: &K) -> usize { + self.entries.get(key).map_or(0, |entry| entry.pin_count) + } + + /// Returns true when `key` exists in cache and has `pin_count > 0`. + pub fn is_pinned(&self, key: &K) -> bool { + self.pin_count(key) > 0 + } + + /// Looks up `key` and marks it most-recently-used. + pub fn get(&mut self, key: &K) -> Option> { + let tick = self.next_tick(); + let entry = self.entries.get_mut(key)?; + entry.last_touch = tick; + Some(Arc::clone(&entry.image)) + } + + /// Inserts or replaces `key` and evicts unpinned LRU entries if limits are exceeded. + /// + /// Replacing an existing entry preserves its existing `pin_count`. + pub fn insert(&mut self, key: K, image: Arc) -> EvictionReport { + self.insert_internal(key, image, false) + } + + /// Inserts or replaces `key` and increments its pin count atomically before eviction. + pub fn insert_pinned(&mut self, key: K, image: Arc) -> EvictionReport { + self.insert_internal(key, image, true) + } + + /// Increments the on-screen pin count for `key` and marks it recently used. + /// + /// Returns false if `key` is not in the cache. + pub fn acquire_pin(&mut self, key: &K) -> bool { + let tick = self.next_tick(); + let Some(entry) = self.entries.get_mut(key) else { + return false; + }; + if entry.pin_count == 0 { + self.pinned_entries += 1; + self.pinned_bytes += entry.bytes; + } + entry.pin_count += 1; + entry.last_touch = tick; + true + } + + /// Decrements the on-screen pin count for `key` and evicts excess unpinned entries. + /// + /// Returns false if `key` is not in the cache or was not pinned. + pub fn release_pin(&mut self, key: &K) -> bool { + let Some(entry) = self.entries.get_mut(key) else { + return false; + }; + if entry.pin_count == 0 { + return false; + } + entry.pin_count -= 1; + if entry.pin_count == 0 { + self.pinned_entries = self.pinned_entries.saturating_sub(1); + self.pinned_bytes = self.pinned_bytes.saturating_sub(entry.bytes); + self.evict_if_needed(); + } + true + } + + /// Removes all entries (including pinned entries) and resets byte accounting. + pub fn clear(&mut self) { + self.entries.clear(); + self.total_bytes = 0; + self.pinned_entries = 0; + self.pinned_bytes = 0; + } + + /// Removes all unpinned entries while keeping pinned entries intact. + pub fn clear_unpinned(&mut self) -> EvictionReport { + let unpinned_keys: Vec = self + .entries + .iter() + .filter(|(_, entry)| entry.pin_count == 0) + .map(|(key, _)| key.clone()) + .collect(); + + let mut report = EvictionReport::default(); + for key in unpinned_keys { + if let Some(removed) = self.entries.remove(&key) { + self.total_bytes = self.total_bytes.saturating_sub(removed.bytes); + report.evicted_entries += 1; + report.evicted_bytes += removed.bytes; + } + } + report + } + + fn insert_internal( + &mut self, + key: K, + image: Arc, + pin: bool, + ) -> EvictionReport { + let bytes = image.byte_len(); + let existing_is_pinned = self + .entries + .get(&key) + .is_some_and(|entry| entry.pin_count > 0); + // Skip unpinned entries that cannot fit in the remaining unpinned budget + // without evicting live cache items and then immediately evicting themselves. + if !pin + && !existing_is_pinned + && (self.limits.max_entries == 0 + || self.pinned_entries >= self.limits.max_entries + || self.pinned_bytes.saturating_add(bytes) > self.limits.max_bytes) + { + return EvictionReport::default(); + } + let tick = self.next_tick(); + + if let Some(existing) = self.entries.get_mut(&key) { + self.total_bytes = self.total_bytes.saturating_sub(existing.bytes) + bytes; + if existing.pin_count > 0 { + self.pinned_bytes = self.pinned_bytes.saturating_sub(existing.bytes) + bytes; + } else if pin { + self.pinned_entries += 1; + self.pinned_bytes += bytes; + } + if pin { + existing.pin_count += 1; + } + existing.image = image; + existing.bytes = bytes; + existing.last_touch = tick; + } else { + let pin_count = usize::from(pin); + if pin { + self.pinned_entries += 1; + self.pinned_bytes += bytes; + } + self.total_bytes += bytes; + self.entries.insert( + key, + CacheEntry { + image, + bytes, + pin_count, + last_touch: tick, + }, + ); + } + + self.evict_if_needed() + } + + fn evict_if_needed(&mut self) -> EvictionReport { + let mut report = EvictionReport::default(); + + while self.entries.len() > self.limits.max_entries + || self.total_bytes > self.limits.max_bytes + { + let victim = self + .entries + .iter() + .filter(|(_, entry)| entry.pin_count == 0) + .min_by_key(|(_, entry)| entry.last_touch) + .map(|(key, _)| key.clone()); + + let Some(victim_key) = victim else { + break; + }; + + if let Some(removed) = self.entries.remove(&victim_key) { + self.total_bytes = self.total_bytes.saturating_sub(removed.bytes); + report.evicted_entries += 1; + report.evicted_bytes += removed.bytes; + } + } + + report + } + + fn next_tick(&mut self) -> u64 { + self.clock = self.clock.wrapping_add(1); + self.clock + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dummy_buffer(width: u32, height: u32) -> Arc { + Arc::new(RgbaImageBuffer { + width_px: width, + height_px: height, + logical_width: width as f32, + logical_height: height as f32, + pixels: vec![0u8; (width * height * 4) as usize], + }) + } + + #[test] + fn enforces_entry_and_byte_limits_with_lru_order() { + let mut cache = PinnedPixelCache::new(CacheLimits { + max_entries: 2, + max_bytes: 1024, + }); + cache.insert("a", dummy_buffer(4, 4)); // 64 bytes + cache.insert("b", dummy_buffer(4, 4)); // 64 bytes + // Touch "a" so "b" becomes least recently used. + assert!(cache.get(&"a").is_some()); + let report = cache.insert("c", dummy_buffer(4, 4)); + assert_eq!(report.evicted_entries, 1); + assert_eq!(report.evicted_bytes, 64); + assert!(cache.get(&"b").is_none()); + assert!(cache.get(&"a").is_some()); + assert!(cache.get(&"c").is_some()); + + // Now trigger byte limit eviction (max_bytes = 128). + let mut byte_cache = PinnedPixelCache::new(CacheLimits { + max_entries: 10, + max_bytes: 128, + }); + byte_cache.insert("x", dummy_buffer(4, 4)); // 64 + byte_cache.insert("y", dummy_buffer(4, 4)); // 64 -> total 128 + let report = byte_cache.insert("z", dummy_buffer(4, 8)); // 128 -> evicts x and y + assert_eq!(report.evicted_entries, 2); + assert_eq!(byte_cache.len(), 1); + assert_eq!(byte_cache.total_bytes(), 128); + assert!(byte_cache.get(&"z").is_some()); + } + + #[test] + fn pinned_entries_are_never_evicted_until_released() { + let mut cache = PinnedPixelCache::new(CacheLimits { + max_entries: 2, + max_bytes: 128, + }); + cache.insert_pinned("pinned-1", dummy_buffer(4, 4)); // 64 + assert!(cache.acquire_pin(&"pinned-1")); // pin_count = 2 + cache.insert_pinned("pinned-2", dummy_buffer(4, 4)); // 64 + cache.insert("unpinned", dummy_buffer(4, 4)); // exceeds both limits + + // Unpinned entry is evicted immediately, both pinned entries stay. + assert_eq!(cache.len(), 2); + assert_eq!(cache.pinned_count(), 2); + assert!(cache.is_pinned(&"pinned-1")); + assert!(cache.is_pinned(&"pinned-2")); + + // Inserting a third pinned entry exceeds limits without evicting any pinned item. + cache.insert_pinned("pinned-3", dummy_buffer(4, 4)); + assert_eq!(cache.len(), 3); + assert_eq!(cache.total_bytes(), 192); + + // First release on pinned-1 keeps it pinned (refcount 2 -> 1). + assert!(cache.release_pin(&"pinned-1")); + assert_eq!(cache.pin_count(&"pinned-1"), 1); + assert_eq!(cache.len(), 3); + + // Second release drops refcount to 0 and triggers immediate eviction. + assert!(cache.release_pin(&"pinned-1")); + assert_eq!(cache.len(), 2); + assert_eq!(cache.total_bytes(), 128); + assert!(cache.get(&"pinned-1").is_none()); + } + + #[test] + fn oversized_unpinned_entry_does_not_wipe_existing_cache() { + let mut cache = PinnedPixelCache::new(CacheLimits { + max_entries: 4, + max_bytes: 128, + }); + cache.insert("keep-1", dummy_buffer(4, 4)); // 64 bytes + cache.insert("keep-2", dummy_buffer(4, 4)); // 64 bytes + + // Unpinned 256-byte image exceeds max_bytes (128); must skip without evicting live entries. + let report = cache.insert("too-big", dummy_buffer(8, 8)); + assert_eq!(report, EvictionReport::default()); + assert_eq!(cache.len(), 2); + assert_eq!(cache.total_bytes(), 128); + assert!(cache.get(&"keep-1").is_some()); + assert!(cache.get(&"keep-2").is_some()); + assert!(cache.get(&"too-big").is_none()); + } + + #[test] + fn remaining_budget_after_pinned_entries_protects_live_unpinned_entries() { + let mut cache = PinnedPixelCache::new(CacheLimits { + max_entries: 4, + max_bytes: 1000, + }); + cache.insert_pinned("pinned", dummy_buffer(20, 10)); // 800 bytes pinned + cache.insert("A", dummy_buffer(10, 5)); // 200 bytes unpinned -> total 1000 bytes + + // Remaining unpinned budget is 200 B; inserting a 300 B unpinned entry must skip + // rather than evicting live entry A and then immediately evicting itself. + let report = cache.insert("new", dummy_buffer(15, 5)); // 300 bytes + assert_eq!(report, EvictionReport::default()); + assert!(cache.get(&"new").is_none()); + assert!(cache.get(&"A").is_some()); + assert!(cache.is_pinned(&"pinned")); + assert_eq!(cache.len(), 2); + assert_eq!(cache.total_bytes(), 1000); + + // Updating an already-pinned key via `insert` must still update its buffer. + let updated_pinned = dummy_buffer(20, 10); + let _ = cache.insert("pinned", Arc::clone(&updated_pinned)); + assert!(Arc::ptr_eq(&cache.get(&"pinned").unwrap(), &updated_pinned)); + assert!(cache.is_pinned(&"pinned")); + } +} diff --git a/blocksuite/crates/preview/src/engine.rs b/blocksuite/crates/preview/src/engine.rs new file mode 100644 index 0000000000..f917b5cbee --- /dev/null +++ b/blocksuite/crates/preview/src/engine.rs @@ -0,0 +1,601 @@ +#[cfg(feature = "pdf")] +use std::collections::HashMap; +#[cfg(any(feature = "mermaid", feature = "typst"))] +use std::sync::Arc; + +#[cfg(feature = "typst")] +use sha2::{Digest, Sha256}; + +use crate::cache::{CacheLimits, PinnedPixelCache}; +use crate::error::PreviewError; +use crate::font_pool::FontPool; +#[cfg(any(feature = "mermaid", feature = "math", feature = "typst"))] +use crate::svg_raster::RasterOptions; +#[cfg(any(feature = "mermaid", feature = "typst", feature = "pdf"))] +use crate::svg_raster::RgbaImageBuffer; +use crate::svg_raster::SvgRasterizer; + +#[cfg(feature = "math")] +use crate::math::{MathRenderOptions, MathRgbaOutput, MathSvgOutput, render_latex_svg}; +#[cfg(feature = "mermaid")] +use crate::mermaid::{MermaidOptions, MermaidRenderer}; +#[cfg(feature = "pdf")] +use crate::pdf::{HayroPdfRenderer, PdfPageRenderer, PdfRenderRequest}; +#[cfg(feature = "typst")] +use crate::typst_world::{InMemoryTypstWorld, TypstSvgOutput}; + +#[cfg(feature = "typst")] +struct CachedTypstDocument { + source_hash: [u8; 32], + today: crate::PreviewDate, + font_generation: u64, + inputs_generation: u64, + document: Arc, +} + +/// Stateful offline preview engine retaining registered fonts, pixel cache, +/// in-memory Typst files/packages, and parsed PDF handles across calls. +pub struct PreviewEngine { + font_pool: FontPool, + font_generation: u64, + rasterizer: SvgRasterizer, + cache: PinnedPixelCache, + #[cfg(feature = "typst")] + typst_files: Vec<(String, Vec)>, + #[cfg(feature = "typst")] + typst_package_files: Vec<(String, String, String, String, Vec)>, + #[cfg(feature = "typst")] + typst_inputs_generation: u64, + #[cfg(feature = "typst")] + typst_world: Option, + #[cfg(feature = "typst")] + last_typst_doc: Option, + #[cfg(feature = "pdf")] + pdf_docs: HashMap, + #[cfg(feature = "pdf")] + next_pdf_handle: u32, +} + +impl Default for PreviewEngine { + fn default() -> Self { + Self::new(CacheLimits::MOBILE_DEFAULT) + } +} + +impl PreviewEngine { + /// Creates an empty preview engine with the given pixel cache limits. + pub fn new(limits: CacheLimits) -> Self { + let font_pool = FontPool::new(); + let rasterizer = SvgRasterizer::new(&font_pool); + Self { + font_pool, + font_generation: 0, + rasterizer, + cache: PinnedPixelCache::new(limits), + #[cfg(feature = "typst")] + typst_files: Vec::new(), + #[cfg(feature = "typst")] + typst_package_files: Vec::new(), + #[cfg(feature = "typst")] + typst_inputs_generation: 0, + #[cfg(feature = "typst")] + typst_world: None, + #[cfg(feature = "typst")] + last_typst_doc: None, + #[cfg(feature = "pdf")] + pdf_docs: HashMap::new(), + #[cfg(feature = "pdf")] + next_pdf_handle: 1, + } + } + + /// Registers a font byte buffer into the persistent [`FontPool`]. + /// + /// Increments `font_generation` and clears cached pixel buffers from the + /// previous generation so stale bitmaps are freed immediately. + pub fn register_font(&mut self, bytes: impl Into>) -> Result { + let added = self.font_pool.register_font_bytes(bytes)?; + self.font_generation = self.font_generation.wrapping_add(1); + self.cache.clear(); + self.rasterizer = SvgRasterizer::new(&self.font_pool); + #[cfg(feature = "typst")] + { + self.typst_world = None; + self.last_typst_doc = None; + } + Ok(added) + } + + /// Returns the monotonically increasing font registration generation counter. + pub fn font_generation(&self) -> u64 { + self.font_generation + } + + /// Returns the total number of registered font faces. + pub fn font_face_count(&self) -> usize { + self.font_pool.face_count() + } + + /// Returns a shared reference to the engine's [`FontPool`]. + pub fn font_pool(&self) -> &FontPool { + &self.font_pool + } + + /// Returns a mutable reference to the engine's [`PinnedPixelCache`]. + pub fn cache_mut(&mut self) -> &mut PinnedPixelCache { + &mut self.cache + } + + /// Registers an in-memory Typst file accessible via `#include` or `#import`. + #[cfg(feature = "typst")] + pub fn register_typst_file( + &mut self, + path: impl Into, + bytes: impl Into>, + ) -> Result<(), PreviewError> { + let path_str = path.into(); + let data = bytes.into(); + if let Some(world) = self.typst_world.as_mut() { + world.insert_file(&path_str, data.clone())?; + } + self.typst_files.push((path_str, data)); + self.typst_inputs_generation = self.typst_inputs_generation.wrapping_add(1); + self.last_typst_doc = None; + Ok(()) + } + + /// Registers an in-memory Typst package file (for example `@preview/demo:0.1.0`). + #[cfg(feature = "typst")] + pub fn register_typst_package_file( + &mut self, + namespace: impl Into, + name: impl Into, + version: impl Into, + path: impl Into, + bytes: impl Into>, + ) -> Result<(), PreviewError> { + let ns = namespace.into(); + let pkg_name = name.into(); + let ver = version.into(); + let file_path = path.into(); + let data = bytes.into(); + let spec = parse_package_spec(&ns, &pkg_name, &ver)?; + if let Some(world) = self.typst_world.as_mut() { + world.insert_package_file(spec, &file_path, data.clone())?; + } + self.typst_package_files + .push((ns, pkg_name, ver, file_path, data)); + self.typst_inputs_generation = self.typst_inputs_generation.wrapping_add(1); + self.last_typst_doc = None; + Ok(()) + } + + /// Renders a Mermaid diagram to `resvg`-safe SVG. + #[cfg(feature = "mermaid")] + pub fn render_mermaid_svg( + &self, + source: &str, + options: &MermaidOptions, + ) -> Result { + MermaidRenderer::new().render_svg(source, options) + } + + /// Renders a Mermaid diagram to RGBA8 pixels using registered fonts and pixel cache. + /// + /// Fails with [`PreviewError::MissingGlyphFont`] when any non-ignorable glyph in + /// the SVG `` elements is uncovered by the registered [`FontPool`]. + #[cfg(feature = "mermaid")] + pub fn render_mermaid_rgba( + &mut self, + source: &str, + options: &MermaidOptions, + scale_factor: f32, + ) -> Result, PreviewError> { + self.render_mermaid_rgba_internal(source, options, scale_factor, false) + } + + /// Renders a Mermaid diagram to RGBA8 pixels in lenient mode, allowing missing + /// glyphs to fall back when the host has no additional script fonts to register. + #[cfg(feature = "mermaid")] + pub fn render_mermaid_rgba_lenient( + &mut self, + source: &str, + options: &MermaidOptions, + scale_factor: f32, + ) -> Result, PreviewError> { + self.render_mermaid_rgba_internal(source, options, scale_factor, true) + } + + #[cfg(feature = "mermaid")] + fn render_mermaid_rgba_internal( + &mut self, + source: &str, + options: &MermaidOptions, + scale_factor: f32, + allow_missing_glyphs: bool, + ) -> Result, PreviewError> { + let diagram_id_tag = match options.diagram_id.as_deref() { + Some(id) => format!("some({}:{id})", id.len()), + None => "none".to_string(), + }; + let mode_tag = if allow_missing_glyphs { + "lenient" + } else { + "strict" + }; + let key = format!( + "mermaid:{mode_tag}:fg={}:date={:04}-{:02}-{:02}:tz={}:pad={:016x}:id={diagram_id_tag}:scale={:08x}:src={source}", + self.font_generation, + options.today.year, + options.today.month, + options.today.day, + options.timezone_offset_minutes, + options.viewbox_padding.to_bits(), + scale_factor.to_bits(), + ); + if let Some(cached) = self.cache.get(&key) { + return Ok(cached); + } + let svg = MermaidRenderer::new().render_svg(source, options)?; + let raster_opts = RasterOptions { + allow_missing_glyphs, + ..RasterOptions::with_scale(scale_factor) + }; + let buf = Arc::new(self.rasterizer.rasterize_with_options(&svg, raster_opts)?); + self.cache.insert(key, Arc::clone(&buf)); + Ok(buf) + } + + /// Renders a LaTeX formula to pure-`` SVG using registered fonts. + #[cfg(feature = "math")] + pub fn render_latex_svg( + &self, + latex: &str, + options: &MathRenderOptions, + ) -> Result { + render_latex_svg(latex, options, &self.font_pool) + } + + /// Renders a LaTeX formula to RGBA8 pixels with baseline metrics. + #[cfg(feature = "math")] + pub fn render_latex_rgba( + &mut self, + latex: &str, + options: &MathRenderOptions, + scale_factor: f32, + ) -> Result { + let svg_out = render_latex_svg(latex, options, &self.font_pool)?; + let image = self + .rasterizer + .rasterize_with_options(&svg_out.svg, RasterOptions::with_scale(scale_factor))?; + Ok(MathRgbaOutput { + width_pt: svg_out.width_pt, + ascent_pt: svg_out.ascent_pt, + descent_pt: svg_out.descent_pt, + image, + }) + } + + /// Compiles a native Typst document and returns all rendered pages. + #[cfg(feature = "typst")] + pub fn compile_typst_pages( + &mut self, + source: &str, + today: crate::PreviewDate, + ) -> Result, PreviewError> { + let document = self.compile_or_reuse_typst_document(source, today)?; + Ok(InMemoryTypstWorld::render_document_pages_svg(&document)) + } + + /// Compiles a native Typst document and rasterizes `page_index` to RGBA8. + /// + /// Consecutive page renders for the same source, date, font generation, and + /// registered virtual inputs reuse the cached compiled `PagedDocument`. + #[cfg(feature = "typst")] + pub fn compile_typst_page_rgba( + &mut self, + source: &str, + today: crate::PreviewDate, + page_index: usize, + scale_factor: f32, + ) -> Result, PreviewError> { + let document = self.compile_or_reuse_typst_document(source, today)?; + let page = InMemoryTypstWorld::render_document_page_svg(&document, page_index)?; + let image = Arc::new( + self.rasterizer + .rasterize_with_options(&page.svg, RasterOptions::with_scale(scale_factor))?, + ); + Ok(image) + } + + /// Parses and caches a PDF document, returning a handle for fast page flipping. + #[cfg(feature = "pdf")] + pub fn load_pdf(&mut self, pdf_bytes: impl Into>) -> Result { + let renderer = HayroPdfRenderer::from_bytes(pdf_bytes)?; + let handle = self.next_pdf_handle; + self.next_pdf_handle = self.next_pdf_handle.wrapping_add(1).max(1); + self.pdf_docs.insert(handle, renderer); + Ok(handle) + } + + /// Removes a previously loaded PDF document handle from memory. + #[cfg(feature = "pdf")] + pub fn unload_pdf(&mut self, handle: u32) -> bool { + self.pdf_docs.remove(&handle).is_some() + } + + /// Returns the page count for a cached PDF handle. + #[cfg(feature = "pdf")] + pub fn pdf_page_count(&self, handle: u32) -> Result { + let doc = self + .pdf_docs + .get(&handle) + .ok_or_else(|| PreviewError::Pdf(format!("unknown pdf handle {handle}")))?; + Ok(doc.page_count()) + } + + /// Renders a single page of a cached PDF document handle to RGBA8. + #[cfg(feature = "pdf")] + pub fn render_pdf_page( + &self, + handle: u32, + request: PdfRenderRequest, + ) -> Result<(usize, RgbaImageBuffer), PreviewError> { + let doc = self + .pdf_docs + .get(&handle) + .ok_or_else(|| PreviewError::Pdf(format!("unknown pdf handle {handle}")))?; + let page_count = doc.page_count(); + let buffer = doc.render_page(request)?; + Ok((page_count, buffer)) + } + + #[cfg(feature = "typst")] + fn compile_or_reuse_typst_document( + &mut self, + source: &str, + today: crate::PreviewDate, + ) -> Result, PreviewError> { + let mut hasher = Sha256::new(); + hasher.update(source.as_bytes()); + let source_hash: [u8; 32] = hasher.finalize().into(); + + if let Some(cached) = self.last_typst_doc.as_ref() + && cached.source_hash == source_hash + && cached.today == today + && cached.font_generation == self.font_generation + && cached.inputs_generation == self.typst_inputs_generation + { + return Ok(Arc::clone(&cached.document)); + } + + let world = self.ensure_typst_world()?; + world.set_today(Some(today)); + let document = world.compile_document(source)?; + self.last_typst_doc = Some(CachedTypstDocument { + source_hash, + today, + font_generation: self.font_generation, + inputs_generation: self.typst_inputs_generation, + document: Arc::clone(&document), + }); + Ok(document) + } + + #[cfg(feature = "typst")] + fn ensure_typst_world(&mut self) -> Result<&mut InMemoryTypstWorld, PreviewError> { + if self.typst_world.is_none() { + let mut world = InMemoryTypstWorld::new(&self.font_pool); + for (path, bytes) in &self.typst_files { + world.insert_file(path, bytes.clone())?; + } + for (ns, name, ver, path, bytes) in &self.typst_package_files { + let spec = parse_package_spec(ns, name, ver)?; + world.insert_package_file(spec, path, bytes.clone())?; + } + self.typst_world = Some(world); + } + Ok(self.typst_world.as_mut().expect("typst world initialized")) + } +} + +#[cfg(feature = "typst")] +fn parse_package_spec( + namespace: &str, + name: &str, + version: &str, +) -> Result { + let parsed_version: typst::syntax::package::PackageVersion = + version.parse().map_err(|err| { + PreviewError::Typst(format!("invalid package version '{version}': {err}")) + })?; + Ok(typst::syntax::package::PackageSpec { + namespace: namespace.into(), + name: name.into(), + version: parsed_version, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PreviewDate; + use crate::test_support::build_test_cjk_ttf; + + #[cfg(all(feature = "mermaid", feature = "typst"))] + #[test] + fn persistent_engine_supports_multi_font_cjk_mermaid_and_typst_packages() { + let mut engine = PreviewEngine::default(); + let first_latin = typst_assets::fonts().next().expect("typst bundled font"); + assert!(engine.register_font(first_latin.to_vec()).unwrap() >= 1); + assert!(engine.register_font(build_test_cjk_ttf()).unwrap() >= 1); + + // 1. CJK Mermaid 2x RGBA rendering and cache reuse. + let opts = MermaidOptions { + today: PreviewDate::new(2026, 3, 10), + timezone_offset_minutes: 480, + ..MermaidOptions::default() + }; + let img = engine + .render_mermaid_rgba("flowchart LR\n A[中文] --> B[通过]", &opts, 2.0) + .unwrap(); + assert!(img.width_px > 0 && img.height_px > 0); + assert!(img.count_non_transparent_pixels() > 100); + let cached = engine + .render_mermaid_rgba("flowchart LR\n A[中文] --> B[通过]", &opts, 2.0) + .unwrap(); + assert!(Arc::ptr_eq(&img, &cached)); + + // 2. Multi-font + in-memory @preview package + multi-page Typst compilation & doc reuse. + engine + .register_typst_package_file( + "preview", + "demo", + "0.1.0", + "typst.toml", + b"[package]\nname = \"demo\"\nversion = \"0.1.0\"\nentrypoint = \"lib.typ\"\n", + ) + .unwrap(); + engine + .register_typst_package_file( + "preview", + "demo", + "0.1.0", + "lib.typ", + b"#let badge(t) = [Package: #t]", + ) + .unwrap(); + + let source = r#" +#import "@preview/demo:0.1.0": badge +#set page(width: 140pt, height: 60pt, margin: 4pt) +#badge[Page 1 中文] +#pagebreak() +#badge[Page 2 测试] +"#; + let date = PreviewDate::new(2026, 3, 10); + let pages = engine.compile_typst_pages(source, date).unwrap(); + assert_eq!(pages.len(), 2); + assert!(pages[0].svg.contains(" gen_after_1); + let second = engine.render_mermaid_rgba(latin_src, &opts, 2.0).unwrap(); + assert!(!Arc::ptr_eq(&first, &second)); + + // Now register the CJK font and verify the CJK diagram succeeds with visible ink. + engine.register_font(build_test_cjk_ttf()).unwrap(); + let cjk_ok = engine.render_mermaid_rgba(cjk_src, &opts, 2.0).unwrap(); + assert!(cjk_ok.count_non_transparent_pixels() > 100); + } + + #[cfg(feature = "mermaid")] + #[test] + fn mermaid_options_all_fields_participate_in_pixel_cache_key() { + let mut engine = PreviewEngine::default(); + engine + .register_font(typst_assets::fonts().next().expect("font").to_vec()) + .unwrap(); + let src = "flowchart LR\n A[Start] --> B[Done]"; + + let tight = MermaidOptions { + viewbox_padding: 0.0, + ..MermaidOptions::default() + }; + let wide = MermaidOptions { + viewbox_padding: 64.0, + ..MermaidOptions::default() + }; + let a = engine.render_mermaid_rgba(src, &tight, 2.0).unwrap(); + let b = engine.render_mermaid_rgba(src, &wide, 2.0).unwrap(); + assert!(!Arc::ptr_eq(&a, &b)); + let a_hit = engine.render_mermaid_rgba(src, &tight, 2.0).unwrap(); + assert!(Arc::ptr_eq(&a, &a_hit)); + + let id_a = MermaidOptions { + diagram_id: Some("diag-a".to_string()), + ..MermaidOptions::default() + }; + let id_b = MermaidOptions { + diagram_id: Some("diag-b".to_string()), + ..MermaidOptions::default() + }; + let img_id_a = engine.render_mermaid_rgba(src, &id_a, 2.0).unwrap(); + let img_id_b = engine.render_mermaid_rgba(src, &id_b, 2.0).unwrap(); + assert!(!Arc::ptr_eq(&img_id_a, &img_id_b)); + } + + #[cfg(feature = "mermaid")] + #[test] + fn variation_selector_default_ignorable_passes_and_lenient_mode_falls_back() { + let mut engine = PreviewEngine::default(); + let latin = typst_assets::fonts().next().expect("typst bundled font"); + engine.register_font(latin.to_vec()).unwrap(); + assert!(engine.font_pool().has_glyph('\u{00A9}')); + assert!(!engine.font_pool().has_glyph('\u{FE0F}')); + + let opts = MermaidOptions::default(); + let plain = engine.render_mermaid_rgba( + "flowchart LR\n A[Copyright \u{00A9} 2026] --> B[Done]", + &opts, + 2.0, + ); + let with_vs16 = engine.render_mermaid_rgba( + "flowchart LR\n A[Copyright \u{00A9}\u{FE0F} 2026] --> B[Done]", + &opts, + 2.0, + ); + assert!(plain.is_ok(), "plain copyright failed: {plain:?}"); + assert!( + with_vs16.is_ok(), + "copyright + U+FE0F variation selector must not fail: {with_vs16:?}" + ); + + // Uncovered CJK fails in strict mode, succeeds in lenient mode under a distinct cache key. + let cjk = "flowchart LR\n A[中文] --> B[Done]"; + assert!(matches!( + engine.render_mermaid_rgba(cjk, &opts, 2.0), + Err(PreviewError::MissingGlyphFont(_)) + )); + let lenient = engine + .render_mermaid_rgba_lenient(cjk, &opts, 2.0) + .expect("lenient mode must render available glyphs"); + assert!(lenient.count_non_transparent_pixels() > 0); + } +} diff --git a/blocksuite/crates/preview/src/error.rs b/blocksuite/crates/preview/src/error.rs new file mode 100644 index 0000000000..17a2f40132 --- /dev/null +++ b/blocksuite/crates/preview/src/error.rs @@ -0,0 +1,49 @@ +use thiserror::Error; + +/// Error returned by preview rendering and rasterization operations. +#[derive(Debug, Error)] +pub enum PreviewError { + /// Input source is empty or contains only whitespace. + #[error("input source is empty")] + EmptyInput, + + /// Font bytes are invalid or contain no readable font faces. + #[error("invalid font data: {0}")] + InvalidFont(String), + + /// SVG parsing failed. + #[error("svg parse failed: {0}")] + SvgParse(String), + + /// Raster target dimensions are zero, non-finite, or exceed limits. + #[error("invalid raster size: {0}")] + InvalidSize(String), + + /// Mermaid diagram parsing or layout failed. + #[error("mermaid render failed: {0}")] + Mermaid(String), + + /// Typst compilation or export failed. + #[error("typst compile failed: {0}")] + Typst(String), + + /// LaTeX math parsing or layout failed. + #[error("math render failed: {0}")] + Math(String), + + /// PDF parsing or page rendering failed. + #[error("pdf render failed: {0}")] + Pdf(String), + + /// Requested page index is outside the document page count. + #[error("page index {index} is out of range for {page_count} pages")] + PageOutOfRange { index: usize, page_count: usize }, + + /// Required glyph is missing from all registered fonts in [`crate::FontPool`]. + #[error("missing glyph font: {0}")] + MissingGlyphFont(String), + + /// Caller supplied an invalid or unsafe CSS color string. + #[error("invalid CSS color: {0}")] + InvalidColor(String), +} diff --git a/blocksuite/crates/preview/src/font_pool.rs b/blocksuite/crates/preview/src/font_pool.rs new file mode 100644 index 0000000000..09672c0326 --- /dev/null +++ b/blocksuite/crates/preview/src/font_pool.rs @@ -0,0 +1,329 @@ +use std::sync::Arc; + +use usvg::fontdb::{Database, Source}; + +use crate::error::PreviewError; + +/// Explicit in-memory font registry for deterministic preview rendering. +/// +/// This pool never scans host system fonts. Callers register application +/// font bytes explicitly so Linux, macOS, iOS, Android, and WebAssembly +/// produce identical glyph selection and pixel output. +#[derive(Clone, Default)] +pub struct FontPool { + blobs: Vec>, + families: Vec, + covered_ranges: Vec<(u32, u32)>, + sans_serif: Option, + serif: Option, + monospace: Option, + math: Option, + db: Arc, +} + +impl std::fmt::Debug for FontPool { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FontPool") + .field("blob_count", &self.blobs.len()) + .field("face_count", &self.db.len()) + .field("sans_serif", &self.sans_serif) + .field("serif", &self.serif) + .field("monospace", &self.monospace) + .field("math", &self.math) + .finish() + } +} + +impl FontPool { + /// Creates an empty font pool with no system fonts loaded. + pub fn new() -> Self { + Self::default() + } + + /// Registers a single TrueType, OpenType, or font collection byte buffer. + pub fn register_font_bytes( + &mut self, + bytes: impl Into>, + ) -> Result { + let data: Vec = bytes.into(); + let face_count = ttf_parser::fonts_in_collection(&data).unwrap_or(1) as usize; + let mut parsed_any = false; + let mut discovered_families = Vec::new(); + let mut new_codepoints = Vec::new(); + + for index in 0..face_count { + if let Ok(face) = ttf_parser::Face::parse(&data, index as u32) { + parsed_any = true; + if let Some(family) = extract_family_name(&face) + && !discovered_families.contains(&family) + { + discovered_families.push(family); + } + collect_face_codepoints(&face, &mut new_codepoints); + } + } + + if !parsed_any { + return Err(PreviewError::InvalidFont( + "no valid TrueType or OpenType face found".to_string(), + )); + } + + let arc_bytes: Arc<[u8]> = Arc::from(data); + let db = Arc::make_mut(&mut self.db); + let before = db.len(); + db.load_font_source(Source::Binary(Arc::new(SharedFontBytes(Arc::clone( + &arc_bytes, + ))))); + let added = db.len().saturating_sub(before); + if added == 0 { + return Err(PreviewError::InvalidFont( + "fontdb rejected all faces in buffer".to_string(), + )); + } + + self.blobs.push(arc_bytes); + merge_codepoint_ranges(&mut self.covered_ranges, new_codepoints); + for family in discovered_families { + if !self.families.contains(&family) { + self.families.push(family); + } + } + + self.sync_generic_families(); + Ok(added) + } + + /// Sets the default sans-serif family name used for generic CSS queries. + pub fn set_sans_serif_family(&mut self, family: impl Into) { + self.sans_serif = Some(family.into()); + self.sync_generic_families(); + } + + /// Sets the default serif family name used for generic CSS queries. + pub fn set_serif_family(&mut self, family: impl Into) { + self.serif = Some(family.into()); + self.sync_generic_families(); + } + + /// Sets the default monospace family name used for generic CSS queries. + pub fn set_monospace_family(&mut self, family: impl Into) { + self.monospace = Some(family.into()); + self.sync_generic_families(); + } + + /// Sets the preferred math font family name. + pub fn set_math_family(&mut self, family: impl Into) { + self.math = Some(family.into()); + } + + /// Returns the shared in-memory `fontdb::Database`. + pub fn database(&self) -> Arc { + Arc::clone(&self.db) + } + + /// Returns all registered raw font byte buffers in registration order. + pub fn font_blobs(&self) -> &[Arc<[u8]>] { + &self.blobs + } + + /// Returns registered family names in registration order. + pub fn families(&self) -> &[String] { + &self.families + } + + /// Returns the configured default sans-serif family name, if any. + pub fn sans_serif_family(&self) -> Option<&str> { + self.sans_serif + .as_deref() + .or_else(|| self.families.first().map(String::as_str)) + } + + /// Returns the configured default serif family name, if any. + pub fn serif_family(&self) -> Option<&str> { + self.serif.as_deref().or_else(|| self.sans_serif_family()) + } + + /// Returns the configured default monospace family name, if any. + pub fn monospace_family(&self) -> Option<&str> { + self.monospace + .as_deref() + .or_else(|| self.sans_serif_family()) + } + + /// Returns the configured math family name, if any. + pub fn math_family(&self) -> Option<&str> { + self.math.as_deref() + } + + /// Returns the number of loaded font faces. + pub fn face_count(&self) -> usize { + self.db.len() + } + + /// Returns true when no font faces are registered. + pub fn is_empty(&self) -> bool { + self.db.is_empty() + } + + /// Returns true when at least one registered font face contains a glyph for `ch`. + /// + /// Uses the precomputed sorted scalar-range table built during registration (`O(log R)`). + pub fn has_glyph(&self, ch: char) -> bool { + let cp = ch as u32; + self.covered_ranges + .binary_search_by(|&(start, end)| { + if cp < start { + std::cmp::Ordering::Greater + } else if cp > end { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Equal + } + }) + .is_ok() + } + + fn sync_generic_families(&mut self) { + let Some(fallback) = self + .sans_serif + .clone() + .or_else(|| self.families.first().cloned()) + else { + return; + }; + let serif = self.serif.clone().unwrap_or_else(|| fallback.clone()); + let mono = self.monospace.clone().unwrap_or_else(|| fallback.clone()); + + let db = Arc::make_mut(&mut self.db); + db.set_sans_serif_family(&fallback); + db.set_serif_family(&serif); + db.set_monospace_family(&mono); + db.set_cursive_family(&fallback); + db.set_fantasy_family(&fallback); + } +} + +pub(crate) struct SharedFontBytes(pub(crate) Arc<[u8]>); + +impl AsRef<[u8]> for SharedFontBytes { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +fn collect_face_codepoints(face: &ttf_parser::Face<'_>, out: &mut Vec) { + let Some(cmap) = face.tables().cmap else { + return; + }; + for subtable in cmap.subtables { + if !subtable.is_unicode() { + continue; + } + subtable.codepoints(|cp| { + if let Some(ch) = char::from_u32(cp) + && face.glyph_index(ch).is_some() + { + out.push(cp); + } + }); + } +} + +fn merge_codepoint_ranges(ranges: &mut Vec<(u32, u32)>, mut points: Vec) { + if points.is_empty() { + return; + } + points.sort_unstable(); + points.dedup(); + + let mut all_ranges = Vec::with_capacity(ranges.len() + points.len()); + all_ranges.extend_from_slice(ranges); + + let mut start = points[0]; + let mut end = points[0]; + for &cp in &points[1..] { + if cp == end.saturating_add(1) { + end = cp; + } else { + all_ranges.push((start, end)); + start = cp; + end = cp; + } + } + all_ranges.push((start, end)); + + all_ranges.sort_unstable_by_key(|&(s, _)| s); + ranges.clear(); + for (s, e) in all_ranges { + if let Some(last) = ranges.last_mut() + && s <= last.1.saturating_add(1) + { + last.1 = last.1.max(e); + } else { + ranges.push((s, e)); + } + } +} + +fn extract_family_name(face: &ttf_parser::Face<'_>) -> Option { + let mut fallback = None; + for name in face.names() { + let is_typographic = name.name_id == ttf_parser::name_id::TYPOGRAPHIC_FAMILY; + let is_family = name.name_id == ttf_parser::name_id::FAMILY; + if !is_typographic && !is_family { + continue; + } + if let Some(text) = name.to_string() { + if is_typographic { + return Some(text); + } + if fallback.is_none() { + fallback = Some(text); + } + } + } + fallback +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_pool_loads_zero_system_fonts() { + let pool = FontPool::new(); + assert!(pool.is_empty()); + assert_eq!(pool.face_count(), 0); + assert!(pool.font_blobs().is_empty()); + assert!(pool.families().is_empty()); + } + + #[test] + fn invalid_font_bytes_are_rejected() { + let mut pool = FontPool::new(); + let err = pool + .register_font_bytes(b"not-a-font".to_vec()) + .unwrap_err(); + assert!(matches!(err, PreviewError::InvalidFont(_))); + assert!(pool.is_empty()); + } + + #[test] + fn registers_valid_font_bytes_and_populates_generic_families() { + let font_bytes = typst_assets::fonts().next().expect("typst bundled font"); + let mut pool = FontPool::new(); + let added = pool.register_font_bytes(font_bytes.to_vec()).unwrap(); + assert!(added >= 1); + assert_eq!(pool.face_count(), added); + assert_eq!(pool.font_blobs().len(), 1); + assert!(pool.sans_serif_family().is_some()); + + let db = pool.database(); + let sans = db.query(&usvg::fontdb::Query { + families: &[usvg::fontdb::Family::SansSerif], + ..Default::default() + }); + assert!(sans.is_some()); + } +} diff --git a/blocksuite/crates/preview/src/lib.rs b/blocksuite/crates/preview/src/lib.rs new file mode 100644 index 0000000000..299f7f958e --- /dev/null +++ b/blocksuite/crates/preview/src/lib.rs @@ -0,0 +1,73 @@ +#![forbid(unsafe_code)] + +//! Pure-Rust deterministic offline preview kernel for BlockSuite blocks. +//! +//! Covers four isolated capabilities: +//! - Deterministic in-memory font registry ([`FontPool`]), `resvg` SVG rasterizer +//! ([`SvgRasterizer`]), and pin-protected dual-limit pixel cache ([`PinnedPixelCache`]). +//! - `resvg`-safe Mermaid diagram rendering ([`mermaid`]). +//! - Pure in-memory Typst compilation ([`typst_world`]) and LaTeX math typesetting ([`math`]). +//! - Pure safe Rust PDF page rendering ([`pdf`]). + +pub mod cache; +pub mod engine; +pub mod error; +pub mod font_pool; +pub mod svg_raster; + +#[cfg(feature = "mermaid")] +pub mod mermaid; + +#[cfg(feature = "math")] +pub mod math; + +#[cfg(feature = "typst")] +pub mod typst_world; + +#[cfg(feature = "pdf")] +pub mod pdf; + +#[cfg(feature = "wasm-worker")] +pub mod wasm; + +#[cfg(test)] +pub(crate) mod test_support; + +pub use cache::{CacheLimits, EvictionReport, PinnedPixelCache}; +pub use engine::PreviewEngine; +pub use error::PreviewError; +pub use font_pool::FontPool; +pub use svg_raster::{DEFAULT_MAX_EDGE_PX, RasterOptions, RgbaImageBuffer, SvgRasterizer}; + +/// Deterministic calendar date injected into diagram and document renderers. +/// +/// Using an explicit date avoids reading the host wall clock. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PreviewDate { + /// Four-digit calendar year (for example `2026`). + pub year: i32, + /// One-based month (`1..=12`). + pub month: u8, + /// One-based day of month (`1..=31`). + pub day: u8, +} + +impl PreviewDate { + /// Creates a deterministic calendar date. + pub const fn new(year: i32, month: u8, day: u8) -> Self { + Self { year, month, day } + } + + /// Fixed fallback date used when callers do not supply a date (`2026-01-01`). + pub const DEFAULT: Self = Self { + year: 2026, + month: 1, + day: 1, + }; +} + +impl Default for PreviewDate { + fn default() -> Self { + Self::DEFAULT + } +} diff --git a/blocksuite/crates/preview/src/math.rs b/blocksuite/crates/preview/src/math.rs new file mode 100644 index 0000000000..ac3d25c167 --- /dev/null +++ b/blocksuite/crates/preview/src/math.rs @@ -0,0 +1,1055 @@ +use std::fmt::Write; + +use ratex_layout::{LayoutOptions, layout, to_display_list}; +use ratex_types::color::Color; +use ratex_types::display_item::{DisplayItem, DisplayList}; +use ratex_types::math_style::MathStyle; +use ratex_types::path_command::PathCommand; + +use crate::error::PreviewError; +use crate::font_pool::FontPool; +use crate::svg_raster::{RasterOptions, RgbaImageBuffer, SvgRasterizer}; + +/// Display mode for LaTeX mathematical formulas. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MathDisplayMode { + /// Inline math aligned to the surrounding text baseline (`$...$`). + Inline, + /// Centered display math block (`$$...$$`). + Display, +} + +/// Options controlling LaTeX math typesetting and pure-outline SVG export. +#[derive(Debug, Clone, PartialEq)] +pub struct MathRenderOptions { + /// Inline or display style. + pub mode: MathDisplayMode, + /// Base font size in points (for example `16.0`). + pub font_size_pt: f64, + /// Optional padding around the SVG box in points. + pub padding_pt: f64, + /// Foreground CSS color applied to default-black math glyphs and rules. + pub color_css: String, +} + +impl Default for MathRenderOptions { + fn default() -> Self { + Self { + mode: MathDisplayMode::Inline, + font_size_pt: 16.0, + padding_pt: 0.0, + color_css: "currentColor".to_string(), + } + } +} + +/// Typeset math box metrics and standalone pure-`` SVG output. +#[derive(Debug, Clone, PartialEq)] +pub struct MathSvgOutput { + /// Total box width in points. + pub width_pt: f64, + /// Height above the baseline in points. + pub ascent_pt: f64, + /// Depth below the baseline in points. + pub descent_pt: f64, + /// Standalone SVG string containing only vector primitives (zero ``). + pub svg: String, +} + +/// Rasterized math formula with exact baseline metrics. +#[derive(Debug, Clone, PartialEq)] +pub struct MathRgbaOutput { + /// Total box width in points. + pub width_pt: f64, + /// Height above the baseline in points. + pub ascent_pt: f64, + /// Depth below the baseline in points. + pub descent_pt: f64, + /// Rasterized RGBA8 pixel buffer. + pub image: RgbaImageBuffer, +} + +/// Renders a LaTeX math expression into a pure in-memory `` SVG. +/// +/// KaTeX math glyphs come from embedded `ratex-katex-fonts` bytes. Non-KaTeX +/// Unicode characters (such as CJK text inside `\text{...}`) are resolved strictly +/// from `font_pool` with zero host filesystem or system-font access. Missing +/// glyphs return [`PreviewError::MissingGlyphFont`]. +pub fn render_latex_svg( + latex: &str, + options: &MathRenderOptions, + font_pool: &FontPool, +) -> Result { + if latex.trim().is_empty() { + return Err(PreviewError::EmptyInput); + } + if !options.font_size_pt.is_finite() || options.font_size_pt <= 0.0 { + return Err(PreviewError::InvalidSize(format!( + "font_size_pt must be positive and finite, got {}", + options.font_size_pt + ))); + } + let validated_color = validate_css_color(&options.color_css)?; + + let nodes = ratex_parser::parse(latex).map_err(|err| PreviewError::Math(err.to_string()))?; + let style = match options.mode { + MathDisplayMode::Inline => MathStyle::Text, + MathDisplayMode::Display => MathStyle::Display, + }; + let layout_opts = LayoutOptions::default().with_style(style); + let layout_box = layout(&nodes, &layout_opts); + let display_list = to_display_list(&layout_box); + + let svg = display_list_to_outline_svg(&display_list, options, &validated_color, font_pool)?; + let width_pt = display_list.width * options.font_size_pt + 2.0 * options.padding_pt; + let ascent_pt = display_list.height * options.font_size_pt + options.padding_pt; + let descent_pt = display_list.depth * options.font_size_pt + options.padding_pt; + + Ok(MathSvgOutput { + width_pt, + ascent_pt, + descent_pt, + svg, + }) +} + +/// Renders a LaTeX math formula to RGBA8 pixels with exact baseline metrics. +pub fn render_latex_rgba( + latex: &str, + options: &MathRenderOptions, + font_pool: &FontPool, + rasterizer: &SvgRasterizer, + scale_factor: f32, +) -> Result { + let svg_out = render_latex_svg(latex, options, font_pool)?; + let image = + rasterizer.rasterize_with_options(&svg_out.svg, RasterOptions::with_scale(scale_factor))?; + Ok(MathRgbaOutput { + width_pt: svg_out.width_pt, + ascent_pt: svg_out.ascent_pt, + descent_pt: svg_out.descent_pt, + image, + }) +} + +fn display_list_to_outline_svg( + list: &DisplayList, + options: &MathRenderOptions, + validated_color: &str, + font_pool: &FontPool, +) -> Result { + let fs = options.font_size_pt; + let pad = options.padding_pt; + let total_w = (list.width * fs + 2.0 * pad).max(1.0); + let total_h = (list.total_height() * fs + 2.0 * pad).max(1.0); + let stroke_w = (fs * 0.04).max(0.5); + + let mut out = String::with_capacity(list.items.len() * 128 + 256); + let _ = write!( + out, + r#""#, + ); + + for item in &list.items { + match item { + DisplayItem::GlyphPath { + x, + y, + scale, + font, + char_code, + color, + } => { + let Some(ch) = char::from_u32(*char_code) else { + continue; + }; + if ch.is_whitespace() || ch == '\u{00A0}' { + continue; + } + let origin_x = pad + x * fs; + let origin_y = pad + y * fs; + let d = + extract_glyph_svg_path(font, ch, origin_x, origin_y, *scale * fs, font_pool)?; + if !d.is_empty() { + let (paint, opacity_attr) = format_paint(*color, validated_color, "fill"); + let _ = write!(out, r#""#); + } + } + DisplayItem::Line { + x, + y, + width, + thickness, + color, + dashed, + } => { + let x1 = pad + x * fs; + let y1 = pad + y * fs; + let w = width * fs; + let t = (thickness * fs).max(0.4); + if *dashed { + let (paint, opacity_attr) = format_paint(*color, validated_color, "stroke"); + let x2 = x1 + w; + let dash = (fs * 0.25).max(2.0); + let _ = write!( + out, + r#""#, + ); + } else { + let (paint, opacity_attr) = format_paint(*color, validated_color, "fill"); + let top = y1 - t * 0.5; + let _ = write!( + out, + r#""#, + ); + } + } + DisplayItem::Rect { + x, + y, + width, + height, + color, + } => { + let rx = pad + x * fs; + let ry = pad + y * fs; + let rw = width * fs; + let rh = height * fs; + let (paint, opacity_attr) = format_paint(*color, validated_color, "fill"); + let _ = write!( + out, + r#""#, + ); + } + DisplayItem::Path { + x, + y, + commands, + fill, + color, + } => { + let ox = pad + x * fs; + let oy = pad + y * fs; + let mut d = String::with_capacity(commands.len() * 24); + for cmd in commands { + match *cmd { + PathCommand::MoveTo { x: px, y: py } => { + let _ = write!(d, "M{:.3} {:.3}", ox + px * fs, oy + py * fs); + } + PathCommand::LineTo { x: px, y: py } => { + let _ = write!(d, "L{:.3} {:.3}", ox + px * fs, oy + py * fs); + } + PathCommand::QuadTo { + x1, + y1, + x: px, + y: py, + } => { + let _ = write!( + d, + "Q{:.3} {:.3} {:.3} {:.3}", + ox + x1 * fs, + oy + y1 * fs, + ox + px * fs, + oy + py * fs + ); + } + PathCommand::CubicTo { + x1, + y1, + x2, + y2, + x: px, + y: py, + } => { + let _ = write!( + d, + "C{:.3} {:.3} {:.3} {:.3} {:.3} {:.3}", + ox + x1 * fs, + oy + y1 * fs, + ox + x2 * fs, + oy + y2 * fs, + ox + px * fs, + oy + py * fs + ); + } + PathCommand::Close => d.push('Z'), + } + } + if !d.is_empty() { + if *fill { + let (paint, opacity_attr) = format_paint(*color, validated_color, "fill"); + let _ = write!(out, r#""#); + } else { + let (paint, opacity_attr) = format_paint(*color, validated_color, "stroke"); + let _ = write!( + out, + r#""#, + ); + } + } + } + } + } + + out.push_str(""); + Ok(out) +} + +fn extract_glyph_svg_path( + font_name: &str, + ch: char, + origin_x: f64, + origin_y: f64, + size_px: f64, + font_pool: &FontPool, +) -> Result { + if let Some(katex_bytes) = lookup_katex_font_bytes(font_name) + && let Ok(face) = ttf_parser::Face::parse(&katex_bytes, 0) + && let Some(gid) = face.glyph_index(ch) + { + return Ok(outline_glyph(&face, gid, origin_x, origin_y, size_px)); + } + + for blob in font_pool.font_blobs() { + let count = ttf_parser::fonts_in_collection(blob).unwrap_or(1); + for face_idx in 0..count { + if let Ok(face) = ttf_parser::Face::parse(blob, face_idx) + && let Some(gid) = face.glyph_index(ch) + { + return Ok(outline_glyph(&face, gid, origin_x, origin_y, size_px)); + } + } + } + + Err(PreviewError::MissingGlyphFont(format!( + "no glyph for U+{:04X} ('{ch}') in KaTeX font '{font_name}' or registered FontPool", + ch as u32 + ))) +} + +fn lookup_katex_font_bytes(font_name: &str) -> Option> { + let filename = if font_name.starts_with("KaTeX_") { + format!("{font_name}.ttf") + } else { + format!("KaTeX_{font_name}.ttf") + }; + ratex_katex_fonts::ttf_bytes(&filename) +} + +fn outline_glyph( + face: &ttf_parser::Face<'_>, + gid: ttf_parser::GlyphId, + origin_x: f64, + origin_y: f64, + size_px: f64, +) -> String { + let upem = f64::from(face.units_per_em()).max(1.0); + let scale = size_px / upem; + let mut builder = SvgOutlineBuilder { + origin_x, + origin_y, + scale, + d: String::new(), + }; + let _ = face.outline_glyph(gid, &mut builder); + builder.d +} + +struct SvgOutlineBuilder { + origin_x: f64, + origin_y: f64, + scale: f64, + d: String, +} + +impl ttf_parser::OutlineBuilder for SvgOutlineBuilder { + fn move_to(&mut self, x: f32, y: f32) { + let _ = write!( + self.d, + "M{:.3} {:.3}", + self.origin_x + f64::from(x) * self.scale, + self.origin_y - f64::from(y) * self.scale + ); + } + + fn line_to(&mut self, x: f32, y: f32) { + let _ = write!( + self.d, + "L{:.3} {:.3}", + self.origin_x + f64::from(x) * self.scale, + self.origin_y - f64::from(y) * self.scale + ); + } + + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + let _ = write!( + self.d, + "Q{:.3} {:.3} {:.3} {:.3}", + self.origin_x + f64::from(x1) * self.scale, + self.origin_y - f64::from(y1) * self.scale, + self.origin_x + f64::from(x) * self.scale, + self.origin_y - f64::from(y) * self.scale + ); + } + + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + let _ = write!( + self.d, + "C{:.3} {:.3} {:.3} {:.3} {:.3} {:.3}", + self.origin_x + f64::from(x1) * self.scale, + self.origin_y - f64::from(y1) * self.scale, + self.origin_x + f64::from(x2) * self.scale, + self.origin_y - f64::from(y2) * self.scale, + self.origin_x + f64::from(x) * self.scale, + self.origin_y - f64::from(y) * self.scale + ); + } + + fn close(&mut self) { + self.d.push('Z'); + } +} + +/// Exact W3C CSS Color Module Level 4 named colors plus `transparent` (149 keywords, sorted lowercase). +const CSS_NAMED_COLORS: &[&str] = &[ + "aliceblue", + "antiquewhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "black", + "blanchedalmond", + "blue", + "blueviolet", + "brown", + "burlywood", + "cadetblue", + "chartreuse", + "chocolate", + "coral", + "cornflowerblue", + "cornsilk", + "crimson", + "cyan", + "darkblue", + "darkcyan", + "darkgoldenrod", + "darkgray", + "darkgreen", + "darkgrey", + "darkkhaki", + "darkmagenta", + "darkolivegreen", + "darkorange", + "darkorchid", + "darkred", + "darksalmon", + "darkseagreen", + "darkslateblue", + "darkslategray", + "darkslategrey", + "darkturquoise", + "darkviolet", + "deeppink", + "deepskyblue", + "dimgray", + "dimgrey", + "dodgerblue", + "firebrick", + "floralwhite", + "forestgreen", + "fuchsia", + "gainsboro", + "ghostwhite", + "gold", + "goldenrod", + "gray", + "green", + "greenyellow", + "grey", + "honeydew", + "hotpink", + "indianred", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderblush", + "lawngreen", + "lemonchiffon", + "lightblue", + "lightcoral", + "lightcyan", + "lightgoldenrodyellow", + "lightgray", + "lightgreen", + "lightgrey", + "lightpink", + "lightsalmon", + "lightseagreen", + "lightskyblue", + "lightslategray", + "lightslategrey", + "lightsteelblue", + "lightyellow", + "lime", + "limegreen", + "linen", + "magenta", + "maroon", + "mediumaquamarine", + "mediumblue", + "mediumorchid", + "mediumpurple", + "mediumseagreen", + "mediumslateblue", + "mediumspringgreen", + "mediumturquoise", + "mediumvioletred", + "midnightblue", + "mintcream", + "mistyrose", + "moccasin", + "navajowhite", + "navy", + "oldlace", + "olive", + "olivedrab", + "orange", + "orangered", + "orchid", + "palegoldenrod", + "palegreen", + "paleturquoise", + "palevioletred", + "papayawhip", + "peachpuff", + "peru", + "pink", + "plum", + "powderblue", + "purple", + "rebeccapurple", + "red", + "rosybrown", + "royalblue", + "saddlebrown", + "salmon", + "sandybrown", + "seagreen", + "seashell", + "sienna", + "silver", + "skyblue", + "slateblue", + "slategray", + "slategrey", + "snow", + "springgreen", + "steelblue", + "tan", + "teal", + "thistle", + "tomato", + "transparent", + "turquoise", + "violet", + "wheat", + "white", + "whitesmoke", + "yellow", + "yellowgreen", +]; + +fn validate_css_color(raw: &str) -> Result { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return Err(PreviewError::InvalidColor( + "color_css must not be empty".to_string(), + )); + } + if trimmed.chars().any(|ch| { + matches!( + ch, + '"' | '\'' | '<' | '>' | '&' | ';' | '\\' | '\n' | '\r' | '\0' + ) + }) { + return Err(PreviewError::InvalidColor(format!( + "color_css contains forbidden characters: {trimmed}" + ))); + } + if trimmed.eq_ignore_ascii_case("currentColor") { + return Ok("currentColor".to_string()); + } + if let Some(hex) = trimmed.strip_prefix('#') { + if matches!(hex.len(), 3 | 4 | 6 | 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return Ok(format!("#{}", hex.to_ascii_lowercase())); + } + return Err(PreviewError::InvalidColor(format!( + "invalid hex CSS color: {trimmed}" + ))); + } + let lower = trimmed.to_ascii_lowercase(); + if let Some(inner) = lower + .strip_prefix("rgb(") + .or_else(|| lower.strip_prefix("rgba(")) + .and_then(|rest| rest.strip_suffix(')')) + { + return parse_and_normalize_rgb(inner, trimmed); + } + if CSS_NAMED_COLORS.binary_search(&lower.as_str()).is_ok() { + return Ok(lower); + } + Err(PreviewError::InvalidColor(format!( + "unsupported CSS color syntax: {trimmed}" + ))) +} + +fn parse_and_normalize_rgb(inner: &str, raw: &str) -> Result { + let err = |msg: &str| PreviewError::InvalidColor(format!("{msg}: {raw}")); + let inner = inner.trim(); + if inner.is_empty() { + return Err(err("empty rgb/rgba channel list")); + } + + let (channels, alpha_str) = if inner.contains(',') { + if inner.contains('/') { + return Err(err("cannot mix ',' and '/' in rgb/rgba")); + } + let parts: Vec<&str> = inner.split(',').map(str::trim).collect(); + if parts.iter().any(|p| p.is_empty()) || !matches!(parts.len(), 3 | 4) { + return Err(err("invalid comma-separated rgb/rgba channels")); + } + let is_pct = [parts[0], parts[1], parts[2]].map(|p| p.ends_with('%')); + if is_pct[0] != is_pct[1] || is_pct[1] != is_pct[2] { + return Err(err( + "comma-separated rgb/rgba cannot mix numbers and percentages", + )); + } + ([parts[0], parts[1], parts[2]], parts.get(3).copied()) + } else { + let mut slash_split = inner.split('/'); + let rgb_part = slash_split.next().unwrap_or("").trim(); + let alpha_part = slash_split.next().map(str::trim); + if slash_split.next().is_some() { + return Err(err("multiple '/' separators in rgb/rgba")); + } + let rgb_tokens: Vec<&str> = rgb_part.split_ascii_whitespace().collect(); + if rgb_tokens.len() != 3 { + return Err(err("expected 3 space-separated rgb channels")); + } + if let Some(a) = alpha_part + && (a.is_empty() || a.split_ascii_whitespace().count() != 1) + { + return Err(err("invalid alpha component after '/'")); + } + ([rgb_tokens[0], rgb_tokens[1], rgb_tokens[2]], alpha_part) + }; + + let r = parse_rgb_channel(channels[0], raw)?; + let g = parse_rgb_channel(channels[1], raw)?; + let b = parse_rgb_channel(channels[2], raw)?; + if let Some(alpha_tok) = alpha_str { + let a = parse_alpha_channel(alpha_tok, raw)?; + Ok(format!("rgba({r},{g},{b},{a:.4})")) + } else { + Ok(format!("rgb({r},{g},{b})")) + } +} + +fn parse_rgb_channel(tok: &str, raw: &str) -> Result { + if let Some(pct) = tok.strip_suffix('%') { + let v = parse_css_number_in_range(pct, 0.0..=100.0, "rgb percentage", raw)?; + Ok(((v * 255.0) / 100.0).round().clamp(0.0, 255.0) as u8) + } else { + let v = parse_css_number_in_range(tok, 0.0..=255.0, "rgb channel", raw)?; + Ok(v.round() as u8) + } +} + +fn parse_alpha_channel(tok: &str, raw: &str) -> Result { + if let Some(pct) = tok.strip_suffix('%') { + Ok(parse_css_number_in_range(pct, 0.0..=100.0, "alpha percentage", raw)? / 100.0) + } else { + parse_css_number_in_range(tok, 0.0..=1.0, "alpha", raw) + } +} + +fn is_valid_css_number(tok: &str) -> bool { + let b = tok.as_bytes(); + let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-'))); + let int_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + let has_int = i > int_start; + let mut has_frac = false; + if i < b.len() && b[i] == b'.' { + i += 1; + let frac_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + has_frac = i > frac_start; + if !has_frac { + return false; + } + } + if !has_int && !has_frac { + return false; + } + if i < b.len() && matches!(b[i], b'e' | b'E') { + i += 1; + i += usize::from(i < b.len() && matches!(b[i], b'+' | b'-')); + let exp_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if i == exp_start { + return false; + } + } + i == b.len() +} + +fn parse_css_number_in_range( + tok: &str, + range: std::ops::RangeInclusive, + label: &str, + raw: &str, +) -> Result { + if !is_valid_css_number(tok) { + return Err(PreviewError::InvalidColor(format!( + "invalid CSS number '{tok}' in {raw}" + ))); + } + let val = tok + .parse::() + .ok() + .filter(|v| v.is_finite()) + .ok_or_else(|| { + PreviewError::InvalidColor(format!("invalid numeric channel '{tok}' in {raw}")) + })?; + if !range.contains(&val) { + return Err(PreviewError::InvalidColor(format!( + "{label} out of range: {raw}" + ))); + } + Ok(val) +} + +fn escape_xml_attr(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for ch in value.chars() { + match ch { + '&' => out.push_str("&"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + _ => out.push(ch), + } + } + out +} + +fn format_paint(color: Color, default_css: &str, attr_prefix: &str) -> (String, String) { + let is_default_black = + color.r == 0.0 && color.g == 0.0 && color.b == 0.0 && (color.a - 1.0).abs() < 1e-4; + if is_default_black { + // Use explicit #000000 when caller passed currentColor so resvg renders black cleanly. + let css = if default_css.eq_ignore_ascii_case("currentColor") { + "#000000".to_string() + } else { + escape_xml_attr(default_css) + }; + return (css, String::new()); + } + let r = (color.r.clamp(0.0, 1.0) * 255.0).round() as u8; + let g = (color.g.clamp(0.0, 1.0) * 255.0).round() as u8; + let b = (color.b.clamp(0.0, 1.0) * 255.0).round() as u8; + let paint = format!("rgb({r},{g},{b})"); + let opacity = if color.a < 0.999 { + format!(r#" {attr_prefix}-opacity="{:.3}""#, color.a.clamp(0.0, 1.0)) + } else { + String::new() + }; + (paint, opacity) +} + +#[cfg(test)] +mod tests { + use serde::Deserialize; + + use super::*; + use crate::test_support::build_test_font_pool; + + #[derive(Deserialize)] + struct KatexFixtureFile { + katex_version: String, + formulas: Vec, + } + + #[derive(Deserialize)] + struct KatexFormulaFixture { + name: String, + latex: String, + display_mode: bool, + katex_ok: bool, + height_em: f64, + depth_em: f64, + width_em: f64, + } + + #[test] + fn ratex_matches_v0275_katex_metrics_and_emits_zero_text_elements() { + let raw = include_str!("../tests/fixtures/katex_v0275_metrics.json"); + let fixture: KatexFixtureFile = + serde_json::from_str(raw).expect("valid katex_v0275_metrics.json"); + assert_eq!(fixture.katex_version, "0.18.10"); + assert_eq!(fixture.formulas.len(), 52); + + let pool = build_test_font_pool(); + let empty_pool = FontPool::new(); + let rasterizer = SvgRasterizer::new(&empty_pool); + + let mut passed = 0usize; + let mut metrics_matched = 0usize; + let mut katex_comparable = 0usize; + let mut width_rel_errors: Vec<(f64, String, f64, f64)> = Vec::new(); + + for item in &fixture.formulas { + let mode = if item.display_mode { + MathDisplayMode::Display + } else { + MathDisplayMode::Inline + }; + let opts = MathRenderOptions { + mode, + font_size_pt: 16.0, + padding_pt: 0.0, + color_css: "#000000".to_string(), + }; + let res = render_latex_svg(&item.latex, &opts, &pool); + if item.name == "edge_newcommand_builtin" { + // `\R` is a built-in RaTeX macro; `\newcommand{\R}` errors by design (use `\renewcommand`). + assert!(res.is_err(), "expected builtin \\R redefinition error"); + continue; + } + let out = res.unwrap_or_else(|err| { + panic!("ratex failed on {} ({}): {err}", item.name, item.latex) + }); + passed += 1; + assert!(out.svg.contains("", item.name); + assert!( + !out.svg.contains("", + item.name + ); + assert!(out.svg.contains("", item.name); + + // Pure SVG must rasterize with an empty FontPool (zero external fonts). + let rgba = rasterizer.rasterize(&out.svg, 2.0).unwrap(); + assert!( + rgba.count_non_transparent_pixels() > 0, + "{}: zero raster ink", + item.name + ); + + if item.katex_ok && !item.name.contains("cjk") { + katex_comparable += 1; + let height_em = out.ascent_pt / 16.0; + let depth_em = out.descent_pt / 16.0; + let dh = (height_em - item.height_em).abs(); + let dd = (depth_em - item.depth_em).abs(); + let limit = match item.name.as_str() { + "sum_squares" | "product_k" | "sinc_limit" | "accents" | "left_right_norm" => { + 0.085 + } + _ => 0.005, + }; + assert!( + dh <= limit && dd <= limit, + "KaTeX metric drift on {}: ratex=({height_em:.4}, {depth_em:.4}) vs katex=({:.4}, {:.4}), diff=({dh:.4}, {dd:.4}), limit={limit}", + item.name, + item.height_em, + item.depth_em, + ); + let width_em = out.width_pt / 16.0; + assert!(width_em > 0.0 && item.width_em > 0.0); + let rel_w = (width_em - item.width_em).abs() / item.width_em.max(0.5); + width_rel_errors.push((rel_w, item.name.clone(), width_em, item.width_em)); + metrics_matched += 1; + } + } + + // 51/52 pass (all 48 main + 3 of 4 edge cases including custom \newcommand). + assert_eq!(passed, 51); + assert_eq!(metrics_matched, katex_comparable); + + // Horizontal width parity check across all 48 non-CJK formulas (real Chromium katex@0.18.10 CSS + fonts). + width_rel_errors.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); + let p50 = width_rel_errors[width_rel_errors.len() / 2].0; + let p90 = width_rel_errors[(width_rel_errors.len() * 9) / 10].0; + let worst = width_rel_errors.last().unwrap(); + let within_10pct = width_rel_errors.iter().filter(|r| r.0 <= 0.10).count(); + eprintln!( + "KATEX_WIDTH_STATS n={} p50={:.4} p90={:.4} max={:.4} ({} ratex={:.3} katex={:.3}) <=10%={}", + width_rel_errors.len(), + p50, + p90, + worst.0, + worst.1, + worst.2, + worst.3, + within_10pct + ); + assert!( + p50 <= 0.01, + "median width relative error too high: {p50:.4}" + ); + assert!(p90 <= 0.05, "p90 width relative error too high: {p90:.4}"); + assert_eq!( + within_10pct, + width_rel_errors.len(), + "expected 100% width agreement <=10%, got {within_10pct}/{} (worst: {} {:.4})", + width_rel_errors.len(), + worst.1, + worst.0 + ); + } + + #[test] + fn color_css_is_strictly_validated_and_xml_escaped() { + let pool = FontPool::new(); + for valid in [ + "#1e293b", + "#fff", + "rgb(30, 41, 59)", + "rgb(30 41 59 / 50%)", + "rgb(10% 20 30)", + "rgb(50%, 50%, 50%)", + "rgba(0, 0, 0, 0.5)", + "currentColor", + "transparent", + "rebeccapurple", + "navy", + ] { + let opts = MathRenderOptions { + color_css: valid.to_string(), + ..MathRenderOptions::default() + }; + let out = render_latex_svg("E = mc^2", &opts, &pool) + .unwrap_or_else(|err| panic!("expected valid color '{valid}' to pass: {err}")); + assert!( + roxmltree::Document::parse(&out.svg).is_ok(), + "rendered SVG must be well-formed XML for color '{valid}'" + ); + } + assert_eq!( + validate_css_color("rgb(50%,50%,50%)").unwrap(), + "rgb(128,128,128)" + ); + let half_gray = render_latex_svg( + "E = mc^2", + &MathRenderOptions { + color_css: "rgb(50%,50%,50%)".to_string(), + ..MathRenderOptions::default() + }, + &pool, + ) + .unwrap(); + assert!(half_gray.svg.contains("rgb(128,128,128)")); + + for invalid in [ + "", + " ", + "notacolor", + r##"#000" onload="alert(1)"##, + "#12345", + "rgb(1, 2)", + "rgb(+, ., -)", + "rgb(,,1,2,3)", + "rgb(1.,2,3)", + "rgb(+1., 2, 3)", + "rgb(10%,20,30)", + "rgba(10%, 20, 30, 0.5)", + "rgb(256, 0, 0)", + "rgb(-1, 0, 0)", + "rgb(1, 2 3)", + "rgba(0, 0, 0, 1.5)", + "red; fill:url(http://evil)", + "