Truly independent web browser
LibWeb: Rasterize SVG images at their drawn size in drawImage()
Shannon Boothc6958153621d
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rsindex c28eb774d17..a1ace4f7af6 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs@@ -93,8 +93,13 @@ unsafe extern "C" {out_canvas_id: *mut u64,out_source_is_2d: *mut bool,) -> bool;- fn web_canvas_2d_image_source_frame(source_wrapper: *mut c_void, source_kind: CanvasImageSourceKind)- -> *mut c_void;+ fn web_canvas_2d_image_source_frame(+ source_wrapper: *mut c_void,+ source_kind: CanvasImageSourceKind,+ raster_width: i32,+ raster_height: i32,+ out_rasterized: *mut bool,+ ) -> *mut c_void;fn web_canvas_2d_capture_video_frame(source_wrapper: *mut c_void, out_frame: *mut CapturedVideoFrameAbi) -> bool;fn web_canvas_2d_video_transport(source_wrapper: *mut c_void) -> *mut c_void;fn web_canvas_2d_video_frame_hold_unref(hold: *mut c_void);@@ -464,9 +469,29 @@ impl CanvasImageSourceKind {/// The frame of an image or a canvas, if it has one. This can read a canvas back, which flushes the commands of/// every canvas.pub(crate) fn frame(self, source: CppInterface) -> Option<ImageFrameHandle> {- let frame = unsafe { web_canvas_2d_image_source_frame(source.wrapper().as_ptr().cast(), self) };+ self.frame_rasterized_at(source, 0, 0).map(|(frame, _)| frame)+ }++ /// The frame of an image or a canvas, as frame() returns it, except that a vector image is rasterized at the+ /// given size if it is not empty. Also returns whether it was.+ pub(crate) fn frame_rasterized_at(+ self,+ source: CppInterface,+ raster_width: i32,+ raster_height: i32,+ ) -> Option<(ImageFrameHandle, bool)> {+ let mut rasterized = false;+ let frame = unsafe {+ web_canvas_2d_image_source_frame(+ source.wrapper().as_ptr().cast(),+ self,+ raster_width,+ raster_height,+ &raw mut rasterized,+ )+ };// SAFETY: LibWeb hands over a frame that it allocated with new, or null.- (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })+ (!frame.is_null()).then(|| (unsafe { ImageFrameHandle::adopt(frame) }, rasterized))}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rsindex eb53c7c8b41..bc1dd87da4b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs@@ -11,7 +11,7 @@ use core::ptr::NonNull;use ak::Utf16String;use libcompositing_rust::display_list::commands::CanvasId;use libgfx_rust::image_frame::ImageFrameHandle;-use libgfx_rust::{FloatRect, ScalingMode};+use libgfx_rust::{AffineTransform, FloatRect, IntSize, ScalingMode};use super::image_bitmap::ImageBitmap;use crate::bindings::conversions::CppInterface;@@ -115,6 +115,51 @@ impl CanvasImageSource {}}}++ /// The frame to paint the source rectangle of the image from, and that rectangle in the frame's pixels. A vector+ /// image is rasterized at the size it is painted at, so that it stays sharp when it is scaled up.+ fn frame_for_painting(+ self,+ source_rect: FloatRect,+ destination_rect: FloatRect,+ transform: AffineTransform,+ canvas_size: IntSize,+ ) -> Option<(ImageFrameHandle, FloatRect)> {+ let (Self::HTMLImageElement(source) | Self::SVGImageElement(source)) = self else {+ return self.frame().map(|frame| (frame, source_rect));+ };+ let kind = self.cpp_source().expect("an image element is implemented in C++").1;+ let (natural_width, natural_height) = kind.size(source);+ let scale_x = destination_rect.width / source_rect.width * transform.x_scale();+ let scale_y = destination_rect.height / source_rect.height * transform.y_scale();+ if natural_width <= 0 || natural_height <= 0 || (scale_x <= 1.0 && scale_y <= 1.0) {+ return kind.frame(source).map(|frame| (frame, source_rect));+ }++ // The image is rasterized at one scale in both directions, as the vector image would be fitted into a raster of+ // another aspect ratio rather than stretched. The raster is capped at the canvas's size, so that painting a+ // small part of an image enlarged can't allocate a raster much larger than the canvas.+ let scale = scale_x+ .max(scale_y)+ .min(canvas_size.width.max(natural_width) as f32 / natural_width as f32)+ .min(canvas_size.height.max(natural_height) as f32 / natural_height as f32);+ let raster_width = (natural_width as f32 * scale).ceil() as i32;+ let raster_height = (natural_height as f32 * scale).ceil() as i32;+ let (frame, rasterized) = kind.frame_rasterized_at(source, raster_width, raster_height)?;+ if !rasterized {+ return Some((frame, source_rect));+ }++ let frame_scale_x = frame.width() as f32 / natural_width as f32;+ let frame_scale_y = frame.height() as f32 / natural_height as f32;+ let frame_source_rect = FloatRect::new(+ source_rect.x * frame_scale_x,+ source_rect.y * frame_scale_y,+ source_rect.width * frame_scale_x,+ source_rect.height * frame_scale_y,+ );+ Some((frame, frame_source_rect))+ }}impl ContextState {@@ -265,7 +310,10 @@ impl ContextState {return Ok(());}- let Some(frame) = image.frame() else {+ let transform = self.drawing_state().transform;+ let Some((frame, source_rect)) =+ image.frame_for_painting(source_rect, destination_rect, transform, self.size())+ else {return Ok(());};diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cppindex 0ac0a1a6673..9c21dfe62de 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp@@ -57,6 +57,7 @@#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/FontPlugin.h>#include <LibWeb/SVG/SVGAnimatedLength.h>+#include <LibWeb/SVG/SVGDecodedImageData.h>#include <LibWeb/SVG/SVGImageElement.h>#include <LibWebCommon/Bindings/PredefinedColorSpace.h>@@ -175,7 +176,7 @@ u8 web_canvas_2d_check_usability_of_image(void* source_wrapper, CanvasImageSourcvoid web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind, i32* out_width, i32* out_height);bool web_canvas_2d_image_is_not_origin_clean(void* source_wrapper, CanvasImageSourceKind);bool web_canvas_2d_image_source_canvas_id(void* source_wrapper, CanvasImageSourceKind, u64* out_canvas_id, bool* out_source_is_2d);-Gfx::DecodedImageFrame* web_canvas_2d_image_source_frame(void* source_wrapper, CanvasImageSourceKind);+Gfx::DecodedImageFrame* web_canvas_2d_image_source_frame(void* source_wrapper, CanvasImageSourceKind, i32 raster_width, i32 raster_height, bool* out_rasterized);bool web_canvas_2d_capture_video_frame(void* source_wrapper, CapturedVideoFrame* out_frame);void* web_canvas_2d_video_transport(void* source_wrapper);void web_canvas_2d_video_frame_hold_unref(Compositing::VideoFrameHold*);@@ -812,13 +813,24 @@ bool web_canvas_2d_image_source_canvas_id(void* source_wrapper, CanvasImageSourcreturn true;}-Gfx::DecodedImageFrame* web_canvas_2d_image_source_frame(void* source_wrapper, CanvasImageSourceKind kind)+// The frame of an image or a canvas. A vector image is rasterized at the raster size instead of its natural size, if+// that size is not empty and the raster can be made, and out_rasterized says whether it was.+Gfx::DecodedImageFrame* web_canvas_2d_image_source_frame(void* source_wrapper, CanvasImageSourceKind kind, i32 raster_width, i32 raster_height, bool* out_rasterized){- auto frame = image_source_from(source_wrapper, kind).visit([](OneOf<GC::Ref<HTMLImageElement>, GC::Ref<SVG::SVGImageElement>> auto const& element) -> Optional<Gfx::DecodedImageFrame> {+ *out_rasterized = false;+ auto frame = image_source_from(source_wrapper, kind).visit([&](OneOf<GC::Ref<HTMLImageElement>, GC::Ref<SVG::SVGImageElement>> auto const& element) -> Optional<Gfx::DecodedImageFrame> {auto image_data = element->decoded_image_data();if (!image_data)return {};+ Gfx::IntSize raster_size { raster_width, raster_height };+ if (!raster_size.is_empty() && is<SVG::SVGDecodedImageData>(*image_data)) {+ if (auto raster_frame = image_data->default_frame(raster_size); raster_frame.has_value()) {+ *out_rasterized = true;+ return raster_frame;+ }+ }+Gfx::IntSize size;auto intrinsic_width = element->intrinsic_width();auto intrinsic_height = element->intrinsic_height();diff --git a/Tests/LibWeb/Text/expected/canvas/drawimage-svg-scaled-up-stays-sharp.txt b/Tests/LibWeb/Text/expected/canvas/drawimage-svg-scaled-up-stays-sharp.txtnew file mode 100644index 00000000000..a6897efeb13--- /dev/null+++ b/Tests/LibWeb/Text/expected/canvas/drawimage-svg-scaled-up-stays-sharp.txt@@ -0,0 +1,6 @@+transform: partially covered 0, black 1600, red 400+destination size and transform: partially covered 0, black 1600, red 400+source rectangle: partially covered 0, black 6400, red 0+source rectangle in the corner: partially covered 0, black 0, red 6400+rotated: partially covered 0, black 1600, red 400+non-uniform destination: partially covered 0, black 800, red 200diff --git a/Tests/LibWeb/Text/input/canvas/drawimage-svg-scaled-up-stays-sharp.html b/Tests/LibWeb/Text/input/canvas/drawimage-svg-scaled-up-stays-sharp.htmlnew file mode 100644index 00000000000..550eaa2e632--- /dev/null+++ b/Tests/LibWeb/Text/input/canvas/drawimage-svg-scaled-up-stays-sharp.html@@ -0,0 +1,50 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ // A 10x10 SVG whose black square has its edges on half pixels.+ const svg =+ '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect x="2.5" y="2.5" width="5" height="5"/><rect width="2.5" height="2.5" fill="red"/></svg>';+ const img = new Image();+ img.src = "data:image/svg+xml," + encodeURIComponent(svg);+ await img.decode();++ function draw(label, drawFunction) {+ const canvas = document.createElement("canvas");+ canvas.width = canvas.height = 80;+ const ctx = canvas.getContext("2d");+ drawFunction(ctx);+ const data = ctx.getImageData(0, 0, 80, 80).data;+ let partial = 0;+ let black = 0;+ let red = 0;+ for (let i = 0; i < data.length; i += 4) {+ const alpha = data[i + 3];+ if (alpha > 5 && alpha < 250) ++partial;+ else if (alpha >= 250 && data[i] < 5) ++black;+ else if (alpha >= 250 && data[i] > 250) ++red;+ }+ println(`${label}: partially covered ${partial}, black ${black}, red ${red}`);+ }++ // Scaled up 8x, each edge lands on a pixel boundary, so nothing is partially covered.+ draw("transform", ctx => {+ ctx.setTransform(8, 0, 0, 8, 0, 0);+ ctx.drawImage(img, 0, 0);+ });+ draw("destination size and transform", ctx => {+ ctx.scale(2, 2);+ ctx.drawImage(img, 0, 0, 40, 40);+ });+ draw("source rectangle", ctx => ctx.drawImage(img, 2.5, 2.5, 5, 5, 0, 0, 80, 80));+ draw("source rectangle in the corner", ctx => ctx.drawImage(img, 0, 0, 2.5, 2.5, 0, 0, 80, 80));+ draw("rotated", ctx => {+ ctx.translate(40, 40);+ ctx.rotate(Math.PI / 2);+ ctx.scale(8, 8);+ ctx.drawImage(img, -5, -5);+ });+ // Stretched rather than fitted into the destination.+ draw("non-uniform destination", ctx => ctx.drawImage(img, 0, 0, 80, 40));+ });+</script>