Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion crates/nsh-core/src/js/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,19 @@ impl OpArg<Drawing> for Option<Path> {
while path.more() {
let code = path.code()?;
if code == CV_SVG_PATH {
ops.extend(parse_svg_path(&path.arg()?.as_string().unwrap_or_default()));
let value = path.arg()?;
if let Some(parsed) = value.canvas_path() {
// A path made from SVG alone keeps its parsed geometry
// across drawings. Appended operations still decode here,
// with any animated values bound to this drawing's slots.
if ops.is_empty() && !path.more() {
return Ok(Some(Some(parsed)));
}
ops.extend_from_slice(&parsed);
} else {
// Browser recordings and existing hosts keep the source.
ops.extend(parse_svg_path(&value.as_string().unwrap_or_default()));
}
continue;
}
match PathOp::decode(code, &mut path, drawing)? {
Expand Down
6 changes: 6 additions & 0 deletions crates/nsh-core/src/js/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ pub trait HostInput: Sized {
.and_then(|v| v.as_number())
.map(|n| n as crate::animation::NodeId)
}
/// A decoded canvas path with constant coordinates, shared by a native
/// recorder. Paths with animated slots must be decoded for each drawing:
/// their slot indices belong to that drawing alone.
fn canvas_path(&self) -> Option<crate::canvas::Path> {
None
}
}

/// A JS array, read by index.
Expand Down
134 changes: 133 additions & 1 deletion crates/nsh-engine/tests/engine/canvas.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! `Canvas` end to end: what a `draw` records (the generated methods and
//! properties, and the hand-written ones) as the core decodes it.

use std::time::Duration;
use std::{sync::Arc, time::Duration};

use nsh_core::{
ApproxTextEngine, MountBatch, MountItem, Size,
Expand Down Expand Up @@ -292,6 +292,138 @@ fn canvases_redraw_when_what_they_read_changes() {
assert_eq!(d[1].ops.len(), 2);
}

#[test]
fn svg_paths_share_their_parsed_operations_across_drawings() {
let (_engine, rx) = start(
r#"import { Canvas, Path2D, mount, signal } from "nsh";
const path = new Path2D("M0 0 L10 0 L10 10 Z");
const copy = new Path2D(path);
const added = new Path2D();
added.addPath(path);
const frame = signal(0);
mount(() => <Canvas style={{ width: 20, height: 20 }} draw={cx => {
const n = frame();
cx.lineWidth = n + 1;
cx.fill(path);
cx.stroke(path);
cx.clip(path);
cx.stroke(copy);
cx.stroke(added);
if (n === 0) setTimeout(() => frame.set(1), 30);
}} />);
"#,
);
let drawings = drawings(&rx, 2);
assert_eq!(drawings.len(), 2);
let paths: Vec<_> = drawings
.iter()
.flat_map(|d| &d.ops)
.filter_map(|op| match op {
CanvasOp::Fill(Some(path), _)
| CanvasOp::Stroke(Some(path))
| CanvasOp::Clip(Some(path), _) => Some(path),
_ => None,
})
.collect();
assert_eq!(paths.len(), 10);
let c = Num::Const;
let expected = [
PathOp::MoveTo(c(0.0), c(0.0)),
PathOp::LineTo(c(10.0), c(0.0)),
PathOp::LineTo(c(10.0), c(10.0)),
PathOp::Close,
];
for &path in &paths {
assert_eq!(path.as_ref(), expected.as_slice());
assert!(
Arc::ptr_eq(paths[0], path),
"fill, stroke, clip, copies and redraws reuse the parsed SVG"
);
}
}

#[test]
fn svg_path_snapshots_keep_mutations_and_animation_slots_separate() {
let (_engine, rx) = start(
r#"import { Canvas, Path2D, createAnimatedValue, mount, signal } from "nsh";
const path = new Path2D("M0 0 L10 0");
const moving = new Path2D(path);
const x = createAnimatedValue(5);
const alpha = createAnimatedValue(0.5);
moving.lineTo(x, 20);
const frame = signal(0);
mount(() => <Canvas style={{ width: 40, height: 40 }} draw={cx => {
const n = frame();
// The same animated tail has a different slot in the second drawing.
if (n !== 0) cx.globalAlpha = alpha;
const source = new Path2D(path);
const copy = new Path2D(source);
const added = new Path2D();
added.moveTo(-1, -1);
added.addPath(source);
cx.stroke(source);
source.lineTo(20, 30);
cx.stroke(source);
cx.stroke(copy);
cx.stroke(added);
copy.addPath(copy);
cx.stroke(copy);
cx.stroke(moving);
cx.stroke(path);
added.addPath(source);
cx.stroke(added);
if (n === 0) setTimeout(() => frame.set(1), 30);
}} />);
"#,
);
let drawings = drawings(&rx, 2);
assert_eq!(drawings.len(), 2);
let c = Num::Const;
let original = [
PathOp::MoveTo(c(0.0), c(0.0)),
PathOp::LineTo(c(10.0), c(0.0)),
];
let tail = PathOp::LineTo(c(20.0), c(30.0));
let updated = [original.as_slice(), &[tail]].concat();
let prefixed = [&[PathOp::MoveTo(c(-1.0), c(-1.0))][..], original.as_slice()].concat();
let doubled = [original.as_slice(), original.as_slice()].concat();
let combined = [prefixed.as_slice(), updated.as_slice()].concat();
for (n, drawing) in drawings.iter().enumerate() {
let paths: Vec<_> = drawing
.ops
.iter()
.filter_map(|op| match op {
CanvasOp::Stroke(Some(path)) => Some(path.as_ref()),
_ => None,
})
.collect();
assert_eq!(paths.len(), 8);
assert_eq!(paths[0], original.as_slice(), "before the source changed");
assert_eq!(paths[1], updated.as_slice(), "after the source changed");
assert_eq!(paths[2], original.as_slice(), "the copy kept its snapshot");
assert_eq!(paths[3], prefixed.as_slice(), "addPath kept its snapshot");
assert_eq!(paths[4], doubled.as_slice(), "self-add appends once");
assert_eq!(
paths[5],
[
original.as_slice(),
&[PathOp::LineTo(Num::Slot(n as u16), c(20.0))],
]
.concat()
.as_slice()
);
assert_eq!(
paths[6],
original.as_slice(),
"the original stays unchanged"
);
assert_eq!(paths[7], combined.as_slice());
assert_eq!(drawing.slots.len(), n + 1);
}
assert_eq!(drawings[0].slots[0], drawings[1].slots[1]);
assert_ne!(drawings[1].slots[0], drawings[1].slots[1]);
}

/// A `draw` that derives a node from an animated value, run again: the same
/// node (no new one in the graph each time), the same slot.
const DERIVED: &str = r#"import { signal, mount } from "nsh";
Expand Down
22 changes: 17 additions & 5 deletions crates/nsh-js/src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ use std::{

use nsh_core::{
EventKind, FontVariant, Op, Tag,
canvas::{CanvasFont, CanvasOp, FillRule, PathOp, point_in_path, point_in_stroke},
canvas::{
CanvasFont, CanvasOp, FillRule, Path, PathOp, point_in_path, point_in_stroke, svg_path,
},
element::TsTypes,
js::{
canvas::*,
Expand Down Expand Up @@ -54,6 +56,9 @@ pub(crate) enum Rec {
Num(f64),
Str(Rc<str>),
List(Rc<Vec<Rec>>),
/// SVG geometry, parsed once by `Path2D` and shared by its snapshots.
/// Only constants: animated path operations are recorded separately.
Path(Path),
/// A native animation node (`AnimatedNode.__av`).
Node(nsh_core::animation::NodeId),
}
Expand Down Expand Up @@ -81,7 +86,7 @@ impl HostInput for Rec {
}

fn is_object(&self) -> bool {
matches!(self, Rec::List(_) | Rec::Node(_))
matches!(self, Rec::List(_) | Rec::Path(_) | Rec::Node(_))
}

fn as_bool(&self) -> Option<bool> {
Expand Down Expand Up @@ -129,7 +134,7 @@ impl HostInput for Rec {
Rec::Bool(b) => *b,
Rec::Num(n) => *n != 0.0 && !n.is_nan(),
Rec::Str(s) => !s.is_empty(),
Rec::List(_) | Rec::Node(_) => true,
Rec::List(_) | Rec::Path(_) | Rec::Node(_) => true,
}
}

Expand All @@ -139,6 +144,13 @@ impl HostInput for Rec {
_ => None,
}
}

fn canvas_path(&self) -> Option<Path> {
match self {
Rec::Path(path) => Some(path.clone()),
_ => None,
}
}
}

/// The recording methods and properties, made from the core's specs once.
Expand Down Expand Up @@ -1227,10 +1239,10 @@ unsafe extern "C" fn path_2d(
let from = arg(argc, argv, 0);
// SAFETY: an inline tag check.
if unsafe { qjs::JS_IsString(from) } {
let svg = rc_str(cx, from);
let parsed = svg_path(&rc_str(cx, from));
if let Some(r) = recording(cx, path) {
r.out.push(Rec::Num(CV_SVG_PATH as f64));
r.out.push(Rec::Str(svg));
r.out.push(Rec::Path(parsed));
}
} else if is_path(cx, from) {
append_path(cx, path, from);
Expand Down
7 changes: 7 additions & 0 deletions docs/dev/canvas.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@
into the `drawRect:` context, keeping its own transform and path in view space; Android `CanvasPainter.java` interprets an `int[]` (`encode.rs`) for `CanvasBox.java` and offscreen renders. Not
supported: `getImageData` / `putImageData`, filters.

QuickJS's `new Path2D(svg)` parses the SVG path data once, at construction, into an immutable `Path` shared by
the path's recording snapshots, copies and `addPath` segments. A drawing using that SVG path alone keeps the same
geometry; adding operations assembles a path from those segments without parsing the SVG again. Animated path
arguments still decode for each drawing, because their slot indices belong to that drawing. The browser runtime's
recorded SVG strings remain supported by the same decoder. This shares parsed geometry, not platform drawing
resources such as `CGPath`.

**Offscreen canvases** (`OffscreenCanvas` of `nsh`, `nsh-js` `canvas/offscreen.rs`; Rust:
`Painter::render` with `canvas::render::RenderOptions`). An object of a size of its own whose `getContext("2d")` is
a context recording as `<Canvas draw>`'s does (`new_recording`, never closed); `convertToBlob` decodes what it
Expand Down
26 changes: 26 additions & 0 deletions docs/dev/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,32 @@ sends 2631 mount items instead of 2885 (no `ViewProps` set and set back in one c
it replaced did (0.57ms).
The native context records into a Rust list (`nsh-js` `canvas.rs`): the same 17 500 calls take ~1.0–1.1ms
(~1.7ms in the former JS runtime, measured A/B), and 12 of them plus decoding one commit 21–22ms (61ms).
- Retained SVG paths (`examples/bench/CanvasPaths.tsx`, Linux x86_64, 2026-12-03): QuickJS shares the parsed
geometry of `Path2D(svg)` across recordings. Against `59a945f`, three alternating before/after runs with
five warmups and 20 measured presses per mode per run: `event js` median / nearest-rank p95 of each
version's 60 samples, in microseconds:

| SVG line segments | Event | Before | After |
|---|---|---|---|
| 4 | 64 strokes of one retained path | 204 / 336 | 108 / 187 |
| 128 | 64 strokes of one retained path | 1432 / 1787 | 125.5 / 228 |
| 4 | 64 paths constructed and stroked once each | 283 / 366 | 283 / 374 |
| 128 | 64 paths constructed and stroked once each | 1523.5 / 1992 | 1509.5 / 2060 |
| 4 | 256 paths constructed and replaced, without drawing | 221 / 325 | 521 / 623 |
| 128 | 256 paths constructed and replaced, without drawing | 250.5 / 394 | 5255.5 / 6027 |

Both CLIs were built with Rust 1.100.1 and the workspace's development optimization levels, with debug info
and incremental compilation disabled. The event includes the JS callback, recording and decoding, not native
painting; every redraw submits the same 1 op / 1 mount item / 9 nodes, and construction alone submits none.
Construction alone is slower because parsing now happens even for an unused path. Constructing and drawing
once costs about the same; reusing an unchanged SVG-only path avoids parsing and allocating its geometry on
each use. Composite paths still assemble their geometry, and recording snapshots still allocate their small
lists. The counter control (`nsh test examples/counter/App.tsx --trace`, three
alternating runs, 25 presses each, first five discarded) kept the same commit counts, including its initial
56 ops / 50 items / 15 nodes; event medians were 162.5 / 147µs and first frames 6.75–7.94 / 6.08–10.13ms.
To reproduce, run `nsh test examples/bench/CanvasPaths.tsx --trace` with 25 presses of each of `id:reuse`,
`id:fresh` and `id:construct` on standard input; discard each mode's first five `event js` samples. Change
`SEGMENTS` to 4 for the small path. Redirect the full trace, which prints every path operation.
- Canvas text on macOS (`cargo test --release -p nsh-platform-macos --lib bench_canvas_text -- --ignored --nocapture`,
a 40 × 8 quote table of 320 `fillText`s painted into a 760 × 820 point bitmap at scale 2, Apple Silicon): with each
canvas keeping its fonts and `CTLine`s (`canvas/lines.rs`), a paint with the same texts (a window being resized)
Expand Down
54 changes: 54 additions & 0 deletions examples/bench/CanvasPaths.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// SVG Path2D recording and decoding, with paths retained or made per use.
// echo 'for (let i = 0; i < 25; i++) await app.press("id:reuse");' |
// nsh test examples/bench/CanvasPaths.tsx --trace
// Compare `event js` after five warmups; `fresh` includes construction,
// `construct` only constructs and replaces paths. Redirect the full trace:
// it prints every path operation. Change SEGMENTS to 4 for a small path.
import { Canvas, Path2D, Text, View, mount, signal } from "nsh";
import { Window } from "nsh/desktop";

const SEGMENTS = 128;
const USES = 64;
const CONSTRUCTS = 256;
const data =
"M0 0 " +
Array.from({ length: SEGMENTS }, (_, i) => `L${i % 16} ${(i * 7) % 16}`).join(" ") +
" Z";

function App() {
const tick = signal(0);
let path = new Path2D(data);
let fresh = false;
const redraw = (create: boolean) => {
fresh = create;
tick.update((n) => n + 1);
};
const construct = () => {
// Keep one path alive, including the cost of replacing the others.
for (let i = 0; i < CONSTRUCTS; i++) path = new Path2D(data);
};
return (
<View style={{ padding: 16, gap: 8 }}>
<View testID="reuse" style={{ width: 200, height: 32 }} onPress={() => redraw(false)}>
<Text>Reuse path</Text>
</View>
<View testID="fresh" style={{ width: 200, height: 32 }} onPress={() => redraw(true)}>
<Text>Construct and draw</Text>
</View>
<View testID="construct" style={{ width: 200, height: 32 }} onPress={construct}>
<Text>Construct only</Text>
</View>
<Canvas
style={{ width: 32, height: 32 }}
draw={(cx) => {
// Differ at the first operation: no unchanged-drawing shortcut or
// long equality walk through all paths before finding a change.
cx.globalAlpha = tick() % 2 ? 0.99 : 1;
for (let i = 0; i < USES; i++) cx.stroke(fresh ? new Path2D(data) : path);
}}
/>
</View>
);
}

mount(() => <Window id="main">{App}</Window>);
Loading