Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(canvas): apply default path transforms at command time

ldm03f07c186a8c6
diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rs b/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rs
index d253a8595..5fcd51971 100644
--- a/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rs
+++ b/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rs
@@ -1059,13 +1059,13 @@ pub(crate) fn canvas_context_fill_callback<'s>(
};
let path_state = canvas_path_state(scope, args.this());
let fragment = with_path_state(&path_state, |state| {
- if state.is_empty() {
+ if state.is_empty() || state.inverse_transform().is_none() {
return None;
}
Some(PaintFragment::Fill {
shape: PaintShape::Path(state.paint_path()),
brush: PaintBrush::Solid(context_fill_color(scope, args.this())),
- transform: state.transform(),
+ transform: PaintTransform2D::IDENTITY,
})
});
if let Some(fragment) = fragment {
@@ -1093,7 +1093,7 @@ pub(crate) fn canvas_context_stroke_callback<'s>(
Some(PaintFragment::Stroke(context_stroke(
scope,
args.this(),
- state.paint_path(),
+ state.stroke_path()?,
state.transform(),
)))
});
@@ -1133,12 +1133,15 @@ pub(crate) fn canvas_context_stroke_rect_callback<'s>(
};
let path_state = canvas_path_state(scope, args.this());
// strokeRect must not alter the current default path.
- let (path, transform) = with_path_state(&path_state, |state| {
- let mut rect_path = state.clone();
- rect_path.begin_path();
+ let path = with_path_state(&path_state, |state| {
+ let mut rect_path = super::path::Canvas2dPathState::default();
rect_path.rect(x, y, width, height);
- (rect_path.paint_path(), state.transform())
+ state.inverse_transform()?;
+ Some((rect_path.paint_path(), state.transform()))
});
+ let Some((path, transform)) = path else {
+ return;
+ };
let stroke = context_stroke(scope, args.this(), path, transform);
rasterize_canvas_fragment(scope, canvas, PaintFragment::Stroke(stroke));
rv.set_undefined();
diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/path.rs b/moli-renderer-v8/src/context_bootstrap/canvas/path.rs
index 23410506d..b65e477a5 100644
--- a/moli-renderer-v8/src/context_bootstrap/canvas/path.rs
+++ b/moli-renderer-v8/src/context_bootstrap/canvas/path.rs
@@ -8,6 +8,8 @@ use moli_layout::{
/// subpath, `Close` ends it, and a new `MoveTo` begins the next one.
#[derive(Clone, Debug)]
pub(crate) struct Canvas2dPathState {
+ // Default-path geometry is already in canvas coordinates. The current
+ // transform only affects newly recorded commands, never earlier elements.
elements: Vec<PaintPathElement>,
current: (f64, f64),
current_subpath_start: (f64, f64),
@@ -41,6 +43,10 @@ impl Canvas2dPathState {
}
pub(super) fn move_to(&mut self, x: f64, y: f64) {
+ if ![x, y].into_iter().all(f64::is_finite) {
+ return;
+ }
+ let (x, y) = self.map_point(x, y);
self.elements.push(PaintPathElement::MoveTo(point(x, y)));
self.current = (x, y);
self.current_subpath_start = (x, y);
@@ -65,18 +71,27 @@ impl Canvas2dPathState {
}
pub(super) fn line_to(&mut self, x: f64, y: f64) {
+ if ![x, y].into_iter().all(f64::is_finite) {
+ return;
+ }
if !self.ensure_open_subpath() {
self.move_to(x, y);
return;
}
+ let (x, y) = self.map_point(x, y);
self.elements.push(PaintPathElement::LineTo(point(x, y)));
self.current = (x, y);
}
pub(super) fn quadratic_curve_to(&mut self, cpx: f64, cpy: f64, x: f64, y: f64) {
+ if ![cpx, cpy, x, y].into_iter().all(f64::is_finite) {
+ return;
+ }
if !self.ensure_open_subpath() {
self.move_to(cpx, cpy);
}
+ let (cpx, cpy) = self.map_point(cpx, cpy);
+ let (x, y) = self.map_point(x, y);
self.elements
.push(PaintPathElement::QuadTo(point(cpx, cpy), point(x, y)));
self.current = (x, y);
@@ -91,9 +106,15 @@ impl Canvas2dPathState {
x: f64,
y: f64,
) {
+ if ![c1x, c1y, c2x, c2y, x, y].into_iter().all(f64::is_finite) {
+ return;
+ }
if !self.ensure_open_subpath() {
self.move_to(c1x, c1y);
}
+ let (c1x, c1y) = self.map_point(c1x, c1y);
+ let (c2x, c2y) = self.map_point(c2x, c2y);
+ let (x, y) = self.map_point(x, y);
self.elements.push(PaintPathElement::CubicTo(
point(c1x, c1y),
point(c2x, c2y),
@@ -112,6 +133,11 @@ impl Canvas2dPathState {
}
pub(super) fn rect(&mut self, x: f64, y: f64, width: f64, height: f64) {
+ if ![x, y, width, height].into_iter().all(f64::is_finite)
+ || self.inverse_transform().is_none()
+ {
+ return;
+ }
self.move_to(x, y);
self.line_to(x + width, y);
self.line_to(x + width, y + height);
@@ -148,6 +174,7 @@ impl Canvas2dPathState {
.all(f64::is_finite)
|| radius_x < 0.0
|| radius_y < 0.0
+ || self.inverse_transform().is_none()
{
return false;
}
@@ -170,7 +197,13 @@ impl Canvas2dPathState {
self.move_to(x1, y1);
return true;
}
- let p0 = kurbo::Point::from(self.current);
+ let Some(inverse) = self.inverse_transform() else {
+ self.line_to(x1, y1);
+ return true;
+ };
+ // arcTo constructs a circular arc in the current user coordinate
+ // system. The previous point was recorded under a possibly older CTM.
+ let p0 = inverse * kurbo::Point::from(self.current);
let p1 = kurbo::Point::new(x1, y1);
let p2 = kurbo::Point::new(x2, y2);
let incoming = p0 - p1;
@@ -215,7 +248,9 @@ impl Canvas2dPathState {
}
pub(super) fn set_transform(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
- self.transform = LayoutTransform2D::new([a, b, c, d, e, f]);
+ if [a, b, c, d, e, f].into_iter().all(f64::is_finite) {
+ self.transform = LayoutTransform2D::new([a, b, c, d, e, f]);
+ }
}
pub(super) fn reset_transform(&mut self) {
@@ -223,75 +258,115 @@ impl Canvas2dPathState {
}
pub(super) fn translate(&mut self, x: f64, y: f64) {
- self.transform = self
- .transform
- .concatenate(LayoutTransform2D::translation(x as f32, y as f32));
+ self.concatenate_transform(1.0, 0.0, 0.0, 1.0, x, y);
}
pub(super) fn scale(&mut self, x: f64, y: f64) {
- self.transform = self.transform.concatenate(LayoutTransform2D::scale(x, y));
+ self.concatenate_transform(x, 0.0, 0.0, y, 0.0, 0.0);
}
pub(super) fn rotate(&mut self, radians: f64) {
- self.transform = self
- .transform
- .concatenate(LayoutTransform2D::rotation(radians));
+ let (sin, cos) = radians.sin_cos();
+ self.concatenate_transform(cos, sin, -sin, cos, 0.0, 0.0);
}
pub(super) fn concatenate_transform(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
- self.transform = self
- .transform
- .concatenate(LayoutTransform2D::new([a, b, c, d, e, f]));
+ if [a, b, c, d, e, f].into_iter().all(f64::is_finite) {
+ self.transform = self
+ .transform
+ .concatenate(LayoutTransform2D::new([a, b, c, d, e, f]));
+ }
}
pub(super) fn transform(&self) -> LayoutTransform2D {
self.transform
}
+ fn map_point(&self, x: f64, y: f64) -> (f64, f64) {
+ let p = kurbo::Affine::new(self.transform.coefficients) * kurbo::Point::new(x, y);
+ (p.x, p.y)
+ }
+
+ pub(super) fn inverse_transform(&self) -> Option<kurbo::Affine> {
+ let transform = kurbo::Affine::new(self.transform.coefficients);
+ let determinant = transform.determinant();
+ // A small nonzero scale is still invertible; do not use EPSILON as
+ // a singularity threshold (e.g. scale(1e-9,1e-9) is valid).
+ (determinant != 0.0 && determinant.is_finite()).then(|| transform.inverse())
+ }
+
+ /// Stroke metrics are in the *current* user space. Bring the frozen path
+ /// back to that space and let the painter transform the resulting stroke,
+ /// so anisotropic line widths, joins and dashes change without moving it.
+ pub(super) fn stroke_path(&self) -> Option<PaintPath> {
+ let inverse = self.inverse_transform()?;
+ let map = |p: LayoutPoint| {
+ let p = inverse * kurbo::Point::new(f64::from(p.x), f64::from(p.y));
+ point(p.x, p.y)
+ };
+ let elements = self
+ .elements
+ .iter()
+ .map(|element| match *element {
+ PaintPathElement::MoveTo(p) => PaintPathElement::MoveTo(map(p)),
+ PaintPathElement::LineTo(p) => PaintPathElement::LineTo(map(p)),
+ PaintPathElement::QuadTo(a, p) => PaintPathElement::QuadTo(map(a), map(p)),
+ PaintPathElement::CubicTo(a, b, p) => {
+ PaintPathElement::CubicTo(map(a), map(b), map(p))
+ }
+ PaintPathElement::Close => PaintPathElement::Close,
+ })
+ .collect::<Vec<_>>();
+ Some(PaintPath {
+ bounds: path_bounds(&elements),
+ elements,
+ })
+ }
+
/// Builds an owned `PaintPath` with conservative local bounds.
pub(super) fn paint_path(&self) -> PaintPath {
PaintPath {
elements: self.elements.clone(),
- bounds: self.bounds(),
+ bounds: path_bounds(&self.elements),
}
}
pub(super) fn is_empty(&self) -> bool {
self.elements.is_empty()
}
+}
- fn bounds(&self) -> PaintRect {
- let mut min_x = f64::INFINITY;
- let mut min_y = f64::INFINITY;
- let mut max_x = f64::NEG_INFINITY;
- let mut max_y = f64::NEG_INFINITY;
- for element in &self.elements {
- match *element {
- PaintPathElement::MoveTo(point) | PaintPathElement::LineTo(point) => {
- expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, point);
- }
- PaintPathElement::QuadTo(first, second) => {
- expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, first);
- expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, second);
- }
- PaintPathElement::CubicTo(first, second, third) => {
- expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, first);
- expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, second);
- expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, third);
- }
- PaintPathElement::Close => {}
+fn path_bounds(elements: &[PaintPathElement]) -> PaintRect {
+ let mut min_x = f64::INFINITY;
+ let mut min_y = f64::INFINITY;
+ let mut max_x = f64::NEG_INFINITY;
+ let mut max_y = f64::NEG_INFINITY;
+ for element in elements {
+ match *element {
+ PaintPathElement::MoveTo(point) | PaintPathElement::LineTo(point) => {
+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, point);
}
+ PaintPathElement::QuadTo(first, second) => {
+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, first);
+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, second);
+ }
+ PaintPathElement::CubicTo(first, second, third) => {
+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, first);
+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, second);
+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, third);
+ }
+ PaintPathElement::Close => {}
}
- if !min_x.is_finite() {
- return LayoutRect::ZERO;
- }
- LayoutRect::new(
- min_x as f32,
- min_y as f32,
- (max_x - min_x) as f32,
- (max_y - min_y) as f32,
- )
}
+ if !min_x.is_finite() {
+ return LayoutRect::ZERO;
+ }
+ LayoutRect::new(
+ min_x as f32,
+ min_y as f32,
+ (max_x - min_x) as f32,
+ (max_y - min_y) as f32,
+ )
}
fn point(x: f64, y: f64) -> LayoutPoint {
diff --git a/moli-renderer-v8/src/script_vm/tests/canvas_paths.rs b/moli-renderer-v8/src/script_vm/tests/canvas_paths.rs
index 75ce95417..920ec35e2 100644
--- a/moli-renderer-v8/src/script_vm/tests/canvas_paths.rs
+++ b/moli-renderer-v8/src/script_vm/tests/canvas_paths.rs
@@ -217,3 +217,138 @@ fn canvas_path_state_is_independent_between_contexts_and_after_reset() {
return JSON.stringify([x.getImageData(5,5,1,1).data[3],y.getImageData(15,15,1,1).data[3],y.getImageData(5,5,1,1).data[3]]);
})()"#).unwrap(),"[0,255,0]");
}
+
+#[test]
+fn canvas_later_transforms_do_not_move_recorded_geometry() {
+ for transform in [
+ "ctx.translate(20,0)",
+ "ctx.scale(2,3)",
+ "ctx.rotate(Math.PI/2)",
+ ] {
+ canvas_pixels(
+ &format!("ctx.rect(5,5,10,10);{transform};ctx.fill();"),
+ &[(10, 10), (30, 10), (20, 30)],
+ &[255, 0, 0],
+ );
+ }
+}
+
+#[test]
+fn canvas_path_records_each_commands_coordinate_system() {
+ canvas_pixels(
+ "ctx.rect(0,0,10,10);ctx.translate(20,0);ctx.rect(0,0,10,10);ctx.resetTransform();ctx.fill();",
+ &[(5, 5), (25, 5), (45, 5)],
+ &[255, 255, 0],
+ );
+ // Adapted from WPT 2d.path.transformation.changing. The final CTM must
+ // not be applied a second time to the previously recorded rectangle.
+ canvas_pixels(
+ "ctx.moveTo(0,0);ctx.translate(40,0);ctx.lineTo(0,0);ctx.translate(0,40);ctx.lineTo(0,0);ctx.translate(-40,0);ctx.lineTo(0,0);ctx.translate(1000,1000);ctx.rotate(Math.PI/2);ctx.scale(.1,.1);ctx.fill();",
+ &[(20, 20), (50, 50)],
+ &[255, 0],
+ );
+}
+
+#[test]
+fn canvas_current_transform_changes_stroke_metrics_not_path_position() {
+ // Same contract as WPT 2d.path.stroke.scale1/scale2, without depending on
+ // the separately unsupported save/restore implementation.
+ canvas_pixels(
+ "ctx.moveTo(10,20);ctx.lineTo(30,20);ctx.scale(2,3);ctx.lineWidth=4;ctx.stroke();",
+ &[(15, 15), (15, 20), (15, 25), (15, 27), (40, 60)],
+ &[255, 255, 255, 0, 0],
+ );
+ canvas_pixels(
+ "ctx.moveTo(10,20);ctx.lineTo(30,20);ctx.rotate(Math.PI/2);ctx.scale(3,2);ctx.lineWidth=4;ctx.stroke();",
+ &[(15, 15), (15, 20), (15, 25), (15, 27)],
+ &[255, 255, 255, 0],
+ );
+}
+
+#[test]
+fn canvas_stroke_dashes_follow_the_current_transform() {
+ canvas_pixels(
+ "ctx.moveTo(10,20);ctx.lineTo(90,20);ctx.scale(2,1);ctx.setLineDash([10,10]);ctx.stroke();",
+ &[
+ (15, 20),
+ (25, 20),
+ (35, 20),
+ (45, 20),
+ (55, 20),
+ (65, 20),
+ (75, 20),
+ ],
+ &[255, 255, 0, 0, 255, 255, 0],
+ );
+}
+
+#[test]
+fn canvas_arc_to_resolves_the_old_point_in_the_new_user_space() {
+ canvas_pixels(
+ "ctx.moveTo(10,20);ctx.translate(20,0);ctx.arcTo(20,20,20,50,10);ctx.stroke();",
+ &[(15, 20), (30, 20), (39, 29), (50, 20)],
+ &[255, 255, 255, 0],
+ );
+}
+
+#[test]
+fn canvas_continuing_a_closed_subpath_does_not_transform_its_start_again() {
+ canvas_pixels(
+ "ctx.moveTo(5,5);ctx.lineTo(15,5);ctx.lineTo(15,15);ctx.closePath();ctx.translate(20,0);ctx.lineTo(-15,25);ctx.stroke();",
+ &[(5, 20), (25, 20)],
+ &[255, 0],
+ );
+}
+
+#[test]
+fn canvas_stroke_rect_uses_current_transform_without_changing_default_path() {
+ canvas_pixels(
+ "ctx.rect(5,5,10,10);ctx.translate(20,0);ctx.strokeRect(0,30,10,10);ctx.resetTransform();ctx.fill();",
+ &[(10, 10), (25, 35), (20, 35)],
+ &[255, 0, 255],
+ );
+}
+
+#[test]
+fn canvas_singular_transform_suppresses_paint_without_losing_the_old_path() {
+ canvas_pixels(
+ "ctx.rect(5,5,10,10);ctx.scale(0,1);ctx.fill();ctx.stroke();",
+ &[(10, 10)],
+ &[0],
+ );
+ canvas_pixels(
+ "ctx.rect(5,5,10,10);ctx.scale(0,1);ctx.fill();ctx.resetTransform();ctx.fill();",
+ &[(10, 10)],
+ &[255],
+ );
+}
+
+#[test]
+fn canvas_small_invertible_scale_is_not_treated_as_singular() {
+ canvas_pixels(
+ "ctx.scale(1e-9,1e-9);ctx.rect(0,0,1e10,1e10);ctx.fill();",
+ &[(5, 5), (15, 5)],
+ &[255, 0],
+ );
+}
+
+#[test]
+fn canvas_curves_are_transformed_when_recorded() {
+ for curve in [
+ "ctx.quadraticCurveTo(5,0,10,0)",
+ "ctx.bezierCurveTo(3,0,7,0,10,0)",
+ ] {
+ canvas_pixels(
+ &format!(
+ "ctx.translate(10,20);ctx.moveTo(0,0);{curve};ctx.resetTransform();ctx.stroke();"
+ ),
+ &[(15, 20), (15, 0)],
+ &[255, 0],
+ );
+ }
+ canvas_pixels(
+ "ctx.translate(20,20);ctx.arc(12,12,10,0,2*Math.PI);ctx.resetTransform();ctx.fill();",
+ &[(32, 32), (12, 12)],
+ &[255, 0],
+ );
+}