Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

LR6: a composition's 2D context measures and reads back. measureText is the text shaped by usvg as the canvas draws it, in the page's fonts (canvas.measure: width, actualBoundingBox*, fontBoundingBox*, from the alignment point), and getImageData reads back what was drawn (canvas.read); raea-runtime-canvas serves both as natives, which @raea/ui's wire reaches through the composition's __ui_sync (sdk/raea canvas2d.ts). putImageData writes its pixels as they are (a put op). OffscreenCanvas is a canvas no page shows. raea's bundled faces (Inter and the rest) now reach usvg's font database too, so a canvas measures and draws them, not a fallback. probes/measure.tsx matches Chrome: width exact, ink and font box within 0.8 px, pixels read back equal

shinyobjectz34629d33b826
diff --git a/Cargo.lock b/Cargo.lock
index 51cfa5ee..b7e5f98e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14847,6 +14847,16 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-runtime-canvas"
+version = "0.1.0"
+dependencies = [
+ "blitz-dom",
+ "raea-native",
+ "raea-sys-canvas",
+ "serde_json",
+]
+
[[package]]
name = "raea-runtime-cssurls"
version = "0.1.0"
@@ -15122,6 +15132,7 @@ dependencies = [
"raea-render",
"raea-runtime-bundle",
"raea-runtime-calls",
+ "raea-runtime-canvas",
"raea-runtime-input",
"raea-runtime-jsengine",
"raea-runtime-plugins",
diff --git a/Cargo.toml b/Cargo.toml
index c697a804..e1d64cb7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -150,6 +150,7 @@ members = [
"engine/shape-web",
"runtime/calls",
"runtime/shots",
+ "runtime/canvas",
"runtime/export",
"runtime/live",
"runtime/page",
diff --git a/bench/layout-reads/probes/measure.tsx b/bench/layout-reads/probes/measure.tsx
new file mode 100644
index 00000000..21c989d6
--- /dev/null
+++ b/bench/layout-reads/probes/measure.tsx
@@ -0,0 +1,64 @@
+// LR6's reads as a probe (docs/layout-reads.feature): a 2D context's measureText and its image data. Each measure
+// places a word (its left or top at the value read), so the harness's 1 px box check holds it to Chrome's; the pixels
+// read back are printed as words, which must match exactly.
+import { AbsoluteFill } from "raea";
+import { loadFont } from "raea/text";
+import { useLayoutEffect, useState } from "react";
+
+const { fontFamily } = loadFont("Inter");
+
+export const conf = { width: 640, height: 360, fps: 30, durationInFrames: 3 };
+export const props = {};
+
+type Read = { w: number; inkL: number; inkR: number; asc: number; desc: number; fasc: number; pixels: string; put: string };
+
+function read(): Read {
+ const c = new OffscreenCanvas(64, 64);
+ const ctx = c.getContext("2d")!;
+ ctx.font = `48px ${fontFamily}`;
+ const hello = ctx.measureText("Hello, measured");
+ const g = ctx.measureText("g");
+ ctx.textAlign = "center";
+ const mid = ctx.measureText("Wide");
+ ctx.textAlign = "left";
+ // what was drawn, read back: a red square on clear, the middle of it and a corner outside it
+ ctx.fillStyle = "#f00";
+ ctx.fillRect(8, 8, 16, 16);
+ const px = (x: number, y: number) => [...ctx.getImageData(x, y, 1, 1).data].join(" ");
+ // putImageData writes its pixels as they are: half-transparent green, no blending with the red under it
+ const img = ctx.createImageData(2, 2);
+ for (let i = 0; i < img.data.length; i += 4) img.data.set([0, 255, 0, 128], i);
+ ctx.globalAlpha = 0.25;
+ ctx.putImageData(img, 10, 10);
+ return {
+ w: hello.width,
+ inkL: mid.actualBoundingBoxLeft,
+ inkR: mid.actualBoundingBoxRight,
+ asc: hello.actualBoundingBoxAscent,
+ desc: g.actualBoundingBoxDescent,
+ fasc: hello.fontBoundingBoxAscent,
+ pixels: `${px(16, 16)} and ${px(40, 40)}`,
+ put: px(11, 11),
+ };
+}
+
+export function Comp() {
+ const [r, setR] = useState<Read | null>(null);
+ useLayoutEffect(() => setR(read()), []);
+ if (!r) return <AbsoluteFill style={{ background: "#fff" }} />;
+ const at = (left: number, top: number, word: string) => (
+ <div style={{ position: "absolute", left, top, fontSize: 16, lineHeight: "20px" }}>{word}</div>
+ );
+ return (
+ <AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily }}>
+ {at(r.w, 10, "width")}
+ {at(320 - r.inkL, 40, "inkleft")}
+ {at(320 + r.inkR, 70, "inkright")}
+ {at(20, 100 + r.asc, "ascent")}
+ {at(20 + r.desc * 10, 160, "descent")}
+ {at(20, 180 + r.fasc, "fontascent")}
+ {at(20, 260, `red ${r.pixels}`)}
+ {at(20, 290, `put ${r.put}`)}
+ </AbsoluteFill>
+ );
+}
diff --git a/runtime/canvas/Cargo.toml b/runtime/canvas/Cargo.toml
new file mode 100644
index 00000000..92827e26
--- /dev/null
+++ b/runtime/canvas/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "raea-runtime-canvas"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "A composition's 2D context's host calls as native calls: measureText shaped from the page's fonts, getImageData's read-back (docs/layout-reads.feature LR6)"
+
+[dependencies]
+# the native-call registry
+raea-native = { path = "../../engine/native", default-features = false }
+# the canvas's replay, its text shaping and its read-back
+raea-sys-canvas = { path = "../../systems/canvas" }
+# the page's font database (every face the composition loaded), which a canvas draws its text in
+blitz-dom = { version = "=0.3.0-beta.4", default-features = false, features = ["svg"] }
+serde_json = "1"
diff --git a/runtime/canvas/src/lib.rs b/runtime/canvas/src/lib.rs
new file mode 100644
index 00000000..18080025
--- /dev/null
+++ b/runtime/canvas/src/lib.rs
@@ -0,0 +1,31 @@
+//! A composition's 2D context answered by the host (docs/layout-reads.feature LR6): the calls an app page's canvas makes
+//! of its host (`canvas.measure`, `canvas.advances`, `canvas.read`), as native calls. The context (@raea/ui's) asks
+//! through its wire's synchronous call, which a composition's entry routes here (sdk/raea/src/canvas2d.ts), so
+//! measureText is shaped from the fonts the page draws with and getImageData reads back what the context drew.
+
+/// The calls, registered with the composition's other natives (raea-runtime-react's thread.rs).
+pub fn register() {
+ // the faces a canvas's text is shaped in: the page's (blitz-dom adds every face the composition loads)
+ raea_sys_canvas::fonts(blitz_dom::util::svg_fonts);
+ raea_native::register(
+ "canvas.measure",
+ "{ font: { family: string; size: number; weight: string; style: string }; text: string; align?: string; baseline?: string }",
+ "{ width: number; actualBoundingBoxLeft: number; actualBoundingBoxRight: number; actualBoundingBoxAscent: number; actualBoundingBoxDescent: number; fontBoundingBoxAscent: number; fontBoundingBoxDescent: number }",
+ "measureText: the text shaped as the canvas draws it, in the page's fonts; its advance, ink and font box from the alignment point (docs/layout-reads.feature LR6)",
+ |a| raea_sys_canvas::metrics(a),
+ );
+ raea_native::register(
+ "canvas.advances",
+ "{ font: { family: string; weight: string; style: string }; chars: string }",
+ "{ adv: (number | null)[]; own: boolean[] }",
+ "each character's advance (a fraction of the font size) in the face a canvas draws it with, and whether the font's own family has it",
+ |a| raea_sys_canvas::advances(a),
+ );
+ raea_native::register(
+ "canvas.read",
+ "{ width: number; height: number; __canvas2d: unknown; x: number; y: number; w: number; h: number }",
+ "{ data: string }",
+ "getImageData: a canvas's display list drawn on a bitmap of its own, and a rectangle of it read off as base64 RGBA",
+ |a| raea_sys_canvas::read(a),
+ );
+}
diff --git a/runtime/react/Cargo.toml b/runtime/react/Cargo.toml
index ea64c474..9be175e2 100644
--- a/runtime/react/Cargo.toml
+++ b/runtime/react/Cargo.toml
@@ -76,6 +76,8 @@ raea-sys-bake = { path = "../../systems/bake" }
raea-runtime-track = { path = "../../runtime/track" }
# <BlenderShot> and <GodotShot>'s native calls (blender.shot, godot.shot)
raea-runtime-shots = { path = "../shots" }
+# a composition's 2D context's host calls (canvas.measure, canvas.advances, canvas.read; layout-reads LR6)
+raea-runtime-canvas = { path = "../canvas" }
[package.metadata.cargo-shear]
# raea-io-media is here for its features (h264), which the platform decoders raea-render reads take
diff --git a/runtime/react/src/thread.rs b/runtime/react/src/thread.rs
index a906edba..4a096125 100644
--- a/runtime/react/src/thread.rs
+++ b/runtime/react/src/thread.rs
@@ -37,7 +37,7 @@ fn log(a: &[String]) -> Result<Ret, String> {
pub fn register_natives() {
raea_native::register("page.viewBox", "{}", "[number, number, number, number] | null", "the box (x, y, w, h in frame px) a camera in a page element draws its view in, as last laid out; null when it draws under the whole frame (3D picking in the box, docs/sdk.feature S3a)", |_| Ok(serde_json::json!(*VIEW_BOX.lock().unwrap())));
// the calls crate's, matchmove.solve (scene/track.rs), physics.* (systems/bake), scene.* (scene/contact.rs), *.shot (runtime/shots)
- [native::register, layout::register, scene::track::register, scene::physics::register, raea_runtime_shots::register, scene::register_scene].iter().for_each(|r| r());
+ [native::register, layout::register, scene::track::register, scene::physics::register, raea_runtime_shots::register, raea_runtime_canvas::register, scene::register_scene].iter().for_each(|r| r());
}
/// The JS thread: the prelude, the shims, the bundle, then timers and Bevy's events. Both engines run promise jobs as
diff --git a/sdk/raea/src/canvas2d.ts b/sdk/raea/src/canvas2d.ts
index 030b7fdf..fd9af02a 100644
--- a/sdk/raea/src/canvas2d.ts
+++ b/sdk/raea/src/canvas2d.ts
@@ -5,9 +5,14 @@
//
// The handle bevy-react gives a ref keeps no props, so a canvas's width and height (its bitmap's size, 300 x 150 unset,
// as a browser has it) are read from the ops the bridge sends, each batch passing the host's op_flush as JSON; setting
-// them on the ref sends them as props, and clears the bitmap, as it does in a browser. getImageData reads zeros: a
-// composition has no host to read pixels back from.
+// them on the ref sends them as props, and clears the bitmap, as it does in a browser.
+//
+// The context asks its host for what JS can't know (layout-reads LR6): measureText is shaped in the page's fonts and
+// getImageData reads back what was drawn, through @raea/ui's wire's synchronous call, which the composition answers
+// with raea-runtime-canvas's natives. A canvas no page shows (OffscreenCanvas, and LR7's
+// document.createElement("canvas")) has the same context, drawing into a list of its own.
+import { native } from "@raea/app/native";
import { CanvasRenderingContext2D_ } from "@raea/ui/canvas";
/** bevy-react's canvas handle, as the entry passes it (this module can't import bevy-react: the SDK's checks load it
@@ -46,10 +51,67 @@ function send(id: number, props: Record<string, unknown>): void {
HOST.op_flush(JSON.stringify([{ op: "update", id, kind: "canvas", props }]), false);
}
+/** The host calls the context makes, answered by the composition's natives (raea-runtime-canvas); any other answers
+ * nothing, as where there's no host. */
+const CALLS = new Set(["canvas.measure", "canvas.advances", "canvas.read"]);
+function hostCalls(): void {
+ const g = globalThis as { __ui_sync?: (name: string, json: string) => string };
+ if (typeof g.__ui_sync === "function") return;
+ g.__ui_sync = (name, json) => {
+ if (!CALLS.has(name)) return "{}";
+ try {
+ return JSON.stringify({ ok: native(name as "canvas.read", JSON.parse(json)) });
+ } catch (e) {
+ return JSON.stringify({ err: e instanceof Error ? e.message : String(e) });
+ }
+ };
+}
+
+/** A canvas no page shows: its 2D context draws into a list of its own, which getImageData reads back and drawImage
+ * draws from (`_ctx`), as an OffscreenCanvas or a canvas element never appended does in a browser. */
+export class OffscreenCanvas {
+ readonly tagName = "CANVAS";
+ readonly nodeName = "CANVAS";
+ private size: Size;
+ private ctx?: CanvasRenderingContext2D_;
+ constructor(width = 300, height = 150) {
+ this.size = { width: dim(width, 300), height: dim(height, 150) };
+ }
+ get width() {
+ return this.size.width;
+ }
+ set width(v: number) {
+ this.size.width = dim(v, 0);
+ this.ctx?._reset();
+ }
+ get height() {
+ return this.size.height;
+ }
+ set height(v: number) {
+ this.size.height = dim(v, 0);
+ this.ctx?._reset();
+ }
+ get _ctx() {
+ return this.ctx;
+ }
+ getContext(kind = "2d") {
+ if (kind !== "2d") return null;
+ const size = this.size;
+ const host = { get width() { return size.width; }, get height() { return size.height; }, getAttribute: (k: string) => (k === "width" || k === "height" ? String(size[k]) : null), _send: () => {} };
+ return (this.ctx ??= new CanvasRenderingContext2D_(host));
+ }
+ toDataURL() {
+ return this.ctx?._dataUrl() ?? "data:,";
+ }
+}
+
/** Installs the context on bevy-react's canvas handle (`El`, its BevyCanvasElement), once, from the entry. */
export function canvas2d(El: HandleClass): void {
if (!HOST || typeof HOST.op_flush !== "function" || HOST.__canvas2d) return;
HOST.__canvas2d = true;
+ hostCalls();
+ const g = globalThis as { OffscreenCanvas?: unknown };
+ g.OffscreenCanvas ??= OffscreenCanvas;
const flush = HOST.op_flush;
HOST.op_flush = (json: string, devtools: boolean) => {
sniff(json);
diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts
index e17ae84f..12f20e44 100644
--- a/sdk/raea/src/native-calls.ts
+++ b/sdk/raea/src/native-calls.ts
@@ -28,6 +28,12 @@ export interface NativeCalls {
"blender.post": { args: { sid: string; ops: unknown[] }; answer: { r: Record<string, unknown>; n: number; err?: { i: number; type: string; msg: string; trace: string } } };
/** a layer drawn by Blender (<BlenderShot>): a raea/blender script's scene or a .blend's animation rendered frame for frame, made once and kept (0000.png on in dir) */
"blender.shot": { args: { script?: string; file?: string; engine?: string; samples?: number; transparent?: boolean; args?: string[]; fps: number; width: number; height: number; frames: number }; answer: { dir: string; frames: number } };
+ /** each character's advance (a fraction of the font size) in the face a canvas draws it with, and whether the font's own family has it */
+ "canvas.advances": { args: { font: { family: string; weight: string; style: string }; chars: string }; answer: { adv: (number | null)[]; own: boolean[] } };
+ /** measureText: the text shaped as the canvas draws it, in the page's fonts; its advance, ink and font box from the alignment point (docs/layout-reads.feature LR6) */
+ "canvas.measure": { args: { font: { family: string; size: number; weight: string; style: string }; text: string; align?: string; baseline?: string }; answer: { width: number; actualBoundingBoxLeft: number; actualBoundingBoxRight: number; actualBoundingBoxAscent: number; actualBoundingBoxDescent: number; fontBoundingBoxAscent: number; fontBoundingBoxDescent: number } };
+ /** getImageData: a canvas's display list drawn on a bitmap of its own, and a rectangle of it read off as base64 RGBA */
+ "canvas.read": { args: { width: number; height: number; __canvas2d: unknown; x: number; y: number; w: number; h: number }; answer: { data: string } };
/** raea's command line (render, play, guide, bundle, types; the media verbs: raea media, raea ffmpeg), run in process in cwd */
"cli.raea": { args: { args: string[]; cwd: string }; answer: { exit: number; stdout: string; stderr: string } };
/** a headless run ends with this exit code */
diff --git a/sdk/ui/src/canvas/context.ts b/sdk/ui/src/canvas/context.ts
index 74247545..2db17d7a 100644
--- a/sdk/ui/src/canvas/context.ts
+++ b/sdk/ui/src/canvas/context.ts
@@ -412,7 +412,7 @@ export class CanvasRenderingContext2D_ {
}
private text(kind: "fill" | "stroke", text: string, x: number, y: number, maxWidth?: number) {
const f = parseFont(this.s.font)!;
- const align = this.s.align === "start" ? "left" : this.s.align === "end" ? "right" : this.s.align;
+ const align = this.side;
const paint = kind === "fill" ? paintOf(this.s.fill, this.s.ts) : paintOf(this.s.stroke, this.s.ts);
this.push(["text", kind, String(text), x, y, f, align, this.s.baseline, maxWidth ?? null, paint, kind === "stroke" ? this.strokeParams() : null, this.state()]);
}
@@ -422,8 +422,12 @@ export class CanvasRenderingContext2D_ {
strokeText(t: string, x: number, y: number, maxWidth?: number) {
this.text("stroke", t, x, y, maxWidth);
}
+ /** textAlign as a side: start and end are left and right (the context's direction is ltr) */
+ private get side() {
+ return this.s.align === "start" ? "left" : this.s.align === "end" ? "right" : this.s.align;
+ }
measureText(text: string) {
- return measure(this.s.font, String(text));
+ return measure(this.s.font, String(text), this.side, this.s.baseline);
}
drawImage(img: { src?: string; currentSrc?: string; _canvas2d?: CanvasRenderingContext2D_; width?: number; height?: number; naturalWidth?: number; naturalHeight?: number }, ...a: number[]) {
let s: (number | null)[];
@@ -459,6 +463,15 @@ export class CanvasRenderingContext2D_ {
if (r) unb64(r.data, out.data);
return out;
}
+ /** The image's pixels written onto the bitmap as they are (no transform, alpha, compositing or clip), only its dirty
+ * rectangle when one is given: a "put" in the list, which the host writes in order with the draws (layout-reads LR6). */
+ putImageData(img: ImageData_, dx: number, dy: number, x = 0, y = 0, w = img.width, h = img.height) {
+ [dx, dy, x, y, w, h] = [dx, dy, x, y, w, h].map((n) => Math.trunc(Number(n)));
+ if ([dx, dy, x, y, w, h].some((n) => !Number.isFinite(n))) return;
+ if (w < 0) [x, w] = [x + w, -w];
+ if (h < 0) [y, h] = [y + h, -h];
+ this.push(["put", { w: img.width, h: img.height, data: base64(new Uint8Array(img.data.buffer, img.data.byteOffset, img.data.byteLength)) }, dx, dy, x, y, w, h]);
+ }
createImageData(a: number | ImageData_, h?: number) {
if (a instanceof ImageData_) return new ImageData_(a.width, a.height);
return new ImageData_(Math.abs(Math.trunc(a)), Math.abs(Math.trunc(Number(h))));
diff --git a/sdk/ui/src/canvas/measure.ts b/sdk/ui/src/canvas/measure.ts
index b26061d2..3b2319c9 100644
--- a/sdk/ui/src/canvas/measure.ts
+++ b/sdk/ui/src/canvas/measure.ts
@@ -1,10 +1,26 @@
-// measureText: each character's advance from the host's faces (canvas.advances), else the bundled metrics.
+// measureText: the text shaped by the host as the canvas draws it (canvas.measure, a composition's: layout-reads LR6),
+// else each character's advance from the host's faces (canvas.advances), else the bundled metrics.
import * as wire from "../wire";
import { S, metrics, parseFont } from "./all";
-/** measureText's answer for `text` in a CSS `font`. */
-export function measure(font: string, text: string) {
+/** The host's TextMetrics, where it shapes text (canvas.measure); asked no more once it says it can't. */
+let shapes = true;
+function hostMetrics(font: unknown, text: string, align: string, baseline: string) {
+ if (!shapes) return undefined;
+ try {
+ return wire.callSync<Record<string, number>>("canvas.measure", { font, text, align, baseline });
+ } catch {
+ shapes = false;
+ return undefined;
+ }
+}
+
+/** measureText's answer for `text` in a CSS `font`, from the point the context's textAlign (left, center or right)
+ * and textBaseline put it at. */
+export function measure(font: string, text: string, align = "left", baseline = "alphabetic") {
const f = parseFont(font)!;
+ const shaped = hostMetrics(f, text, align, baseline);
+ if (shaped) return shaped;
const fam = f.family.replace(/["']/g, "").split(",")[0].trim().toLowerCase();
const m = metrics.get(fam) ?? metrics.get(S.defaultFamily.toLowerCase());
const host = hostAdvances(f, text);
diff --git a/systems/canvas/src/draw.rs b/systems/canvas/src/draw.rs
index 34c0c938..c9948bce 100644
--- a/systems/canvas/src/draw.rs
+++ b/systems/canvas/src/draw.rs
@@ -67,6 +67,25 @@ impl Ctx<'_> {
let Some(img) = a.get(1).and_then(Value::as_str).and_then(|src| video_frame(src, a.get(11).and_then(Value::as_f64).unwrap_or(0.0))) else { return };
self.image(pm, a, &img)
}
+ // ["put", {w, h, data}, dx, dy, x, y, w, h]: putImageData, the image's RGBA (base64) written as it is, with
+ // no transform, alpha, compositing or clip, its dirty rectangle (x, y, w, h in the image) only (LR6)
+ Some("put") => {
+ use base64::Engine as _;
+ let (iw, ih) = (a[1]["w"].as_i64().unwrap_or(0), a[1]["h"].as_i64().unwrap_or(0));
+ let data = a[1]["data"].as_str().and_then(|d| base64::engine::general_purpose::STANDARD.decode(d).ok());
+ let Some(px) = data.filter(|p| p.len() as i64 == iw * ih * 4) else { return };
+ let n = |i: usize| a.get(i).and_then(Value::as_f64).unwrap_or(0.0) as i64;
+ let (dx, dy) = (n(2), n(3));
+ let (x0, y0, x1, y1) = (n(4).max(0), n(5).max(0), (n(4) + n(6)).min(iw), (n(5) + n(7)).min(ih));
+ let (w, h) = (i64::from(w), i64::from(h));
+ let out = pm.pixels_mut();
+ for y in (y0..y1).filter(|y| (0..h).contains(&(dy + y))) {
+ for x in (x0..x1).filter(|x| (0..w).contains(&(dx + x))) {
+ let s = ((y * iw + x) * 4) as usize;
+ out[((dy + y) * w + dx + x) as usize] = sk::ColorU8::from_rgba(px[s], px[s + 1], px[s + 2], px[s + 3]).premultiply();
+ }
+ }
+ }
_ => {}
}
}
@@ -112,41 +131,6 @@ impl Ctx<'_> {
// ["text", kind, text, x, y, font, align, baseline, maxWidth, paint, stroke, state]
let (Some(kind), Some(text)) = (a.get(1).and_then(Value::as_str), a.get(2).and_then(Value::as_str)) else { return };
let st = &a[11];
- let font = &a[5];
- let anchor = match a[6].as_str() {
- Some("center") => "middle",
- Some("right") => "end",
- _ => "start",
- };
- let base = match a[7].as_str() {
- Some("top") => "text-before-edge",
- Some("hanging") => "hanging",
- Some("middle") => "middle",
- Some("bottom") => "text-after-edge",
- Some("ideographic") => "ideographic",
- _ => "alphabetic",
- };
- let escape = |s: &str| {
- let mut e = String::new();
- for c in s.chars() {
- match c {
- '&' => e.push_str("&amp;"),
- '<' => e.push_str("&lt;"),
- _ => e.push(c),
- }
- }
- e
- };
- let fam = font["family"].as_str().unwrap_or("sans-serif").replace('"', "'");
- // a family split across files by unicode-range: each run names the file that has its glyphs (subsets.rs)
- let split = crate::split_families(&self.opt.fontdb).and_then(|s| crate::subsets::runs(&self.opt.fontdb, &s, &fam, text));
- let esc = match split {
- Some(runs) => runs.iter().map(|(f, s)| match f {
- Some(f) => format!("<tspan font-family=\"'{}', {fam}\">{}</tspan>", f.replace('\'', ""), escape(s)),
- None => format!("<tspan>{}</tspan>", escape(s)),
- }).collect(),
- None => escape(text),
- };
let paint_attr = if kind == "fill" {
"fill=\"#fff\"".to_string()
} else {
@@ -154,14 +138,7 @@ impl Ctx<'_> {
format!("fill=\"none\" stroke=\"#fff\" stroke-width=\"{}\" stroke-linejoin=\"{}\"", f(&s["width"]), s["join"].as_str().unwrap_or("miter"))
};
let (w, h) = (pm.width(), pm.height());
- let doc = format!(
- "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><text x=\"{}\" y=\"{}\" font-size=\"{}\" font-family=\"{fam}\" font-weight=\"{}\" font-style=\"{}\" text-anchor=\"{anchor}\" dominant-baseline=\"{base}\" {paint_attr}>{esc}</text></svg>",
- f(&a[3]),
- f(&a[4]),
- f(&font["size"]),
- font["weight"].as_str().unwrap_or("400"),
- font["style"].as_str().unwrap_or("normal"),
- );
+ let doc = crate::measure::text_doc(self.opt, &a[5], text, (f(&a[3]), f(&a[4])), (&a[6], &a[7]), &paint_attr, (w, h));
let Ok(tree) = usvg::Tree::from_str(&doc, self.opt) else { return };
let ts = ts_of(&st["ts"]);
// the glyphs' coverage in the call's space, then the paint through it
diff --git a/systems/canvas/src/lib.rs b/systems/canvas/src/lib.rs
index cf1b13e8..7593e94c 100644
--- a/systems/canvas/src/lib.rs
+++ b/systems/canvas/src/lib.rs
@@ -27,7 +27,7 @@ use tiny_skia as sk;
mod draw;
mod measure;
-pub use measure::advances;
+pub use measure::{advances, metrics};
mod filter;
mod paint;
mod subsets;
diff --git a/systems/canvas/src/measure.rs b/systems/canvas/src/measure.rs
index 30beba8e..2ce1cbc5 100644
--- a/systems/canvas/src/measure.rs
+++ b/systems/canvas/src/measure.rs
@@ -1,10 +1,86 @@
-//! A canvas's measureText: each character's advance in the face the canvas would draw it with (text in draw.rs).
-//! The page asks for the characters it hasn't measured yet in a font, and keeps the ones its own family has; a
-//! character another family stood in for is asked again, so a face the page loads later takes over.
+//! A canvas's text as usvg shapes it, for drawing (draw.rs) and measuring. measureText is `canvas.measure`: the text
+//! shaped as the canvas would draw it, its advance and its ink (docs/layout-reads.feature LR6). An app page without it
+//! asks `canvas.advances`, each character's advance in the face the canvas would draw it with: the characters it hasn't
+//! measured yet in a font, keeping the ones its own family has, so a face the page loads later takes over.
use serde_json::{json, Value};
use usvg::fontdb::{Family, Query, Style, Weight, ID};
+/// A 2D context's text call as the SVG usvg shapes: `text` at `at` in `font` ({family, size, weight, style}), on the
+/// context's (textAlign, textBaseline), painted by `paint` (attributes), on a `size` document.
+pub(crate) fn text_doc(opt: &usvg::Options, font: &Value, text: &str, at: (f32, f32), (align, baseline): (&Value, &Value), paint: &str, (w, h): (u32, u32)) -> String {
+ let anchor = match align.as_str() {
+ Some("center") => "middle",
+ Some("right") => "end",
+ _ => "start",
+ };
+ let base = match baseline.as_str() {
+ Some("top") => "text-before-edge",
+ Some("hanging") => "hanging",
+ Some("middle") => "middle",
+ Some("bottom") => "text-after-edge",
+ Some("ideographic") => "ideographic",
+ _ => "alphabetic",
+ };
+ let escape = |s: &str| s.replace('&', "&amp;").replace('<', "&lt;");
+ let fam = font["family"].as_str().unwrap_or("sans-serif").replace('"', "'");
+ // a family split across files by unicode-range: each run names the file that has its glyphs (subsets.rs)
+ let split = crate::split_families(&opt.fontdb).and_then(|s| crate::subsets::runs(&opt.fontdb, &s, &fam, text));
+ let esc = match split {
+ Some(runs) => runs.iter().map(|(f, s)| match f {
+ Some(f) => format!("<tspan font-family=\"'{}', {fam}\">{}</tspan>", f.replace('\'', ""), escape(s)),
+ None => format!("<tspan>{}</tspan>", escape(s)),
+ }).collect(),
+ None => escape(text),
+ };
+ format!(
+ "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><text x=\"{}\" y=\"{}\" font-size=\"{}\" font-family=\"{fam}\" font-weight=\"{}\" font-style=\"{}\" text-anchor=\"{anchor}\" dominant-baseline=\"{base}\" {paint}>{esc}</text></svg>",
+ at.0,
+ at.1,
+ crate::paint::f(&font["size"]),
+ font["weight"].as_str().unwrap_or("400"),
+ font["style"].as_str().unwrap_or("normal"),
+ )
+}
+
+/// `canvas.measure`: {font, text, align, baseline} -> TextMetrics (width, actualBoundingBox{Left,Right,Ascent,Descent},
+/// fontBoundingBox{Ascent,Descent}): the text shaped as the canvas draws it, from the alignment point. Its advance and
+/// the font's ascent and descent are usvg's layout box; the ink is its glyphs' outlines. Spaces are kept, as fillText
+/// keeps them.
+pub fn metrics(args: &Value) -> Result<Value, String> {
+ Ok(metrics_in(&crate::page_options(), args))
+}
+
+fn metrics_in(opt: &usvg::Options, args: &Value) -> Value {
+ let text = args["text"].as_str().unwrap_or("");
+ let shape = |text: &str| {
+ let doc = text_doc(opt, &args["font"], text, (0.0, 0.0), (&args["align"], &args["baseline"]), "xml:space=\"preserve\" fill=\"#fff\"", (1, 1));
+ let tree = usvg::Tree::from_str(&doc, opt).ok()?;
+ tree.root().children().iter().find_map(|n| if let usvg::Node::Text(t) = n { Some((t.bounding_box(), t.flattened().bounding_box())) } else { None })
+ };
+ let none = usvg::Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();
+ let (lay, ink, width) = match shape(text) {
+ Some((lay, ink)) => (lay, ink, lay.width()),
+ // nothing usvg draws (empty, or spaces alone, which it drops): no ink, the characters' advances, and the font's
+ // box from a glyph it does draw
+ None => {
+ let adv = advances_in(opt, &json!({ "font": args["font"], "chars": text }));
+ let em: f64 = adv["adv"].as_array().into_iter().flatten().filter_map(Value::as_f64).sum();
+ let lay = if text.is_empty() { none } else { shape("x").map_or(none, |(lay, _)| lay) };
+ (lay, none, em as f32 * crate::paint::f(&args["font"]["size"]))
+ }
+ };
+ json!({
+ "width": width,
+ "actualBoundingBoxLeft": -ink.left(),
+ "actualBoundingBoxRight": ink.right(),
+ "actualBoundingBoxAscent": -ink.top(),
+ "actualBoundingBoxDescent": ink.bottom(),
+ "fontBoundingBoxAscent": -lay.top(),
+ "fontBoundingBoxDescent": lay.bottom(),
+ })
+}
+
/// `canvas.advances`: {font: {family, weight, style}, chars} -> {adv: [em or null], own: [bool]}, one per character:
/// its advance as a fraction of the font size, and whether the font's first family has it.
pub fn advances(args: &Value) -> Result<Value, String> {
@@ -76,5 +152,18 @@ mod tests {
let r = advances_in(&opt, &json!({"font": {"family": "Nope, sans-serif", "weight": "400", "style": "normal"}, "chars": "i"}));
assert_eq!(r["own"], json!([false]));
assert!((r["adv"][0].as_f64().unwrap() - i).abs() < 1e-9);
+ // measureText: the advance is the characters' (Arial has no kerning between these), the ink the glyphs'
+ let mt = |text: &str, align: &str| metrics_in(&opt, &json!({"font": {"family": "Arial", "size": 100, "weight": "400", "style": "normal"}, "text": text, "align": align, "baseline": "alphabetic"}));
+ let (x, h) = (mt("x", "left"), mt("H", "left"));
+ let g = |v: &Value, k: &str| v[k].as_f64().unwrap();
+ assert!((g(&mt("im", "left"), "width") - (i + m) * 100.0).abs() < 0.01, "{}", mt("im", "left"));
+ assert!(g(&x, "actualBoundingBoxAscent") > 45.0 && g(&x, "actualBoundingBoxAscent") < g(&h, "actualBoundingBoxAscent"), "{x} {h}");
+ assert!(g(&mt("g", "left"), "actualBoundingBoxDescent") > 15.0 && g(&h, "actualBoundingBoxDescent").abs() < 0.5);
+ assert!(g(&h, "fontBoundingBoxAscent") > g(&h, "actualBoundingBoxAscent"));
+ // right-aligned, the ink is left of the alignment point; spaces keep their advance and have no ink
+ assert!(g(&mt("H", "right"), "actualBoundingBoxLeft") > 60.0);
+ assert!(g(&mt(" ", "left"), "width") > 50.0 && g(&mt(" ", "left"), "actualBoundingBoxRight") == 0.0);
+ assert!((g(&mt(" H ", "left"), "width") - g(&h, "width") - g(&mt(" ", "left"), "width")).abs() < 0.01, "{}", mt(" H ", "left"));
+ assert_eq!(g(&mt("", "left"), "width"), 0.0);
}
}
diff --git a/systems/fonts/src/lib.rs b/systems/fonts/src/lib.rs
index da12ce02..fda8043b 100644
--- a/systems/fonts/src/lib.rs
+++ b/systems/fonts/src/lib.rs
@@ -80,6 +80,9 @@ fn build(dir: &Path) -> (FontContext, Own) {
continue;
};
let named = p.file_name().and_then(|f| index.get(f.to_str()?));
+ // SVG text and a canvas's text (usvg's font database) have the bundled faces too, by the same family name: a
+ // composition's canvas measured and drew Inter in a fallback face (layout-reads LR6)
+ blitz_dom::util::add_svg_font(ttf.clone(), named.map(|(family, _, _)| family.as_str()));
let info = named.map(|(family, weight, italic)| FontInfoOverride {
family_name: Some(family.as_str()),
weight: Some(FontWeight::new(*weight)),
diff --git a/tools/layers.toml b/tools/layers.toml
index 07de515e..65759e12 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -130,6 +130,7 @@ raea-runtime-bundle = "runtime"
raea-runtime-bundle-lib = "runtime"
raea-runtime-calls = "runtime"
raea-runtime-shots = "runtime"
+raea-runtime-canvas = "runtime"
raea-runtime-export = "runtime"
raea-runtime-pagestore = "runtime"
raea-runtime-cssurls = "runtime"
diff --git a/tools/taxonomy.list b/tools/taxonomy.list
index 4064049e..50cfddbc 100644
--- a/tools/taxonomy.list
+++ b/tools/taxonomy.list
@@ -6,6 +6,7 @@
web Audio HTML's <audio>: sound in step with the frame
web Img HTML's <img>: the renderer holds the frame until it has loaded
web Video HTML's <video>: a clip in step with the frame
+web OffscreenCanvas the web's OffscreenCanvas: a canvas no page shows, its 2D context measured and read back (layout-reads LR6)
web Tone Tone.js as a namespace (import * as Tone), as its users write it
web Loop Tone.js's Loop: a callback every interval in transport time
web Part Tone.js's Part: values at times