Truly independent web browser
LibWeb: Keep the path when the transform of a context becomes singular
Andreas Kling99ce0b9899e2
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rsindex d9db5a6227e..5da33fa7260 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs@@ -146,6 +146,12 @@ pub(crate) struct ContextState {/// The current default path, in the coordinates of the current transformation matrix.#[gc(untraced)]path: RefCell<OwnedPath>,+ /// The matrix in whose coordinates the current default path is.+ ///+ /// NB: This is the current transformation matrix while that matrix is invertible. A path cannot be kept in the+ /// coordinates of a matrix that is not invertible, so it stays in those of the last matrix that was.+ #[gc(untraced)]+ path_transform: Cell<AffineTransform>,#[gc(untraced)]backing_storage: RefCell<Option<BackingStorage>>,/// OPTIMIZATION: A readback requires a synchronous IPC to the Compositor, so its pixels are reused while no@@ -191,6 +197,7 @@ impl ContextState {context_lost: Cell::new(false),states: RefCell::new(vec![DrawingState::default()]),path: RefCell::new(empty_path()),+ path_transform: Cell::new(AffineTransform::identity()),backing_storage: RefCell::new(None),cached_readback: RefCell::new(None),color_cache: RefCell::new(Vec::new()),@@ -268,6 +275,15 @@ impl ContextState {self.path.replace(empty_path());}+ /// The matrix in whose coordinates the current default path is.+ pub(crate) fn path_transform(&self) -> AffineTransform {+ self.path_transform.get()+ }++ pub(crate) fn set_path_transform(&self, transform: AffineTransform) {+ self.path_transform.set(transform);+ }+/// Transforms every point of the current default path.pub(crate) fn transform_path(&self, transform: AffineTransform) {let transformed = self.path.borrow().copy_transformed(transform.values);@@ -481,6 +497,7 @@ impl ContextState {// 3. Clear the context's drawing state stack.// 4. Reset everything that drawing state consists of to their initial values.self.states.replace(vec![DrawingState::default()]);+ self.path_transform.set(AffineTransform::identity());if has_recorder {self.did_draw();diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_state.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_state.rsindex a210f8a8561..3eebc323cc5 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_state.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_state.rs@@ -23,12 +23,11 @@ impl<K: CanvasKind> RenderingContext2D<K> {pub(crate) fn restore(&self, _: &mut CallContext) -> WebIdlResult<()> {// The restore() method steps are to pop the top entry in the drawing state stack, and reset the drawing state// it describes. If there is no saved state, then the method must do nothing.- let original_transform = self.drawing_state().transform;if !self.pop_drawing_state() {return Ok(());}// NB: The current default path is not part of the drawing state.- self.keep_path_in_place(original_transform);+ self.keep_path_in_place();self.record_if_ready(CanvasRecorder::restore);Ok(())diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rsindex df9cb3f6660..4d264503dc2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs@@ -34,11 +34,14 @@ impl<K: CanvasKind> RenderingContext2D<K> {state.transform = scaled(state.transform, x, y);}self.flush_transform();- self.transform_path(scaled(- AffineTransform::identity(),- float(1.0 / f64::from(x)),- float(1.0 / f64::from(y)),- ));+ // NB: A zero factor leaves the matrix without an inverse, and then there is no 1 / x or 1 / y.+ self.keep_path_in_place_after_multiplication(|| {+ Some(scaled(+ AffineTransform::identity(),+ float(1.0 / f64::from(x)),+ float(1.0 / f64::from(y)),+ ))+ });Ok(())}@@ -53,7 +56,7 @@ impl<K: CanvasKind> RenderingContext2D<K> {state.transform = translated(state.transform, x, y);}self.flush_transform();- self.transform_path(translated(AffineTransform::identity(), -x, -y));+ self.keep_path_in_place_after_multiplication(|| Some(translated(AffineTransform::identity(), -x, -y)));Ok(())}@@ -68,7 +71,7 @@ impl<K: CanvasKind> RenderingContext2D<K> {state.transform = rotated(state.transform, radians);}self.flush_transform();- self.transform_path(rotated(AffineTransform::identity(), -radians));+ self.keep_path_in_place_after_multiplication(|| Some(rotated(AffineTransform::identity(), -radians)));Ok(())}@@ -105,10 +108,30 @@ impl<K: CanvasKind> RenderingContext2D<K> {state.transform = multiply_transforms(state.transform, transform);}- if let Some(inverse) = transform.inverse() {+ self.keep_path_in_place_after_multiplication(|| transform.inverse());+ self.flush_transform();+ }++ /// Moves the current default path into the coordinates of the current transformation matrix, after a+ /// multiplication of the matrix with another whose inverse is given, so that the points of the path stay where+ /// they were on the output bitmap when they were added.+ ///+ /// NB: A path cannot be kept in the coordinates of a matrix that is not invertible. When a multiplication leaves+ /// the matrix without an inverse, the path stays in the coordinates of the last matrix that was invertible,+ /// and every later multiplication leaves the matrix without one too. keep_path_in_place() moves the path from+ /// there when the matrix is replaced with an invertible one again.+ fn keep_path_in_place_after_multiplication(+ &self,+ inverse_of_multiplication: impl FnOnce() -> Option<AffineTransform>,+ ) {+ let transform = self.drawing_state().transform;+ if transform.inverse().is_none() {+ return;+ }+ if let Some(inverse) = inverse_of_multiplication() {self.transform_path(inverse);}- self.flush_transform();+ self.set_path_transform(transform);}/// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-gettransform@@ -176,26 +199,26 @@ impl<K: CanvasKind> RenderingContext2D<K> {/// Replaces the current transformation matrix, which leaves the current default path where it is on the output/// bitmap.fn set_current_transform(&self, transform: AffineTransform) {- let original_transform = core::mem::replace(&mut self.drawing_state_mut().transform, transform);- self.keep_path_in_place(original_transform);+ self.drawing_state_mut().transform = transform;+ self.keep_path_in_place();self.flush_transform();}- /// Moves the current default path from the coordinates of the original transformation matrix to those of the- /// current one, after a change of the matrix that is not a multiplication with another, so that the points of- /// the path stay where they were on the output bitmap when they were added.- pub(crate) fn keep_path_in_place(&self, original_transform: AffineTransform) {+ /// Moves the current default path into the coordinates of the current transformation matrix, after a change of+ /// the matrix that is not a multiplication with another, so that the points of the path stay where they were on+ /// the output bitmap when they were added.+ pub(crate) fn keep_path_in_place(&self) {let transform = self.drawing_state().transform;- if transform.values == original_transform.values {+ // NB: A path cannot be kept in the coordinates of a matrix that is not invertible, so it stays in those of the+ // last matrix that was, as it does for a multiplication.+ let Some(inverse) = transform.inverse() else {return;- }- // NB: A path cannot be kept in the coordinates of a matrix that is not invertible, so it stays as it is when it- // changes to or from one, as it does for transform().- if original_transform.inverse().is_none() {+ };+ let path_transform = self.path_transform();+ self.set_path_transform(transform);+ if transform.values == path_transform.values {return;}- if let Some(inverse) = transform.inverse() {- self.transform_path(multiply_transforms(inverse, original_transform));- }+ self.transform_path(multiply_transforms(inverse, path_transform));}}diff --git a/Tests/LibWeb/Text/expected/canvas/path-across-singular-transform.txt b/Tests/LibWeb/Text/expected/canvas/path-across-singular-transform.txtnew file mode 100644index 00000000000..d7390015a6a--- /dev/null+++ b/Tests/LibWeb/Text/expected/canvas/path-across-singular-transform.txt@@ -0,0 +1,14 @@+No change: 255 255 0+scale(0, 1): 255 255 0+scale(1, 0): 255 255 0+scale(0, 0): 255 255 0+transform(0, 0, 0, 0, 0, 0): 255 255 0+scale(0, 1) and translate(5, 5): 255 255 0+scale(0, 1) and rotate(1): 255 255 0+scale(0, 1) and scale(2, 2): 255 255 0+scale(0, 1) and restore(): 255 255 0+scale(0, 1) and setTransform(2, 0, 0, 2, 0, 0): 255 255 0+scale(0, 1) and setTransform() with a DOMMatrix: 255 255 0+scale(0, 1) and resetTransform(): 255 255 0+scale(0, 1) and restore() to a scale: 255 255 0+scale(0, 1), save(), restore() and setTransform(2, 0, 0, 2, 0, 0): 255 255 0diff --git a/Tests/LibWeb/Text/input/canvas/path-across-singular-transform.html b/Tests/LibWeb/Text/input/canvas/path-across-singular-transform.htmlnew file mode 100644index 00000000000..0775f6bf17c--- /dev/null+++ b/Tests/LibWeb/Text/input/canvas/path-across-singular-transform.html@@ -0,0 +1,83 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A transform that leaves the current transformation matrix singular does not move the points of the current+ // default path, so they are still where they were on the bitmap when a later transform makes it invertible again.+ function run(label, change) {+ const canvas = document.createElement("canvas");+ canvas.width = 30;+ canvas.height = 30;+ const context = canvas.getContext("2d");+ context.save();+ context.moveTo(5, 15);+ context.lineTo(25, 15);+ change(context);+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.lineWidth = 4;+ context.stroke();+ const alphaAt = (x, y) => context.getImageData(x, y, 1, 1).data[3];+ println(`${label}: ${[alphaAt(10, 15), alphaAt(20, 15), alphaAt(15, 5)].join(" ")}`);+ }++ // The points of the path are then in the coordinates of the last invertible matrix, and a matrix that replaces+ // the singular one moves them from there, also when it is not the identity.+ function runWithRecovery(label, steps) {+ const canvas = document.createElement("canvas");+ canvas.width = 30;+ canvas.height = 30;+ const context = canvas.getContext("2d");+ context.lineWidth = 4;+ steps(context);+ context.stroke();+ const alphaAt = (x, y) => context.getImageData(x, y, 1, 1).data[3];+ println(`${label}: ${[alphaAt(10, 15), alphaAt(20, 15), alphaAt(15, 5)].join(" ")}`);+ }++ test(() => {+ run("No change", () => {});+ run("scale(0, 1)", context => context.scale(0, 1));+ run("scale(1, 0)", context => context.scale(1, 0));+ run("scale(0, 0)", context => context.scale(0, 0));+ run("transform(0, 0, 0, 0, 0, 0)", context => context.transform(0, 0, 0, 0, 0, 0));+ run("scale(0, 1) and translate(5, 5)", context => { context.scale(0, 1); context.translate(5, 5); });+ run("scale(0, 1) and rotate(1)", context => { context.scale(0, 1); context.rotate(1); });+ run("scale(0, 1) and scale(2, 2)", context => { context.scale(0, 1); context.scale(2, 2); });+ run("scale(0, 1) and restore()", context => { context.scale(0, 1); context.restore(); });+ runWithRecovery("scale(0, 1) and setTransform(2, 0, 0, 2, 0, 0)", context => {+ context.moveTo(5, 15);+ context.lineTo(25, 15);+ context.scale(0, 1);+ context.setTransform(2, 0, 0, 2, 0, 0);+ });+ runWithRecovery("scale(0, 1) and setTransform() with a DOMMatrix", context => {+ context.moveTo(5, 15);+ context.lineTo(25, 15);+ context.scale(0, 1);+ context.setTransform(new DOMMatrix([2, 0, 0, 2, 0, 0]));+ });+ runWithRecovery("scale(0, 1) and resetTransform()", context => {+ context.setTransform(2, 0, 0, 2, 0, 0);+ context.moveTo(2.5, 7.5);+ context.lineTo(12.5, 7.5);+ context.scale(0, 1);+ context.resetTransform();+ });+ runWithRecovery("scale(0, 1) and restore() to a scale", context => {+ context.setTransform(2, 0, 0, 2, 0, 0);+ context.save();+ context.resetTransform();+ context.moveTo(5, 15);+ context.lineTo(25, 15);+ context.scale(0, 1);+ context.restore();+ });+ runWithRecovery("scale(0, 1), save(), restore() and setTransform(2, 0, 0, 2, 0, 0)", context => {+ context.moveTo(5, 15);+ context.lineTo(25, 15);+ context.scale(0, 1);+ context.save();+ context.restore();+ context.setTransform(2, 0, 0, 2, 0, 0);+ });+ });+</script>