mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(preview): add pure-Rust offline preview kernel crate
This commit is contained in:
1 parent
0c9e634d08
commit
d619bfbcda
24 files changed
+8975
-64
No files matched your search
@@ -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
|
||||
|
||||
@@ -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:<docId>`), 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).
|
||||
|
||||
@@ -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 `<name>.rs` beside a `<name>/` 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
|
||||
```
|
||||
@@ -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 `<path>` 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 `<path>` outline determinism (zero `<text>` 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 `<foreignObject>` 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 <feature>,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 `<image href>` filesystem or network resolution.
|
||||
- Across the Wasm Worker boundary, Mermaid and Typst copy cached RGBA pixels once from the shared `Arc<RgbaImageBuffer>` (or move them via `Arc::try_unwrap` when unshared), while `take_pixels(&mut self)` eliminates a second clone on JS property access.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -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
|
||||
+218
@@ -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(`<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="stylesheet" href="/katex.min.css" />
|
||||
<style>
|
||||
body { margin: 0; padding: 16px; background: #fff; }
|
||||
#stage { font-size: 64px; line-height: 1; }
|
||||
.probe-inline { display: inline-block; white-space: nowrap; }
|
||||
.probe-display { display: block; width: 4000px; }
|
||||
.probe-display .katex-display > .katex > .katex-html { display: inline-block; }
|
||||
</style>
|
||||
<script src="/katex.min.js"></script>
|
||||
</head>
|
||||
<body><div id="stage"></div></body>
|
||||
</html>`);
|
||||
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();
|
||||
}
|
||||
@@ -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<RgbaImageBuffer>,
|
||||
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<K> {
|
||||
limits: CacheLimits,
|
||||
entries: HashMap<K, CacheEntry>,
|
||||
total_bytes: usize,
|
||||
pinned_entries: usize,
|
||||
pinned_bytes: usize,
|
||||
clock: u64,
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash + Clone> PinnedPixelCache<K> {
|
||||
/// 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<Arc<RgbaImageBuffer>> {
|
||||
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<RgbaImageBuffer>) -> 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<RgbaImageBuffer>) -> 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<K> = 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<RgbaImageBuffer>,
|
||||
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<RgbaImageBuffer> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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<typst_layout::PagedDocument>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
#[cfg(feature = "typst")]
|
||||
typst_files: Vec<(String, Vec<u8>)>,
|
||||
#[cfg(feature = "typst")]
|
||||
typst_package_files: Vec<(String, String, String, String, Vec<u8>)>,
|
||||
#[cfg(feature = "typst")]
|
||||
typst_inputs_generation: u64,
|
||||
#[cfg(feature = "typst")]
|
||||
typst_world: Option<InMemoryTypstWorld>,
|
||||
#[cfg(feature = "typst")]
|
||||
last_typst_doc: Option<CachedTypstDocument>,
|
||||
#[cfg(feature = "pdf")]
|
||||
pdf_docs: HashMap<u32, HayroPdfRenderer>,
|
||||
#[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<Vec<u8>>) -> Result<usize, PreviewError> {
|
||||
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<String> {
|
||||
&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<String>,
|
||||
bytes: impl Into<Vec<u8>>,
|
||||
) -> 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<String>,
|
||||
name: impl Into<String>,
|
||||
version: impl Into<String>,
|
||||
path: impl Into<String>,
|
||||
bytes: impl Into<Vec<u8>>,
|
||||
) -> 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<String, PreviewError> {
|
||||
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 `<text>` 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<Arc<RgbaImageBuffer>, 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<Arc<RgbaImageBuffer>, 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<Arc<RgbaImageBuffer>, 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-`<path>` SVG using registered fonts.
|
||||
#[cfg(feature = "math")]
|
||||
pub fn render_latex_svg(
|
||||
&self,
|
||||
latex: &str,
|
||||
options: &MathRenderOptions,
|
||||
) -> Result<MathSvgOutput, PreviewError> {
|
||||
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<MathRgbaOutput, PreviewError> {
|
||||
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<Vec<TypstSvgOutput>, 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<Arc<RgbaImageBuffer>, 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<Vec<u8>>) -> Result<u32, PreviewError> {
|
||||
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<usize, PreviewError> {
|
||||
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<Arc<typst_layout::PagedDocument>, 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<typst::syntax::package::PackageSpec, PreviewError> {
|
||||
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("<svg") && pages[1].svg.contains("<svg"));
|
||||
assert_ne!(pages[0].svg, pages[1].svg);
|
||||
|
||||
// Consecutive page RGBA renders reuse the cached compiled PagedDocument.
|
||||
let doc_before = Arc::clone(&engine.last_typst_doc.as_ref().unwrap().document);
|
||||
let p0 = engine
|
||||
.compile_typst_page_rgba(source, date, 0, 2.0)
|
||||
.unwrap();
|
||||
let p1 = engine
|
||||
.compile_typst_page_rgba(source, date, 1, 2.0)
|
||||
.unwrap();
|
||||
let doc_after = Arc::clone(&engine.last_typst_doc.as_ref().unwrap().document);
|
||||
assert!(Arc::ptr_eq(&doc_before, &doc_after));
|
||||
assert_ne!(p0.sha256(), p1.sha256());
|
||||
}
|
||||
|
||||
#[cfg(feature = "mermaid")]
|
||||
#[test]
|
||||
fn register_font_signals_missing_cjk_and_invalidates_mermaid_pixel_cache() {
|
||||
let mut engine = PreviewEngine::default();
|
||||
let mut fonts = typst_assets::fonts();
|
||||
let latin_1 = fonts.next().expect("font 1").to_vec();
|
||||
let latin_2 = fonts.next().expect("font 2").to_vec();
|
||||
engine.register_font(latin_1).unwrap();
|
||||
let gen_after_1 = engine.font_generation();
|
||||
|
||||
let opts = MermaidOptions::default();
|
||||
|
||||
// (a) Latin-only FontPool must return MissingGlyphFont on CJK Mermaid text
|
||||
// instead of silently rendering .notdef boxes, then succeed once CJK font is added.
|
||||
let cjk_src = "flowchart LR\n A[中文测试] --> B[Done]";
|
||||
let missing = engine.render_mermaid_rgba(cjk_src, &opts, 2.0);
|
||||
assert!(matches!(missing, Err(PreviewError::MissingGlyphFont(_))));
|
||||
|
||||
// (b) Pure-Latin Mermaid caches an Arc, and registering a second font bumps
|
||||
// font_generation so re-rendering does not return the stale cached Arc.
|
||||
let latin_src = "flowchart LR\n A[Start] --> B[Done]";
|
||||
let first = engine.render_mermaid_rgba(latin_src, &opts, 2.0).unwrap();
|
||||
engine.register_font(latin_2).unwrap();
|
||||
assert!(engine.font_generation() > 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);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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<Arc<[u8]>>,
|
||||
families: Vec<String>,
|
||||
covered_ranges: Vec<(u32, u32)>,
|
||||
sans_serif: Option<String>,
|
||||
serif: Option<String>,
|
||||
monospace: Option<String>,
|
||||
math: Option<String>,
|
||||
db: Arc<Database>,
|
||||
}
|
||||
|
||||
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<Vec<u8>>,
|
||||
) -> Result<usize, PreviewError> {
|
||||
let data: Vec<u8> = 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<String>) {
|
||||
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<String>) {
|
||||
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<String>) {
|
||||
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<String>) {
|
||||
self.math = Some(family.into());
|
||||
}
|
||||
|
||||
/// Returns the shared in-memory `fontdb::Database`.
|
||||
pub fn database(&self) -> Arc<Database> {
|
||||
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<u32>) {
|
||||
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<u32>) {
|
||||
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<String> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,326 @@
|
||||
use merman::model::OperationControl;
|
||||
use merman::model::runtime::RuntimePolicy;
|
||||
use merman::model::time::CivilDate;
|
||||
use merman::svg::SvgPipeline;
|
||||
use merman::{RenderOutput, RenderRequest, Renderer, SvgEnvironment, SvgRequest};
|
||||
|
||||
use crate::PreviewDate;
|
||||
use crate::error::PreviewError;
|
||||
use crate::svg_raster::{RasterOptions, RgbaImageBuffer, SvgRasterizer};
|
||||
|
||||
/// Configuration for deterministic `resvg_safe` Mermaid rendering.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MermaidOptions {
|
||||
/// Explicit calendar date used for Gantt `today` markers.
|
||||
pub today: PreviewDate,
|
||||
/// Explicit UTC offset in minutes (for example `+480` for UTC+8, `0` for UTC).
|
||||
pub timezone_offset_minutes: i16,
|
||||
/// Optional stable diagram identifier for scoped SVG ids.
|
||||
pub diagram_id: Option<String>,
|
||||
/// Extra padding around the computed SVG viewBox in CSS pixels.
|
||||
pub viewbox_padding: f64,
|
||||
}
|
||||
|
||||
impl Default for MermaidOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
today: PreviewDate::DEFAULT,
|
||||
timezone_offset_minutes: 0,
|
||||
diagram_id: None,
|
||||
viewbox_padding: 8.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure-Rust Mermaid renderer that emits `resvg`-safe SVG without `<foreignObject>`.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct MermaidRenderer;
|
||||
|
||||
impl MermaidRenderer {
|
||||
/// Creates a new deterministic Mermaid renderer.
|
||||
pub const fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
/// Renders Mermaid source into a `resvg`-safe SVG string (no `<foreignObject>`).
|
||||
pub fn render_svg(
|
||||
&self,
|
||||
source: &str,
|
||||
options: &MermaidOptions,
|
||||
) -> Result<String, PreviewError> {
|
||||
if source.trim().is_empty() {
|
||||
return Err(PreviewError::EmptyInput);
|
||||
}
|
||||
|
||||
let civil_date = CivilDate::new(
|
||||
options.today.year,
|
||||
u32::from(options.today.month),
|
||||
u32::from(options.today.day),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
PreviewError::Mermaid(format!(
|
||||
"invalid calendar date: {:04}-{:02}-{:02}",
|
||||
options.today.year, options.today.month, options.today.day
|
||||
))
|
||||
})?;
|
||||
|
||||
let runtime = RuntimePolicy::deterministic()
|
||||
.try_with_fixed_local_offset_minutes(i32::from(options.timezone_offset_minutes))
|
||||
.map_err(|err| PreviewError::Mermaid(err.to_string()))?
|
||||
.try_with_fixed_today_at_local_midnight(civil_date)
|
||||
.map_err(|err| PreviewError::Mermaid(err.to_string()))?;
|
||||
|
||||
let mut svg_request = SvgRequest {
|
||||
environment: SvgEnvironment::deterministic(),
|
||||
pipeline: Some(SvgPipeline::resvg_safe()),
|
||||
..SvgRequest::default()
|
||||
};
|
||||
svg_request.options.viewbox_padding = options.viewbox_padding;
|
||||
svg_request.options.diagram_id = options.diagram_id.clone();
|
||||
|
||||
let request = RenderRequest::svg(source, OperationControl::new(), svg_request);
|
||||
let renderer = Renderer::new().with_runtime_policy(runtime);
|
||||
let output = renderer
|
||||
.render(request)
|
||||
.map_err(|err| PreviewError::Mermaid(err.to_string()))?;
|
||||
|
||||
match output {
|
||||
RenderOutput::Svg(Some(document)) => {
|
||||
let svg = document.svg().to_string();
|
||||
if svg.contains("<foreignObject") {
|
||||
return Err(PreviewError::Mermaid(
|
||||
"merman emitted forbidden <foreignObject> tag under resvg_safe pipeline"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
Ok(svg)
|
||||
}
|
||||
RenderOutput::Svg(None) => Err(PreviewError::Mermaid(
|
||||
"source did not contain a Mermaid diagram".to_string(),
|
||||
)),
|
||||
_ => Err(PreviewError::Mermaid(
|
||||
"unexpected non-SVG output from Mermaid renderer".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders Mermaid source to `resvg`-safe SVG and rasterizes it into RGBA8 pixels.
|
||||
pub fn render_rgba(
|
||||
&self,
|
||||
source: &str,
|
||||
options: &MermaidOptions,
|
||||
rasterizer: &SvgRasterizer,
|
||||
raster_options: RasterOptions,
|
||||
) -> Result<RgbaImageBuffer, PreviewError> {
|
||||
let svg = self.render_svg(source, options)?;
|
||||
rasterizer.rasterize_with_options(&svg, raster_options)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::font_pool::FontPool;
|
||||
use crate::test_support::build_test_font_pool;
|
||||
|
||||
struct MermaidCase {
|
||||
name: &'static str,
|
||||
source: &'static str,
|
||||
has_cjk: bool,
|
||||
}
|
||||
|
||||
const CORPUS: &[MermaidCase] = &[
|
||||
MermaidCase {
|
||||
name: "flowchart",
|
||||
source: "flowchart TD\n A[Start] --> B{Valid?}\n B -->|Yes| C[Done]\n B -->|No| D[Retry]",
|
||||
has_cjk: false,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "flowchart_cjk",
|
||||
source: "flowchart LR\n A[开始流程] --> B[数据处理]\n B --> C[结束渲染]",
|
||||
has_cjk: true,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "sequence",
|
||||
source: "sequenceDiagram\n participant 用户\n participant 系统\n 用户->>系统: 发送请求\n 系统-->>用户: 返回预览",
|
||||
has_cjk: true,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "class",
|
||||
source: "classDiagram\n class PreviewCache {\n +usize max_bytes\n +acquire_pin()\n }\n class FontPool {\n +register_font_bytes()\n }\n PreviewCache --> FontPool",
|
||||
has_cjk: false,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "state",
|
||||
source: "stateDiagram-v2\n [*] --> Idle\n Idle --> Rendering: render\n Rendering --> Cached: ok\n Cached --> [*]",
|
||||
has_cjk: false,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "er",
|
||||
source: "erDiagram\n WORKSPACE ||--o{ DOCUMENT : contains\n DOCUMENT ||--|{ BLOCK : has",
|
||||
has_cjk: false,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "gantt",
|
||||
source: "gantt\n title 发布计划\n dateFormat YYYY-MM-DD\n section 预览核\n 光栅底座 :done, a1, 2026-01-01, 2d\n 公式渲染 :active, a2, after a1, 3d",
|
||||
has_cjk: true,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "pie",
|
||||
source: "pie title 占比分布\n \"流程图表\" : 45\n \"数学公式\" : 35\n \"文档预览\" : 20",
|
||||
has_cjk: true,
|
||||
},
|
||||
MermaidCase {
|
||||
name: "gitgraph",
|
||||
source: "gitGraph\n commit id: \"init\"\n branch preview\n checkout preview\n commit id: \"merman\"\n checkout main\n merge preview",
|
||||
has_cjk: false,
|
||||
},
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn renders_all_diagram_families_without_foreign_object_and_deterministically() {
|
||||
let pool = build_test_font_pool();
|
||||
let rasterizer = SvgRasterizer::new(&pool);
|
||||
let renderer = MermaidRenderer::new();
|
||||
let opts = MermaidOptions {
|
||||
today: PreviewDate::new(2026, 1, 3),
|
||||
timezone_offset_minutes: 480,
|
||||
diagram_id: Some("test-diagram".to_string()),
|
||||
viewbox_padding: 8.0,
|
||||
};
|
||||
|
||||
let mut total_2x_bytes = 0usize;
|
||||
let mut max_2x_bytes = 0usize;
|
||||
|
||||
for case in CORPUS {
|
||||
let svg = renderer
|
||||
.render_svg(case.source, &opts)
|
||||
.unwrap_or_else(|err| panic!("case {} failed to render svg: {err}", case.name));
|
||||
assert!(
|
||||
!svg.contains("<foreignObject"),
|
||||
"case {} must not emit <foreignObject>",
|
||||
case.name
|
||||
);
|
||||
assert!(
|
||||
svg.contains("<text"),
|
||||
"case {} must emit SVG <text> elements",
|
||||
case.name
|
||||
);
|
||||
|
||||
let first = rasterizer
|
||||
.rasterize(&svg, 2.0)
|
||||
.unwrap_or_else(|err| panic!("case {} failed to rasterize: {err}", case.name));
|
||||
let second = rasterizer.rasterize(&svg, 2.0).unwrap();
|
||||
|
||||
assert!(first.width_px > 0 && first.height_px > 0);
|
||||
assert_eq!(
|
||||
first.sha256(),
|
||||
second.sha256(),
|
||||
"case {} must be deterministic across repeated renders",
|
||||
case.name
|
||||
);
|
||||
let ink = first.count_non_transparent_pixels();
|
||||
assert!(
|
||||
ink > 100,
|
||||
"case {} rendered too few ink pixels: {ink}",
|
||||
case.name
|
||||
);
|
||||
|
||||
if case.has_cjk {
|
||||
// Empty FontPool must fail explicitly on SVG <text> instead of silently dropping glyphs.
|
||||
let empty_rasterizer = SvgRasterizer::new(&FontPool::new());
|
||||
assert!(matches!(
|
||||
empty_rasterizer.rasterize(&svg, 2.0),
|
||||
Err(PreviewError::MissingGlyphFont(_))
|
||||
));
|
||||
}
|
||||
|
||||
total_2x_bytes += first.byte_len();
|
||||
max_2x_bytes = max_2x_bytes.max(first.byte_len());
|
||||
}
|
||||
|
||||
assert!(total_2x_bytes > 0 && max_2x_bytes > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gantt_today_marker_moves_with_injected_preview_date() {
|
||||
let renderer = MermaidRenderer::new();
|
||||
let gantt = "gantt\n title Release\n dateFormat YYYY-MM-DD\n section Core\n Task A :a1, 2026-03-01, 20d\n";
|
||||
let early = renderer
|
||||
.render_svg(
|
||||
gantt,
|
||||
&MermaidOptions {
|
||||
today: PreviewDate::new(2026, 3, 2),
|
||||
timezone_offset_minutes: 0,
|
||||
..MermaidOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let late = renderer
|
||||
.render_svg(
|
||||
gantt,
|
||||
&MermaidOptions {
|
||||
today: PreviewDate::new(2026, 3, 18),
|
||||
timezone_offset_minutes: 0,
|
||||
..MermaidOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let extract_today_x = |svg: &str| -> f64 {
|
||||
let line_tag = svg
|
||||
.split("<line ")
|
||||
.skip(1)
|
||||
.filter_map(|part| part.split('>').next())
|
||||
.find(|attrs| attrs.contains("class=\"today\"") || attrs.contains("todayMarker"))
|
||||
.unwrap_or_else(|| {
|
||||
panic!("gantt SVG must contain a <line> with class=\"today\": {svg}")
|
||||
});
|
||||
let x1_pos = line_tag
|
||||
.find("x1=\"")
|
||||
.unwrap_or_else(|| panic!("today <line> must have x1 attribute: {line_tag}"));
|
||||
let after = &line_tag[x1_pos + 4..];
|
||||
let end = after.find('"').expect("closing quote");
|
||||
after[..end].parse::<f64>().expect("numeric x1")
|
||||
};
|
||||
|
||||
let x_early = extract_today_x(&early);
|
||||
let x_late = extract_today_x(&late);
|
||||
assert!(
|
||||
x_late > x_early + 20.0,
|
||||
"today marker must shift right from 2026-03-02 ({x_early}) to 2026-03-18 ({x_late})"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_cjk_labels_render_distinct_raster_pixels() {
|
||||
let pool = build_test_font_pool();
|
||||
let rasterizer = SvgRasterizer::new(&pool);
|
||||
let renderer = MermaidRenderer::new();
|
||||
let opts = MermaidOptions::default();
|
||||
|
||||
let svg_a = renderer
|
||||
.render_svg("flowchart LR\n A[中文] --> B[开始]", &opts)
|
||||
.unwrap();
|
||||
let svg_b = renderer
|
||||
.render_svg("flowchart LR\n A[测试] --> B[结束]", &opts)
|
||||
.unwrap();
|
||||
|
||||
let img_a = rasterizer.rasterize(&svg_a, 2.0).unwrap();
|
||||
let img_b = rasterizer.rasterize(&svg_b, 2.0).unwrap();
|
||||
assert_ne!(
|
||||
img_a.sha256(),
|
||||
img_b.sha256(),
|
||||
"different CJK labels must produce distinct glyph pixels"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_mermaid_input() {
|
||||
let renderer = MermaidRenderer::new();
|
||||
assert!(matches!(
|
||||
renderer.render_svg(" ", &MermaidOptions::default()),
|
||||
Err(PreviewError::EmptyInput)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use hayro::hayro_interpret::InterpreterSettings;
|
||||
use hayro::hayro_syntax::Pdf;
|
||||
use hayro::vello_cpu::color::{AlphaColor, Srgb};
|
||||
use hayro::{PixmapSettings, RenderCache, RenderSettings};
|
||||
|
||||
use crate::error::PreviewError;
|
||||
use crate::svg_raster::{DEFAULT_MAX_EDGE_PX, RgbaImageBuffer};
|
||||
|
||||
/// Intrinsic PDF page dimensions in PDF points (1/72 inch).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PdfPageSize {
|
||||
/// Page width in points.
|
||||
pub width_pt: f32,
|
||||
/// Page height in points.
|
||||
pub height_pt: f32,
|
||||
}
|
||||
|
||||
/// Parameters controlling a single PDF page rasterization pass.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PdfRenderRequest {
|
||||
/// Zero-based page index.
|
||||
pub page_index: usize,
|
||||
/// Device pixel scale factor relative to PDF points.
|
||||
pub scale: f32,
|
||||
/// Maximum allowed physical width or height in pixels.
|
||||
pub max_edge_px: u32,
|
||||
/// Background clear color as `[r, g, b, a]` bytes.
|
||||
pub background_rgba: [u8; 4],
|
||||
}
|
||||
|
||||
impl Default for PdfRenderRequest {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
page_index: 0,
|
||||
scale: 2.0,
|
||||
max_edge_px: DEFAULT_MAX_EDGE_PX,
|
||||
background_rgba: [255, 255, 255, 255],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PdfRenderRequest {
|
||||
/// Creates a render request for `page_index` at the given scale factor.
|
||||
pub fn for_page(page_index: usize, scale: f32) -> Self {
|
||||
Self {
|
||||
page_index,
|
||||
scale,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cross-platform PDF page rendering contract.
|
||||
///
|
||||
/// Native iOS and Android hosts can back this trait with `PDFKit` and
|
||||
/// `PdfRenderer`, while Web and cross-platform callers use [`HayroPdfRenderer`].
|
||||
pub trait PdfPageRenderer {
|
||||
/// Returns the total number of pages in the PDF document.
|
||||
fn page_count(&self) -> usize;
|
||||
|
||||
/// Returns the intrinsic point dimensions of `page_index`.
|
||||
fn page_size(&self, page_index: usize) -> Result<PdfPageSize, PreviewError>;
|
||||
|
||||
/// Renders `request.page_index` into a compact RGBA8 pixel buffer.
|
||||
fn render_page(&self, request: PdfRenderRequest) -> Result<RgbaImageBuffer, PreviewError>;
|
||||
}
|
||||
|
||||
/// Pure safe Rust PDF page renderer powered by `hayro`.
|
||||
pub struct HayroPdfRenderer {
|
||||
pdf: Pdf,
|
||||
}
|
||||
|
||||
impl HayroPdfRenderer {
|
||||
/// Parses a PDF byte buffer into a reusable renderer.
|
||||
pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self, PreviewError> {
|
||||
let data = bytes.into();
|
||||
if data.is_empty() {
|
||||
return Err(PreviewError::EmptyInput);
|
||||
}
|
||||
let pdf = Pdf::new(Arc::new(data)).map_err(|err| PreviewError::Pdf(format!("{err:?}")))?;
|
||||
Ok(Self { pdf })
|
||||
}
|
||||
}
|
||||
|
||||
impl PdfPageRenderer for HayroPdfRenderer {
|
||||
fn page_count(&self) -> usize {
|
||||
self.pdf.pages().len()
|
||||
}
|
||||
|
||||
fn page_size(&self, page_index: usize) -> Result<PdfPageSize, PreviewError> {
|
||||
let pages = self.pdf.pages();
|
||||
let page = pages.get(page_index).ok_or(PreviewError::PageOutOfRange {
|
||||
index: page_index,
|
||||
page_count: pages.len(),
|
||||
})?;
|
||||
let (width_pt, height_pt) = page.render_dimensions();
|
||||
Ok(PdfPageSize {
|
||||
width_pt,
|
||||
height_pt,
|
||||
})
|
||||
}
|
||||
|
||||
fn render_page(&self, request: PdfRenderRequest) -> Result<RgbaImageBuffer, PreviewError> {
|
||||
if !request.scale.is_finite() || request.scale <= 0.0 {
|
||||
return Err(PreviewError::InvalidSize(format!(
|
||||
"pdf scale must be positive and finite, got {}",
|
||||
request.scale
|
||||
)));
|
||||
}
|
||||
if request.max_edge_px == 0 {
|
||||
return Err(PreviewError::InvalidSize(
|
||||
"max_edge_px must be greater than zero".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let pages = self.pdf.pages();
|
||||
let page = pages
|
||||
.get(request.page_index)
|
||||
.ok_or(PreviewError::PageOutOfRange {
|
||||
index: request.page_index,
|
||||
page_count: pages.len(),
|
||||
})?;
|
||||
|
||||
let (logical_width, logical_height) = page.render_dimensions();
|
||||
if !logical_width.is_finite()
|
||||
|| !logical_height.is_finite()
|
||||
|| logical_width <= 0.0
|
||||
|| logical_height <= 0.0
|
||||
{
|
||||
return Err(PreviewError::InvalidSize(format!(
|
||||
"pdf page dimensions are invalid: {logical_width}x{logical_height}"
|
||||
)));
|
||||
}
|
||||
|
||||
let max_edge = (request.max_edge_px.min(u16::MAX as u32)) as f32;
|
||||
let raw_w = (logical_width * request.scale).max(1.0);
|
||||
let raw_h = (logical_height * request.scale).max(1.0);
|
||||
let clamp = (max_edge / raw_w).min(max_edge / raw_h).min(1.0);
|
||||
let effective_scale = request.scale * clamp;
|
||||
|
||||
let [r, g, b, a] = request.background_rgba;
|
||||
let bg_color = AlphaColor::<Srgb>::from_rgba8(r, g, b, a);
|
||||
|
||||
let cache = RenderCache::new();
|
||||
let interpreter_settings = InterpreterSettings::default();
|
||||
let render_settings = RenderSettings::default();
|
||||
let pixmap_settings = PixmapSettings {
|
||||
x_scale: effective_scale,
|
||||
y_scale: effective_scale,
|
||||
bg_color,
|
||||
};
|
||||
|
||||
let pixmap = hayro::render(
|
||||
page,
|
||||
&cache,
|
||||
&interpreter_settings,
|
||||
&render_settings,
|
||||
&pixmap_settings,
|
||||
);
|
||||
|
||||
let width_px = u32::from(pixmap.width());
|
||||
let height_px = u32::from(pixmap.height());
|
||||
let pixels = pixmap.data_as_u8_slice().to_vec();
|
||||
|
||||
Ok(RgbaImageBuffer {
|
||||
width_px,
|
||||
height_px,
|
||||
logical_width,
|
||||
logical_height,
|
||||
pixels,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Builds a valid multi-page PDF 1.4 fixture with text, vector paths, and transparency.
|
||||
fn build_multipage_pdf_fixture() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
|
||||
|
||||
let mut offsets = vec![0usize];
|
||||
let mut push_obj = |body: &str| {
|
||||
offsets.push(out.len());
|
||||
let id = offsets.len() - 1;
|
||||
out.extend_from_slice(format!("{id} 0 obj\n{body}\nendobj\n").as_bytes());
|
||||
};
|
||||
|
||||
// 1: Catalog
|
||||
push_obj("<< /Type /Catalog /Pages 2 0 R >>");
|
||||
// 2: Pages (3 pages)
|
||||
push_obj("<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>");
|
||||
// 3: Page 1 (text + filled vector shapes)
|
||||
push_obj(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 120] \
|
||||
/Resources << /Font << /F1 6 0 R >> >> /Contents 7 0 R >>",
|
||||
);
|
||||
// 4: Page 2 (transparency + overlapping shapes)
|
||||
push_obj(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 240 160] \
|
||||
/Resources << /Font << /F1 6 0 R >> /ExtGState << /GS1 9 0 R >> >> /Contents 8 0 R >>",
|
||||
);
|
||||
// 5: Page 3 (Type3 embedded glyph font + Bezier curve)
|
||||
push_obj(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 180 100] \
|
||||
/Resources << /Font << /F3 10 0 R >> >> /Contents 12 0 R >>",
|
||||
);
|
||||
// 6: Standard Type1 Helvetica font
|
||||
push_obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
|
||||
// 7: Page 1 content stream
|
||||
let p1_stream = "0.1 0.4 0.9 rg 12 12 60 36 re f \
|
||||
0.8 0.1 0.2 RG 2 w 80 12 40 36 re S \
|
||||
0 0 0 rg BT /F1 18 Tf 16 80 Td (Hello PDF) Tj ET";
|
||||
push_obj(&format!(
|
||||
"<< /Length {} >>\nstream\n{p1_stream}\nendstream",
|
||||
p1_stream.len()
|
||||
));
|
||||
// 8: Page 2 content stream (alpha transparency)
|
||||
let p2_stream = "0.9 0.2 0.2 rg 20 20 90 90 re f \
|
||||
/GS1 gs 0.1 0.3 0.9 rg 60 40 90 90 re f \
|
||||
0 0 0 rg BT /F1 14 Tf 24 132 Td (Alpha Layer) Tj ET";
|
||||
push_obj(&format!(
|
||||
"<< /Length {} >>\nstream\n{p2_stream}\nendstream",
|
||||
p2_stream.len()
|
||||
));
|
||||
// 9: ExtGState with 50% fill and stroke opacity
|
||||
push_obj("<< /Type /ExtGState /ca 0.5 /CA 0.5 >>");
|
||||
// 10: Embedded Type3 font with custom glyph 'A'
|
||||
push_obj(
|
||||
"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] \
|
||||
/FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /A 11 0 R >> \
|
||||
/Encoding << /Type /Encoding /Differences [65 /A] >> \
|
||||
/FirstChar 65 /LastChar 65 /Widths [700] >>",
|
||||
);
|
||||
// 11: Type3 glyph 'A' outline stream
|
||||
let glyph_a = "700 0 0 0 650 700 d1 100 0 m 350 700 l 600 0 l 500 0 l 350 450 l 200 0 l f";
|
||||
push_obj(&format!(
|
||||
"<< /Length {} >>\nstream\n{glyph_a}\nendstream",
|
||||
glyph_a.len()
|
||||
));
|
||||
// 12: Page 3 content stream
|
||||
let p3_stream = "0.1 0.6 0.3 RG 3 w 10 20 m 60 90 120 10 170 80 c S \
|
||||
0 0 0 rg BT /F3 24 Tf 30 40 Td (AA) Tj ET";
|
||||
push_obj(&format!(
|
||||
"<< /Length {} >>\nstream\n{p3_stream}\nendstream",
|
||||
p3_stream.len()
|
||||
));
|
||||
|
||||
let xref_pos = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n", offsets.len()).as_bytes());
|
||||
out.extend_from_slice(b"0000000000 65535 f \n");
|
||||
for offset in offsets.iter().skip(1) {
|
||||
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n",
|
||||
offsets.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_multipage_pdf_fixture_deterministically() {
|
||||
let bytes = build_multipage_pdf_fixture();
|
||||
let renderer = HayroPdfRenderer::from_bytes(bytes).unwrap();
|
||||
assert_eq!(renderer.page_count(), 3);
|
||||
|
||||
let cases = [
|
||||
(0usize, 200.0_f32, 120.0_f32, 1.5_f32),
|
||||
(1usize, 240.0_f32, 160.0_f32, 2.0_f32),
|
||||
(2usize, 180.0_f32, 100.0_f32, 2.0_f32),
|
||||
];
|
||||
|
||||
for (page_index, expected_w, expected_h, scale) in cases {
|
||||
let size = renderer.page_size(page_index).unwrap();
|
||||
assert_eq!(size.width_pt, expected_w);
|
||||
assert_eq!(size.height_pt, expected_h);
|
||||
|
||||
let req = PdfRenderRequest::for_page(page_index, scale);
|
||||
let first = renderer.render_page(req).unwrap();
|
||||
let second = renderer.render_page(req).unwrap();
|
||||
assert_eq!(first.width_px, (expected_w * scale) as u32);
|
||||
assert_eq!(first.height_px, (expected_h * scale) as u32);
|
||||
assert_eq!(
|
||||
first.byte_len(),
|
||||
(first.width_px * first.height_px * 4) as usize
|
||||
);
|
||||
assert!(
|
||||
first.count_ink_pixels([255, 255, 255, 255], 4) > 50,
|
||||
"page {page_index} must contain visible rendered ink"
|
||||
);
|
||||
assert_eq!(first.sha256(), second.sha256());
|
||||
}
|
||||
|
||||
assert!(matches!(
|
||||
renderer.page_size(3),
|
||||
Err(PreviewError::PageOutOfRange {
|
||||
index: 3,
|
||||
page_count: 3
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_pdf_render_to_max_edge_and_rejects_empty_input() {
|
||||
assert!(matches!(
|
||||
HayroPdfRenderer::from_bytes(Vec::new()),
|
||||
Err(PreviewError::EmptyInput)
|
||||
));
|
||||
|
||||
let renderer = HayroPdfRenderer::from_bytes(build_multipage_pdf_fixture()).unwrap();
|
||||
let buf = renderer
|
||||
.render_page(PdfRenderRequest {
|
||||
page_index: 1,
|
||||
scale: 4.0,
|
||||
max_edge_px: 120,
|
||||
background_rgba: [255, 255, 255, 255],
|
||||
})
|
||||
.unwrap();
|
||||
assert!(buf.width_px <= 120 && buf.height_px <= 120);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,846 @@
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use resvg::tiny_skia::{Pixmap, Transform};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::error::PreviewError;
|
||||
use crate::font_pool::FontPool;
|
||||
|
||||
/// Default maximum raster edge in physical pixels to bound memory usage.
|
||||
pub const DEFAULT_MAX_EDGE_PX: u32 = 4096;
|
||||
|
||||
/// Compact RGBA8 pixel buffer produced by SVG or PDF rasterization.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RgbaImageBuffer {
|
||||
/// Physical pixel width.
|
||||
pub width_px: u32,
|
||||
/// Physical pixel height.
|
||||
pub height_px: u32,
|
||||
/// Logical width in CSS pixels or points.
|
||||
pub logical_width: f32,
|
||||
/// Logical height in CSS pixels or points.
|
||||
pub logical_height: f32,
|
||||
/// Tightly packed RGBA8 pixel bytes (`width_px * height_px * 4`).
|
||||
pub pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
impl RgbaImageBuffer {
|
||||
/// Returns the total byte size of the pixel buffer.
|
||||
pub fn byte_len(&self) -> usize {
|
||||
self.pixels.len()
|
||||
}
|
||||
|
||||
/// Computes a deterministic SHA-256 digest over dimensions and pixel bytes.
|
||||
pub fn sha256(&self) -> [u8; 32] {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(self.width_px.to_le_bytes());
|
||||
hasher.update(self.height_px.to_le_bytes());
|
||||
hasher.update(&self.pixels);
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
/// Formats the deterministic SHA-256 digest as lowercase hexadecimal.
|
||||
pub fn sha256_hex(&self) -> String {
|
||||
let digest = self.sha256();
|
||||
let mut out = String::with_capacity(64);
|
||||
for byte in digest {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(&mut out, "{byte:02x}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Counts pixels that differ from the given RGBA color by more than `tolerance`.
|
||||
pub fn count_ink_pixels(&self, background: [u8; 4], tolerance: u8) -> usize {
|
||||
self.pixels
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|px| {
|
||||
px[0].abs_diff(background[0]) > tolerance
|
||||
|| px[1].abs_diff(background[1]) > tolerance
|
||||
|| px[2].abs_diff(background[2]) > tolerance
|
||||
|| px[3].abs_diff(background[3]) > tolerance
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Counts non-transparent pixels (`alpha > 0`).
|
||||
pub fn count_non_transparent_pixels(&self) -> usize {
|
||||
self.pixels
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|px| px[3] > 0)
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Target sizing options for SVG rasterization.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RasterOptions {
|
||||
/// Device scale factor applied to logical dimensions (for example `2.0`).
|
||||
pub scale_factor: f32,
|
||||
/// Optional logical width override. When set without height, aspect ratio is preserved.
|
||||
pub target_logical_width: Option<f32>,
|
||||
/// Optional logical height override. When set without width, aspect ratio is preserved.
|
||||
pub target_logical_height: Option<f32>,
|
||||
/// Maximum allowed physical width or height in pixels.
|
||||
pub max_edge_px: u32,
|
||||
/// When `false` (default), missing glyphs in SVG `<text>` elements fail with
|
||||
/// [`PreviewError::MissingGlyphFont`] so hosts can fetch script fonts on demand.
|
||||
/// When `true`, rasterization proceeds best-effort even if some glyphs are uncovered.
|
||||
pub allow_missing_glyphs: bool,
|
||||
}
|
||||
|
||||
impl Default for RasterOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
scale_factor: 2.0,
|
||||
target_logical_width: None,
|
||||
target_logical_height: None,
|
||||
max_edge_px: DEFAULT_MAX_EDGE_PX,
|
||||
allow_missing_glyphs: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterOptions {
|
||||
/// Creates raster options with the given scale factor and default limits.
|
||||
pub fn with_scale(scale_factor: f32) -> Self {
|
||||
Self {
|
||||
scale_factor,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure-Rust deterministic SVG rasterizer backed by `usvg` and `resvg`.
|
||||
///
|
||||
/// Uses only fonts explicitly registered in its [`FontPool`] and blocks all
|
||||
/// external filesystem or URL `<image href="...">` resolution.
|
||||
#[derive(Clone)]
|
||||
pub struct SvgRasterizer {
|
||||
options: Arc<usvg::Options<'static>>,
|
||||
font_pool: FontPool,
|
||||
}
|
||||
|
||||
impl SvgRasterizer {
|
||||
/// Builds a rasterizer bound to the given explicit [`FontPool`].
|
||||
pub fn new(font_pool: &FontPool) -> Self {
|
||||
let fontdb = font_pool.database();
|
||||
let default_selector = usvg::FontResolver::default_font_selector();
|
||||
let default_fallback = usvg::FontResolver::default_fallback_selector();
|
||||
|
||||
let select_font = Box::new(
|
||||
move |font: &usvg::Font, db: &mut Arc<usvg::fontdb::Database>| {
|
||||
if let Some(id) = default_selector(font, db) {
|
||||
return Some(id);
|
||||
}
|
||||
let sans_query = usvg::fontdb::Query {
|
||||
families: &[usvg::fontdb::Family::SansSerif],
|
||||
..Default::default()
|
||||
};
|
||||
db.query(&sans_query)
|
||||
.or_else(|| db.faces().next().map(|face| face.id))
|
||||
},
|
||||
);
|
||||
|
||||
let select_fallback = Box::new(
|
||||
move |ch: char, fonts: &[usvg::fontdb::ID], db: &mut Arc<usvg::fontdb::Database>| {
|
||||
default_fallback(ch, fonts, db)
|
||||
},
|
||||
);
|
||||
|
||||
// Allow inline `data:` images only; block all host filesystem paths and URLs.
|
||||
let image_href_resolver = usvg::ImageHrefResolver {
|
||||
resolve_data: usvg::ImageHrefResolver::default_data_resolver(),
|
||||
resolve_string: Box::new(|_, _| None),
|
||||
};
|
||||
|
||||
let mut usvg_options = usvg::Options {
|
||||
fontdb,
|
||||
font_resolver: usvg::FontResolver {
|
||||
select_font,
|
||||
select_fallback,
|
||||
},
|
||||
image_href_resolver,
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(sans) = font_pool.sans_serif_family() {
|
||||
usvg_options.font_family = sans.to_string();
|
||||
}
|
||||
|
||||
Self {
|
||||
options: Arc::new(usvg_options),
|
||||
font_pool: font_pool.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterizes an SVG string at the given scale factor.
|
||||
pub fn rasterize(&self, svg: &str, scale_factor: f32) -> Result<RgbaImageBuffer, PreviewError> {
|
||||
self.rasterize_with_options(svg, RasterOptions::with_scale(scale_factor))
|
||||
}
|
||||
|
||||
/// Rasterizes an SVG string with explicit sizing and scale options.
|
||||
pub fn rasterize_with_options(
|
||||
&self,
|
||||
svg: &str,
|
||||
options: RasterOptions,
|
||||
) -> Result<RgbaImageBuffer, PreviewError> {
|
||||
if svg.trim().is_empty() {
|
||||
return Err(PreviewError::EmptyInput);
|
||||
}
|
||||
if !options.scale_factor.is_finite() || options.scale_factor <= 0.0 {
|
||||
return Err(PreviewError::InvalidSize(format!(
|
||||
"scale_factor must be positive and finite, got {}",
|
||||
options.scale_factor
|
||||
)));
|
||||
}
|
||||
if options.max_edge_px == 0 {
|
||||
return Err(PreviewError::InvalidSize(
|
||||
"max_edge_px must be greater than zero".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let tree = usvg::Tree::from_str(svg, &self.options)
|
||||
.map_err(|err| PreviewError::SvgParse(err.to_string()))?;
|
||||
if !options.allow_missing_glyphs {
|
||||
// Collect uncovered codepoints across both the actual render tree and the synthetic
|
||||
// non-empty `.notdef` probe tree in one shared deduplicated pass so neither glyphs
|
||||
// kept only by real font metrics (e.g. negative-`startOffset` `<textPath>`) nor `<text>`
|
||||
// elements dropped by outline-less `.notdef` subset fonts omit missing codepoints.
|
||||
let probe = usvg::Tree::from_str(svg, glyph_probe_options())
|
||||
.map_err(|err| PreviewError::SvgParse(err.to_string()))?;
|
||||
verify_trees_text_glyph_coverage(&[&tree, &probe], &self.font_pool)?;
|
||||
}
|
||||
|
||||
rasterize_tree(&tree, options)
|
||||
}
|
||||
}
|
||||
|
||||
fn rasterize_tree(
|
||||
tree: &usvg::Tree,
|
||||
options: RasterOptions,
|
||||
) -> Result<RgbaImageBuffer, PreviewError> {
|
||||
let svg_size = tree.size();
|
||||
let src_w = svg_size.width();
|
||||
let src_h = svg_size.height();
|
||||
if !src_w.is_finite() || !src_h.is_finite() || src_w <= 0.0 || src_h <= 0.0 {
|
||||
return Err(PreviewError::InvalidSize(format!(
|
||||
"svg intrinsic size is invalid: {src_w}x{src_h}"
|
||||
)));
|
||||
}
|
||||
|
||||
let (logical_width, logical_height) =
|
||||
match (options.target_logical_width, options.target_logical_height) {
|
||||
(Some(w), Some(h)) => (w, h),
|
||||
(Some(w), None) => (w, src_h * (w / src_w)),
|
||||
(None, Some(h)) => (src_w * (h / src_h), h),
|
||||
(None, None) => (src_w, src_h),
|
||||
};
|
||||
|
||||
if !logical_width.is_finite()
|
||||
|| !logical_height.is_finite()
|
||||
|| logical_width <= 0.0
|
||||
|| logical_height <= 0.0
|
||||
{
|
||||
return Err(PreviewError::InvalidSize(format!(
|
||||
"logical size must be positive and finite: {logical_width}x{logical_height}"
|
||||
)));
|
||||
}
|
||||
|
||||
let raw_w = (logical_width * options.scale_factor).max(1.0);
|
||||
let raw_h = (logical_height * options.scale_factor).max(1.0);
|
||||
let max_edge = options.max_edge_px as f32;
|
||||
let clamp = (max_edge / raw_w).min(max_edge / raw_h).min(1.0);
|
||||
let width_px = (raw_w * clamp).round().max(1.0) as u32;
|
||||
let height_px = (raw_h * clamp).round().max(1.0) as u32;
|
||||
|
||||
let mut pixmap = Pixmap::new(width_px, height_px).ok_or_else(|| {
|
||||
PreviewError::InvalidSize(format!(
|
||||
"failed to allocate pixmap of size {width_px}x{height_px}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let scale_x = width_px as f32 / src_w;
|
||||
let scale_y = height_px as f32 / src_h;
|
||||
let transform = Transform::from_scale(scale_x, scale_y);
|
||||
resvg::render(tree, transform, &mut pixmap.as_mut());
|
||||
|
||||
Ok(RgbaImageBuffer {
|
||||
width_px,
|
||||
height_px,
|
||||
logical_width,
|
||||
logical_height,
|
||||
pixels: pixmap.take(),
|
||||
})
|
||||
}
|
||||
|
||||
fn verify_trees_text_glyph_coverage(
|
||||
trees: &[&usvg::Tree],
|
||||
font_pool: &FontPool,
|
||||
) -> Result<(), PreviewError> {
|
||||
let mut missing: Vec<char> = Vec::new();
|
||||
for tree in trees {
|
||||
walk_usvg_root_group(tree.root(), font_pool, &mut missing);
|
||||
}
|
||||
|
||||
if !missing.is_empty() {
|
||||
let list = missing
|
||||
.iter()
|
||||
.map(|&ch| format!("U+{:04X} ('{ch}')", ch as u32))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let detail = if font_pool.is_empty() {
|
||||
format!("SVG <text> requires glyphs [{list}] but FontPool has no registered fonts")
|
||||
} else {
|
||||
format!("SVG <text> contains uncovered glyphs [{list}] not present in FontPool")
|
||||
};
|
||||
return Err(PreviewError::MissingGlyphFont(detail));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn walk_usvg_root_group(group: &usvg::Group, font_pool: &FontPool, missing: &mut Vec<char>) {
|
||||
if let Some(clip) = group.clip_path() {
|
||||
walk_usvg_root_group(clip.root(), font_pool, missing);
|
||||
}
|
||||
if let Some(mask) = group.mask() {
|
||||
walk_usvg_root_group(mask.root(), font_pool, missing);
|
||||
}
|
||||
walk_usvg_children(group, font_pool, missing);
|
||||
}
|
||||
|
||||
fn walk_usvg_children(group: &usvg::Group, font_pool: &FontPool, missing: &mut Vec<char>) {
|
||||
for node in group.children() {
|
||||
match node {
|
||||
usvg::Node::Group(child_group) => {
|
||||
node.subroots(|subroot| walk_usvg_root_group(subroot, font_pool, missing));
|
||||
walk_usvg_children(child_group, font_pool, missing);
|
||||
}
|
||||
usvg::Node::Path(path) => {
|
||||
if !path.is_visible() {
|
||||
continue;
|
||||
}
|
||||
if path.data().bounds().width() > 0.0
|
||||
&& path.data().bounds().height() > 0.0
|
||||
&& let Some(usvg::Paint::Pattern(pattern)) = path.fill().map(|f| f.paint())
|
||||
{
|
||||
walk_usvg_root_group(pattern.root(), font_pool, missing);
|
||||
}
|
||||
if let Some(usvg::Paint::Pattern(pattern)) = path.stroke().map(|s| s.paint()) {
|
||||
walk_usvg_root_group(pattern.root(), font_pool, missing);
|
||||
}
|
||||
}
|
||||
usvg::Node::Image(image) => {
|
||||
if !image.is_visible() {
|
||||
continue;
|
||||
}
|
||||
node.subroots(|subroot| walk_usvg_root_group(subroot, font_pool, missing));
|
||||
}
|
||||
usvg::Node::Text(text) => {
|
||||
walk_usvg_root_group(text.flattened(), font_pool, missing);
|
||||
for chunk in text.chunks() {
|
||||
let chunk_text = chunk.text();
|
||||
for span in chunk.spans() {
|
||||
if !span.is_visible() {
|
||||
continue;
|
||||
}
|
||||
if let Some(slice) = chunk_text.get(span.start()..span.end()) {
|
||||
for ch in slice.chars() {
|
||||
if !is_ignorable_for_glyph_check(ch)
|
||||
&& !font_pool.has_glyph(ch)
|
||||
&& !missing.contains(&ch)
|
||||
{
|
||||
missing.push(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `usvg::Options` with a minimal 1-glyph synthetic `.notdef` font so `usvg`
|
||||
/// preserves reachable `Node::Text` elements (expanding `<use>`/`<tref>` while pruning
|
||||
/// unreferenced `<defs>`) even when [`FontPool`] is empty or its selected face has an
|
||||
/// outline-less `.notdef` glyph.
|
||||
fn glyph_probe_options() -> &'static usvg::Options<'static> {
|
||||
static PROBE_OPTS: OnceLock<usvg::Options<'static>> = OnceLock::new();
|
||||
PROBE_OPTS.get_or_init(|| {
|
||||
let mut db = usvg::fontdb::Database::new();
|
||||
db.load_font_data(build_minimal_probe_ttf());
|
||||
debug_assert!(
|
||||
db.faces().next().is_some(),
|
||||
"synthetic probe TTF must register one face in fontdb"
|
||||
);
|
||||
db.set_sans_serif_family("Probe");
|
||||
let fontdb = Arc::new(db);
|
||||
let select_font = Box::new(
|
||||
move |_font: &usvg::Font, db: &mut Arc<usvg::fontdb::Database>| {
|
||||
db.faces().next().map(|face| face.id)
|
||||
},
|
||||
);
|
||||
let select_fallback = Box::new(
|
||||
move |_ch: char, _fonts: &[usvg::fontdb::ID], _db: &mut Arc<usvg::fontdb::Database>| {
|
||||
None
|
||||
},
|
||||
);
|
||||
usvg::Options {
|
||||
fontdb,
|
||||
font_family: "Probe".to_string(),
|
||||
font_resolver: usvg::FontResolver {
|
||||
select_font,
|
||||
select_fallback,
|
||||
},
|
||||
image_href_resolver: usvg::ImageHrefResolver {
|
||||
resolve_data: usvg::ImageHrefResolver::default_data_resolver(),
|
||||
resolve_string: Box::new(|_, _| None),
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn build_minimal_probe_ttf() -> Vec<u8> {
|
||||
let mut head = vec![0u8; 54];
|
||||
head[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
head[4..8].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
head[12..16].copy_from_slice(&0x5F0F_3CF5_u32.to_be_bytes());
|
||||
head[18..20].copy_from_slice(&1000_u16.to_be_bytes());
|
||||
head[50..52].copy_from_slice(&1_i16.to_be_bytes());
|
||||
|
||||
let mut hhea = vec![0u8; 36];
|
||||
hhea[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
hhea[4..6].copy_from_slice(&800_i16.to_be_bytes());
|
||||
hhea[6..8].copy_from_slice(&(-200_i16).to_be_bytes());
|
||||
hhea[34..36].copy_from_slice(&1_u16.to_be_bytes());
|
||||
|
||||
let mut maxp = vec![0u8; 32];
|
||||
maxp[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
maxp[4..6].copy_from_slice(&1_u16.to_be_bytes());
|
||||
maxp[6..8].copy_from_slice(&4_u16.to_be_bytes());
|
||||
maxp[8..10].copy_from_slice(&1_u16.to_be_bytes());
|
||||
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[0..2].copy_from_slice(&1_u16.to_be_bytes());
|
||||
os2[4..6].copy_from_slice(&400_u16.to_be_bytes());
|
||||
os2[6..8].copy_from_slice(&5_u16.to_be_bytes());
|
||||
os2[62..64].copy_from_slice(&0x0040_u16.to_be_bytes());
|
||||
os2[68..70].copy_from_slice(&800_i16.to_be_bytes());
|
||||
os2[70..72].copy_from_slice(&(-200_i16).to_be_bytes());
|
||||
|
||||
let records = [
|
||||
(1_u16, "Probe"),
|
||||
(2_u16, "Regular"),
|
||||
(4_u16, "Probe Regular"),
|
||||
(6_u16, "Probe-Regular"),
|
||||
];
|
||||
let mut storage = Vec::new();
|
||||
let mut entries = Vec::new();
|
||||
for (name_id, text) in records {
|
||||
let utf16: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
entries.push((name_id, utf16.len() as u16, storage.len() as u16));
|
||||
storage.extend_from_slice(&utf16);
|
||||
}
|
||||
let count = entries.len() as u16;
|
||||
let mut name = Vec::new();
|
||||
name.extend_from_slice(&0_u16.to_be_bytes());
|
||||
name.extend_from_slice(&count.to_be_bytes());
|
||||
name.extend_from_slice(&(6 + count * 12).to_be_bytes());
|
||||
for (name_id, len, off) in entries {
|
||||
name.extend_from_slice(&3_u16.to_be_bytes());
|
||||
name.extend_from_slice(&1_u16.to_be_bytes());
|
||||
name.extend_from_slice(&0x0409_u16.to_be_bytes());
|
||||
name.extend_from_slice(&name_id.to_be_bytes());
|
||||
name.extend_from_slice(&len.to_be_bytes());
|
||||
name.extend_from_slice(&off.to_be_bytes());
|
||||
}
|
||||
name.extend_from_slice(&storage);
|
||||
|
||||
let mut post = vec![0u8; 32];
|
||||
post[0..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes());
|
||||
|
||||
// Minimal cmap format 4 with only the 0xFFFF sentinel segment.
|
||||
let cmap: Vec<u8> = [
|
||||
0_u16, 1, 3, 1, 0, 12, // header + 1 encoding record (offset 12)
|
||||
4, 24, 0, 2, 2, 0, 0, // format 4 subtable (len 24, segCountX2=2)
|
||||
0xFFFF, 0, 0xFFFF, 1, 0, // sentinel end/pad/start/delta/offset
|
||||
]
|
||||
.into_iter()
|
||||
.flat_map(u16::to_be_bytes)
|
||||
.collect();
|
||||
|
||||
let hmtx = [500_u16, 0_u16]
|
||||
.into_iter()
|
||||
.flat_map(u16::to_be_bytes)
|
||||
.collect::<Vec<_>>();
|
||||
// Glyph 0 (.notdef): 4-point rectangle so usvg never elides reachable Node::Text as empty.
|
||||
let mut glyf = Vec::with_capacity(36);
|
||||
for v in [1_i16, 50, 0, 450, 700, 3, 0] {
|
||||
glyf.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
glyf.extend_from_slice(&[0x01, 0x01, 0x01, 0x01]);
|
||||
for d in [50_i16, 400, 0, -400, 0, 0, 700, 0] {
|
||||
glyf.extend_from_slice(&d.to_be_bytes());
|
||||
}
|
||||
while !glyf.len().is_multiple_of(4) {
|
||||
glyf.push(0);
|
||||
}
|
||||
let mut loca = Vec::with_capacity(8);
|
||||
loca.extend_from_slice(&0_u32.to_be_bytes());
|
||||
loca.extend_from_slice(&(glyf.len() as u32).to_be_bytes());
|
||||
|
||||
let mut tables: Vec<([u8; 4], Vec<u8>)> = vec![
|
||||
(*b"OS/2", os2),
|
||||
(*b"cmap", cmap),
|
||||
(*b"glyf", glyf),
|
||||
(*b"head", head),
|
||||
(*b"hhea", hhea),
|
||||
(*b"hmtx", hmtx),
|
||||
(*b"loca", loca),
|
||||
(*b"maxp", maxp),
|
||||
(*b"name", name),
|
||||
(*b"post", post),
|
||||
];
|
||||
tables.sort_by_key(|(tag, _)| *tag);
|
||||
|
||||
let num_tables = tables.len() as u16;
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
out.extend_from_slice(&num_tables.to_be_bytes());
|
||||
out.extend_from_slice(&128_u16.to_be_bytes());
|
||||
out.extend_from_slice(&3_u16.to_be_bytes());
|
||||
out.extend_from_slice(&((num_tables * 16).saturating_sub(128)).to_be_bytes());
|
||||
|
||||
let mut offset = 12 + tables.len() * 16;
|
||||
for (tag, data) in &tables {
|
||||
let checksum = data.chunks(4).fold(0u32, |acc, chunk| {
|
||||
let mut buf = [0u8; 4];
|
||||
buf[..chunk.len()].copy_from_slice(chunk);
|
||||
acc.wrapping_add(u32::from_be_bytes(buf))
|
||||
});
|
||||
out.extend_from_slice(tag);
|
||||
out.extend_from_slice(&checksum.to_be_bytes());
|
||||
out.extend_from_slice(&(offset as u32).to_be_bytes());
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
offset += (data.len() + 3) & !3;
|
||||
}
|
||||
for (_, data) in &tables {
|
||||
out.extend_from_slice(data);
|
||||
while !out.len().is_multiple_of(4) {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Returns true for whitespace, control characters, and Unicode `Default_Ignorable_Code_Point`
|
||||
/// scalars (including variation selectors such as `U+FE0F`, joiners, and bidi/tag formatters)
|
||||
/// that render invisibly and do not require font glyph coverage.
|
||||
pub(crate) fn is_ignorable_for_glyph_check(ch: char) -> bool {
|
||||
if ch.is_whitespace() || ch.is_control() {
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
ch,
|
||||
'\u{00AD}'
|
||||
| '\u{034F}'
|
||||
| '\u{061C}'
|
||||
| '\u{115F}'..='\u{1160}'
|
||||
| '\u{17B4}'..='\u{17B5}'
|
||||
| '\u{180B}'..='\u{180F}'
|
||||
| '\u{200B}'..='\u{200F}'
|
||||
| '\u{202A}'..='\u{202E}'
|
||||
| '\u{2060}'..='\u{206F}'
|
||||
| '\u{3164}'
|
||||
| '\u{FE00}'..='\u{FE0F}'
|
||||
| '\u{FEFF}'
|
||||
| '\u{FFA0}'
|
||||
| '\u{FFF0}'..='\u{FFF8}'
|
||||
| '\u{E0000}'..='\u{E0FFF}'
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rasterizes_vector_svg_deterministically_at_multiple_scales() {
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20" viewBox="0 0 40 20">
|
||||
<rect x="2" y="2" width="36" height="16" fill="#1e66f5"/>
|
||||
</svg>"##;
|
||||
|
||||
let rasterizer = SvgRasterizer::new(&FontPool::new());
|
||||
let cases = [(1.0_f32, 40_u32, 20_u32), (2.0_f32, 80_u32, 40_u32)];
|
||||
for (scale, expected_w, expected_h) in cases {
|
||||
let first = rasterizer.rasterize(svg, scale).unwrap();
|
||||
let second = rasterizer.rasterize(svg, scale).unwrap();
|
||||
assert_eq!(first.width_px, expected_w);
|
||||
assert_eq!(first.height_px, expected_h);
|
||||
assert_eq!(first.byte_len(), (expected_w * expected_h * 4) as usize);
|
||||
assert!(first.count_non_transparent_pixels() > 0);
|
||||
assert_eq!(first.sha256(), second.sha256());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_oversized_raster_target_to_max_edge() {
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="500" viewBox="0 0 1000 500">
|
||||
<rect width="1000" height="500" fill="#000000"/>
|
||||
</svg>"##;
|
||||
|
||||
let rasterizer = SvgRasterizer::new(&FontPool::new());
|
||||
let opts = RasterOptions {
|
||||
scale_factor: 2.0,
|
||||
target_logical_width: None,
|
||||
target_logical_height: None,
|
||||
max_edge_px: 256,
|
||||
allow_missing_glyphs: false,
|
||||
};
|
||||
let buf = rasterizer.rasterize_with_options(svg, opts).unwrap();
|
||||
assert_eq!(buf.width_px, 256);
|
||||
assert_eq!(buf.height_px, 128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_svg_and_non_positive_scale() {
|
||||
let rasterizer = SvgRasterizer::new(&FontPool::new());
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(" ", 2.0),
|
||||
Err(PreviewError::EmptyInput)
|
||||
));
|
||||
let valid = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"></svg>"#;
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(valid, 0.0),
|
||||
Err(PreviewError::InvalidSize(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(valid, f32::NAN),
|
||||
Err(PreviewError::InvalidSize(_))
|
||||
));
|
||||
|
||||
let text_svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><text x="2" y="14">Hi</text></svg>"#;
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(text_svg, 1.0),
|
||||
Err(PreviewError::MissingGlyphFont(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_external_filesystem_image_href_resolution() {
|
||||
// Minimal valid 1x1 red PNG file written to a temporary path.
|
||||
const ONE_BY_ONE_RED_PNG: &[u8] = &[
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
|
||||
0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
|
||||
0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
|
||||
0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0x18, 0xDD, 0x8D,
|
||||
0xB0, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
|
||||
];
|
||||
static TMP_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let seq = TMP_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let tmp_path = std::env::temp_dir().join(format!(
|
||||
"blocksuite_preview_blocked_href_{}_{seq}.png",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::write(&tmp_path, ONE_BY_ONE_RED_PNG).expect("write temp png");
|
||||
|
||||
let svg_existing = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><image href="{}" width="16" height="16"/></svg>"#,
|
||||
tmp_path.display()
|
||||
);
|
||||
let svg_missing = r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><image href="/nonexistent/preview_blocked.png" width="16" height="16"/></svg>"#;
|
||||
|
||||
let rasterizer = SvgRasterizer::new(&FontPool::new());
|
||||
let with_file = rasterizer.rasterize(&svg_existing, 1.0).unwrap();
|
||||
let without_file = rasterizer.rasterize(svg_missing, 1.0).unwrap();
|
||||
let _ = std::fs::remove_file(&tmp_path);
|
||||
|
||||
assert_eq!(with_file.sha256(), without_file.sha256());
|
||||
assert_eq!(with_file.count_non_transparent_pixels(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_empty_latin_font_pool_signals_missing_cjk_glyph_until_cjk_font_registered() {
|
||||
let mut pool = FontPool::new();
|
||||
let latin = typst_assets::fonts().next().expect("typst bundled font");
|
||||
pool.register_font_bytes(latin.to_vec()).unwrap();
|
||||
|
||||
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="120" height="30"><text x="4" y="20">中文 Done</text></svg>"#;
|
||||
let latin_only = SvgRasterizer::new(&pool);
|
||||
assert!(matches!(
|
||||
latin_only.rasterize(svg, 2.0),
|
||||
Err(PreviewError::MissingGlyphFont(_))
|
||||
));
|
||||
|
||||
pool.register_font_bytes(crate::test_support::build_test_cjk_ttf())
|
||||
.unwrap();
|
||||
let with_cjk = SvgRasterizer::new(&pool);
|
||||
let img = with_cjk.rasterize(svg, 2.0).unwrap();
|
||||
assert!(img.count_non_transparent_pixels() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_tree_glyph_check_handles_cdata_comments_dedup_and_lenient_mode() {
|
||||
let mut pool = FontPool::new();
|
||||
let latin = typst_assets::fonts().next().expect("typst bundled font");
|
||||
pool.register_font_bytes(latin.to_vec()).unwrap();
|
||||
let rasterizer = SvgRasterizer::new(&pool);
|
||||
|
||||
// (a) Direct CJK text fails with deduplicated missing codepoints.
|
||||
let direct = r#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="24"><text x="2" y="16">中文中</text></svg>"#;
|
||||
let err = rasterizer.rasterize(direct, 1.0).unwrap_err();
|
||||
let msg = err.to_string();
|
||||
assert!(matches!(err, PreviewError::MissingGlyphFont(_)));
|
||||
assert!(msg.contains("U+4E2D") && msg.contains("U+6587"));
|
||||
assert_eq!(msg.matches("U+4E2D").count(), 1);
|
||||
|
||||
// (b) CDATA inside <text> must also be checked and rejected.
|
||||
let cdata = r#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="24"><text x="2" y="16"><![CDATA[中]]></text></svg>"#;
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(cdata, 1.0),
|
||||
Err(PreviewError::MissingGlyphFont(_))
|
||||
));
|
||||
|
||||
// (c) XML comments, <metadata> foreign namespaces, and <title>/<desc> inside <text> are ignored.
|
||||
let commented = r#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="24"><!-- <text>中文</text> --><metadata><x:text xmlns:x="urn:meta">中文</x:text></metadata><text x="2" y="16"><title>中文说明</title><desc>不绘制</desc>A</text></svg>"#;
|
||||
assert!(rasterizer.rasterize(commented, 1.0).is_ok());
|
||||
|
||||
// (d) Nested <tspan> with CDATA inside <text> must still report MissingGlyphFont.
|
||||
let nested_tspan = r#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="24"><text x="2" y="16"><tspan><![CDATA[中]]></tspan></text></svg>"#;
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(nested_tspan, 1.0),
|
||||
Err(PreviewError::MissingGlyphFont(_))
|
||||
));
|
||||
|
||||
// (e) Unreferenced <defs><text> is not rendered by usvg and must not false-positive.
|
||||
let unused_defs = r#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="24"><defs><text id="unused">中</text></defs><text x="2" y="16">A</text></svg>"#;
|
||||
assert!(rasterizer.rasterize(unused_defs, 1.0).is_ok());
|
||||
|
||||
// (f) Referenced <defs><text> via <use> and <tref> must report MissingGlyphFont.
|
||||
let used_defs = r##"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="24"><defs><text id="used" x="2" y="16">中</text></defs><use href="#used"/></svg>"##;
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(used_defs, 1.0),
|
||||
Err(PreviewError::MissingGlyphFont(_))
|
||||
));
|
||||
let tref_xlink = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="80" height="24"><defs><g id="label">中</g></defs><text x="2" y="16"><tref xlink:href="#label"/></text></svg>"##;
|
||||
assert!(matches!(
|
||||
rasterizer.rasterize(tref_xlink, 1.0),
|
||||
Err(PreviewError::MissingGlyphFont(_))
|
||||
));
|
||||
|
||||
// (g) Visible pattern fill subroots on converted paths report uncovered glyphs, whereas a
|
||||
// hidden `<rect visibility="hidden" fill="url(#p)"/>` is skipped by resvg and must not fail.
|
||||
let hidden_pattern_svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><defs><pattern id="p" patternUnits="userSpaceOnUse" width="24" height="24"><text y="18">A中</text></pattern></defs><text y="18">A</text><rect width="24" height="24" visibility="hidden" fill="url(#p)"/></svg>"##;
|
||||
assert!(rasterizer.rasterize(hidden_pattern_svg, 1.0).is_ok());
|
||||
|
||||
let visible_pattern_svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><defs><pattern id="p" patternUnits="userSpaceOnUse" width="24" height="24"><text y="18">A中</text></pattern></defs><text y="18">A</text><rect width="24" height="24" visibility="visible" fill="url(#p)"/></svg>"##;
|
||||
let pat_err = rasterizer.rasterize(visible_pattern_svg, 1.0).unwrap_err();
|
||||
assert!(pat_err.to_string().contains("U+4E2D"));
|
||||
|
||||
let hidden_tspan = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="24"><text y="18">A<tspan visibility="hidden">中</tspan></text></svg>"#;
|
||||
assert!(rasterizer.rasterize(hidden_tspan, 1.0).is_ok());
|
||||
|
||||
let visible_tspan = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="24"><text y="18">A<tspan visibility="visible">中</tspan></text></svg>"#;
|
||||
let vis_err = rasterizer.rasterize(visible_tspan, 1.0).unwrap_err();
|
||||
assert!(vis_err.to_string().contains("U+4E2D"));
|
||||
|
||||
// (h) Subset font with an outline-less `.notdef` (0 contours, like `pyftsubset` defaults)
|
||||
// and base64-encoded nested `<image>` SVGs still report uncovered CJK glyphs in strict mode.
|
||||
let mut empty_notdef_pool = FontPool::new();
|
||||
empty_notdef_pool
|
||||
.register_font_bytes(crate::test_support::build_test_latin_empty_notdef_ttf())
|
||||
.unwrap();
|
||||
let subset_rasterizer = SvgRasterizer::new(&empty_notdef_pool);
|
||||
let all_cjk = r#"<svg xmlns="http://www.w3.org/2000/svg" width="120" height="30"><text x="4" y="20">中文标签</text></svg>"#;
|
||||
let subset_err = subset_rasterizer.rasterize(all_cjk, 2.0).unwrap_err();
|
||||
let subset_msg = subset_err.to_string();
|
||||
for code in ["U+4E2D", "U+6587", "U+6807", "U+7B7E"] {
|
||||
assert!(subset_msg.contains(code), "missing {code} in {subset_msg}");
|
||||
}
|
||||
|
||||
// Base64-encoded `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><text y="14">中</text></svg>`
|
||||
let b64_inner = "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSIyMCI+PHRleHQgeT0iMTQiPuS4rTwvdGV4dD48L3N2Zz4=";
|
||||
let nested_visible = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><image width="40" height="20" href="data:image/svg+xml;base64,{b64_inner}"/></svg>"#
|
||||
);
|
||||
let nested_err = subset_rasterizer
|
||||
.rasterize(&nested_visible, 1.0)
|
||||
.unwrap_err();
|
||||
assert!(nested_err.to_string().contains("U+4E2D"));
|
||||
let nested_hidden = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><image width="40" height="20" visibility="hidden" href="data:image/svg+xml;base64,{b64_inner}"/></svg>"#
|
||||
);
|
||||
assert!(subset_rasterizer.rasterize(&nested_hidden, 1.0).is_ok());
|
||||
|
||||
// (i) Negative-`startOffset` `<textPath>` where the real font's `.notdef` (`0.90 em` =
|
||||
// `18 px` at `20 px`, midpoint `-6 + 9 = +3 px >= 0`) is kept and drawn in `tree` while
|
||||
// the `0.50 em` probe `.notdef` (`10 px`, midpoint `-6 + 5 = -1 px < 0`) is clipped off
|
||||
// the start of the path in `probe`: strict mode must still reject `U+4E2D`.
|
||||
let mut latin_notdef_pool = FontPool::new();
|
||||
latin_notdef_pool
|
||||
.register_font_bytes(crate::test_support::build_test_latin_with_notdef_ttf())
|
||||
.unwrap();
|
||||
let latin_notdef_rasterizer = SvgRasterizer::new(&latin_notdef_pool);
|
||||
let text_path_svg = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="50"><defs><path id="p" d="M20 30h70"/></defs><text font-family="TestLatinWithNotdef" font-size="20"><textPath xlink:href="#p" startOffset="-6">中</textPath></text></svg>"##;
|
||||
let lenient_opts = RasterOptions {
|
||||
allow_missing_glyphs: true,
|
||||
..RasterOptions::with_scale(1.0)
|
||||
};
|
||||
let drawn_notdef = latin_notdef_rasterizer
|
||||
.rasterize_with_options(text_path_svg, lenient_opts)
|
||||
.unwrap();
|
||||
assert!(
|
||||
drawn_notdef.count_non_transparent_pixels() > 0,
|
||||
"real tree keeps and draws `.notdef` on negative-startOffset textPath"
|
||||
);
|
||||
let tp_err = latin_notdef_rasterizer
|
||||
.rasterize(text_path_svg, 1.0)
|
||||
.unwrap_err();
|
||||
assert!(matches!(tp_err, PreviewError::MissingGlyphFont(_)));
|
||||
assert!(tp_err.to_string().contains("U+4E2D"));
|
||||
|
||||
// Combined dual-font SVG where `tree` retains only `中` (negative-`startOffset` `<textPath>`
|
||||
// on `TestLatinWithNotdef`) while `probe` retains only `文` (`EmptyNotdefLatin` drops `<text>`
|
||||
// in `tree`), plus `startOffset="0"` where `probe` retains `[中, 文]`: both must report
|
||||
// `U+4E2D` and `U+6587` once each in a single deduplicated `MissingGlyphFont` error.
|
||||
let mut dual_pool = FontPool::new();
|
||||
dual_pool
|
||||
.register_font_bytes(crate::test_support::build_test_latin_with_notdef_ttf())
|
||||
.unwrap();
|
||||
dual_pool
|
||||
.register_font_bytes(crate::test_support::build_test_latin_empty_notdef_ttf())
|
||||
.unwrap();
|
||||
let dual_rasterizer = SvgRasterizer::new(&dual_pool);
|
||||
for offset in ["-6", "0"] {
|
||||
let dual_svg = format!(
|
||||
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="70"><defs><path id="p" d="M20 30h70"/></defs><text font-family="TestLatinWithNotdef" font-size="20"><textPath xlink:href="#p" startOffset="{offset}">中</textPath></text><text x="4" y="55" font-family="EmptyNotdefLatin">文</text></svg>"##
|
||||
);
|
||||
let dual_err = dual_rasterizer.rasterize(&dual_svg, 1.0).unwrap_err();
|
||||
let dual_msg = dual_err.to_string();
|
||||
assert!(matches!(dual_err, PreviewError::MissingGlyphFont(_)));
|
||||
assert_eq!(
|
||||
dual_msg.matches("U+4E2D").count(),
|
||||
1,
|
||||
"offset={offset}: {dual_msg}"
|
||||
);
|
||||
assert_eq!(
|
||||
dual_msg.matches("U+6587").count(),
|
||||
1,
|
||||
"offset={offset}: {dual_msg}"
|
||||
);
|
||||
}
|
||||
|
||||
// (j) Lenient mode allows rendering available glyphs when host has no more fonts to fetch.
|
||||
assert!(
|
||||
rasterizer
|
||||
.rasterize_with_options(direct, lenient_opts)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
use crate::font_pool::FontPool;
|
||||
|
||||
/// Builds a deterministic test [`FontPool`] with zero system font scanning.
|
||||
///
|
||||
/// Registers bundled Typst text/math fonts and a synthesized CJK TrueType font
|
||||
/// where each distinct CJK character has a distinct advance width and outline.
|
||||
pub(crate) fn build_test_font_pool() -> FontPool {
|
||||
let mut pool = FontPool::new();
|
||||
for font_bytes in typst_assets::fonts() {
|
||||
let _ = pool.register_font_bytes(font_bytes.to_vec());
|
||||
}
|
||||
pool.register_font_bytes(build_test_cjk_ttf())
|
||||
.expect("synthesized CJK test font must parse cleanly");
|
||||
pool
|
||||
}
|
||||
|
||||
/// Returns a deterministic synthesized CJK TrueType font where each codepoint
|
||||
/// maps to a unique glyph ID with a distinct rectangular outline variant
|
||||
/// (varying advance width and bounding box coordinates per glyph index).
|
||||
pub(crate) fn build_test_cjk_ttf() -> Vec<u8> {
|
||||
synthesize_distinct_bmp_ttf(
|
||||
"TestCJK",
|
||||
"开始流程数据处理结束渲染用户系统发送请求返回预览核发布计划光栅底座公式占比分布图表数学文档速度距离时间最大值当时中文测试通过标签",
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// Synthesizes a Latin-only TrueType font whose `.notdef` (glyph 0) has a visible rectangular
|
||||
/// outline and `0.90 em` advance (`900 / 1000` units).
|
||||
pub(crate) fn build_test_latin_with_notdef_ttf() -> Vec<u8> {
|
||||
synthesize_distinct_bmp_ttf(
|
||||
"TestLatinWithNotdef",
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ",
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// Synthesizes a Latin-only TrueType font whose `.notdef` (glyph 0) has zero outline bytes
|
||||
/// (`loca[0] == loca[1] == 0`), matching default `pyftsubset` subsets.
|
||||
pub(crate) fn build_test_latin_empty_notdef_ttf() -> Vec<u8> {
|
||||
synthesize_distinct_bmp_ttf(
|
||||
"EmptyNotdefLatin",
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ",
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
/// Synthesizes a compact, valid TrueType font where each unique BMP character
|
||||
/// receives its own glyph ID and a per-index rectangular outline variant
|
||||
/// (distinct advance width and bounding box) so different characters rasterize
|
||||
/// to distinct pixel buffers without shipping a multi-megabyte font in tests.
|
||||
fn synthesize_distinct_bmp_ttf(
|
||||
family_name: &str,
|
||||
chars: &str,
|
||||
include_notdef_outline: bool,
|
||||
) -> Vec<u8> {
|
||||
let mut codepoints: Vec<u16> = chars
|
||||
.chars()
|
||||
.filter_map(|ch| u16::try_from(ch as u32).ok())
|
||||
.collect();
|
||||
codepoints.sort_unstable();
|
||||
codepoints.dedup();
|
||||
|
||||
// Glyph 0 = .notdef, Glyphs 1..=N = distinct per-codepoint outlines.
|
||||
let num_glyphs: u16 = (codepoints.len() + 1) as u16;
|
||||
let units_per_em: u16 = 1000;
|
||||
|
||||
let head = build_head_table(units_per_em);
|
||||
let hhea = build_hhea_table(num_glyphs);
|
||||
let maxp = build_maxp_table(num_glyphs);
|
||||
let os2 = build_os2_table();
|
||||
let name = build_name_table(family_name);
|
||||
let post = build_post_table();
|
||||
let hmtx = build_hmtx_table(&codepoints);
|
||||
let (glyf, loca) = build_glyf_and_loca(&codepoints, include_notdef_outline);
|
||||
let cmap = build_cmap_format4(&codepoints);
|
||||
|
||||
let mut tables: Vec<([u8; 4], Vec<u8>)> = vec![
|
||||
(*b"OS/2", os2),
|
||||
(*b"cmap", cmap),
|
||||
(*b"glyf", glyf),
|
||||
(*b"head", head),
|
||||
(*b"hhea", hhea),
|
||||
(*b"hmtx", hmtx),
|
||||
(*b"loca", loca),
|
||||
(*b"maxp", maxp),
|
||||
(*b"name", name),
|
||||
(*b"post", post),
|
||||
];
|
||||
tables.sort_by_key(|(tag, _)| *tag);
|
||||
|
||||
assemble_sfnt(&tables)
|
||||
}
|
||||
|
||||
fn glyph_advance_and_box(index: usize, cp: u16) -> (u16, i16, i16, i16, i16) {
|
||||
let variant = ((cp as usize) + index * 3) % 7;
|
||||
let advance = (820 + variant * 45) as u16;
|
||||
let x_min = (60 + (variant % 3) * 25) as i16;
|
||||
let y_min = (20 + (variant % 4) * 30) as i16;
|
||||
let x_max = (advance as i16) - 60;
|
||||
let y_max = (640 + (variant % 5) * 40) as i16;
|
||||
(advance, x_min, y_min, x_max, y_max)
|
||||
}
|
||||
|
||||
fn build_head_table(units_per_em: u16) -> Vec<u8> {
|
||||
let mut t = Vec::with_capacity(54);
|
||||
t.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
t.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
t.extend_from_slice(&0_u32.to_be_bytes());
|
||||
t.extend_from_slice(&0x5F0F_3CF5_u32.to_be_bytes());
|
||||
t.extend_from_slice(&0x000B_u16.to_be_bytes());
|
||||
t.extend_from_slice(&units_per_em.to_be_bytes());
|
||||
t.extend_from_slice(&0_i64.to_be_bytes());
|
||||
t.extend_from_slice(&0_i64.to_be_bytes());
|
||||
t.extend_from_slice(&60_i16.to_be_bytes());
|
||||
t.extend_from_slice(&0_i16.to_be_bytes());
|
||||
t.extend_from_slice(&1040_i16.to_be_bytes());
|
||||
t.extend_from_slice(&840_i16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&8_u16.to_be_bytes());
|
||||
t.extend_from_slice(&2_i16.to_be_bytes());
|
||||
t.extend_from_slice(&1_i16.to_be_bytes());
|
||||
t.extend_from_slice(&0_i16.to_be_bytes());
|
||||
t
|
||||
}
|
||||
|
||||
fn build_hhea_table(num_glyphs: u16) -> Vec<u8> {
|
||||
let mut t = Vec::with_capacity(36);
|
||||
t.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
t.extend_from_slice(&880_i16.to_be_bytes());
|
||||
t.extend_from_slice(&(-120_i16).to_be_bytes());
|
||||
t.extend_from_slice(&0_i16.to_be_bytes());
|
||||
t.extend_from_slice(&1100_u16.to_be_bytes());
|
||||
t.extend_from_slice(&60_i16.to_be_bytes());
|
||||
t.extend_from_slice(&60_i16.to_be_bytes());
|
||||
t.extend_from_slice(&1040_i16.to_be_bytes());
|
||||
t.extend_from_slice(&1_i16.to_be_bytes());
|
||||
t.extend_from_slice(&0_i16.to_be_bytes());
|
||||
t.extend_from_slice(&0_i16.to_be_bytes());
|
||||
t.extend_from_slice(&[0u8; 8]);
|
||||
t.extend_from_slice(&0_i16.to_be_bytes());
|
||||
t.extend_from_slice(&num_glyphs.to_be_bytes());
|
||||
t
|
||||
}
|
||||
|
||||
fn build_maxp_table(num_glyphs: u16) -> Vec<u8> {
|
||||
let mut t = Vec::with_capacity(32);
|
||||
t.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
t.extend_from_slice(&num_glyphs.to_be_bytes());
|
||||
t.extend_from_slice(&4_u16.to_be_bytes());
|
||||
t.extend_from_slice(&1_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&1_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t
|
||||
}
|
||||
|
||||
fn build_os2_table() -> Vec<u8> {
|
||||
let mut t = vec![0u8; 78];
|
||||
t[0..2].copy_from_slice(&1_u16.to_be_bytes());
|
||||
t[2..4].copy_from_slice(&950_i16.to_be_bytes());
|
||||
t[4..6].copy_from_slice(&400_u16.to_be_bytes());
|
||||
t[6..8].copy_from_slice(&5_u16.to_be_bytes());
|
||||
t[58..62].copy_from_slice(b"TEST");
|
||||
t[62..64].copy_from_slice(&0x0040_u16.to_be_bytes());
|
||||
t[64..66].copy_from_slice(&0x0020_u16.to_be_bytes());
|
||||
t[66..68].copy_from_slice(&0x9FFF_u16.to_be_bytes());
|
||||
t[68..70].copy_from_slice(&880_i16.to_be_bytes());
|
||||
t[70..72].copy_from_slice(&(-120_i16).to_be_bytes());
|
||||
t[74..76].copy_from_slice(&880_u16.to_be_bytes());
|
||||
t[76..78].copy_from_slice(&120_u16.to_be_bytes());
|
||||
t
|
||||
}
|
||||
|
||||
fn build_name_table(family: &str) -> Vec<u8> {
|
||||
let records = [
|
||||
(1_u16, family.to_string()),
|
||||
(2_u16, "Regular".to_string()),
|
||||
(4_u16, format!("{family} Regular")),
|
||||
(6_u16, format!("{family}-Regular")),
|
||||
];
|
||||
let mut string_storage = Vec::new();
|
||||
let mut entries = Vec::new();
|
||||
for (name_id, text) in &records {
|
||||
let utf16: Vec<u8> = text
|
||||
.encode_utf16()
|
||||
.flat_map(|unit| unit.to_be_bytes())
|
||||
.collect();
|
||||
let offset = string_storage.len() as u16;
|
||||
let length = utf16.len() as u16;
|
||||
string_storage.extend_from_slice(&utf16);
|
||||
entries.push((*name_id, length, offset));
|
||||
}
|
||||
|
||||
let count = entries.len() as u16;
|
||||
let string_offset = 6 + count * 12;
|
||||
let mut t = Vec::new();
|
||||
t.extend_from_slice(&0_u16.to_be_bytes());
|
||||
t.extend_from_slice(&count.to_be_bytes());
|
||||
t.extend_from_slice(&string_offset.to_be_bytes());
|
||||
for (name_id, length, offset) in entries {
|
||||
t.extend_from_slice(&3_u16.to_be_bytes());
|
||||
t.extend_from_slice(&1_u16.to_be_bytes());
|
||||
t.extend_from_slice(&0x0409_u16.to_be_bytes());
|
||||
t.extend_from_slice(&name_id.to_be_bytes());
|
||||
t.extend_from_slice(&length.to_be_bytes());
|
||||
t.extend_from_slice(&offset.to_be_bytes());
|
||||
}
|
||||
t.extend_from_slice(&string_storage);
|
||||
t
|
||||
}
|
||||
|
||||
fn build_post_table() -> Vec<u8> {
|
||||
let mut t = vec![0u8; 32];
|
||||
t[0..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes());
|
||||
t
|
||||
}
|
||||
|
||||
fn build_hmtx_table(codepoints: &[u16]) -> Vec<u8> {
|
||||
let mut t = Vec::with_capacity((codepoints.len() + 1) * 4);
|
||||
// Glyph 0 (.notdef)
|
||||
t.extend_from_slice(&900_u16.to_be_bytes());
|
||||
t.extend_from_slice(&80_i16.to_be_bytes());
|
||||
for (idx, &cp) in codepoints.iter().enumerate() {
|
||||
let (advance, x_min, _, _, _) = glyph_advance_and_box(idx, cp);
|
||||
t.extend_from_slice(&advance.to_be_bytes());
|
||||
t.extend_from_slice(&x_min.to_be_bytes());
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
fn encode_rect_glyph(x_min: i16, y_min: i16, x_max: i16, y_max: i16) -> Vec<u8> {
|
||||
let mut g = Vec::new();
|
||||
g.extend_from_slice(&1_i16.to_be_bytes());
|
||||
g.extend_from_slice(&x_min.to_be_bytes());
|
||||
g.extend_from_slice(&y_min.to_be_bytes());
|
||||
g.extend_from_slice(&x_max.to_be_bytes());
|
||||
g.extend_from_slice(&y_max.to_be_bytes());
|
||||
g.extend_from_slice(&3_u16.to_be_bytes());
|
||||
g.extend_from_slice(&0_u16.to_be_bytes());
|
||||
g.extend_from_slice(&[0x01, 0x01, 0x01, 0x01]);
|
||||
let w = x_max - x_min;
|
||||
let h = y_max - y_min;
|
||||
for dx in [x_min, 0, w, 0] {
|
||||
g.extend_from_slice(&dx.to_be_bytes());
|
||||
}
|
||||
for dy in [y_min, h, 0, -h] {
|
||||
g.extend_from_slice(&dy.to_be_bytes());
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
fn build_glyf_and_loca(codepoints: &[u16], include_notdef_outline: bool) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut glyf = Vec::new();
|
||||
let mut offsets = Vec::with_capacity(codepoints.len() + 2);
|
||||
|
||||
// Glyph 0 (.notdef)
|
||||
offsets.push(0_u32);
|
||||
if include_notdef_outline {
|
||||
glyf.extend_from_slice(&encode_rect_glyph(80, 0, 820, 760));
|
||||
}
|
||||
|
||||
// Glyphs 1..=N
|
||||
for (idx, &cp) in codepoints.iter().enumerate() {
|
||||
offsets.push(glyf.len() as u32);
|
||||
let (_, x_min, y_min, x_max, y_max) = glyph_advance_and_box(idx, cp);
|
||||
glyf.extend_from_slice(&encode_rect_glyph(x_min, y_min, x_max, y_max));
|
||||
}
|
||||
offsets.push(glyf.len() as u32);
|
||||
|
||||
let mut loca = Vec::with_capacity(offsets.len() * 4);
|
||||
for off in offsets {
|
||||
loca.extend_from_slice(&off.to_be_bytes());
|
||||
}
|
||||
(glyf, loca)
|
||||
}
|
||||
|
||||
fn build_cmap_format4(codepoints: &[u16]) -> Vec<u8> {
|
||||
let seg_count = (codepoints.len() + 1) as u16;
|
||||
let seg_count_x2 = seg_count * 2;
|
||||
let mut search_range = 2_u16;
|
||||
let mut entry_selector = 0_u16;
|
||||
while search_range * 2 <= seg_count_x2 {
|
||||
search_range *= 2;
|
||||
entry_selector += 1;
|
||||
}
|
||||
let range_shift = seg_count_x2 - search_range;
|
||||
|
||||
let mut subtable = Vec::new();
|
||||
subtable.extend_from_slice(&4_u16.to_be_bytes());
|
||||
let subtable_len = 16 + seg_count_x2 * 4;
|
||||
subtable.extend_from_slice(&subtable_len.to_be_bytes());
|
||||
subtable.extend_from_slice(&0_u16.to_be_bytes());
|
||||
subtable.extend_from_slice(&seg_count_x2.to_be_bytes());
|
||||
subtable.extend_from_slice(&search_range.to_be_bytes());
|
||||
subtable.extend_from_slice(&entry_selector.to_be_bytes());
|
||||
subtable.extend_from_slice(&range_shift.to_be_bytes());
|
||||
|
||||
for &cp in codepoints {
|
||||
subtable.extend_from_slice(&cp.to_be_bytes());
|
||||
}
|
||||
subtable.extend_from_slice(&0xFFFF_u16.to_be_bytes());
|
||||
subtable.extend_from_slice(&0_u16.to_be_bytes());
|
||||
|
||||
for &cp in codepoints {
|
||||
subtable.extend_from_slice(&cp.to_be_bytes());
|
||||
}
|
||||
subtable.extend_from_slice(&0xFFFF_u16.to_be_bytes());
|
||||
|
||||
// Map codepoint at index `i` to distinct glyph ID `(i + 1)`.
|
||||
for (idx, &cp) in codepoints.iter().enumerate() {
|
||||
let gid = (idx + 1) as u16;
|
||||
let delta = gid.wrapping_sub(cp) as i16;
|
||||
subtable.extend_from_slice(&delta.to_be_bytes());
|
||||
}
|
||||
subtable.extend_from_slice(&1_i16.to_be_bytes());
|
||||
|
||||
for _ in 0..seg_count {
|
||||
subtable.extend_from_slice(&0_u16.to_be_bytes());
|
||||
}
|
||||
|
||||
let mut cmap = Vec::new();
|
||||
cmap.extend_from_slice(&0_u16.to_be_bytes());
|
||||
cmap.extend_from_slice(&1_u16.to_be_bytes());
|
||||
cmap.extend_from_slice(&3_u16.to_be_bytes());
|
||||
cmap.extend_from_slice(&1_u16.to_be_bytes());
|
||||
cmap.extend_from_slice(&12_u32.to_be_bytes());
|
||||
cmap.extend_from_slice(&subtable);
|
||||
cmap
|
||||
}
|
||||
|
||||
fn assemble_sfnt(tables: &[([u8; 4], Vec<u8>)]) -> Vec<u8> {
|
||||
let num_tables = tables.len() as u16;
|
||||
let mut search_range = 16_u16;
|
||||
let mut entry_selector = 0_u16;
|
||||
while search_range * 2 <= num_tables * 16 {
|
||||
search_range *= 2;
|
||||
entry_selector += 1;
|
||||
}
|
||||
let range_shift = num_tables * 16 - search_range;
|
||||
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
out.extend_from_slice(&num_tables.to_be_bytes());
|
||||
out.extend_from_slice(&search_range.to_be_bytes());
|
||||
out.extend_from_slice(&entry_selector.to_be_bytes());
|
||||
out.extend_from_slice(&range_shift.to_be_bytes());
|
||||
|
||||
let mut offset = 12 + usize::from(num_tables) * 16;
|
||||
let mut head_offset = 0usize;
|
||||
for (tag, data) in tables {
|
||||
if tag == b"head" {
|
||||
head_offset = offset;
|
||||
}
|
||||
let checksum = sfnt_checksum(data);
|
||||
out.extend_from_slice(tag);
|
||||
out.extend_from_slice(&checksum.to_be_bytes());
|
||||
out.extend_from_slice(&(offset as u32).to_be_bytes());
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
offset += (data.len() + 3) & !3;
|
||||
}
|
||||
|
||||
for (_, data) in tables {
|
||||
out.extend_from_slice(data);
|
||||
while out.len() % 4 != 0 {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
|
||||
let full_checksum = sfnt_checksum(&out);
|
||||
let adjustment = 0xB1B0_AFBA_u32.wrapping_sub(full_checksum);
|
||||
out[head_offset + 8..head_offset + 12].copy_from_slice(&adjustment.to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn sfnt_checksum(data: &[u8]) -> u32 {
|
||||
let mut sum = 0_u32;
|
||||
let (chunks, rem) = data.as_chunks::<4>();
|
||||
for chunk in chunks {
|
||||
sum = sum.wrapping_add(u32::from_be_bytes(*chunk));
|
||||
}
|
||||
if !rem.is_empty() {
|
||||
let mut last = [0u8; 4];
|
||||
last[..rem.len()].copy_from_slice(rem);
|
||||
sum = sum.wrapping_add(u32::from_be_bytes(last));
|
||||
}
|
||||
sum
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use typst::diag::{FileError, FileResult};
|
||||
use typst::foundations::{Bytes, Datetime, Duration};
|
||||
use typst::layout::{Abs, Frame, FrameItem};
|
||||
use typst::syntax::package::PackageSpec;
|
||||
use typst::syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot};
|
||||
use typst::text::{Font, FontBook};
|
||||
use typst::utils::LazyHash;
|
||||
use typst::{Library, LibraryExt, World};
|
||||
use typst_layout::PagedDocument;
|
||||
use typst_svg::SvgOptions;
|
||||
|
||||
use crate::PreviewDate;
|
||||
use crate::error::PreviewError;
|
||||
use crate::font_pool::{FontPool, SharedFontBytes};
|
||||
use crate::svg_raster::{RasterOptions, RgbaImageBuffer, SvgRasterizer};
|
||||
|
||||
/// Layout metrics and SVG output for a compiled Typst page.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct TypstSvgOutput {
|
||||
/// Compiled SVG document string.
|
||||
pub svg: String,
|
||||
/// Page width in Typst points.
|
||||
pub width_pt: f64,
|
||||
/// Page height in Typst points.
|
||||
pub height_pt: f64,
|
||||
/// Distance from the top edge to the baseline in points.
|
||||
pub ascent_pt: f64,
|
||||
/// Distance from the baseline to the bottom edge in points.
|
||||
pub descent_pt: f64,
|
||||
}
|
||||
|
||||
/// Rasterized RGBA8 output and layout metrics for a compiled Typst page.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct TypstRgbaOutput {
|
||||
/// Rasterized RGBA8 pixel buffer.
|
||||
pub image: RgbaImageBuffer,
|
||||
/// Page width in Typst points.
|
||||
pub width_pt: f64,
|
||||
/// Distance from the top edge to the baseline in points.
|
||||
pub ascent_pt: f64,
|
||||
/// Distance from the baseline to the bottom edge in points.
|
||||
pub descent_pt: f64,
|
||||
}
|
||||
|
||||
/// Pure in-memory `typst::World` implementation with zero OS I/O, network, or wall clock.
|
||||
///
|
||||
/// Fonts come strictly from [`FontPool`] byte buffers, and optional virtual files
|
||||
/// or `@preview` package files are registered in memory.
|
||||
pub struct InMemoryTypstWorld {
|
||||
library: LazyHash<Library>,
|
||||
book: LazyHash<FontBook>,
|
||||
fonts: Vec<Font>,
|
||||
main_id: FileId,
|
||||
main_source: Source,
|
||||
files: HashMap<FileId, Bytes>,
|
||||
today: Option<PreviewDate>,
|
||||
}
|
||||
|
||||
impl InMemoryTypstWorld {
|
||||
/// Creates an in-memory Typst world backed by the fonts in `font_pool`.
|
||||
pub fn new(font_pool: &FontPool) -> Self {
|
||||
let mut book = FontBook::new();
|
||||
let mut fonts = Vec::new();
|
||||
for blob in font_pool.font_blobs() {
|
||||
let bytes = Bytes::new(SharedFontBytes(Arc::clone(blob)));
|
||||
for font in Font::iter(bytes) {
|
||||
book.push(font.info().clone());
|
||||
fonts.push(font);
|
||||
}
|
||||
}
|
||||
|
||||
let main_path = VirtualPath::new("main.typ").expect("static main.typ path is valid");
|
||||
let main_id = FileId::new(RootedPath::new(VirtualRoot::Project, main_path));
|
||||
let main_source = Source::new(main_id, String::new());
|
||||
|
||||
Self {
|
||||
library: LazyHash::new(Library::default()),
|
||||
book: LazyHash::new(book),
|
||||
fonts,
|
||||
main_id,
|
||||
main_source,
|
||||
files: HashMap::new(),
|
||||
today: Some(PreviewDate::DEFAULT),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the deterministic date returned by `World::today`.
|
||||
pub fn set_today(&mut self, date: Option<PreviewDate>) {
|
||||
self.today = date;
|
||||
}
|
||||
|
||||
/// Registers an in-memory virtual file accessible via `#include` or `#read`.
|
||||
pub fn insert_file(
|
||||
&mut self,
|
||||
virtual_path: &str,
|
||||
bytes: impl Into<Vec<u8>>,
|
||||
) -> Result<(), PreviewError> {
|
||||
let vpath = VirtualPath::new(virtual_path)
|
||||
.map_err(|err| PreviewError::Typst(format!("invalid virtual path: {err:?}")))?;
|
||||
let id = FileId::new(RootedPath::new(VirtualRoot::Project, vpath));
|
||||
self.files.insert(id, Bytes::new(bytes.into()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Registers an in-memory file belonging to a Typst package (such as `@preview/pkg:0.1.0`).
|
||||
pub fn insert_package_file(
|
||||
&mut self,
|
||||
package: PackageSpec,
|
||||
virtual_path: &str,
|
||||
bytes: impl Into<Vec<u8>>,
|
||||
) -> Result<(), PreviewError> {
|
||||
let vpath = VirtualPath::new(virtual_path)
|
||||
.map_err(|err| PreviewError::Typst(format!("invalid package path: {err:?}")))?;
|
||||
let id = FileId::new(RootedPath::new(VirtualRoot::Package(package), vpath));
|
||||
self.files.insert(id, Bytes::new(bytes.into()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compiles Typst markup into a paged document and bounds resident `comemo` caches.
|
||||
pub fn compile_document(&mut self, source: &str) -> Result<Arc<PagedDocument>, PreviewError> {
|
||||
if source.trim().is_empty() {
|
||||
return Err(PreviewError::EmptyInput);
|
||||
}
|
||||
|
||||
self.main_source = Source::new(self.main_id, source.to_string());
|
||||
let warned = typst::compile::<PagedDocument>(self);
|
||||
comemo::evict(10);
|
||||
let document = warned.output.map_err(|errors| {
|
||||
let joined = errors
|
||||
.iter()
|
||||
.map(|diag| diag.message.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
PreviewError::Typst(joined)
|
||||
})?;
|
||||
|
||||
if document.pages().is_empty() {
|
||||
return Err(PreviewError::Typst(
|
||||
"compiled document has zero pages".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Arc::new(document))
|
||||
}
|
||||
|
||||
/// Exports every page of an already-compiled [`PagedDocument`] to SVG.
|
||||
pub fn render_document_pages_svg(document: &PagedDocument) -> Vec<TypstSvgOutput> {
|
||||
document
|
||||
.pages()
|
||||
.iter()
|
||||
.map(|page| {
|
||||
let svg = typst_svg::svg(page, &SvgOptions::default());
|
||||
let (width_pt, height_pt, ascent_pt, descent_pt) =
|
||||
extract_frame_metrics(&page.frame);
|
||||
TypstSvgOutput {
|
||||
svg,
|
||||
width_pt,
|
||||
height_pt,
|
||||
ascent_pt,
|
||||
descent_pt,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Exports a single page of an already-compiled [`PagedDocument`] to SVG.
|
||||
pub fn render_document_page_svg(
|
||||
document: &PagedDocument,
|
||||
page_index: usize,
|
||||
) -> Result<TypstSvgOutput, PreviewError> {
|
||||
let pages = document.pages();
|
||||
let page = pages.get(page_index).ok_or(PreviewError::PageOutOfRange {
|
||||
index: page_index,
|
||||
page_count: pages.len(),
|
||||
})?;
|
||||
let svg = typst_svg::svg(page, &SvgOptions::default());
|
||||
let (width_pt, height_pt, ascent_pt, descent_pt) = extract_frame_metrics(&page.frame);
|
||||
Ok(TypstSvgOutput {
|
||||
svg,
|
||||
width_pt,
|
||||
height_pt,
|
||||
ascent_pt,
|
||||
descent_pt,
|
||||
})
|
||||
}
|
||||
|
||||
/// Compiles Typst markup and returns every page SVG with its frame metrics.
|
||||
pub fn compile_pages_svg(&mut self, source: &str) -> Result<Vec<TypstSvgOutput>, PreviewError> {
|
||||
let document = self.compile_document(source)?;
|
||||
Ok(Self::render_document_pages_svg(&document))
|
||||
}
|
||||
|
||||
/// Compiles Typst markup and returns the first page SVG and frame metrics.
|
||||
pub fn compile_svg(&mut self, source: &str) -> Result<TypstSvgOutput, PreviewError> {
|
||||
self.compile_pages_svg(source)?
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| PreviewError::Typst("compiled document has zero pages".to_string()))
|
||||
}
|
||||
|
||||
/// Compiles Typst markup and rasterizes the resulting SVG into an RGBA8 buffer.
|
||||
pub fn compile_rgba(
|
||||
&mut self,
|
||||
source: &str,
|
||||
rasterizer: &SvgRasterizer,
|
||||
scale_factor: f32,
|
||||
) -> Result<TypstRgbaOutput, PreviewError> {
|
||||
let svg_out = self.compile_svg(source)?;
|
||||
let image = rasterizer
|
||||
.rasterize_with_options(&svg_out.svg, RasterOptions::with_scale(scale_factor))?;
|
||||
Ok(TypstRgbaOutput {
|
||||
image,
|
||||
width_pt: svg_out.width_pt,
|
||||
ascent_pt: svg_out.ascent_pt,
|
||||
descent_pt: svg_out.descent_pt,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the number of font faces loaded into this world.
|
||||
pub fn font_count(&self) -> usize {
|
||||
self.fonts.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl World for InMemoryTypstWorld {
|
||||
fn library(&self) -> &LazyHash<Library> {
|
||||
&self.library
|
||||
}
|
||||
|
||||
fn book(&self) -> &LazyHash<FontBook> {
|
||||
&self.book
|
||||
}
|
||||
|
||||
fn main(&self) -> FileId {
|
||||
self.main_id
|
||||
}
|
||||
|
||||
fn source(&self, id: FileId) -> FileResult<Source> {
|
||||
if id == self.main_id {
|
||||
return Ok(self.main_source.clone());
|
||||
}
|
||||
let bytes = self.file(id)?;
|
||||
let text = std::str::from_utf8(&bytes).map_err(|_| FileError::InvalidUtf8)?;
|
||||
Ok(Source::new(id, text.to_string()))
|
||||
}
|
||||
|
||||
fn file(&self, id: FileId) -> FileResult<Bytes> {
|
||||
if id == self.main_id {
|
||||
return Ok(Bytes::from_string(self.main_source.text().to_string()));
|
||||
}
|
||||
self.files
|
||||
.get(&id)
|
||||
.cloned()
|
||||
.ok_or_else(|| FileError::NotFound(PathBuf::from(id.vpath().get_without_slash())))
|
||||
}
|
||||
|
||||
fn font(&self, index: usize) -> Option<Font> {
|
||||
self.fonts.get(index).cloned()
|
||||
}
|
||||
|
||||
fn today(&self, _offset: Option<Duration>) -> Option<Datetime> {
|
||||
let date = self.today?;
|
||||
Datetime::from_ymd(date.year, date.month, date.day)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts `(width_pt, height_pt, ascent_pt, descent_pt)` from a compiled page frame.
|
||||
///
|
||||
/// Typst page frames often store the math or inline baseline on a child group frame
|
||||
/// rather than the outer page frame. We walk nested group items to locate the first
|
||||
/// explicit baseline in page coordinates, falling back to `frame.baseline()`.
|
||||
pub(crate) fn extract_frame_metrics(frame: &Frame) -> (f64, f64, f64, f64) {
|
||||
let width_pt = frame.width().to_pt();
|
||||
let height_pt = frame.height().to_pt();
|
||||
let baseline = find_explicit_baseline(frame, Abs::zero()).unwrap_or_else(|| frame.baseline());
|
||||
let ascent_pt = baseline.to_pt().clamp(0.0, height_pt);
|
||||
let descent_pt = (height_pt - ascent_pt).max(0.0);
|
||||
(width_pt, height_pt, ascent_pt, descent_pt)
|
||||
}
|
||||
|
||||
fn find_explicit_baseline(frame: &Frame, y_offset: Abs) -> Option<Abs> {
|
||||
if frame.has_baseline() {
|
||||
return Some(y_offset + frame.baseline());
|
||||
}
|
||||
for (pos, item) in frame.items() {
|
||||
if let FrameItem::Group(group) = item
|
||||
&& let Some(found) = find_explicit_baseline(&group.frame, y_offset + pos.y)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Shared reference wrapper so callers can reuse an `Arc<FontPool>` cleanly.
|
||||
pub fn new_typst_world_from_arc(font_pool: &Arc<FontPool>) -> InMemoryTypstWorld {
|
||||
InMemoryTypstWorld::new(font_pool.as_ref())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::build_test_font_pool;
|
||||
|
||||
#[test]
|
||||
fn compiles_native_typst_block_and_in_memory_include_without_io() {
|
||||
let pool = build_test_font_pool();
|
||||
let rasterizer = SvgRasterizer::new(&pool);
|
||||
let mut world = InMemoryTypstWorld::new(&pool);
|
||||
world
|
||||
.insert_file("helper.typ", b"#let greeting = [Hello In-Memory Typst]")
|
||||
.unwrap();
|
||||
|
||||
let source = r#"
|
||||
#set page(width: auto, height: auto, margin: 4pt)
|
||||
#import "helper.typ": greeting
|
||||
#greeting
|
||||
$ E = m c^2 $
|
||||
"#;
|
||||
let svg_out = world.compile_svg(source).unwrap();
|
||||
assert!(svg_out.svg.contains("<svg"));
|
||||
assert!(svg_out.width_pt > 0.0 && svg_out.height_pt > 0.0);
|
||||
|
||||
let rgba_first = world.compile_rgba(source, &rasterizer, 2.0).unwrap();
|
||||
let rgba_second = world.compile_rgba(source, &rasterizer, 2.0).unwrap();
|
||||
assert!(rgba_first.image.count_non_transparent_pixels() > 50);
|
||||
assert_eq!(rgba_first.image.sha256(), rgba_second.image.sha256());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_deterministic_today_date_without_wall_clock() {
|
||||
let pool = build_test_font_pool();
|
||||
let mut world = InMemoryTypstWorld::new(&pool);
|
||||
world.set_today(Some(PreviewDate::new(2026, 11, 25)));
|
||||
let source = r#"#set page(width: auto, height: auto, margin: 2pt)
|
||||
#datetime.today().display()"#;
|
||||
let first = world.compile_svg(source).unwrap();
|
||||
let second = world.compile_svg(source).unwrap();
|
||||
assert_eq!(first.svg, second.svg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use crate::cache::CacheLimits;
|
||||
use crate::engine::PreviewEngine;
|
||||
|
||||
#[cfg(any(feature = "mermaid", feature = "typst"))]
|
||||
use crate::PreviewDate;
|
||||
#[cfg(feature = "math")]
|
||||
use crate::math::{MathDisplayMode, MathRenderOptions};
|
||||
#[cfg(feature = "mermaid")]
|
||||
use crate::mermaid::MermaidOptions;
|
||||
#[cfg(feature = "pdf")]
|
||||
use crate::pdf::PdfRenderRequest;
|
||||
|
||||
/// Structured SVG output with intrinsic logical pixel dimensions.
|
||||
#[cfg(feature = "mermaid")]
|
||||
#[wasm_bindgen(getter_with_clone)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmSvgOutput {
|
||||
/// Standalone SVG string.
|
||||
pub svg: String,
|
||||
/// Intrinsic logical width in pixels (parsed from SVG root attributes).
|
||||
pub width_px: f32,
|
||||
/// Intrinsic logical height in pixels (parsed from SVG root attributes).
|
||||
pub height_px: f32,
|
||||
}
|
||||
|
||||
/// Structured RGBA8 pixel buffer with physical and logical dimensions.
|
||||
#[cfg(any(feature = "mermaid", feature = "typst"))]
|
||||
#[wasm_bindgen]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmRgbaOutput {
|
||||
/// Physical pixel width.
|
||||
pub width_px: u32,
|
||||
/// Physical pixel height.
|
||||
pub height_px: u32,
|
||||
/// Logical width in CSS pixels or points.
|
||||
pub logical_width: f32,
|
||||
/// Logical height in CSS pixels or points.
|
||||
pub logical_height: f32,
|
||||
pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "mermaid", feature = "typst"))]
|
||||
#[wasm_bindgen]
|
||||
impl WasmRgbaOutput {
|
||||
/// Moves the tightly packed RGBA8 pixel buffer (`width_px * height_px * 4`) to JS.
|
||||
///
|
||||
/// Note: Mermaid and Typst copy the buffer once from the engine's cached
|
||||
/// `Arc<RgbaImageBuffer>` (or take it without copying when unshared), while
|
||||
/// `take_pixels` eliminates a second clone on repeated JS property reads.
|
||||
/// Subsequent calls return an empty buffer.
|
||||
pub fn take_pixels(&mut self) -> Vec<u8> {
|
||||
std::mem::take(&mut self.pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Math SVG output and baseline metrics returned across the Wasm Worker boundary.
|
||||
#[cfg(feature = "math")]
|
||||
#[wasm_bindgen(getter_with_clone)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmMathOutput {
|
||||
/// Total box width in points.
|
||||
pub width_pt: f64,
|
||||
/// Distance from the top edge to the baseline in points.
|
||||
pub ascent_pt: f64,
|
||||
/// Distance from the baseline to the bottom edge in points.
|
||||
pub descent_pt: f64,
|
||||
/// Standalone pure-`<path>` SVG string.
|
||||
pub svg: String,
|
||||
}
|
||||
|
||||
/// Rasterized math RGBA8 output and baseline metrics.
|
||||
#[cfg(feature = "math")]
|
||||
#[wasm_bindgen]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmMathRgbaOutput {
|
||||
/// Total box width in points.
|
||||
pub width_pt: f64,
|
||||
/// Distance from the top edge to the baseline in points.
|
||||
pub ascent_pt: f64,
|
||||
/// Distance from the baseline to the bottom edge in points.
|
||||
pub descent_pt: f64,
|
||||
/// Physical pixel width.
|
||||
pub width_px: u32,
|
||||
/// Physical pixel height.
|
||||
pub height_px: u32,
|
||||
pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "math")]
|
||||
#[wasm_bindgen]
|
||||
impl WasmMathRgbaOutput {
|
||||
/// Moves the tightly packed RGBA8 pixel buffer (`width_px * height_px * 4`) to JS
|
||||
/// without cloning. Subsequent calls return an empty buffer.
|
||||
pub fn take_pixels(&mut self) -> Vec<u8> {
|
||||
std::mem::take(&mut self.pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Multi-page Typst SVG output and first-page metrics returned across the Wasm Worker boundary.
|
||||
#[cfg(feature = "typst")]
|
||||
#[wasm_bindgen(getter_with_clone)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmTypstOutput {
|
||||
/// First-page width in Typst points.
|
||||
pub width_pt: f64,
|
||||
/// First-page height in Typst points.
|
||||
pub height_pt: f64,
|
||||
/// First-page ascent in points.
|
||||
pub ascent_pt: f64,
|
||||
/// First-page descent in points.
|
||||
pub descent_pt: f64,
|
||||
/// Total compiled page count.
|
||||
pub page_count: usize,
|
||||
/// First-page SVG string (convenience alias for `pages_svg[0]`).
|
||||
pub svg: String,
|
||||
/// SVG string for every compiled page in order.
|
||||
pub pages_svg: Vec<String>,
|
||||
}
|
||||
|
||||
/// PDF page RGBA buffer and dimensions returned across the Wasm Worker boundary.
|
||||
#[cfg(feature = "pdf")]
|
||||
#[wasm_bindgen]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmPdfPageOutput {
|
||||
/// Physical pixel width.
|
||||
pub width_px: u32,
|
||||
/// Physical pixel height.
|
||||
pub height_px: u32,
|
||||
/// Logical page width in PDF points.
|
||||
pub logical_width: f32,
|
||||
/// Logical page height in PDF points.
|
||||
pub logical_height: f32,
|
||||
/// Total number of pages in the PDF document.
|
||||
pub page_count: usize,
|
||||
pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "pdf")]
|
||||
#[wasm_bindgen]
|
||||
impl WasmPdfPageOutput {
|
||||
/// Moves the tightly packed RGBA8 pixel buffer (`width_px * height_px * 4`) to JS
|
||||
/// without cloning. Subsequent calls return an empty buffer.
|
||||
pub fn take_pixels(&mut self) -> Vec<u8> {
|
||||
std::mem::take(&mut self.pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent WebAssembly Worker preview engine.
|
||||
///
|
||||
/// Retains registered fonts, pixel cache, in-memory Typst files/packages, and
|
||||
/// parsed PDF handles across Worker RPC calls.
|
||||
#[wasm_bindgen]
|
||||
pub struct WasmPreviewEngine {
|
||||
inner: PreviewEngine,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl WasmPreviewEngine {
|
||||
/// Creates a new persistent preview engine with the given cache limits.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(max_cache_entries: usize, max_cache_bytes: usize) -> Self {
|
||||
let limits = if max_cache_entries == 0 && max_cache_bytes == 0 {
|
||||
CacheLimits::MOBILE_DEFAULT
|
||||
} else {
|
||||
CacheLimits {
|
||||
max_entries: max_cache_entries,
|
||||
max_bytes: max_cache_bytes,
|
||||
}
|
||||
};
|
||||
Self {
|
||||
inner: PreviewEngine::new(limits),
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a TrueType/OpenType font byte buffer into the engine's `FontPool`.
|
||||
pub fn register_font(&mut self, bytes: &[u8]) -> Result<usize, JsValue> {
|
||||
self.inner
|
||||
.register_font(bytes.to_vec())
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))
|
||||
}
|
||||
|
||||
/// Returns the number of font faces registered in this engine.
|
||||
pub fn font_face_count(&self) -> usize {
|
||||
self.inner.font_face_count()
|
||||
}
|
||||
|
||||
/// Registers an in-memory Typst virtual file.
|
||||
#[cfg(feature = "typst")]
|
||||
pub fn register_typst_file(&mut self, path: &str, bytes: &[u8]) -> Result<(), JsValue> {
|
||||
self.inner
|
||||
.register_typst_file(path, bytes.to_vec())
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))
|
||||
}
|
||||
|
||||
/// Registers an in-memory Typst package file (such as `@preview/demo:0.1.0`).
|
||||
#[cfg(feature = "typst")]
|
||||
pub fn register_typst_package_file(
|
||||
&mut self,
|
||||
namespace: &str,
|
||||
name: &str,
|
||||
version: &str,
|
||||
path: &str,
|
||||
bytes: &[u8],
|
||||
) -> Result<(), JsValue> {
|
||||
self.inner
|
||||
.register_typst_package_file(namespace, name, version, path, bytes.to_vec())
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))
|
||||
}
|
||||
|
||||
/// Renders a Mermaid diagram to `resvg`-safe SVG with intrinsic dimensions.
|
||||
#[cfg(feature = "mermaid")]
|
||||
pub fn render_mermaid_svg(
|
||||
&self,
|
||||
source: &str,
|
||||
year: i32,
|
||||
month: u8,
|
||||
day: u8,
|
||||
tz_offset_minutes: i16,
|
||||
) -> Result<WasmSvgOutput, JsValue> {
|
||||
let opts = MermaidOptions {
|
||||
today: PreviewDate::new(year, month, day),
|
||||
timezone_offset_minutes: tz_offset_minutes,
|
||||
..MermaidOptions::default()
|
||||
};
|
||||
let svg = self
|
||||
.inner
|
||||
.render_mermaid_svg(source, &opts)
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))?;
|
||||
let (width_px, height_px) = parse_svg_dimensions(&svg);
|
||||
Ok(WasmSvgOutput {
|
||||
svg,
|
||||
width_px,
|
||||
height_px,
|
||||
})
|
||||
}
|
||||
|
||||
/// Renders a Mermaid diagram to cached RGBA8 pixels at `scale`.
|
||||
#[cfg(feature = "mermaid")]
|
||||
pub fn render_mermaid_rgba(
|
||||
&mut self,
|
||||
source: &str,
|
||||
year: i32,
|
||||
month: u8,
|
||||
day: u8,
|
||||
tz_offset_minutes: i16,
|
||||
scale: f32,
|
||||
) -> Result<WasmRgbaOutput, JsValue> {
|
||||
self.render_mermaid_rgba_with_policy(
|
||||
source,
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
tz_offset_minutes,
|
||||
scale,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
/// Renders a Mermaid diagram to cached RGBA8 pixels in lenient mode, allowing
|
||||
/// missing glyphs to fall back when no additional script fonts are available.
|
||||
#[cfg(feature = "mermaid")]
|
||||
pub fn render_mermaid_rgba_lenient(
|
||||
&mut self,
|
||||
source: &str,
|
||||
year: i32,
|
||||
month: u8,
|
||||
day: u8,
|
||||
tz_offset_minutes: i16,
|
||||
scale: f32,
|
||||
) -> Result<WasmRgbaOutput, JsValue> {
|
||||
self.render_mermaid_rgba_with_policy(
|
||||
source,
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
tz_offset_minutes,
|
||||
scale,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "mermaid")]
|
||||
fn render_mermaid_rgba_with_policy(
|
||||
&mut self,
|
||||
source: &str,
|
||||
year: i32,
|
||||
month: u8,
|
||||
day: u8,
|
||||
tz_offset_minutes: i16,
|
||||
scale: f32,
|
||||
lenient: bool,
|
||||
) -> Result<WasmRgbaOutput, JsValue> {
|
||||
let opts = MermaidOptions {
|
||||
today: PreviewDate::new(year, month, day),
|
||||
timezone_offset_minutes: tz_offset_minutes,
|
||||
..MermaidOptions::default()
|
||||
};
|
||||
let buf = if lenient {
|
||||
self.inner.render_mermaid_rgba_lenient(source, &opts, scale)
|
||||
} else {
|
||||
self.inner.render_mermaid_rgba(source, &opts, scale)
|
||||
}
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))?;
|
||||
let width_px = buf.width_px;
|
||||
let height_px = buf.height_px;
|
||||
let logical_width = buf.logical_width;
|
||||
let logical_height = buf.logical_height;
|
||||
let pixels = std::sync::Arc::try_unwrap(buf)
|
||||
.map(|owned| owned.pixels)
|
||||
.unwrap_or_else(|shared| shared.pixels.clone());
|
||||
Ok(WasmRgbaOutput {
|
||||
width_px,
|
||||
height_px,
|
||||
logical_width,
|
||||
logical_height,
|
||||
pixels,
|
||||
})
|
||||
}
|
||||
|
||||
/// Renders a LaTeX formula to pure-`<path>` SVG with exact baseline metrics.
|
||||
#[cfg(feature = "math")]
|
||||
pub fn render_latex_svg(
|
||||
&self,
|
||||
latex: &str,
|
||||
display_mode: bool,
|
||||
font_size_pt: f64,
|
||||
color_css: Option<String>,
|
||||
) -> Result<WasmMathOutput, JsValue> {
|
||||
let opts = MathRenderOptions {
|
||||
mode: if display_mode {
|
||||
MathDisplayMode::Display
|
||||
} else {
|
||||
MathDisplayMode::Inline
|
||||
},
|
||||
font_size_pt,
|
||||
padding_pt: 0.0,
|
||||
color_css: color_css.unwrap_or_else(|| "#000000".to_string()),
|
||||
};
|
||||
let out = self
|
||||
.inner
|
||||
.render_latex_svg(latex, &opts)
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))?;
|
||||
Ok(WasmMathOutput {
|
||||
width_pt: out.width_pt,
|
||||
ascent_pt: out.ascent_pt,
|
||||
descent_pt: out.descent_pt,
|
||||
svg: out.svg,
|
||||
})
|
||||
}
|
||||
|
||||
/// Renders a LaTeX formula to RGBA8 pixels with exact baseline metrics.
|
||||
#[cfg(feature = "math")]
|
||||
pub fn render_latex_rgba(
|
||||
&mut self,
|
||||
latex: &str,
|
||||
display_mode: bool,
|
||||
font_size_pt: f64,
|
||||
scale: f32,
|
||||
color_css: Option<String>,
|
||||
) -> Result<WasmMathRgbaOutput, JsValue> {
|
||||
let opts = MathRenderOptions {
|
||||
mode: if display_mode {
|
||||
MathDisplayMode::Display
|
||||
} else {
|
||||
MathDisplayMode::Inline
|
||||
},
|
||||
font_size_pt,
|
||||
padding_pt: 0.0,
|
||||
color_css: color_css.unwrap_or_else(|| "#000000".to_string()),
|
||||
};
|
||||
let out = self
|
||||
.inner
|
||||
.render_latex_rgba(latex, &opts, scale)
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))?;
|
||||
Ok(WasmMathRgbaOutput {
|
||||
width_pt: out.width_pt,
|
||||
ascent_pt: out.ascent_pt,
|
||||
descent_pt: out.descent_pt,
|
||||
width_px: out.image.width_px,
|
||||
height_px: out.image.height_px,
|
||||
pixels: out.image.pixels,
|
||||
})
|
||||
}
|
||||
|
||||
/// Compiles native Typst markup into all page SVGs using persistent fonts and packages.
|
||||
#[cfg(feature = "typst")]
|
||||
pub fn compile_typst_svg(
|
||||
&mut self,
|
||||
source: &str,
|
||||
year: i32,
|
||||
month: u8,
|
||||
day: u8,
|
||||
) -> Result<WasmTypstOutput, JsValue> {
|
||||
let pages = self
|
||||
.inner
|
||||
.compile_typst_pages(source, PreviewDate::new(year, month, day))
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))?;
|
||||
let first = pages
|
||||
.first()
|
||||
.ok_or_else(|| JsValue::from_str("compiled typst document has zero pages"))?;
|
||||
let pages_svg: Vec<String> = pages.iter().map(|p| p.svg.clone()).collect();
|
||||
Ok(WasmTypstOutput {
|
||||
width_pt: first.width_pt,
|
||||
height_pt: first.height_pt,
|
||||
ascent_pt: first.ascent_pt,
|
||||
descent_pt: first.descent_pt,
|
||||
page_count: pages.len(),
|
||||
svg: first.svg.clone(),
|
||||
pages_svg,
|
||||
})
|
||||
}
|
||||
|
||||
/// Compiles native Typst markup and rasterizes `page_index` to RGBA8.
|
||||
#[cfg(feature = "typst")]
|
||||
pub fn compile_typst_rgba(
|
||||
&mut self,
|
||||
source: &str,
|
||||
year: i32,
|
||||
month: u8,
|
||||
day: u8,
|
||||
page_index: usize,
|
||||
scale: f32,
|
||||
) -> Result<WasmRgbaOutput, JsValue> {
|
||||
let buf = self
|
||||
.inner
|
||||
.compile_typst_page_rgba(
|
||||
source,
|
||||
PreviewDate::new(year, month, day),
|
||||
page_index,
|
||||
scale,
|
||||
)
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))?;
|
||||
let width_px = buf.width_px;
|
||||
let height_px = buf.height_px;
|
||||
let logical_width = buf.logical_width;
|
||||
let logical_height = buf.logical_height;
|
||||
let pixels = std::sync::Arc::try_unwrap(buf)
|
||||
.map(|owned| owned.pixels)
|
||||
.unwrap_or_else(|shared| shared.pixels.clone());
|
||||
Ok(WasmRgbaOutput {
|
||||
width_px,
|
||||
height_px,
|
||||
logical_width,
|
||||
logical_height,
|
||||
pixels,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses and caches a PDF document, returning a handle for subsequent page renders.
|
||||
#[cfg(feature = "pdf")]
|
||||
pub fn load_pdf(&mut self, pdf_bytes: &[u8]) -> Result<u32, JsValue> {
|
||||
self.inner
|
||||
.load_pdf(pdf_bytes.to_vec())
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))
|
||||
}
|
||||
|
||||
/// Releases a cached PDF document handle.
|
||||
#[cfg(feature = "pdf")]
|
||||
pub fn unload_pdf(&mut self, handle: u32) -> bool {
|
||||
self.inner.unload_pdf(handle)
|
||||
}
|
||||
|
||||
/// Renders a page from a cached PDF document handle into RGBA8 pixels.
|
||||
#[cfg(feature = "pdf")]
|
||||
pub fn render_pdf_page_rgba(
|
||||
&self,
|
||||
handle: u32,
|
||||
page_index: usize,
|
||||
scale: f32,
|
||||
max_edge_px: u32,
|
||||
) -> Result<WasmPdfPageOutput, JsValue> {
|
||||
let req = PdfRenderRequest {
|
||||
page_index,
|
||||
scale,
|
||||
max_edge_px,
|
||||
..PdfRenderRequest::default()
|
||||
};
|
||||
let (page_count, buf) = self
|
||||
.inner
|
||||
.render_pdf_page(handle, req)
|
||||
.map_err(|err| JsValue::from_str(&err.to_string()))?;
|
||||
Ok(WasmPdfPageOutput {
|
||||
width_px: buf.width_px,
|
||||
height_px: buf.height_px,
|
||||
logical_width: buf.logical_width,
|
||||
logical_height: buf.logical_height,
|
||||
page_count,
|
||||
pixels: buf.pixels,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mermaid")]
|
||||
fn parse_svg_dimensions(svg: &str) -> (f32, f32) {
|
||||
if let Some(vb_pos) = svg.find("viewBox=\"") {
|
||||
let after = &svg[vb_pos + 9..];
|
||||
if let Some(end) = after.find('"') {
|
||||
let nums: Vec<f32> = after[..end]
|
||||
.split(|c: char| c.is_whitespace() || c == ',')
|
||||
.filter_map(|part| part.parse::<f32>().ok())
|
||||
.collect();
|
||||
if nums.len() == 4 {
|
||||
return (nums[2], nums[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
(0.0, 0.0)
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
{
|
||||
"katex_version": "0.18.10",
|
||||
"count": 52,
|
||||
"formulas": [
|
||||
{
|
||||
"name": "einstein",
|
||||
"latex": "E = mc^2",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.814108,
|
||||
"depth_em": 0,
|
||||
"width_em": 3.84007
|
||||
},
|
||||
{
|
||||
"name": "pythagoras",
|
||||
"latex": "a^2 + b^2 = c^2",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.814108,
|
||||
"depth_em": 0.08333,
|
||||
"width_em": 5.146726
|
||||
},
|
||||
{
|
||||
"name": "sub_sup_multi",
|
||||
"latex": "x_{i,j}^{n+1} + y_k^{(2)}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.0448,
|
||||
"depth_em": 0.412972,
|
||||
"width_em": 4.62939
|
||||
},
|
||||
{
|
||||
"name": "complex_exp",
|
||||
"latex": "e^{-i\\omega t} = \\cos(\\omega t) - i\\sin(\\omega t)",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.824664,
|
||||
"depth_em": 0.25,
|
||||
"width_em": 11.242978
|
||||
},
|
||||
{
|
||||
"name": "binomial",
|
||||
"latex": "\\binom{n}{k} = \\frac{n!}{k!(n-k)!}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.45,
|
||||
"depth_em": 0.95003,
|
||||
"width_em": 7.906928
|
||||
},
|
||||
{
|
||||
"name": "tensor",
|
||||
"latex": "T^{\\mu\\nu}_{\\alpha\\beta} = g^{\\mu\\rho} g^{\\nu\\sigma} T_{\\rho\\sigma\\alpha\\beta}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.7823,
|
||||
"depth_em": 0.437416,
|
||||
"width_em": 7.947282
|
||||
},
|
||||
{
|
||||
"name": "simple_frac",
|
||||
"latex": "\\frac{a+b}{c+d}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.880108,
|
||||
"depth_em": 0.403331,
|
||||
"width_em": 1.454957
|
||||
},
|
||||
{
|
||||
"name": "continued_frac",
|
||||
"latex": "1 + \\frac{1}{1 + \\frac{1}{1 + \\frac{1}{x}}}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.32144,
|
||||
"depth_em": 1.376928,
|
||||
"width_em": 5.344864
|
||||
},
|
||||
{
|
||||
"name": "partial_deriv",
|
||||
"latex": "\\dfrac{\\partial f}{\\partial x} + \\dfrac{\\partial f}{\\partial y} = 0",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.37144,
|
||||
"depth_em": 0.88044,
|
||||
"width_em": 5.903562
|
||||
},
|
||||
{
|
||||
"name": "tfrac_inline",
|
||||
"latex": "\\tfrac{1}{2} m v^2",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.845108,
|
||||
"depth_em": 0.345,
|
||||
"width_em": 2.388543
|
||||
},
|
||||
{
|
||||
"name": "sqrt_simple",
|
||||
"latex": "\\sqrt{2}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.90722,
|
||||
"depth_em": 0.13278,
|
||||
"width_em": 1.333089
|
||||
},
|
||||
{
|
||||
"name": "nth_root",
|
||||
"latex": "\\sqrt[3]{x^2 + y^2}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.957834,
|
||||
"depth_em": 0.282166,
|
||||
"width_em": 4.092281
|
||||
},
|
||||
{
|
||||
"name": "nested_root",
|
||||
"latex": "\\sqrt{\\frac{a^2 + b^2}{2}}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.699429,
|
||||
"depth_em": 0.740571,
|
||||
"width_em": 4.220001
|
||||
},
|
||||
{
|
||||
"name": "quadratic",
|
||||
"latex": "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.590389,
|
||||
"depth_em": 0.686,
|
||||
"width_em": 8.921221
|
||||
},
|
||||
{
|
||||
"name": "pmatrix",
|
||||
"latex": "\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.45,
|
||||
"depth_em": 0.95003,
|
||||
"width_em": 3.521275
|
||||
},
|
||||
{
|
||||
"name": "bmatrix_3x3",
|
||||
"latex": "\\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 2.05,
|
||||
"depth_em": 1.55002,
|
||||
"width_em": 4.834186
|
||||
},
|
||||
{
|
||||
"name": "vmatrix_det",
|
||||
"latex": "\\begin{vmatrix} a & b \\\\ c & d \\end{vmatrix} = ad - bc",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.45,
|
||||
"depth_em": 0.95002,
|
||||
"width_em": 7.182173
|
||||
},
|
||||
{
|
||||
"name": "smallmatrix",
|
||||
"latex": "\\bigl(\\begin{smallmatrix} a & b \\\\ c & d \\end{smallmatrix}\\bigr)",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.916108,
|
||||
"depth_em": 0.416108,
|
||||
"width_em": 2.038877
|
||||
},
|
||||
{
|
||||
"name": "sum_squares",
|
||||
"latex": "\\sum_{i=1}^{n} i^2 = \\frac{n(n+1)(2n+1)}{6}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.651397,
|
||||
"depth_em": 1.277669,
|
||||
"width_em": 11.230065
|
||||
},
|
||||
{
|
||||
"name": "product_k",
|
||||
"latex": "\\prod_{k=1}^{n} (1 + x_k)",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.651397,
|
||||
"depth_em": 1.302113,
|
||||
"width_em": 4.790604
|
||||
},
|
||||
{
|
||||
"name": "gaussian_integral",
|
||||
"latex": "\\int_{0}^{\\infty} e^{-x^2}\\,dx = \\frac{\\sqrt{\\pi}}{2}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.47728,
|
||||
"depth_em": 0.91195,
|
||||
"width_em": 7.948694
|
||||
},
|
||||
{
|
||||
"name": "contour_integral",
|
||||
"latex": "\\oint_{C} \\vec{F}\\cdot d\\vec{r}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.36,
|
||||
"depth_em": 0.91195,
|
||||
"width_em": 3.826349
|
||||
},
|
||||
{
|
||||
"name": "double_integral",
|
||||
"latex": "\\iint_{D} f(x,y)\\,dx\\,dy",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.36,
|
||||
"depth_em": 0.9117,
|
||||
"width_em": 7.289313
|
||||
},
|
||||
{
|
||||
"name": "sinc_limit",
|
||||
"latex": "\\lim_{x \\to 0} \\frac{\\sin x}{x} = 1",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.34486,
|
||||
"depth_em": 0.717108,
|
||||
"width_em": 5.657202
|
||||
},
|
||||
{
|
||||
"name": "euler_limit",
|
||||
"latex": "\\lim_{n \\to \\infty} \\left(1 + \\frac{1}{n}\\right)^n = e",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.504292,
|
||||
"depth_em": 0.95003,
|
||||
"width_em": 8.290289
|
||||
},
|
||||
{
|
||||
"name": "greek_lower",
|
||||
"latex": "\\alpha + \\beta + \\gamma = \\pi",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.69444,
|
||||
"depth_em": 0.19444,
|
||||
"width_em": 6.219936
|
||||
},
|
||||
{
|
||||
"name": "gamma_fn",
|
||||
"latex": "\\Gamma(z) = \\int_0^\\infty t^{z-1} e^{-t}\\,dt",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.414292,
|
||||
"depth_em": 0.91195,
|
||||
"width_em": 9.185539
|
||||
},
|
||||
{
|
||||
"name": "blackboard",
|
||||
"latex": "f: \\mathbb{R}^n \\to \\mathbb{C}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.69444,
|
||||
"depth_em": 0.19444,
|
||||
"width_em": 4.900568
|
||||
},
|
||||
{
|
||||
"name": "calligraphic",
|
||||
"latex": "\\mathcal{L}\\{f(t)\\} = F(s)",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.75,
|
||||
"depth_em": 0.25,
|
||||
"width_em": 6.789531
|
||||
},
|
||||
{
|
||||
"name": "fraktur_bold",
|
||||
"latex": "\\mathfrak{g} \\subset \\mathbf{GL}_n(\\mathbb{C})",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.75,
|
||||
"depth_em": 0.25,
|
||||
"width_em": 5.403579
|
||||
},
|
||||
{
|
||||
"name": "text_cjk_frac",
|
||||
"latex": "\\text{速度} = \\frac{\\text{距离}}{\\text{时间}}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.36033,
|
||||
"depth_em": 0.686,
|
||||
"width_em": 5.573266
|
||||
},
|
||||
{
|
||||
"name": "text_cjk_inline",
|
||||
"latex": "f(x) = \\text{最大值} + \\alpha",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.75,
|
||||
"depth_em": 0.25,
|
||||
"width_em": 8.147033
|
||||
},
|
||||
{
|
||||
"name": "text_cjk_cond",
|
||||
"latex": "\\text{当 } x > 0 \\text{ 时}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.68333,
|
||||
"depth_em": 0.0391,
|
||||
"width_em": 4.906218
|
||||
},
|
||||
{
|
||||
"name": "aligned_env",
|
||||
"latex": "\\begin{aligned} a &= b + c \\\\ d &= e + f \\end{aligned}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.6,
|
||||
"depth_em": 1.1,
|
||||
"width_em": 4.148373
|
||||
},
|
||||
{
|
||||
"name": "cases_env",
|
||||
"latex": "f(x) = \\begin{cases} x^2 & x \\ge 0 \\\\ -x & x < 0 \\end{cases}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.75,
|
||||
"depth_em": 1.25003,
|
||||
"width_em": 8.962382
|
||||
},
|
||||
{
|
||||
"name": "array_hline",
|
||||
"latex": "\\begin{array}{c|c} a & b \\\\ \\hline c & d \\end{array}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.45,
|
||||
"depth_em": 0.95,
|
||||
"width_em": 3.060837
|
||||
},
|
||||
{
|
||||
"name": "left_right_paren",
|
||||
"latex": "\\left(\\frac{a}{b}\\right)^2",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.054008,
|
||||
"depth_em": 0.35001,
|
||||
"width_em": 1.925886
|
||||
},
|
||||
{
|
||||
"name": "left_right_bracket",
|
||||
"latex": "\\left[\\frac{1}{2}, \\frac{3}{4}\\right]",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.85,
|
||||
"depth_em": 0.35001,
|
||||
"width_em": 2.458355
|
||||
},
|
||||
{
|
||||
"name": "left_right_brace",
|
||||
"latex": "\\left\\{x \\in \\mathbb{R} \\mid x^2 < 2\\right\\}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.85,
|
||||
"depth_em": 0.35001,
|
||||
"width_em": 7.321394
|
||||
},
|
||||
{
|
||||
"name": "left_right_norm",
|
||||
"latex": "\\left\\| \\mathbf{x} \\right\\|_2 = \\sqrt{\\sum_i x_i^2}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.520043,
|
||||
"depth_em": 1.519957,
|
||||
"width_em": 6.923304
|
||||
},
|
||||
{
|
||||
"name": "left_right_angle",
|
||||
"latex": "\\left\\langle u, v \\right\\rangle",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.75,
|
||||
"depth_em": 0.25,
|
||||
"width_em": 2.315502
|
||||
},
|
||||
{
|
||||
"name": "left_dot_eval",
|
||||
"latex": "\\left. \\frac{df}{dx} \\right|_{x=0}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.44998,
|
||||
"depth_em": 0.99972,
|
||||
"width_em": 3.155064
|
||||
},
|
||||
{
|
||||
"name": "accents",
|
||||
"latex": "\\hat{x} + \\bar{y} + \\tilde{z} + \\vec{v}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.714,
|
||||
"depth_em": 0.19444,
|
||||
"width_em": 5.794607
|
||||
},
|
||||
{
|
||||
"name": "over_under",
|
||||
"latex": "\\overline{x + y} + \\underbrace{a + b + \\cdots + z}_{26}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.78333,
|
||||
"depth_em": 1.382438,
|
||||
"width_em": 9.848754
|
||||
},
|
||||
{
|
||||
"name": "logic_quantifiers",
|
||||
"latex": "\\forall x \\in X, \\exists y \\in Y : x \\le y",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.69444,
|
||||
"depth_em": 0.19444,
|
||||
"width_em": 10.073525
|
||||
},
|
||||
{
|
||||
"name": "maxwell_div",
|
||||
"latex": "\\nabla \\cdot \\mathbf{E} = \\frac{\\rho}{\\varepsilon_0}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.10756,
|
||||
"depth_em": 0.836,
|
||||
"width_em": 4.750452
|
||||
},
|
||||
{
|
||||
"name": "color_boxed",
|
||||
"latex": "\\boxed{\\color{blue}{x^2} + \\color{red}{y^2} = r^2}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.204108,
|
||||
"depth_em": 0.53444,
|
||||
"width_em": 5.931608
|
||||
},
|
||||
{
|
||||
"name": "affine_nested_frac",
|
||||
"latex": "a + \\left(\\frac{\\frac{a}{b}}{c}\\right)",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.15,
|
||||
"depth_em": 0.65002,
|
||||
"width_em": 3.689348
|
||||
},
|
||||
{
|
||||
"name": "edge_def_arraystretch",
|
||||
"latex": "\\def\\arraystretch{1.5}\\begin{array}{c:c:c} a & b & c \\\\ \\hline d & e & f \\\\ \\hdashline g & h & i \\end{array}",
|
||||
"display_mode": true,
|
||||
"katex_ok": true,
|
||||
"height_em": 2.95,
|
||||
"depth_em": 2.45,
|
||||
"width_em": 4.726038
|
||||
},
|
||||
{
|
||||
"name": "edge_vcenter_hbox",
|
||||
"latex": "a+\\left(\\vcenter{\\hbox{$\\frac{\\frac a b}c$}}\\right)",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 1.15,
|
||||
"depth_em": 0.65002,
|
||||
"width_em": 3.689348
|
||||
},
|
||||
{
|
||||
"name": "edge_newcommand_builtin",
|
||||
"latex": "\\newcommand{\\R}{\\mathbb{R}} x \\in \\R",
|
||||
"display_mode": false,
|
||||
"katex_ok": false,
|
||||
"height_em": 0,
|
||||
"depth_em": 0,
|
||||
"width_em": 0
|
||||
},
|
||||
{
|
||||
"name": "edge_newcommand_custom",
|
||||
"latex": "\\newcommand{\\myvec}[1]{\\mathbf{#1}} \\myvec{v} \\cdot \\myvec{w}",
|
||||
"display_mode": false,
|
||||
"katex_ok": true,
|
||||
"height_em": 0.44445,
|
||||
"depth_em": 0,
|
||||
"width_em": 2.192423
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -5,7 +5,7 @@ It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98
|
||||
|
||||
## Workspace boundaries and four-domain guards
|
||||
|
||||
- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/ui`, `../common/store`, `../../blocksuite/crates/doc`, and `../../blocksuite/crates/playground`).
|
||||
- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/ui`, `../common/store`, `../../blocksuite/crates/doc`, `../../blocksuite/crates/playground`, and `../../blocksuite/crates/preview`).
|
||||
Never use directory wildcards that can scan asset directories.
|
||||
- `packages/frontend/Cargo.toml` excludes `native` and `mobile-native`.
|
||||
Those legacy crates remain members of the root `Cargo.toml` workspace.
|
||||
|
||||
Generated
+2818
-62
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,7 @@ members = [
|
||||
"../common/store",
|
||||
"../../blocksuite/crates/doc",
|
||||
"../../blocksuite/crates/playground",
|
||||
"../../blocksuite/crates/preview",
|
||||
]
|
||||
default-members = [
|
||||
"../ui/ui",
|
||||
|
||||
@@ -295,6 +295,11 @@ if ! grep -q '#!\[forbid(unsafe_code)\]' "$DOC_DIR/src/lib.rs"; then
|
||||
fail "blocksuite/crates/doc/src/lib.rs must declare #![forbid(unsafe_code)]"
|
||||
fi
|
||||
|
||||
echo "==> Checking blocksuite/crates/preview zero host-font scanning"
|
||||
if grep -rn 'load_system_fonts' "$REPO_ROOT/blocksuite/crates/preview/src" 2>/dev/null; then
|
||||
fail "load_system_fonts is forbidden in blocksuite/crates/preview/src"
|
||||
fi
|
||||
|
||||
echo "==> Checking no wall-clock calls outside packages/ui/ui/src/platform"
|
||||
WALL_CLOCK_HITS=""
|
||||
while IFS=$'\t' read -r _pkg_name member_dir; do
|
||||
|
||||
Reference in new issue
Block a user