Skip to content

Truly independent web browser

LibCompositing+LibWeb: Implement the 2D canvas contexts in Rust

Andreas Klinge022a3080600
diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs
index 8d877f40f40..70e5ec5975e 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs
@@ -7,13 +7,9 @@
//! The recorder of a 2D canvas, which writes a record for each command of the canvas and hands it, with the fonts, the
//! image frames and the video frames that it names, to the stream that WebContent shares between its canvases.
-use super::canvas_2d::{ColorStops, Compositing, Paint, Stroke, TapeWriter};
+use super::canvas_2d::{Compositing, Paint, Stroke, TapeWriter};
use super::commands::*;
-use libgfx_rust::{
- AffineTransform, CapStyle, Color, CompositingAndBlendingOperator, FloatPoint, FloatRect, IntRect, IntSize,
- JoinStyle, ScalingMode, WindingRule,
-};
-use std::ffi::c_void;
+use libgfx_rust::{AffineTransform, Color, FloatPoint, FloatRect, IntRect, IntSize, ScalingMode, WindingRule};
/// The number of commands that the shared stream carries to the Compositor at most in one batch. A batch holds the
/// image frames of its commands, each a bitmap that an IPC attachment carries, so it has to stay small.
@@ -231,103 +227,6 @@ impl<T: Transport> Recorder<T> {
}
}
-/// The fill or stroke style of a draw as C++ lends it to the recorder: the fields that `Canvas2DPaint` has for the kind,
-/// with the color stops and the image of a pattern lent, the image as a Gfx::DecodedImageFrame or null.
-#[repr(C)]
-pub struct FfiCanvas2DPaint<'a> {
- pub kind: Canvas2DPaintKind,
- pub pattern_repetition: Canvas2DPatternRepetition,
- pub has_pattern_transform: bool,
- pub color: Color,
- pub start_point: FloatPoint,
- pub end_point: FloatPoint,
- pub start_radius: f32,
- pub end_radius: f32,
- pub start_angle: f32,
- pub color_stop_colors: ak::Span<'a, Color>,
- pub color_stop_positions: ak::Span<'a, f32>,
- pub pattern_image: *const c_void,
- pub pattern_transform: AffineTransform,
-}
-
-impl<'a> FfiCanvas2DPaint<'a> {
- /// The paint, with the image of a pattern named by the id it travels with.
- pub fn to_paint(&self, pattern_image: Option<ImageFrameResourceId>) -> Paint<'a> {
- let color_stops = ColorStops {
- colors: self.color_stop_colors.as_slice(),
- positions: self.color_stop_positions.as_slice(),
- };
- match self.kind {
- Canvas2DPaintKind::Color => Paint::Color(self.color),
- Canvas2DPaintKind::LinearGradient => Paint::LinearGradient {
- start_point: self.start_point,
- end_point: self.end_point,
- color_stops,
- },
- Canvas2DPaintKind::RadialGradient => Paint::RadialGradient {
- start_center: self.start_point,
- start_radius: self.start_radius,
- end_center: self.end_point,
- end_radius: self.end_radius,
- color_stops,
- },
- Canvas2DPaintKind::ConicGradient => Paint::ConicGradient {
- center: self.start_point,
- start_angle: self.start_angle,
- color_stops,
- },
- Canvas2DPaintKind::Pattern => Paint::Pattern {
- image: pattern_image,
- repetition: self.pattern_repetition,
- transform: self.has_pattern_transform.then_some(self.pattern_transform),
- },
- }
- }
-}
-
-/// How a draw composites, as C++ lends it to the recorder.
-#[repr(C)]
-pub struct FfiCanvas2DCompositing<'a> {
- pub filter: ak::Span<'a, u8>,
- pub has_filter: bool,
- pub global_alpha: f32,
- pub compositing_and_blending_operator: CompositingAndBlendingOperator,
-}
-
-impl<'a> FfiCanvas2DCompositing<'a> {
- pub fn to_compositing(&self) -> Compositing<'a> {
- Compositing {
- filter: self.has_filter.then(|| self.filter.as_slice()),
- global_alpha: self.global_alpha,
- compositing_and_blending_operator: self.compositing_and_blending_operator,
- }
- }
-}
-
-/// The line styles of a stroke, as C++ lends them to the recorder.
-#[repr(C)]
-pub struct FfiCanvas2DStroke<'a> {
- pub thickness: f32,
- pub cap_style: CapStyle,
- pub join_style: JoinStyle,
- pub miter_limit: f32,
- pub dash_array: ak::Span<'a, f32>,
- pub dash_offset: f32,
-}
-
-impl<'a> FfiCanvas2DStroke<'a> {
- pub fn to_stroke(&self) -> Stroke<'a> {
- Stroke {
- thickness: self.thickness,
- cap_style: self.cap_style,
- join_style: self.join_style,
- miter_limit: self.miter_limit,
- dash_array: self.dash_array.as_slice(),
- dash_offset: self.dash_offset,
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -508,45 +407,4 @@ mod tests {
recorder.destroy_context();
assert_eq!(*recorder.transport.events.borrow(), [Event::Present, Event::Flush]);
}
-
- #[test]
- fn a_lent_paint_names_the_image_of_its_pattern_by_the_id_it_travels_with() {
- let colors = [Color(1), Color(2)];
- let positions = [0.25, 0.75];
- let lent = FfiCanvas2DPaint {
- kind: Canvas2DPaintKind::RadialGradient,
- pattern_repetition: Canvas2DPatternRepetition::Repeat,
- has_pattern_transform: false,
- color: Color(0),
- start_point: FloatPoint { x: 1.0, y: 1.0 },
- end_point: FloatPoint { x: 2.0, y: 2.0 },
- start_radius: 3.0,
- end_radius: 4.0,
- start_angle: 0.0,
- color_stop_colors: ak::Span::new(&colors),
- color_stop_positions: ak::Span::new(&positions),
- pattern_image: std::ptr::null(),
- pattern_transform: AffineTransform::default(),
- };
- let Paint::RadialGradient {
- end_radius,
- color_stops,
- ..
- } = lent.to_paint(None)
- else {
- panic!("a radial gradient stays one");
- };
- assert_eq!(end_radius, 4.0);
- assert_eq!(color_stops.positions, positions);
- let pattern = FfiCanvas2DPaint {
- kind: Canvas2DPaintKind::Pattern,
- has_pattern_transform: true,
- ..lent
- };
- let Paint::Pattern { image, transform, .. } = pattern.to_paint(Some(ImageFrameResourceId(6))) else {
- panic!("a pattern stays one");
- };
- assert_eq!(image, Some(ImageFrameResourceId(6)));
- assert_eq!(transform, Some(AffineTransform::default()));
- }
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs
new file mode 100644
index 00000000000..ce9c660dc7b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs
@@ -0,0 +1,452 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What a 2D context asks of the rest of LibWeb, which is C++: its canvas, the CSS values that are resolved against the
+//! canvas, and the image sources that are implemented in C++. Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+//! defines these functions.
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libcompositing_rust::filter_bytes::FfiFilterFunction;
+use libgfx_rust::font::FontCascadeListHandle;
+use libgfx_rust::image_frame::ImageFrameHandle;
+use libgfx_rust::{AffineTransform, Color};
+use libjs_rust::api::{Gc, Object, Realm};
+
+use super::host::CppTransport;
+use crate::bindings::conversions::CppInterface;
+
+unsafe extern "C" {
+ fn web_canvas_2d_canvas_did_change_content(canvas_host: *mut c_void);
+ fn web_canvas_2d_canvas_did_create_backing_storage(canvas_host: *mut c_void);
+ fn web_canvas_2d_canvas_create_transport(canvas_host: *mut c_void) -> *mut c_void;
+ fn web_canvas_2d_canvas_wrapper(canvas: *mut c_void, canvas_is_offscreen: bool, realm: *mut c_void) -> *mut c_void;
+ fn web_canvas_2d_canvas_relevant_realm(canvas_host: *mut c_void) -> *mut c_void;
+ fn web_canvas_2d_canvas_font_environment_generation(canvas_host: *mut c_void) -> u64;
+ fn web_canvas_2d_canvas_resolve_font(
+ canvas: *mut c_void,
+ canvas_is_offscreen: bool,
+ font: usize,
+ out_font: *mut ResolvedFontAbi,
+ ) -> bool;
+ fn web_canvas_2d_canvas_resolve_color(
+ canvas_host: *mut c_void,
+ color: *const c_void,
+ font: FontMetricsSource,
+ out_color: *mut Color,
+ );
+ fn web_canvas_2d_canvas_resolve_length(
+ canvas_host: *mut c_void,
+ length: *const c_void,
+ font: FontMetricsSource,
+ ) -> f32;
+ fn web_canvas_2d_canvas_parse_filter(
+ canvas_host: *mut c_void,
+ filter: usize,
+ font: FontMetricsSource,
+ functions: *mut c_void,
+ append_function: unsafe extern "C" fn(*mut c_void, *const FfiFilterFunction),
+ ) -> bool;
+ fn web_canvas_2d_parse_color(color: usize) -> *const c_void;
+ fn web_canvas_2d_parse_length(length: usize, out_serialized: *mut usize) -> *const c_void;
+ fn web_canvas_2d_style_value_ref(style_value: *const c_void);
+ fn web_canvas_2d_style_value_unref(style_value: *const c_void);
+ fn web_canvas_2d_create_dom_matrix(realm: *mut c_void, transform: *const AffineTransform) -> *mut c_void;
+ fn web_canvas_2d_image_frame_from_pixels(
+ first_row: *const u8,
+ pitch: usize,
+ width: i32,
+ height: i32,
+ ) -> *mut c_void;
+
+ fn web_canvas_2d_check_usability_of_image(
+ source_wrapper: *mut c_void,
+ source_kind: CanvasImageSourceKind,
+ out_message: *mut usize,
+ ) -> u8;
+ fn web_canvas_2d_image_source_size(
+ source_wrapper: *mut c_void,
+ source_kind: CanvasImageSourceKind,
+ out_width: *mut i32,
+ out_height: *mut i32,
+ );
+ fn web_canvas_2d_image_is_not_origin_clean(source_wrapper: *mut c_void, source_kind: CanvasImageSourceKind)
+ -> bool;
+ fn web_canvas_2d_image_source_canvas_id(
+ source_wrapper: *mut c_void,
+ source_kind: CanvasImageSourceKind,
+ 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_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);
+}
+
+/// What a CSS value of a context is resolved with besides its canvas: the font of the context, if it has one yet.
+/// `FontMetricsSource` of Canvas2DContextBase.cpp mirrors it.
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub(crate) struct FontMetricsSource {
+ /// The Gfx::FontCascadeList of the font, or null for the font that a context starts with.
+ cascade: *const c_void,
+ /// The size of the font, as the raw value of a CSSPixels.
+ font_size: i32,
+}
+
+impl FontMetricsSource {
+ pub(crate) fn of(font: Option<&ResolvedFont>) -> Self {
+ match font {
+ Some(font) => Self {
+ cascade: font.cascade.as_raw(),
+ font_size: font.font_size,
+ },
+ None => Self {
+ cascade: core::ptr::null(),
+ font_size: 0,
+ },
+ }
+ }
+}
+
+/// `ResolvedFont` of Canvas2DContextBase.cpp.
+#[repr(C)]
+struct ResolvedFontAbi {
+ /// A Gfx::FontCascadeList with a reference that the caller takes over.
+ cascade: *const c_void,
+ environment_generation: u64,
+ font_size: i32,
+ /// An AK::Utf16String that the caller takes over.
+ serialized: usize,
+}
+
+/// The font of a context: the cascade of fonts that its text is drawn with, the font environment that chose them, and
+/// what the font attribute returns.
+#[derive(Clone)]
+pub(crate) struct ResolvedFont {
+ pub(crate) cascade: FontCascadeListHandle,
+ pub(crate) environment_generation: u64,
+ /// The size of the font, as the raw value of a CSSPixels.
+ pub(crate) font_size: i32,
+ pub(crate) serialized: Utf16String,
+}
+
+/// A CSS::StyleValue of LibWeb, one reference to which the value owns.
+pub(crate) struct StyleValue(NonNull<c_void>);
+
+impl StyleValue {
+ /// # Safety
+ ///
+ /// `style_value` is a CSS::StyleValue with a reference that the value takes over, or null.
+ unsafe fn adopt(style_value: *const c_void) -> Option<Self> {
+ NonNull::new(style_value.cast_mut()).map(Self)
+ }
+}
+
+impl Clone for StyleValue {
+ fn clone(&self) -> Self {
+ // SAFETY: The value owns a reference to the style value, so it is live.
+ unsafe { web_canvas_2d_style_value_ref(self.0.as_ptr()) };
+ Self(self.0)
+ }
+}
+
+impl Drop for StyleValue {
+ fn drop(&mut self) {
+ // SAFETY: The value owns a reference to the style value.
+ unsafe { web_canvas_2d_style_value_unref(self.0.as_ptr()) };
+ }
+}
+
+/// The sources of images that are implemented in C++, in the order of the C++ enum of the same name.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub(crate) enum CanvasImageSourceKind {
+ HTMLImageElement,
+ SVGImageElement,
+ HTMLVideoElement,
+ HTMLCanvasElement,
+ OffscreenCanvas,
+}
+
+/// The values of the C++ enum `CanvasImageSourceUsability`, and an exception.
+const USABILITY_GOOD: u8 = 0;
+const USABILITY_BAD: u8 = 1;
+const USABILITY_INVALID_STATE: u8 = 2;
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
+pub(crate) enum Usability {
+ Good,
+ Bad,
+ /// The check threw an "InvalidStateError" DOMException with the message.
+ InvalidState(Utf16String),
+}
+
+/// `CapturedVideoFrame` of Canvas2DContextBase.cpp.
+#[repr(C)]
+struct CapturedVideoFrameAbi {
+ hold: *mut c_void,
+ sink_handle: u64,
+ generation: u64,
+}
+
+/// A frame of a video, which the hold keeps until the Compositor has drawn it.
+pub(crate) struct CapturedVideoFrame {
+ hold: NonNull<c_void>,
+ pub(crate) sink_handle: u64,
+ pub(crate) generation: u64,
+}
+
+impl CapturedVideoFrame {
+ /// The Compositing::VideoFrameHold, which the value keeps alive.
+ pub(crate) fn hold(&self) -> NonNull<c_void> {
+ self.hold
+ }
+}
+
+impl Drop for CapturedVideoFrame {
+ fn drop(&mut self) {
+ // SAFETY: The value owns a reference to the hold.
+ unsafe { web_canvas_2d_video_frame_hold_unref(self.hold.as_ptr()) };
+ }
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct Canvas {
+ /// The cell of the canvas, which the context keeps alive through a slot of its own.
+ pub(crate) cell: NonNull<c_void>,
+ pub(crate) host: NonNull<c_void>,
+ pub(crate) is_offscreen: bool,
+}
+
+// SAFETY (of every call below): The context that holds the canvas keeps its cell alive, and the host is the same
+// object. Strings are lent for the call, and the style values are live.
+impl Canvas {
+ pub(crate) fn did_change_content(self) {
+ unsafe { web_canvas_2d_canvas_did_change_content(self.host.as_ptr()) };
+ }
+
+ pub(crate) fn did_create_backing_storage(self) {
+ unsafe { web_canvas_2d_canvas_did_create_backing_storage(self.host.as_ptr()) };
+ }
+
+ /// A transport to a new context in the Compositor, if the page of the canvas has a Compositor.
+ pub(crate) fn create_transport(self) -> Option<CppTransport> {
+ let transport = unsafe { web_canvas_2d_canvas_create_transport(self.host.as_ptr()) };
+ // SAFETY: LibWeb hands over a reference to the transport.
+ NonNull::new(transport).map(|transport| unsafe { CppTransport::from_raw(transport) })
+ }
+
+ pub(crate) fn wrapper(self, realm: Gc<Realm>) -> CppInterface {
+ let wrapper =
+ unsafe { web_canvas_2d_canvas_wrapper(self.cell.as_ptr(), self.is_offscreen, realm.as_ptr().cast()) };
+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns the wrapper of the canvas");
+ // SAFETY: LibWeb returns a live wrapper of an HTMLCanvasElement or an OffscreenCanvas.
+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }
+ }
+
+ /// The realm of the relevant global object of the canvas, once that global object has a wrapper.
+ pub(crate) fn relevant_realm(self) -> Option<Gc<Realm>> {
+ let realm = unsafe { web_canvas_2d_canvas_relevant_realm(self.host.as_ptr()) };
+ // SAFETY: LibWeb returns a live realm, or null.
+ NonNull::new(realm.cast::<Realm>()).map(|realm| unsafe { Gc::from_non_null(realm) })
+ }
+
+ /// The generation of the fonts that the canvas can use, which changes when a font loads.
+ pub(crate) fn font_environment_generation(self) -> u64 {
+ unsafe { web_canvas_2d_canvas_font_environment_generation(self.host.as_ptr()) }
+ }
+
+ /// The font that a value of the font attribute describes, resolved against the canvas, unless the value is not a
+ /// CSS font.
+ pub(crate) fn resolve_font(self, font: &Utf16String) -> Option<ResolvedFont> {
+ let mut resolved = ResolvedFontAbi {
+ cascade: core::ptr::null(),
+ environment_generation: 0,
+ font_size: 0,
+ serialized: 0,
+ };
+ let is_font = unsafe {
+ web_canvas_2d_canvas_resolve_font(
+ self.cell.as_ptr(),
+ self.is_offscreen,
+ font.raw_identity(),
+ &raw mut resolved,
+ )
+ };
+ if !is_font {
+ return None;
+ }
+ Some(ResolvedFont {
+ // SAFETY: LibWeb hands over a reference to the cascade.
+ cascade: unsafe { FontCascadeListHandle::adopt(resolved.cascade) },
+ environment_generation: resolved.environment_generation,
+ font_size: resolved.font_size,
+ // SAFETY: LibWeb hands over the string.
+ serialized: unsafe { Utf16String::from_raw_owned(resolved.serialized) },
+ })
+ }
+
+ /// The used color of a parsed CSS color, resolved against the canvas.
+ pub(crate) fn resolve_color(self, color: &StyleValue, font: FontMetricsSource) -> Color {
+ let mut resolved = Color::default();
+ unsafe { web_canvas_2d_canvas_resolve_color(self.host.as_ptr(), color.0.as_ptr(), font, &raw mut resolved) };
+ resolved
+ }
+
+ /// A parsed CSS length in CSS pixels, resolved against the canvas.
+ pub(crate) fn resolve_length(self, length: &StyleValue, font: FontMetricsSource) -> f32 {
+ unsafe { web_canvas_2d_canvas_resolve_length(self.host.as_ptr(), length.0.as_ptr(), font) }
+ }
+
+ /// The functions of a <filter-value-list>, with their lengths and colors resolved against the canvas, unless the
+ /// value is not one.
+ pub(crate) fn parse_filter(self, filter: &Utf16String, font: FontMetricsSource) -> Option<Vec<FfiFilterFunction>> {
+ unsafe extern "C" fn append_function(functions: *mut c_void, function: *const FfiFilterFunction) {
+ // SAFETY: The functions are the vector below, and LibWeb lends the function for the call.
+ unsafe { (*functions.cast::<Vec<FfiFilterFunction>>()).push(*function) };
+ }
+ let mut functions = Vec::new();
+ let is_filter = unsafe {
+ web_canvas_2d_canvas_parse_filter(
+ self.host.as_ptr(),
+ filter.raw_identity(),
+ font,
+ (&raw mut functions).cast(),
+ append_function,
+ )
+ };
+ is_filter.then_some(functions)
+ }
+}
+
+/// A CSS <color>, parsed without a canvas to resolve it against, unless the string is not one.
+pub(crate) fn parse_color(color: &Utf16String) -> Option<StyleValue> {
+ // SAFETY: The string is lent for the call, and LibWeb hands over a reference to the style value, or null.
+ unsafe { StyleValue::adopt(web_canvas_2d_parse_color(color.raw_identity())) }
+}
+
+/// A CSS <length>, parsed without a canvas to resolve it against, and its serialization, unless the string is not
+/// one.
+pub(crate) fn parse_length(length: &Utf16String) -> Option<(StyleValue, Utf16String)> {
+ let mut serialized = 0;
+ // SAFETY: The string is lent for the call, and LibWeb hands over a reference to the style value, or null.
+ let style_value =
+ unsafe { StyleValue::adopt(web_canvas_2d_parse_length(length.raw_identity(), &raw mut serialized)) }?;
+ // SAFETY: LibWeb hands over the serialization with the style value.
+ Some((style_value, unsafe { Utf16String::from_raw_owned(serialized) }))
+}
+
+/// A new DOMMatrix with the transform, in the realm.
+pub(crate) fn create_dom_matrix(realm: Gc<Realm>, transform: AffineTransform) -> CppInterface {
+ // SAFETY: The realm is live, and the transform is lent for the call.
+ let wrapper = unsafe { web_canvas_2d_create_dom_matrix(realm.as_ptr().cast(), &raw const transform) };
+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns the wrapper of the matrix");
+ // SAFETY: LibWeb returns a live wrapper of a DOMMatrix.
+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }
+}
+
+/// A frame of a copy of `height` rows of `width` RGBA8888 pixels that are unpremultiplied, `pitch` bytes apart, or
+/// None if there is no memory for it.
+///
+/// # Safety
+///
+/// The rows must be readable, and no script may change them during the call.
+pub(crate) unsafe fn image_frame_from_pixels(
+ first_row: NonNull<u8>,
+ pitch: usize,
+ width: i32,
+ height: i32,
+) -> Option<ImageFrameHandle> {
+ // SAFETY: The caller passes readable rows.
+ let frame = unsafe { web_canvas_2d_image_frame_from_pixels(first_row.as_ptr(), pitch, width, height) };
+ // SAFETY: LibWeb hands over a frame that it allocated with new, or null.
+ (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })
+}
+
+// SAFETY (of every call below): The wrapper is live and of the interface that the kind names.
+impl CanvasImageSourceKind {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
+ pub(crate) fn check_usability(self, source: CppInterface) -> Usability {
+ let mut message = 0;
+ let usability =
+ unsafe { web_canvas_2d_check_usability_of_image(source.wrapper().as_ptr().cast(), self, &raw mut message) };
+ match usability {
+ USABILITY_GOOD => Usability::Good,
+ USABILITY_BAD => Usability::Bad,
+ // SAFETY: LibWeb hands over the message of the exception.
+ USABILITY_INVALID_STATE => Usability::InvalidState(unsafe { Utf16String::from_raw_owned(message) }),
+ unknown => unreachable!("LibWeb returned {unknown} for the usability of an image"),
+ }
+ }
+
+ /// The width and the height of the image, as the operations that do not take its size use them.
+ pub(crate) fn size(self, source: CppInterface) -> (i32, i32) {
+ let (mut width, mut height) = (0, 0);
+ unsafe {
+ web_canvas_2d_image_source_size(source.wrapper().as_ptr().cast(), self, &raw mut width, &raw mut height);
+ }
+ (width, height)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#the-image-argument-is-not-origin-clean
+ pub(crate) fn is_not_origin_clean(self, source: CppInterface) -> bool {
+ unsafe { web_canvas_2d_image_is_not_origin_clean(source.wrapper().as_ptr().cast(), self) }
+ }
+
+ /// The id of the canvas that a canvas or an OffscreenCanvas draws into, readied to be drawn, and whether a 2D
+ /// context draws into it, if it is drawn by its id.
+ pub(crate) fn canvas_id(self, source: CppInterface) -> Option<(u64, bool)> {
+ let (mut canvas_id, mut source_is_2d) = (0, false);
+ let has_id = unsafe {
+ web_canvas_2d_image_source_canvas_id(
+ source.wrapper().as_ptr().cast(),
+ self,
+ &raw mut canvas_id,
+ &raw mut source_is_2d,
+ )
+ };
+ has_id.then_some((canvas_id, source_is_2d))
+ }
+
+ /// 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) };
+ // SAFETY: LibWeb hands over a frame that it allocated with new, or null.
+ (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })
+ }
+}
+
+/// The frame of the video that its element shows, if it shows one.
+pub(crate) fn capture_video_frame(video: CppInterface) -> Option<CapturedVideoFrame> {
+ let mut frame = CapturedVideoFrameAbi {
+ hold: core::ptr::null_mut(),
+ sink_handle: 0,
+ generation: 0,
+ };
+ // SAFETY: The wrapper is a live HTMLVideoElement, and LibWeb hands over a reference to the hold.
+ if !unsafe { web_canvas_2d_capture_video_frame(video.wrapper().as_ptr().cast(), &raw mut frame) } {
+ return None;
+ }
+ Some(CapturedVideoFrame {
+ hold: NonNull::new(frame.hold).expect("LibWeb passes the hold of the frame"),
+ sink_handle: frame.sink_handle,
+ generation: frame.generation,
+ })
+}
+
+/// A transport to a new context in the Compositor of the page of the video, if the page has a Compositor.
+pub(crate) fn video_transport(video: CppInterface) -> Option<CppTransport> {
+ // SAFETY: The wrapper is a live HTMLVideoElement.
+ let transport = unsafe { web_canvas_2d_video_transport(video.wrapper().as_ptr().cast()) };
+ // SAFETY: LibWeb hands over a reference to the transport.
+ NonNull::new(transport).map(|transport| unsafe { CppTransport::from_raw(transport) })
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs
new file mode 100644
index 00000000000..f51a695aad5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/context.rs
@@ -0,0 +1,828 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The state that CanvasRenderingContext2D and OffscreenCanvasRenderingContext2D share: the drawing state, the current
+//! default path, and the backing storage, which is a context in the Compositor that the context records commands for.
+
+use core::cell::{Cell, Ref as CellRef, RefCell, RefMut};
+use core::marker::PhantomData;
+use core::ops::Deref;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libcompositing_rust::display_list::canvas_2d::{Compositing, Paint, Stroke};
+use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, Recorder};
+use libcompositing_rust::display_list::commands::CanvasId;
+use libgfx_rust::path::{OwnedPath, PathBuilder};
+use libgfx_rust::{AffineTransform, Color, CompositingAndBlendingOperator, FloatRect, IntRect, IntSize, WindingRule};
+use libjs_rust::api::{ForeignCellSlot, Gc, Realm, Trace, Visitor, Vm};
+
+use super::canvas::{Canvas, FontMetricsSource, ResolvedFont, StyleValue, parse_color};
+use super::drawing_state::{DrawingState, FillOrStrokeStyle};
+use super::host::{Bitmap, CppTransport, LentImageFrame};
+use crate::bindings::interface::Wrappable;
+use crate::html::canvas_rendering_context2d_settings::CanvasRenderingContext2DSettings;
+
+pub(crate) type CanvasRecorder = Recorder<CppTransport>;
+
+/// What tells the two kinds of 2D context apart: the canvas that each draws for, an HTMLCanvasElement or an
+/// OffscreenCanvas. Everything else they share.
+pub(crate) trait CanvasKind: 'static {}
+
+/// The kind of a CanvasRenderingContext2D.
+pub(crate) struct OnScreen;
+/// The kind of an OffscreenCanvasRenderingContext2D.
+pub(crate) struct Offscreen;
+
+impl CanvasKind for OnScreen {}
+impl CanvasKind for Offscreen {}
+
+/// The attributes and operations that CanvasRenderingContext2D and OffscreenCanvasRenderingContext2D share are
+/// implemented once, for every `K`.
+pub(crate) struct RenderingContext2D<K: CanvasKind> {
+ state: ContextState,
+ kind: PhantomData<K>,
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ pub(crate) fn new(state: ContextState) -> Self {
+ Self {
+ state,
+ kind: PhantomData,
+ }
+ }
+}
+
+impl<K: CanvasKind> Deref for RenderingContext2D<K> {
+ type Target = ContextState;
+
+ fn deref(&self) -> &ContextState {
+ &self.state
+ }
+}
+
+// SAFETY: The state holds every cell that a context can reach.
+unsafe impl<K: CanvasKind> Trace for RenderingContext2D<K> {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.state.trace(visitor);
+ }
+}
+
+impl<K: CanvasKind> Wrappable for RenderingContext2D<K> {
+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {
+ self.state.canvas.relevant_realm()
+ }
+
+ const OWNS_EXTERNAL_MEMORY: bool = true;
+
+ fn external_memory_size(&self) -> usize {
+ self.state.external_memory_size()
+ }
+}
+
+/// The backing storage of a context: the recorder of the commands of its context in the Compositor. Dropping it
+/// destroys that context.
+struct BackingStorage {
+ recorder: CanvasRecorder,
+}
+
+impl Drop for BackingStorage {
+ fn drop(&mut self) {
+ // Flush the shared stream before destroying the context: it may still hold commands targeting this canvas, and
+ // DrawCanvas commands from other canvases referencing it, which must replay while it is alive.
+ self.recorder.flush();
+ self.recorder.destroy_context();
+ }
+}
+
+/// A readback of the pixels of a rectangle of the canvas.
+#[derive(Clone)]
+struct CachedReadback {
+ pixels: Bitmap,
+ rect: IntRect,
+ alpha_type: AlphaType,
+}
+
+/// A color that a context was given as a string. Context-independent simple colors store a resolved color. Other
+/// colors store their parsed style value so they can be resolved against the current canvas context on every use. An
+/// entry with neither is a parse failure.
+struct ColorCacheEntry {
+ input: Utf16String,
+ parsed_value: Option<StyleValue>,
+ resolved_color: Option<Color>,
+}
+
+const MAX_COLOR_CACHE_SIZE: usize = 8;
+const MAX_COLOR_CACHE_INPUT_LENGTH: usize = 128;
+
+/// What a context is created with.
+pub(crate) struct ContextParameters {
+ pub(crate) canvas: Canvas,
+ pub(crate) context_attributes: CanvasRenderingContext2DSettings,
+ pub(crate) size: IntSize,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ContextState {
+ canvas_cell: ForeignCellSlot,
+ #[gc(untraced)]
+ canvas: Canvas,
+ #[gc(untraced)]
+ pub(crate) context_attributes: CanvasRenderingContext2DSettings,
+ #[gc(untraced)]
+ size: Cell<IntSize>,
+ /// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-clean
+ #[gc(untraced)]
+ origin_clean: Cell<bool>,
+ /// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-context-lost
+ #[gc(untraced)]
+ context_lost: Cell<bool>,
+ /// The drawing state stack, with the current drawing state last.
+ states: RefCell<Vec<DrawingState>>,
+ /// The current default path, in the coordinates of the current transformation matrix.
+ #[gc(untraced)]
+ path: RefCell<OwnedPath>,
+ #[gc(untraced)]
+ backing_storage: RefCell<Option<BackingStorage>>,
+ /// OPTIMIZATION: A readback requires a synchronous IPC to the Compositor, so its pixels are reused while no
+ /// drawing command has changed them.
+ #[gc(untraced)]
+ cached_readback: RefCell<Option<CachedReadback>>,
+ #[gc(untraced)]
+ color_cache: RefCell<Vec<ColorCacheEntry>>,
+}
+
+fn empty_path() -> OwnedPath {
+ PathBuilder::new().build()
+}
+
+/// The paint of a draw with the style, with the image of a pattern added to the stream of the recorder.
+pub(crate) fn paint_of<'a>(recorder: &CanvasRecorder, style: &'a FillOrStrokeStyle) -> Paint<'a> {
+ match style {
+ FillOrStrokeStyle::Color(color) => Paint::Color(*color),
+ // SAFETY: Nothing adds a stop to the gradient while the recorder records the paint.
+ FillOrStrokeStyle::Gradient(gradient) => unsafe { gradient.paint_unguarded() },
+ FillOrStrokeStyle::Pattern(pattern) => Paint::Pattern {
+ image: pattern.image().map(|frame| {
+ let frame = NonNull::new(frame.as_raw().cast_mut()).expect("an image frame has a frame");
+ recorder.add_image_frame(&LentImageFrame(frame))
+ }),
+ repetition: pattern.repetition(),
+ transform: pattern.transform(),
+ },
+ }
+}
+
+impl ContextState {
+ pub(crate) fn new(parameters: ContextParameters) -> Self {
+ let canvas_cell = ForeignCellSlot::empty();
+ // SAFETY: The canvas is a live cell of the heap that the runtime allocates from.
+ unsafe { canvas_cell.set(Some(parameters.canvas.cell)) };
+ Self {
+ canvas_cell,
+ canvas: parameters.canvas,
+ context_attributes: parameters.context_attributes,
+ size: Cell::new(parameters.size),
+ origin_clean: Cell::new(true),
+ context_lost: Cell::new(false),
+ states: RefCell::new(vec![DrawingState::default()]),
+ path: RefCell::new(empty_path()),
+ backing_storage: RefCell::new(None),
+ cached_readback: RefCell::new(None),
+ color_cache: RefCell::new(Vec::new()),
+ }
+ }
+
+ /// The canvas, which the canvas attribute returns.
+ pub(crate) fn canvas_handle(&self) -> Canvas {
+ self.canvas
+ }
+
+ pub(crate) fn size(&self) -> IntSize {
+ self.size.get()
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-clean
+ pub(crate) fn origin_clean(&self) -> bool {
+ self.origin_clean.get()
+ }
+
+ pub(crate) fn set_origin_clean(&self, origin_clean: bool) {
+ self.origin_clean.set(origin_clean);
+ }
+
+ pub(crate) fn context_is_lost(&self) -> bool {
+ self.context_lost.get()
+ }
+
+ pub(crate) fn set_context_lost(&self, context_lost: bool) {
+ self.context_lost.set(context_lost);
+ }
+
+ /// The current drawing state, which nothing may change while the borrow lasts.
+ pub(crate) fn drawing_state(&self) -> CellRef<'_, DrawingState> {
+ CellRef::map(self.states.borrow(), |states| {
+ states.last().expect("a context has a current drawing state")
+ })
+ }
+
+ /// The current drawing state, to change it. Nothing may run script or collect garbage while the borrow lasts.
+ pub(crate) fn drawing_state_mut(&self) -> RefMut<'_, DrawingState> {
+ RefMut::map(self.states.borrow_mut(), |states| {
+ states.last_mut().expect("a context has a current drawing state")
+ })
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-save
+ pub(crate) fn push_drawing_state(&self) {
+ let mut states = self.states.borrow_mut();
+ let current = states.last().expect("a context has a current drawing state").clone();
+ states.push(current);
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-restore
+ pub(crate) fn pop_drawing_state(&self) -> bool {
+ let mut states = self.states.borrow_mut();
+ if states.len() == 1 {
+ return false;
+ }
+ states.pop();
+ true
+ }
+
+ /// The current default path, which nothing may change while the borrow lasts.
+ pub(crate) fn path(&self) -> CellRef<'_, OwnedPath> {
+ self.path.borrow()
+ }
+
+ pub(crate) fn path_mut(&self) -> RefMut<'_, OwnedPath> {
+ self.path.borrow_mut()
+ }
+
+ /// Empties the list of subpaths of the current default path.
+ pub(crate) fn clear_path(&self) {
+ self.path.replace(empty_path());
+ }
+
+ /// 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);
+ self.path.replace(transformed);
+ }
+
+ fn external_memory_size(&self) -> usize {
+ // NB: LibGC asks while it sweeps, when nothing borrows these mutably.
+ let mut size = self
+ .cached_readback
+ .try_borrow()
+ .ok()
+ .and_then(|readback| readback.as_ref().map(|readback| readback.pixels.size_in_bytes()))
+ .unwrap_or(0);
+ let has_backing_storage = self
+ .backing_storage
+ .try_borrow()
+ .is_ok_and(|backing_storage| backing_storage.is_some());
+ if !has_backing_storage {
+ return size;
+ }
+ let surface_size = self.size.get();
+ if surface_size.width <= 0 || surface_size.height <= 0 {
+ return size;
+ }
+ let pixel_size = usize::try_from(surface_size.width)
+ .ok()
+ .zip(usize::try_from(surface_size.height).ok())
+ .and_then(|(width, height)| width.checked_mul(height))
+ .and_then(|pixels| pixels.checked_mul(4));
+ let Some(pixel_size) = pixel_size else {
+ return usize::MAX;
+ };
+ size = size.saturating_add(pixel_size);
+ size
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-alpha
+ pub(crate) fn clear_color(&self) -> Color {
+ if self.context_attributes.alpha {
+ Color::TRANSPARENT
+ } else {
+ Color::from_rgb(0, 0, 0)
+ }
+ }
+
+ pub(crate) fn has_backing_storage(&self) -> bool {
+ self.backing_storage.borrow().is_some()
+ }
+
+ fn ensure_remote_canvas_context(&self) -> bool {
+ if self.has_backing_storage() {
+ return true;
+ }
+ let Some(transport) = self.canvas.create_transport() else {
+ return false;
+ };
+ // FIXME: implement context attribute .color_space
+ // FIXME: implement context attribute .color_type
+ // FIXME: implement context attribute .desynchronized
+ // FIXME: implement context attribute .will_read_frequently
+ let recorder = Recorder::new(transport);
+ if !recorder.create_context(self.size.get(), self.context_attributes.alpha) {
+ return false;
+ }
+ self.backing_storage.replace(Some(BackingStorage { recorder }));
+ true
+ }
+
+ pub(crate) fn ensure_backing_storage(&self) {
+ let size = self.size.get();
+ if self.has_backing_storage() || size.width <= 0 || size.height <= 0 {
+ return;
+ }
+ if !self.ensure_remote_canvas_context() {
+ return;
+ }
+ self.canvas.did_create_backing_storage();
+ }
+
+ pub(crate) fn discard_backing_storage(&self) {
+ self.cached_readback.replace(None);
+ let backing_storage = self.backing_storage.take();
+ drop(backing_storage);
+ }
+
+ /// Readies the recorder of the canvas to record, which it is unless the context is lost or the canvas has no
+ /// backing storage. As the steps of a draw call it before each command they record.
+ pub(crate) fn recorder_is_ready(&self) -> bool {
+ if self.context_lost.get() {
+ return false;
+ }
+ self.ensure_backing_storage();
+ let backing_storage = self.backing_storage.borrow();
+ let Some(backing_storage) = backing_storage.as_ref() else {
+ return false;
+ };
+ backing_storage.recorder.prepare_to_record();
+ true
+ }
+
+ /// Records with the recorder, which the caller has readied.
+ pub(crate) fn record<R>(&self, record: impl FnOnce(&mut CanvasRecorder) -> R) -> R {
+ let mut backing_storage = self.backing_storage.borrow_mut();
+ let backing_storage = backing_storage
+ .as_mut()
+ .expect("the canvas has backing storage while the recorder is ready");
+ record(&mut backing_storage.recorder)
+ }
+
+ /// Readies the recorder and records with it, unless the canvas cannot draw.
+ pub(crate) fn record_if_ready(&self, record: impl FnOnce(&mut CanvasRecorder)) -> bool {
+ if !self.recorder_is_ready() {
+ return false;
+ }
+ self.record(record);
+ true
+ }
+
+ pub(crate) fn did_draw(&self) {
+ self.cached_readback.replace(None);
+ // FIXME: Make use of the rectangle that changed to reduce the invalidated area when possible.
+ self.canvas.did_change_content();
+ }
+
+ /// The pixels of the rectangle of the canvas, read back from the Compositor. Unpremultiplied pixels come back as
+ /// RGBA8888, and premultiplied pixels as BGRA8888.
+ pub(crate) fn read_pixels(&self, rect: IntRect, alpha_type: AlphaType) -> Option<Bitmap> {
+ if !self.has_backing_storage() {
+ return None;
+ }
+ if let Some(readback) = self.cached_readback.borrow().as_ref()
+ && readback.rect == rect
+ && readback.alpha_type == alpha_type
+ {
+ return Some(readback.pixels.clone());
+ }
+ let pixels = {
+ let backing_storage = self.backing_storage.borrow();
+ let recorder = &backing_storage
+ .as_ref()
+ .expect("the canvas has backing storage")
+ .recorder;
+ recorder.flush();
+ recorder.read_back_pixels(rect, alpha_type)
+ };
+ if let Some(pixels) = &pixels {
+ self.cached_readback.replace(Some(CachedReadback {
+ pixels: pixels.clone(),
+ rect,
+ alpha_type,
+ }));
+ }
+ pixels
+ }
+
+ pub(crate) fn drop_cached_readback(&self) {
+ self.cached_readback.replace(None);
+ }
+
+ pub(crate) fn set_size(&self, size: IntSize) {
+ if self.size.get() == size {
+ return;
+ }
+ self.size.set(size);
+ self.discard_backing_storage();
+ }
+
+ pub(crate) fn prepare_for_compositing(&self) {
+ if let Some(backing_storage) = self.backing_storage.borrow().as_ref() {
+ backing_storage.recorder.present();
+ }
+ }
+
+ pub(crate) fn canvas_id(&self) -> Option<CanvasId> {
+ self.backing_storage
+ .borrow()
+ .as_ref()
+ .and_then(|backing_storage| backing_storage.recorder.canvas_id())
+ }
+
+ fn full_rect(&self) -> FloatRect {
+ let size = self.size.get();
+ #[allow(
+ clippy::cast_precision_loss,
+ reason = "the rectangle is in floats, as the C++ had it"
+ )]
+ FloatRect::new(0.0, 0.0, size.width as f32, size.height as f32)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#reset-the-rendering-context-to-its-default-state
+ pub(crate) fn reset_to_default_state(&self) {
+ let has_recorder = self.has_backing_storage() && self.recorder_is_ready();
+
+ // 1. Clear canvas's bitmap to transparent black.
+ if has_recorder {
+ let rect = self.full_rect();
+ let color = self.clear_color();
+ self.record(|recorder| recorder.clear_rect(rect, color));
+ }
+
+ // 2. Empty the list of subpaths in the context's current default path.
+ self.clear_path();
+
+ // 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()]);
+
+ if has_recorder {
+ self.record(CanvasRecorder::reset);
+ self.did_draw();
+ }
+ }
+
+ /// Clears the bitmap of an OffscreenCanvas when transferToImageBitmap() takes it.
+ pub(crate) fn replace_bitmap_with_cleared_bitmap(&self) {
+ self.cached_readback.replace(None);
+ self.origin_clean.set(true);
+ if !self.has_backing_storage() {
+ return;
+ }
+ let color = self.clear_color();
+ if self.record_if_ready(|recorder| recorder.clear_canvas(color)) {
+ self.did_draw();
+ }
+ }
+
+ /// Sets the transformation matrix of the recorder to the current one.
+ pub(crate) fn flush_transform(&self) {
+ let transform = self.drawing_state().transform;
+ self.record_if_ready(|recorder| recorder.set_transform(transform));
+ }
+
+ /// What the font of the current drawing state is resolved with, for the CSS values that are resolved against the
+ /// canvas.
+ pub(crate) fn font_metrics_source(&self) -> FontMetricsSource {
+ FontMetricsSource::of(self.drawing_state().font.as_ref())
+ }
+
+ /// https://drafts.csswg.org/css-color-4/#parse-a-css-color-value
+ pub(crate) fn parse_a_css_color_value(&self, value: &Utf16String) -> Option<Color> {
+ // To parse a CSS <color> value, given a string input, and an optional context element element:
+
+ // 1. Parse input as a <color>. If the result is failure, return failure; otherwise, let color be the result.
+ let input_is_cacheable = value.length_in_code_units() <= MAX_COLOR_CACHE_INPUT_LENGTH;
+ let mut cached = None;
+ if input_is_cacheable {
+ let mut color_cache = self.color_cache.borrow_mut();
+ if let Some(index) = color_cache.iter().position(|entry| entry.input == *value) {
+ let entry = color_cache.remove(index);
+ cached = Some((entry.parsed_value.clone(), entry.resolved_color));
+ color_cache.push(entry);
+ }
+ }
+
+ let (color, resolved_color) = match cached {
+ Some(cached) => cached,
+ None => {
+ let resolved_color = match value.as_units() {
+ ak::Utf16StringUnits::Ascii(units) => libweb_rust::parse_simple_color_ascii(units),
+ ak::Utf16StringUnits::Utf16(units) => libweb_rust::parse_simple_color_utf16(units),
+ }
+ .map(|[red, green, blue, alpha]| Color::from_rgba(red, green, blue, alpha));
+ let color = if resolved_color.is_none() {
+ parse_color(value)
+ } else {
+ None
+ };
+ if input_is_cacheable {
+ let mut color_cache = self.color_cache.borrow_mut();
+ if color_cache.len() == MAX_COLOR_CACHE_SIZE {
+ color_cache.remove(0);
+ }
+ color_cache.push(ColorCacheEntry {
+ input: value.clone(),
+ parsed_value: color.clone(),
+ resolved_color,
+ });
+ }
+ (color, resolved_color)
+ }
+ };
+
+ if resolved_color.is_some() {
+ return resolved_color;
+ }
+ let color = color?;
+
+ // 2. Let used color be the result of resolving color to a used color. If the value of other properties on the
+ // element a <color> is on is required to do the resolution (such as resolving a currentcolor or system
+ // color), use element if it was passed, or the initial values of the properties if not.
+ // AD-HOC: The spec tells us to use the element's properties as context but doesn't tell us how to resolve other
+ // context dependent values (e.g. viewport relative lengths). This also differs from how font-relative
+ // lengths are absolutized (i.e. using the canvas' font rather than the element's) in other canvas values
+ // (e.g. letterSpacing) so we instead use a computation context based on the drawing state. See
+ // https://github.com/whatwg/html/issues/12505.
+ let used_color = self.canvas.resolve_color(&color, self.font_metrics_source());
+
+ // 3. Return used color.
+ Some(used_color)
+ }
+
+ /// Sets the font of the current drawing state, unless the value is not a CSS font.
+ pub(crate) fn assign_font(&self, font: &Utf16String) {
+ if let Some(font) = self.canvas.resolve_font(font) {
+ self.drawing_state_mut().font = Some(font);
+ }
+ }
+
+ /// The font of the current drawing state, which is resolved the first time the context needs one, and again when
+ /// the fonts that the canvas can use change.
+ pub(crate) fn current_font(&self) -> ResolvedFont {
+ // When font style value is empty load default font
+ if self.drawing_state().font.is_none() {
+ self.assign_font(&Utf16String::from_ascii(b"10px sans-serif"));
+ }
+
+ // NB: Drawing states, including saved states, retain their cascades across font loads and font-display
+ // transitions. Refresh them lazily so cached invisible fallback glyphs and metrics cannot outlive the font
+ // environment that selected them.
+ let font = self
+ .drawing_state()
+ .font
+ .clone()
+ .expect("a context has a font once it is set");
+ if font.environment_generation != self.canvas.font_environment_generation() {
+ self.assign_font(&font.serialized);
+ return self
+ .drawing_state()
+ .font
+ .clone()
+ .expect("a context has a font once it is set");
+ }
+ font
+ }
+
+ /// The letter spacing of the current drawing state in CSS pixels.
+ pub(crate) fn resolved_letter_spacing(&self) -> f32 {
+ let letter_spacing = self.drawing_state().letter_spacing.clone();
+ match letter_spacing {
+ Some(letter_spacing) => self
+ .canvas
+ .resolve_length(&letter_spacing.length, self.font_metrics_source()),
+ None => 0.0,
+ }
+ }
+
+ /// How a draw composites under the current drawing state.
+ pub(crate) fn compositing(state: &DrawingState) -> Compositing<'_> {
+ Compositing {
+ filter: state.filter.as_deref(),
+ global_alpha: state.global_alpha,
+ compositing_and_blending_operator: state.current_compositing_and_blending_operator,
+ }
+ }
+
+ /// A shadow is drawn through the filter with its operator, but without the global alpha, which its color holds.
+ fn shadow_compositing(state: &DrawingState) -> Compositing<'_> {
+ Compositing {
+ filter: state.filter.as_deref(),
+ global_alpha: 1.0,
+ compositing_and_blending_operator: state.current_compositing_and_blending_operator,
+ }
+ }
+
+ /// The color and the transformation matrix of the shadow of a draw, unless the draw casts none.
+ fn shadow_of(state: &DrawingState) -> Option<(Color, AffineTransform)> {
+ if state.current_compositing_and_blending_operator == CompositingAndBlendingOperator::Copy {
+ return None;
+ }
+ if state.shadow_blur == 0.0 && state.shadow_offset_x == 0.0 && state.shadow_offset_y == 0.0 {
+ return None;
+ }
+ let mut alpha = state.global_alpha * (f32::from(state.shadow_color.alpha()) / 255.0);
+ if let Some(fill_style_color) = state.fill_style.as_color()
+ && fill_style_color.alpha() > 0
+ {
+ alpha = (f32::from(fill_style_color.alpha()) / 255.0) * state.global_alpha;
+ }
+ if alpha == 0.0 {
+ return None;
+ }
+ let transform = multiply_transforms(
+ translated(
+ AffineTransform::identity(),
+ state.shadow_offset_x,
+ state.shadow_offset_y,
+ ),
+ state.transform,
+ );
+ Some((state.shadow_color.with_opacity(alpha), transform))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#drawing-model
+ /// 7. Composite B within the clipping region over the current output bitmap using the current compositing and
+ /// blending operator.
+ /// NB: A transparent source paint changes nothing only under source-over.
+ fn transparent_source_paint_can_be_ignored(state: &DrawingState) -> bool {
+ state.current_compositing_and_blending_operator == CompositingAndBlendingOperator::SourceOver
+ }
+
+ pub(crate) fn fill_internal(&self, path: &OwnedPath, winding_rule: WindingRule) {
+ if !self.recorder_is_ready() {
+ return;
+ }
+ {
+ let state = self.drawing_state();
+ if !state.fill_style.is_visible() && Self::transparent_source_paint_can_be_ignored(&state) {
+ return;
+ }
+ }
+
+ let path_bytes = path.serialize_to_bytes();
+ self.paint_shadow_for_fill_internal(&path_bytes, winding_rule);
+
+ {
+ let state = self.drawing_state();
+ self.record(|recorder| {
+ let paint = paint_of(recorder, &state.fill_style);
+ recorder.fill_path(&path_bytes, &paint, winding_rule, 0.0, &Self::compositing(&state));
+ });
+ }
+ self.did_draw();
+ }
+
+ /// `path_bytes` is a serialized Gfx::Path. The caller has readied the recorder.
+ fn paint_shadow_for_fill_internal(&self, path_bytes: &[u8], winding_rule: WindingRule) {
+ {
+ let state = self.drawing_state();
+ let Some((shadow_color, transform)) = Self::shadow_of(&state) else {
+ return;
+ };
+ self.record(|recorder| {
+ recorder.save();
+ recorder.set_transform(transform);
+ recorder.fill_path(
+ path_bytes,
+ &Paint::Color(shadow_color),
+ winding_rule,
+ state.shadow_blur,
+ &Self::shadow_compositing(&state),
+ );
+ recorder.restore();
+ });
+ }
+ self.did_draw();
+ }
+
+ pub(crate) fn stroke_internal(&self, path: &OwnedPath) {
+ if !self.recorder_is_ready() {
+ return;
+ }
+ {
+ let state = self.drawing_state();
+ if !state.stroke_style.is_visible() && Self::transparent_source_paint_can_be_ignored(&state) {
+ return;
+ }
+ }
+
+ let dash_array = self.drawing_state().dash_array();
+ let path_bytes = path.serialize_to_bytes();
+ self.paint_shadow_for_stroke_internal(&path_bytes, &dash_array);
+
+ {
+ let state = self.drawing_state();
+ let stroke = Stroke {
+ thickness: state.line_width,
+ cap_style: state.cap_style(),
+ join_style: state.join_style(),
+ miter_limit: state.miter_limit,
+ dash_array: &dash_array,
+ dash_offset: state.line_dash_offset,
+ };
+ self.record(|recorder| {
+ let paint = paint_of(recorder, &state.stroke_style);
+ recorder.stroke_path(&path_bytes, &paint, &stroke, 0.0, &Self::compositing(&state));
+ });
+ }
+ self.did_draw();
+ }
+
+ /// `path_bytes` is a serialized Gfx::Path. The caller has readied the recorder.
+ fn paint_shadow_for_stroke_internal(&self, path_bytes: &[u8], dash_array: &[f32]) {
+ {
+ let state = self.drawing_state();
+ let Some((shadow_color, transform)) = Self::shadow_of(&state) else {
+ return;
+ };
+ let stroke = Stroke {
+ thickness: state.line_width,
+ cap_style: state.cap_style(),
+ join_style: state.join_style(),
+ miter_limit: state.miter_limit,
+ dash_array,
+ dash_offset: state.line_dash_offset,
+ };
+ self.record(|recorder| {
+ recorder.save();
+ recorder.set_transform(transform);
+ recorder.stroke_path(
+ path_bytes,
+ &Paint::Color(shadow_color),
+ &stroke,
+ state.shadow_blur,
+ &Self::shadow_compositing(&state),
+ );
+ recorder.restore();
+ });
+ }
+ self.did_draw();
+ }
+
+ pub(crate) fn clip_internal(&self, path: &OwnedPath, winding_rule: WindingRule) {
+ if !self.recorder_is_ready() {
+ return;
+ }
+ let path_bytes = path.serialize_to_bytes();
+ self.record(|recorder| recorder.clip_path(&path_bytes, winding_rule));
+ }
+}
+
+/// The transform translated by (x, y) in its own coordinates, as Gfx::AffineTransform::translate().
+pub(crate) fn translated(transform: AffineTransform, x: f32, y: f32) -> AffineTransform {
+ let [a, b, c, d, e, f] = transform.values;
+ if a == 1.0 && b == 0.0 && c == 0.0 && d == 1.0 {
+ return AffineTransform::new(a, b, c, d, e + x, f + y);
+ }
+ AffineTransform::new(a, b, c, d, e + (x * a + y * c), f + (x * b + y * d))
+}
+
+/// The transform scaled by (x, y) in its own coordinates, as Gfx::AffineTransform::scale().
+pub(crate) fn scaled(transform: AffineTransform, x: f32, y: f32) -> AffineTransform {
+ let [a, b, c, d, e, f] = transform.values;
+ AffineTransform::new(a * x, b * x, c * y, d * y, e, f)
+}
+
+/// The transform multiplied by another, which applies first, as Gfx::AffineTransform::multiply().
+pub(crate) fn multiply_transforms(transform: AffineTransform, other: AffineTransform) -> AffineTransform {
+ if other.is_identity() {
+ return transform;
+ }
+ let [a, b, c, d, e, f] = transform.values;
+ let [oa, ob, oc, od, oe, of] = other.values;
+ AffineTransform::new(
+ oa * a + ob * c,
+ oa * b + ob * d,
+ oc * a + od * c,
+ oc * b + od * d,
+ oe * a + of * c + e,
+ oe * b + of * d + f,
+ )
+}
+
+/// The transform rotated by the angle in radians, as Gfx::AffineTransform::rotate_radians().
+pub(crate) fn rotated(transform: AffineTransform, radians: f32) -> AffineTransform {
+ let (sin, cos) = radians.sin_cos();
+ multiply_transforms(transform, AffineTransform::new(cos, sin, -sin, cos, 0.0, 0.0))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/drawing_state.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/drawing_state.rs
new file mode 100644
index 00000000000..dcc6cdadcd4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/drawing_state.rs
@@ -0,0 +1,269 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#drawing-state
+
+use std::rc::Rc;
+
+use ak::Utf16String;
+use libgfx_rust::{AffineTransform, CapStyle, Color, CompositingAndBlendingOperator, JoinStyle};
+use libjs_rust::api::{Trace, Visitor};
+
+use super::canvas::{ResolvedFont, StyleValue};
+use crate::bindings::interface::Ref;
+use crate::html::canvas_gradient::CanvasGradient;
+use crate::html::canvas_pattern::CanvasPattern;
+use crate::html::canvas_rendering_context2d::{
+ CanvasDirection, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, ImageSmoothingQuality,
+};
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-fillstyle
+#[derive(Clone, Copy)]
+pub(crate) enum FillOrStrokeStyle {
+ Color(Color),
+ Gradient(Ref<CanvasGradient>),
+ Pattern(Ref<CanvasPattern>),
+}
+
+impl FillOrStrokeStyle {
+ /// Whether a draw with the style can change a pixel.
+ pub(crate) fn is_visible(self) -> bool {
+ match self {
+ Self::Color(color) => color.alpha() > 0,
+ Self::Gradient(gradient) => gradient.is_visible(),
+ Self::Pattern(_) => true,
+ }
+ }
+
+ pub(crate) fn as_color(self) -> Option<Color> {
+ match self {
+ Self::Color(color) => Some(color),
+ Self::Gradient(_) | Self::Pattern(_) => None,
+ }
+ }
+}
+
+// SAFETY: Visits the gradient or the pattern, the cells that a style holds.
+unsafe impl Trace for FillOrStrokeStyle {
+ fn trace(&self, visitor: &mut Visitor) {
+ match self {
+ Self::Color(_) => {}
+ Self::Gradient(gradient) => gradient.trace(visitor),
+ Self::Pattern(pattern) => pattern.trace(visitor),
+ }
+ }
+}
+
+/// The letter spacing of a context, a CSS <length> as the context was given it.
+#[derive(Clone)]
+pub(crate) struct LetterSpacing {
+ pub(crate) length: StyleValue,
+ pub(crate) serialized: Utf16String,
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#drawing-state
+#[derive(Clone)]
+pub(crate) struct DrawingState {
+ pub(crate) transform: AffineTransform,
+ pub(crate) fill_style: FillOrStrokeStyle,
+ pub(crate) stroke_style: FillOrStrokeStyle,
+ pub(crate) shadow_offset_x: f32,
+ pub(crate) shadow_offset_y: f32,
+ pub(crate) shadow_blur: f32,
+ pub(crate) shadow_color: Color,
+ /// The serialized filter graph of the current filter, which the states share.
+ pub(crate) filter: Option<Rc<[u8]>>,
+ /// The value of the filter attribute, unless it is "none".
+ pub(crate) filter_string: Option<Utf16String>,
+ pub(crate) line_width: f32,
+ pub(crate) line_cap: CanvasLineCap,
+ pub(crate) line_join: CanvasLineJoin,
+ pub(crate) miter_limit: f32,
+ pub(crate) dash_list: Vec<f64>,
+ pub(crate) line_dash_offset: f32,
+ pub(crate) image_smoothing_enabled: bool,
+ pub(crate) image_smoothing_quality: ImageSmoothingQuality,
+ pub(crate) global_alpha: f32,
+ pub(crate) current_compositing_and_blending_operator: CompositingAndBlendingOperator,
+ /// The font, which is resolved the first time the context needs one.
+ pub(crate) font: Option<ResolvedFont>,
+ pub(crate) text_align: CanvasTextAlign,
+ pub(crate) text_baseline: CanvasTextBaseline,
+ pub(crate) direction: CanvasDirection,
+ /// The letter spacing, unless it is 0px.
+ pub(crate) letter_spacing: Option<LetterSpacing>,
+}
+
+impl Default for DrawingState {
+ fn default() -> Self {
+ Self {
+ transform: AffineTransform::identity(),
+ fill_style: FillOrStrokeStyle::Color(Color::from_rgb(0, 0, 0)),
+ stroke_style: FillOrStrokeStyle::Color(Color::from_rgb(0, 0, 0)),
+ shadow_offset_x: 0.0,
+ shadow_offset_y: 0.0,
+ shadow_blur: 0.0,
+ shadow_color: Color::TRANSPARENT,
+ filter: None,
+ filter_string: None,
+ line_width: 1.0,
+ line_cap: CanvasLineCap::Butt,
+ line_join: CanvasLineJoin::Miter,
+ miter_limit: 10.0,
+ dash_list: Vec::new(),
+ line_dash_offset: 0.0,
+ image_smoothing_enabled: true,
+ image_smoothing_quality: ImageSmoothingQuality::Low,
+ global_alpha: 1.0,
+ current_compositing_and_blending_operator: CompositingAndBlendingOperator::SourceOver,
+ font: None,
+ text_align: CanvasTextAlign::Start,
+ text_baseline: CanvasTextBaseline::Alphabetic,
+ direction: CanvasDirection::Inherit,
+ letter_spacing: None,
+ }
+ }
+}
+
+// SAFETY: Visits the fill and the stroke style, the cells that a drawing state holds.
+unsafe impl Trace for DrawingState {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.fill_style.trace(visitor);
+ self.stroke_style.trace(visitor);
+ }
+}
+
+impl DrawingState {
+ pub(crate) fn cap_style(&self) -> CapStyle {
+ match self.line_cap {
+ CanvasLineCap::Butt => CapStyle::Butt,
+ CanvasLineCap::Round => CapStyle::Round,
+ CanvasLineCap::Square => CapStyle::Square,
+ }
+ }
+
+ pub(crate) fn join_style(&self) -> JoinStyle {
+ match self.line_join {
+ CanvasLineJoin::Round => JoinStyle::Round,
+ CanvasLineJoin::Bevel => JoinStyle::Bevel,
+ CanvasLineJoin::Miter => JoinStyle::Miter,
+ }
+ }
+
+ /// The dash list in floats, as a stroke records it.
+ #[allow(
+ clippy::cast_possible_truncation,
+ reason = "a stroke records its dashes in floats, as the C++ did"
+ )]
+ pub(crate) fn dash_array(&self) -> Vec<f32> {
+ self.dash_list.iter().map(|&dash| dash as f32).collect()
+ }
+}
+
+/// The names of the compositing and blending operators that globalCompositeOperation takes, in the order that the
+/// getter of the C++ looked the operator up in.
+const COMPOSITE_OPERATIONS: [(&str, CompositingAndBlendingOperator); 30] = [
+ ("normal", CompositingAndBlendingOperator::Normal),
+ ("multiply", CompositingAndBlendingOperator::Multiply),
+ ("screen", CompositingAndBlendingOperator::Screen),
+ ("overlay", CompositingAndBlendingOperator::Overlay),
+ ("darken", CompositingAndBlendingOperator::Darken),
+ ("lighten", CompositingAndBlendingOperator::Lighten),
+ ("color-dodge", CompositingAndBlendingOperator::ColorDodge),
+ ("color-burn", CompositingAndBlendingOperator::ColorBurn),
+ ("hard-light", CompositingAndBlendingOperator::HardLight),
+ ("soft-light", CompositingAndBlendingOperator::SoftLight),
+ ("difference", CompositingAndBlendingOperator::Difference),
+ ("exclusion", CompositingAndBlendingOperator::Exclusion),
+ ("hue", CompositingAndBlendingOperator::Hue),
+ ("saturation", CompositingAndBlendingOperator::Saturation),
+ ("color", CompositingAndBlendingOperator::Color),
+ ("luminosity", CompositingAndBlendingOperator::Luminosity),
+ ("clear", CompositingAndBlendingOperator::Clear),
+ ("copy", CompositingAndBlendingOperator::Copy),
+ ("source-over", CompositingAndBlendingOperator::SourceOver),
+ ("destination-over", CompositingAndBlendingOperator::DestinationOver),
+ ("source-in", CompositingAndBlendingOperator::SourceIn),
+ ("destination-in", CompositingAndBlendingOperator::DestinationIn),
+ ("source-out", CompositingAndBlendingOperator::SourceOut),
+ ("destination-out", CompositingAndBlendingOperator::DestinationOut),
+ ("source-atop", CompositingAndBlendingOperator::SourceATop),
+ ("destination-atop", CompositingAndBlendingOperator::DestinationATop),
+ ("xor", CompositingAndBlendingOperator::Xor),
+ ("lighter", CompositingAndBlendingOperator::Lighter),
+ ("plus-darker", CompositingAndBlendingOperator::PlusDarker),
+ ("plus-lighter", CompositingAndBlendingOperator::PlusLighter),
+];
+
+/// The name of a compositing and blending operator, which every operator that a context can have has.
+pub(crate) fn composite_operation_name(operator: CompositingAndBlendingOperator) -> &'static str {
+ COMPOSITE_OPERATIONS
+ .iter()
+ .find(|(_, candidate)| *candidate == operator)
+ .map(|(name, _)| *name)
+ .expect("a context has an operator that globalCompositeOperation names")
+}
+
+/// The compositing and blending operator that a string names exactly, if it names one.
+pub(crate) fn composite_operation_named(name: &Utf16String) -> Option<CompositingAndBlendingOperator> {
+ let units = name.to_utf16();
+ COMPOSITE_OPERATIONS
+ .iter()
+ .find(|(candidate, _)| candidate.encode_utf16().eq(units.iter().copied()))
+ .map(|(_, operator)| *operator)
+}
+
+/// A color as the attributes of a context serialize it, with HTML-compatible serialization requested.
+/// https://html.spec.whatwg.org/multipage/infrastructure.html#serialisation-of-a-color
+/// https://drafts.csswg.org/css-color-4/#HTML-compatible-serialization-of-srgb
+pub(crate) fn serialize_color(color: Color) -> Utf16String {
+ // NB: Our colors are always sRGB with 8-bit components, and HTML-compatible serialization is always requested
+ // here, so only the alpha decides which serialization is used.
+ // If the following conditions are all true:
+ // 1. The color space is sRGB
+ // 2. The alpha is 1
+ // 3. The RGB component values are internally represented as integers between 0 and 255 inclusive (i.e. 8-bit
+ // unsigned integer)
+ // 4. HTML-compatible serialization is requested
+ // Then corresponding sRGB values are serialized in 6-digit hex color notation as follows:
+ // A seven-character string consisting of the character "#", followed immediately by the two-digit hexadecimal
+ // representations of the red component, the green component, and the blue component, in that order, using ASCII
+ // lower hex digits. No spaces are permitted.
+ if color.alpha() == 255 {
+ let serialized = format!("#{:02x}{:02x}{:02x}", color.red(), color.green(), color.blue());
+ return Utf16String::from_ascii(serialized.as_bytes());
+ }
+ // Otherwise, for sRGB the CSS serialization of sRGB values is used and for other color spaces, the relevant
+ // serialization of the <color> value.
+ let serialized = if color.alpha() == 0 {
+ format!("rgba({}, {}, {}, 0)", color.red(), color.green(), color.blue())
+ } else {
+ format!(
+ "rgba({}, {}, {}, 0.{})",
+ color.red(),
+ color.green(),
+ color.blue(),
+ alpha_digits(color.alpha())
+ )
+ };
+ Utf16String::from_ascii(serialized.as_bytes())
+}
+
+/// The shortest fractional digits of an 8-bit alpha that read back as it, as format_to_8bit_compatible() of
+/// LibGfx/Color.cpp writes them: 127 is "498", and 128 is "5".
+fn alpha_digits(value: u8) -> String {
+ let value = u32::from(value);
+ let three_digits = (value * 1000 + 127) / 255;
+ let rounded_to_two_digits = (three_digits + 5) / 10 * 10;
+ if (rounded_to_two_digits * 255 / 100 + 5) / 10 != value {
+ return format!("{three_digits:03}");
+ }
+ let rounded_to_one_digit = (three_digits + 50) / 100 * 100;
+ if (rounded_to_one_digit * 255 / 100 + 5) / 10 != value {
+ return format!("{:02}", rounded_to_two_digits / 10);
+ }
+ format!("{}", rounded_to_one_digit / 100)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
index 155bac700a7..68c74bd0006 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs
@@ -4,260 +4,208 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The C ABI through which the 2D canvas contexts of LibWeb record, which Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp
-//! declares. A recorder owns the transport it records through. The structs in which C++ lends a paint, a stroke and how
-//! a draw composites are those of display_list/canvas_2d_recorder.rs, which LibCompositing/RustFFI.h declares to C++.
+//! The C ABI that Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp declares, and calls with the cell of a context
+//! of either kind.
use core::ffi::c_void;
+use core::marker::PhantomData;
use core::ptr::NonNull;
-use libcompositing_rust::display_list::canvas_2d::Paint;
-use libcompositing_rust::display_list::canvas_2d_recorder::{
- AlphaType, FfiCanvas2DCompositing, FfiCanvas2DPaint, FfiCanvas2DStroke, Recorder,
-};
-use libcompositing_rust::display_list::commands::{Canvas2DPaintKind, CanvasId, DisplayListGlyph};
-use libgfx_rust::{AffineTransform, Color, FloatPoint, FloatRect, IntRect, IntSize, ScalingMode, WindingRule};
-
-use super::host::{CppTransport, LentFont, LentImageFrame, LentVideoFrameHold};
-
-pub(crate) type CanvasRecorder = Recorder<CppTransport>;
-
-/// The paint, with the image of a pattern added to the stream.
-fn paint_of<'a>(recorder: &CanvasRecorder, paint: &FfiCanvas2DPaint<'a>) -> Paint<'a> {
- let pattern_image = match paint.kind {
- Canvas2DPaintKind::Pattern => {
- NonNull::new(paint.pattern_image.cast_mut()).map(|frame| recorder.add_image_frame(&LentImageFrame(frame)))
- }
- _ => None,
- };
- paint.to_paint(pattern_image)
-}
-
-/// # Safety
-///
-/// `transport` is a RemoteCanvas2DTransport, one reference to which the recorder takes over.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_2d_recorder_create(transport: *mut c_void) -> *mut CanvasRecorder {
- let transport = NonNull::new(transport).expect("C++ passes the transport");
- // SAFETY: The caller hands over a reference to the transport.
- let transport = unsafe { CppTransport::from_raw(transport) };
- Box::into_raw(Box::new(Recorder::new(transport)))
-}
-
-/// # Safety
-///
-/// `recorder` comes from web_canvas_2d_recorder_create(), and nothing uses it after this.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_2d_recorder_destroy(recorder: *mut CanvasRecorder) {
- assert!(!recorder.is_null());
- // SAFETY: The caller passes a recorder that web_canvas_2d_recorder_create() leaked.
- drop(unsafe { Box::from_raw(recorder) });
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_create_context(
- recorder: &CanvasRecorder,
+use libcompositing_rust::display_list::canvas_2d_recorder::AlphaType;
+use libgfx_rust::{IntRect, IntSize};
+
+use super::canvas::Canvas;
+use super::context::{ContextParameters, ContextState, Offscreen, OnScreen, RenderingContext2D};
+use crate::bindings::interface::{Interface, allocate, cell_from_abi, cell_into_abi};
+use crate::html::canvas_draw_image::CanvasImageSource;
+use crate::html::canvas_rendering_context2d_settings::{CanvasColorType, CanvasRenderingContext2DSettings};
+use crate::html::image_bitmap::ImageBitmap;
+use crate::html::predefined_color_space::PredefinedColorSpace;
+
+/// Mirrors `Web::HTML::ContextCreationArguments`.
+#[repr(C)]
+pub struct ContextCreationArguments {
+ canvas: *mut c_void,
+ canvas_host: *mut c_void,
+ canvas_is_offscreen: bool,
width: i32,
height: i32,
alpha: bool,
-) -> bool {
- recorder.create_context(IntSize { width, height }, alpha)
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_canvas_id(recorder: &CanvasRecorder, out_canvas_id: &mut u64) -> bool {
- let Some(canvas_id) = recorder.canvas_id() else {
- return false;
- };
- *out_canvas_id = canvas_id.0;
- true
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_destroy_context(recorder: &CanvasRecorder) {
- recorder.destroy_context();
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_flush(recorder: &CanvasRecorder) {
- recorder.flush();
+ desynchronized: bool,
+ /// The underlying value of a Web::Bindings::PredefinedColorSpace.
+ color_space: u8,
+ /// The underlying value of a Web::Bindings::CanvasColorType.
+ color_type: u8,
+ will_read_frequently: bool,
+}
+
+/// The cell of a CanvasRenderingContext2D or of an OffscreenCanvasRenderingContext2D, which only C++ lends out, for as
+/// long as the context is live.
+#[repr(C)]
+pub struct ContextCell {
+ // NB: The cell is mutable behind a shared reference, and bigger than Rust sees, so a reference to one must not tell
+ // the compiler that the memory behind it is read only or unaliased.
+ _opaque: core::cell::UnsafeCell<[u8; 0]>,
+ _not_send_sync_or_unpin: PhantomData<(*const (), core::marker::PhantomPinned)>,
+}
+
+fn with_context<R>(context: &ContextCell, function: impl FnOnce(&ContextState) -> R) -> R {
+ let cell = NonNull::from(context).cast();
+ // SAFETY: A ContextCell is the live cell of one of the two classes, which the downcasts tell apart.
+ unsafe {
+ if let Some(context) = RenderingContext2D::<OnScreen>::CELL_CLASS.downcast(cell) {
+ return function(&context);
+ }
+ let context = RenderingContext2D::<Offscreen>::CELL_CLASS
+ .downcast(cell)
+ .expect("the cell is a 2D context");
+ function(&context)
+ }
}
-/// Returns a Gfx::Bitmap with one reference, which the caller takes over, or null.
+/// # Safety
+///
+/// `vm` is the live VM, and the pointers of the arguments are what [`ContextCreationArguments`] describes.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_read_back_pixels(
- recorder: &CanvasRecorder,
- rect: IntRect,
- alpha_type: AlphaType,
+pub unsafe extern "C" fn web_canvas_2d_context_create(
+ vm: *mut c_void,
+ arguments: &ContextCreationArguments,
) -> *mut c_void {
- recorder
- .read_back_pixels(rect, alpha_type)
- .map_or(core::ptr::null_mut(), |bitmap| bitmap.into_raw())
+ assert!(!vm.is_null(), "C++ passes the VM");
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { &*vm.cast::<libjs_rust::api::Vm>() };
+ let canvas = Canvas {
+ cell: NonNull::new(arguments.canvas).expect("C++ passes the canvas"),
+ host: NonNull::new(arguments.canvas_host).expect("C++ passes the canvas"),
+ is_offscreen: arguments.canvas_is_offscreen,
+ };
+ let state = ContextState::new(ContextParameters {
+ canvas,
+ context_attributes: CanvasRenderingContext2DSettings {
+ alpha: arguments.alpha,
+ desynchronized: arguments.desynchronized,
+ color_space: PredefinedColorSpace::from_u8(arguments.color_space).expect("C++ passes a color space"),
+ color_type: CanvasColorType::from_u8(arguments.color_type).expect("C++ passes a color type"),
+ will_read_frequently: arguments.will_read_frequently,
+ },
+ size: IntSize {
+ width: arguments.width,
+ height: arguments.height,
+ },
+ });
+ if arguments.canvas_is_offscreen {
+ cell_into_abi(allocate(vm, RenderingContext2D::<Offscreen>::new(state)))
+ } else {
+ cell_into_abi(allocate(vm, RenderingContext2D::<OnScreen>::new(state)))
+ }
}
+/// The Web::HTML::CanvasHost of the canvas of the context.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_present(recorder: &CanvasRecorder) {
- recorder.present();
+pub extern "C" fn web_canvas_2d_context_canvas_host(context: &ContextCell) -> *mut c_void {
+ with_context(context, |context| context.canvas_handle().host.as_ptr())
}
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_prepare_to_record(recorder: &CanvasRecorder) {
- recorder.prepare_to_record();
+pub extern "C" fn web_canvas_2d_context_origin_clean(context: &ContextCell) -> bool {
+ with_context(context, ContextState::origin_clean)
}
-/// `path` is a serialized Gfx::Path.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_fill_path(
- recorder: &mut CanvasRecorder,
- path: ak::Span<'_, u8>,
- paint: &FfiCanvas2DPaint<'_>,
- winding_rule: WindingRule,
- blur_radius: f32,
- compositing: &FfiCanvas2DCompositing<'_>,
-) {
- let paint = paint_of(recorder, paint);
- recorder.fill_path(
- path.as_slice(),
- &paint,
- winding_rule,
- blur_radius,
- &compositing.to_compositing(),
- );
+pub extern "C" fn web_canvas_2d_context_set_size(context: &ContextCell, width: i32, height: i32) {
+ with_context(context, |context| context.set_size(IntSize { width, height }));
}
-/// `path` is a serialized Gfx::Path.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_stroke_path(
- recorder: &mut CanvasRecorder,
- path: ak::Span<'_, u8>,
- paint: &FfiCanvas2DPaint<'_>,
- stroke: &FfiCanvas2DStroke<'_>,
- blur_radius: f32,
- compositing: &FfiCanvas2DCompositing<'_>,
-) {
- let paint = paint_of(recorder, paint);
- recorder.stroke_path(
- path.as_slice(),
- &paint,
- &stroke.to_stroke(),
- blur_radius,
- &compositing.to_compositing(),
- );
+pub extern "C" fn web_canvas_2d_context_reset_to_default_state(context: &ContextCell) {
+ with_context(context, ContextState::reset_to_default_state);
}
-/// `font` is a Gfx::Font that the caller lends for the call.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_draw_glyph_run(
- recorder: &mut CanvasRecorder,
- font: *const c_void,
- glyphs: ak::Span<'_, DisplayListGlyph>,
- translation: FloatPoint,
- paint: &FfiCanvas2DPaint<'_>,
- compositing: &FfiCanvas2DCompositing<'_>,
-) {
- let font = LentFont(NonNull::new(font.cast_mut()).expect("C++ passes the font"));
- let paint = paint_of(recorder, paint);
- recorder.draw_glyph_run(
- &font,
- glyphs.as_slice(),
- translation,
- &paint,
- &compositing.to_compositing(),
- );
+pub extern "C" fn web_canvas_2d_context_ensure_backing_storage(context: &ContextCell) {
+ with_context(context, ContextState::ensure_backing_storage);
}
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_clear_rect(recorder: &mut CanvasRecorder, rect: FloatRect, color: Color) {
- recorder.clear_rect(rect, color);
+pub extern "C" fn web_canvas_2d_context_discard_backing_storage(context: &ContextCell) {
+ with_context(context, ContextState::discard_backing_storage);
}
-/// `frame` is a Gfx::DecodedImageFrame that the caller lends for the call.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_draw_image_frame(
- recorder: &mut CanvasRecorder,
- frame: *const c_void,
- dst_rect: FloatRect,
- src_rect: IntRect,
- scaling_mode: ScalingMode,
- compositing: &FfiCanvas2DCompositing<'_>,
-) {
- let frame = LentImageFrame(NonNull::new(frame.cast_mut()).expect("C++ passes the frame"));
- recorder.draw_image_frame(&frame, dst_rect, src_rect, scaling_mode, &compositing.to_compositing());
+pub extern "C" fn web_canvas_2d_context_has_backing_storage(context: &ContextCell) -> bool {
+ with_context(context, ContextState::has_backing_storage)
}
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_draw_canvas(
- recorder: &mut CanvasRecorder,
- source_canvas_id: u64,
- dst_rect: FloatRect,
- src_rect: IntRect,
- scaling_mode: ScalingMode,
- compositing: &FfiCanvas2DCompositing<'_>,
-) {
- recorder.draw_canvas(
- CanvasId(source_canvas_id),
- dst_rect,
- src_rect,
- scaling_mode,
- &compositing.to_compositing(),
- );
+pub extern "C" fn web_canvas_2d_context_drop_cached_readback(context: &ContextCell) {
+ with_context(context, ContextState::drop_cached_readback);
}
-/// `hold` is a Compositing::VideoFrameHold that the caller lends for the call.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_draw_video_frame(
- recorder: &mut CanvasRecorder,
- hold: *mut c_void,
- video_sink_handle: u64,
- generation: u64,
- dst_rect: FloatRect,
- src_rect: IntRect,
- scaling_mode: ScalingMode,
- compositing: &FfiCanvas2DCompositing<'_>,
-) {
- let hold = LentVideoFrameHold(NonNull::new(hold).expect("C++ passes the hold"));
- recorder.draw_video_frame(
- &hold,
- video_sink_handle,
- generation,
- dst_rect,
- src_rect,
- scaling_mode,
- &compositing.to_compositing(),
- );
+pub extern "C" fn web_canvas_2d_context_is_lost(context: &ContextCell) -> bool {
+ with_context(context, ContextState::context_is_lost)
}
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_set_transform(recorder: &mut CanvasRecorder, transform: &AffineTransform) {
- recorder.set_transform(*transform);
+pub extern "C" fn web_canvas_2d_context_set_lost(context: &ContextCell, lost: bool) {
+ with_context(context, |context| context.set_context_lost(lost));
}
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_save(recorder: &mut CanvasRecorder) {
- recorder.save();
+pub extern "C" fn web_canvas_2d_context_prepare_for_compositing(context: &ContextCell) {
+ with_context(context, ContextState::prepare_for_compositing);
}
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_restore(recorder: &mut CanvasRecorder) {
- recorder.restore();
+pub extern "C" fn web_canvas_2d_context_canvas_id(context: &ContextCell, out_canvas_id: &mut u64) -> bool {
+ let Some(canvas_id) = with_context(context, ContextState::canvas_id) else {
+ return false;
+ };
+ *out_canvas_id = canvas_id.0;
+ true
}
-/// `path` is a serialized Gfx::Path.
+/// A Gfx::Bitmap with a reference that the caller takes over, or null. Unpremultiplied pixels come back as RGBA8888,
+/// and premultiplied pixels as BGRA8888.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_clip_path(
- recorder: &mut CanvasRecorder,
- path: ak::Span<'_, u8>,
- winding_rule: WindingRule,
-) {
- recorder.clip_path(path.as_slice(), winding_rule);
+pub extern "C" fn web_canvas_2d_context_read_pixels(
+ context: &ContextCell,
+ rect: IntRect,
+ alpha_type: AlphaType,
+) -> *mut c_void {
+ with_context(context, |context| context.read_pixels(rect, alpha_type))
+ .map_or(core::ptr::null_mut(), super::host::Bitmap::into_raw)
}
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_reset(recorder: &mut CanvasRecorder) {
- recorder.reset();
+pub extern "C" fn web_canvas_2d_context_replace_bitmap_with_cleared_bitmap(context: &ContextCell) {
+ with_context(context, ContextState::replace_bitmap_with_cleared_bitmap);
}
+/// Draws the ImageBitmap at the point as drawImage() does, and returns whether that threw nothing.
+///
+/// # Safety
+///
+/// `image_bitmap` must be a live cell of an ImageBitmap.
#[unsafe(no_mangle)]
-pub extern "C" fn web_canvas_2d_recorder_clear_canvas(recorder: &mut CanvasRecorder, color: Color) {
- recorder.clear_canvas(color);
+pub unsafe extern "C" fn web_canvas_2d_context_draw_image_bitmap(
+ context: &ContextCell,
+ image_bitmap: *mut c_void,
+ x: f32,
+ y: f32,
+) -> bool {
+ // SAFETY: The caller passes a live cell of an ImageBitmap.
+ let image_bitmap = unsafe { cell_from_abi::<ImageBitmap>(image_bitmap) };
+ let image = CanvasImageSource::ImageBitmap(image_bitmap);
+ let (width, height) = image.size();
+ #[allow(
+ clippy::cast_precision_loss,
+ reason = "a size of an image becomes a float, as the C++ had it"
+ )]
+ let (width, height) = (width as f32, height as f32);
+ with_context(context, |context| {
+ context
+ .draw_image_internal(image, 0.0, 0.0, width, height, x, y, width, height)
+ .is_ok()
+ })
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs
index 603af4ee28c..df8f05c5230 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs
@@ -12,6 +12,7 @@ use core::ptr::NonNull;
use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, Transport};
use libcompositing_rust::display_list::commands::{CanvasId, FontResourceId, ImageFrameResourceId};
+use libgfx_rust::image_frame::ImageFrameHandle;
use libgfx_rust::{IntRect, IntSize};
unsafe extern "C" {
@@ -34,7 +35,17 @@ unsafe extern "C" {
height: i32,
alpha_type: AlphaType,
) -> *mut c_void;
+ fn web_canvas_2d_bitmap_ref(bitmap: *mut c_void);
fn web_canvas_2d_bitmap_unref(bitmap: *mut c_void);
+ fn web_canvas_2d_bitmap_size_in_bytes(bitmap: *mut c_void) -> usize;
+ fn web_canvas_2d_image_frame_from_bitmap(bitmap: *mut c_void) -> *mut c_void;
+ fn web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(
+ bitmap: *mut c_void,
+ out_pixels: *mut *const u8,
+ out_pitch: *mut usize,
+ out_width: *mut i32,
+ out_height: *mut i32,
+ ) -> bool;
}
/// A Gfx::Font that C++ lends.
@@ -49,12 +60,64 @@ pub(crate) struct LentVideoFrameHold(pub(crate) NonNull<c_void>);
/// A Gfx::Bitmap, one reference to which the value owns.
pub(crate) struct Bitmap(NonNull<c_void>);
+/// The pixels of a bitmap that are RGBA8888 and unpremultiplied, as a readback of a canvas gives them: `height` rows of
+/// `width` pixels, `pitch` bytes apart.
+pub(crate) struct UnpremultipliedRgbaPixels {
+ pub(crate) first_row: NonNull<u8>,
+ pub(crate) pitch: usize,
+ pub(crate) width: i32,
+ pub(crate) height: i32,
+}
+
+// SAFETY (of every call below): The value owns a reference to the bitmap.
impl Bitmap {
pub(crate) fn into_raw(self) -> *mut c_void {
let bitmap = self.0.as_ptr();
core::mem::forget(self);
bitmap
}
+
+ /// A frame of the bitmap, which the frame keeps alive.
+ pub(crate) fn into_image_frame(self) -> ImageFrameHandle {
+ let frame = unsafe { web_canvas_2d_image_frame_from_bitmap(self.into_raw()) };
+ // SAFETY: LibWeb hands over a frame that it allocated with new, which took over the reference to the bitmap.
+ unsafe { ImageFrameHandle::adopt(frame) }
+ }
+
+ pub(crate) fn size_in_bytes(&self) -> usize {
+ unsafe { web_canvas_2d_bitmap_size_in_bytes(self.0.as_ptr()) }
+ }
+
+ /// The pixels, which stay valid while the value lives, if the bitmap is RGBA8888 and unpremultiplied.
+ pub(crate) fn unpremultiplied_rgba_pixels(&self) -> Option<UnpremultipliedRgbaPixels> {
+ let (mut first_row, mut pitch, mut width, mut height) = (core::ptr::null(), 0, 0, 0);
+ let is_rgba = unsafe {
+ web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(
+ self.0.as_ptr(),
+ &raw mut first_row,
+ &raw mut pitch,
+ &raw mut width,
+ &raw mut height,
+ )
+ };
+ if !is_rgba {
+ return None;
+ }
+ Some(UnpremultipliedRgbaPixels {
+ first_row: NonNull::new(first_row.cast_mut()).expect("a bitmap has pixels"),
+ pitch,
+ width,
+ height,
+ })
+ }
+}
+
+impl Clone for Bitmap {
+ fn clone(&self) -> Self {
+ // SAFETY: The value owns a reference to the bitmap, so it is live.
+ unsafe { web_canvas_2d_bitmap_ref(self.0.as_ptr()) };
+ Self(self.0)
+ }
}
impl Drop for Bitmap {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/mod.rs
index 1df6d312b45..99491163246 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/mod.rs
@@ -4,11 +4,33 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The WebContent half of the 2D canvas, which records the commands of a canvas for the Compositor. The recorder and
-//! the records are those of the display list tape (Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs); what
-//! is here reaches LibWeb, which the tests of the crate do not link.
+//! The WebContent half of the 2D canvas: the state that the two kinds of 2D context share, which records the commands
+//! of a canvas for the Compositor. The recorder and the records are those of the display list tape
+//! (Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs); the attributes and operations of the contexts are
+//! in the modules of their IDL files in crate::html. What is here reaches LibWeb, which the tests of the crate do not
+//! link.
+#[cfg(not(test))]
+pub(crate) mod canvas;
+#[cfg(not(test))]
+pub(crate) mod context;
+#[cfg(not(test))]
+pub(crate) mod drawing_state;
#[cfg(not(test))]
pub(crate) mod exports;
#[cfg(not(test))]
pub(crate) mod host;
+#[cfg(not(test))]
+pub(crate) mod path;
+#[cfg(not(test))]
+pub(crate) mod text;
+
+/// A number of an argument in a float, as the C++ contexts took most of their numbers.
+#[cfg(not(test))]
+#[allow(
+ clippy::cast_possible_truncation,
+ reason = "these operations take floats, as the C++ did"
+)]
+pub(crate) fn float(number: f64) -> f32 {
+ number as f32
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/path.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/path.rs
new file mode 100644
index 00000000000..985e634ba0c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/path.rs
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The operations of the CanvasPath mixin on the current default path of a 2D context, whose steps are in
+//! html/canvas_path.rs.
+
+use libgfx_rust::path::PathMut;
+
+use super::context::{CanvasKind, RenderingContext2D};
+use super::float;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::html::canvas_path::{
+ self, UnrestrictedDoubleOrDOMPointInitOrUnrestrictedDoubleOrDOMPointInitSequence, round_rect_radii,
+};
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ fn build_path<R>(&self, function: impl FnOnce(&mut PathMut<'_>) -> R) -> R {
+ let mut path = self.path_mut();
+ function(&mut path.as_path_mut())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-closepath
+ pub(crate) fn close_path(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.build_path(|path| canvas_path::close_path(path));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-moveto
+ pub(crate) fn move_to(&self, _: &mut CallContext, x: f64, y: f64) -> WebIdlResult<()> {
+ self.build_path(|path| canvas_path::move_to(path, float(x), float(y)));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-lineto
+ pub(crate) fn line_to(&self, _: &mut CallContext, x: f64, y: f64) -> WebIdlResult<()> {
+ self.build_path(|path| canvas_path::line_to(path, float(x), float(y)));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-quadraticcurveto
+ pub(crate) fn quadratic_curve_to(
+ &self,
+ _: &mut CallContext,
+ cpx: f64,
+ cpy: f64,
+ x: f64,
+ y: f64,
+ ) -> WebIdlResult<()> {
+ self.build_path(|path| canvas_path::quadratic_curve_to(path, float(cpx), float(cpy), float(x), float(y)));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-beziercurveto
+ #[allow(clippy::too_many_arguments, reason = "the arguments of bezierCurveTo()")]
+ pub(crate) fn bezier_curve_to(
+ &self,
+ _: &mut CallContext,
+ cp1x: f64,
+ cp1y: f64,
+ cp2x: f64,
+ cp2y: f64,
+ x: f64,
+ y: f64,
+ ) -> WebIdlResult<()> {
+ self.build_path(|path| canvas_path::bezier_curve_to(path, cp1x, cp1y, cp2x, cp2y, x, y));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-arcto
+ #[allow(clippy::too_many_arguments, reason = "the arguments of arcTo()")]
+ pub(crate) fn arc_to(
+ &self,
+ _: &mut CallContext,
+ x1: f64,
+ y1: f64,
+ x2: f64,
+ y2: f64,
+ radius: f64,
+ ) -> WebIdlResult<()> {
+ let transform = self.drawing_state().transform;
+ self.build_path(|path| canvas_path::arc_to(path, transform, x1, y1, x2, y2, radius))?;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-rect
+ pub(crate) fn rect(&self, _: &mut CallContext, x: f64, y: f64, w: f64, h: f64) -> WebIdlResult<()> {
+ self.build_path(|path| canvas_path::rect(path, x, y, w, h));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-roundrect
+ #[allow(clippy::too_many_arguments, reason = "the arguments of roundRect()")]
+ pub(crate) fn round_rect(
+ &self,
+ _: &mut CallContext,
+ x: f64,
+ y: f64,
+ w: f64,
+ h: f64,
+ radii: UnrestrictedDoubleOrDOMPointInitOrUnrestrictedDoubleOrDOMPointInitSequence,
+ ) -> WebIdlResult<()> {
+ let radii = round_rect_radii(radii);
+ self.build_path(|path| canvas_path::round_rect(path, x, y, w, h, &radii))?;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-arc
+ #[allow(clippy::too_many_arguments, reason = "the arguments of arc()")]
+ pub(crate) fn arc(
+ &self,
+ _: &mut CallContext,
+ x: f64,
+ y: f64,
+ radius: f64,
+ start_angle: f64,
+ end_angle: f64,
+ counterclockwise: bool,
+ ) -> WebIdlResult<()> {
+ self.build_path(|path| {
+ canvas_path::arc(
+ path,
+ float(x),
+ float(y),
+ float(radius),
+ float(start_angle),
+ float(end_angle),
+ counterclockwise,
+ )
+ })?;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-ellipse
+ #[allow(clippy::too_many_arguments, reason = "the arguments of ellipse()")]
+ pub(crate) fn ellipse(
+ &self,
+ _: &mut CallContext,
+ x: f64,
+ y: f64,
+ radius_x: f64,
+ radius_y: f64,
+ rotation: f64,
+ start_angle: f64,
+ end_angle: f64,
+ counterclockwise: bool,
+ ) -> WebIdlResult<()> {
+ self.build_path(|path| {
+ canvas_path::ellipse(
+ path,
+ float(x),
+ float(y),
+ float(radius_x),
+ float(radius_y),
+ float(rotation),
+ float(start_angle),
+ float(end_angle),
+ counterclockwise,
+ )
+ })?;
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/text.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/text.rs
new file mode 100644
index 00000000000..037048f1d23
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/text.rs
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The text of a 2D context: shaping it across the fonts of the cascade of the font of the context, laying it out
+//! as the text preparation algorithm does, and its outlines.
+
+use libgfx_rust::font::{EmojiPresentation, FontCascadeListHandle, FontHandle};
+use libgfx_rust::path::{GlyphRun, OwnedPath};
+use libgfx_rust::text_layout::{DrawGlyph, TextType, shape_text as shape_text_in_font};
+use libgfx_rust::{AffineTransform, FloatPoint};
+
+use super::context::multiply_transforms;
+use super::drawing_state::DrawingState;
+use crate::html::canvas_rendering_context2d::{CanvasDirection, CanvasTextAlign, CanvasTextBaseline};
+
+/// A run of the text that one font of the cascade shapes.
+pub(crate) struct ShapedRun {
+ pub(crate) font: FontHandle,
+ pub(crate) glyphs: Vec<DrawGlyph>,
+ pub(crate) width: f32,
+}
+
+/// The code point at the index of the code units and how many code units it takes, as AK::Utf16View iterates them: a
+/// surrogate that is not part of a pair is a code point of its own.
+fn code_point_at(text: &[u16], index: usize) -> (u32, usize) {
+ let code_unit = text[index];
+ if (0xD800..0xDC00).contains(&code_unit)
+ && let Some(&next_code_unit) = text.get(index + 1)
+ && (0xDC00..0xE000).contains(&next_code_unit)
+ {
+ let code_point = 0x10000 + ((u32::from(code_unit) - 0xD800) << 10) + (u32::from(next_code_unit) - 0xDC00);
+ return (code_point, 2);
+ }
+ (u32::from(code_unit), 1)
+}
+
+/// The text shaped from the baseline start, with a run for each part of it that one font of the cascade draws, as
+/// Gfx::shape_text() shapes it across a Gfx::FontCascadeList.
+pub(crate) fn shape_text(
+ cascade: &FontCascadeListHandle,
+ text: &[u16],
+ baseline_start: FloatPoint,
+ letter_spacing: f32,
+) -> Vec<ShapedRun> {
+ const TEXT_PRESENTATION: EmojiPresentation = EmojiPresentation {
+ is_emoji: false,
+ forced: false,
+ };
+
+ let mut runs = Vec::new();
+ if text.is_empty() {
+ return runs;
+ }
+
+ let mut last_position = baseline_start;
+ let mut add_run = |text: &[u16], font: &FontHandle| {
+ let shaped = shape_text_in_font(font, text, TextType::Common, 0.0, letter_spacing, 0.0);
+ let mut glyphs = shaped.glyphs().to_vec();
+ if last_position.x != 0.0 || last_position.y != 0.0 {
+ for glyph in &mut glyphs {
+ glyph.x += last_position.x;
+ glyph.y += last_position.y;
+ }
+ }
+ last_position.x += shaped.width();
+ runs.push(ShapedRun {
+ font: font.clone(),
+ glyphs,
+ width: shaped.width(),
+ });
+ };
+
+ let (first_code_point, _) = code_point_at(text, 0);
+ let mut last_font = cascade.font_for_code_point(first_code_point, TEXT_PRESENTATION, None);
+ let mut run_start = 0;
+ let mut index = 0;
+ while index < text.len() {
+ let (code_point, length) = code_point_at(text, index);
+ let font = cascade.font_for_code_point(code_point, TEXT_PRESENTATION, Some(&last_font));
+ if font.as_raw() != last_font.as_raw() {
+ add_run(&text[run_start..index], &last_font);
+ last_font = font;
+ run_start = index;
+ }
+ index += length;
+ }
+ if run_start < text.len() {
+ add_run(&text[run_start..], &last_font);
+ }
+ runs
+}
+
+/// The outlines of the glyphs of the runs, as one path.
+pub(crate) fn path_of_runs(runs: &[ShapedRun]) -> OwnedPath {
+ let glyph_runs: Vec<GlyphRun> = runs
+ .iter()
+ .map(|run| GlyphRun {
+ font: run.font.clone(),
+ glyphs: run.glyphs.clone(),
+ })
+ .collect();
+ OwnedPath::from_glyph_runs(&glyph_runs)
+}
+
+/// The distance from the alphabetic baseline down to the baseline that textBaseline names, in the metrics of the
+/// first font of the cascade, https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textbaseline
+pub(crate) fn baseline_offset(text_baseline: CanvasTextBaseline, first_font: &FontHandle) -> f32 {
+ let ascent = first_font.facts().ascent;
+ let descent = first_font.facts().descent;
+ match text_baseline {
+ CanvasTextBaseline::Top => ascent,
+ CanvasTextBaseline::Hanging => ascent * 0.8,
+ CanvasTextBaseline::Middle => (ascent - descent) / 2.0,
+ CanvasTextBaseline::Alphabetic => 0.0,
+ CanvasTextBaseline::Ideographic | CanvasTextBaseline::Bottom => -descent,
+ }
+}
+
+fn translation(x: f32, y: f32) -> AffineTransform {
+ AffineTransform::new(1.0, 0.0, 0.0, 1.0, x, y)
+}
+
+/// Where text of the width goes relative to the point that it is drawn at, and how much it is condensed to fit in the
+/// maximum width.
+#[allow(
+ clippy::cast_possible_truncation,
+ reason = "the transform is in floats, as the C++ had it"
+)]
+pub(crate) fn text_transform(
+ state: &DrawingState,
+ first_font: &FontHandle,
+ mut text_width: f32,
+ max_width: Option<f64>,
+) -> AffineTransform {
+ let mut transform = AffineTransform::identity();
+
+ // https://html.spec.whatwg.org/multipage/canvas.html#text-preparation-algorithm:
+ // 9. If maxWidth was provided and the hypothetical width of the inline box in the hypothetical line box is greater
+ // than maxWidth CSS pixels, then change font to have a more condensed font (if one is available or if a
+ // reasonably readable one can be synthesized by applying a horizontal scale factor to the font) or a smaller
+ // font, and return to the previous step.
+ if let Some(max_width) = max_width
+ && text_width > max_width as f32
+ {
+ let horizontal_scale = max_width as f32 / text_width;
+ transform = AffineTransform::new(horizontal_scale, 0.0, 0.0, 1.0, 0.0, 0.0);
+ text_width *= horizontal_scale;
+ }
+
+ // Apply text align
+ // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textalign
+ // The direction property affects how "start" and "end" are interpreted:
+ // - "ltr" or "inherit" (default): start=left, end=right
+ // - "rtl": start=right, end=left
+ let is_rtl = state.direction == CanvasDirection::Rtl;
+ let alignment_offset = match state.text_align {
+ // Center alignment is the same regardless of direction.
+ CanvasTextAlign::Center => Some(-text_width / 2.0),
+ // In RTL, "start" means right-aligned. In LTR, it means left-aligned, which needs no translation.
+ CanvasTextAlign::Start => is_rtl.then_some(-text_width),
+ // In LTR, "end" means right-aligned. In RTL, it means left-aligned, which needs no translation.
+ CanvasTextAlign::End => (!is_rtl).then_some(-text_width),
+ // Explicit "left" and "right" alignments ignore direction.
+ CanvasTextAlign::Right => Some(-text_width),
+ CanvasTextAlign::Left => None,
+ };
+ if let Some(offset) = alignment_offset {
+ transform = multiply_transforms(translation(offset, 0.0), transform);
+ }
+
+ // Apply text baseline
+ // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textbaseline
+ let baseline_y_offset = baseline_offset(state.text_baseline, first_font);
+ if baseline_y_offset != 0.0 {
+ transform = multiply_transforms(translation(0.0, baseline_y_offset), transform);
+ }
+
+ transform
+}
+
+/// https://infra.spec.whatwg.org/#ascii-whitespace
+fn is_ascii_whitespace(code_unit: u16) -> bool {
+ matches!(code_unit, 0x09 | 0x0A | 0x0C | 0x0D | 0x20)
+}
+
+/// The text with every ASCII whitespace replaced by a U+0020 SPACE, step 2 of the text preparation algorithm.
+pub(crate) fn replace_ascii_whitespace(text: &[u16]) -> Vec<u16> {
+ text.iter()
+ .map(|&code_unit| {
+ if is_ascii_whitespace(code_unit) {
+ 0x20
+ } else {
+ code_unit
+ }
+ })
+ .collect()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_compositing.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_compositing.rs
new file mode 100644
index 00000000000..513bda2d7e3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_compositing.rs
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvascompositing
+
+use ak::Utf16String;
+
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+use crate::canvas_2d::drawing_state::{composite_operation_name, composite_operation_named};
+use crate::canvas_2d::float;
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-globalalpha
+ pub(crate) fn global_alpha(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(f64::from(self.drawing_state().global_alpha))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-globalalpha
+ pub(crate) fn set_global_alpha(&self, _: &mut CallContext, alpha: f64) -> WebIdlResult<()> {
+ let alpha = float(alpha);
+ // 1. If the given value is either infinite, NaN, or not in the range 0.0 to 1.0, then return.
+ if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
+ return Ok(());
+ }
+ // 2. Otherwise, set this's global alpha to the given value.
+ self.drawing_state_mut().global_alpha = alpha;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-globalcompositeoperation
+ pub(crate) fn global_composite_operation(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ let operator = self.drawing_state().current_compositing_and_blending_operator;
+ Ok(Utf16String::from_ascii(composite_operation_name(operator).as_bytes()))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-globalcompositeoperation
+ pub(crate) fn set_global_composite_operation(
+ &self,
+ _: &mut CallContext,
+ global_composite_operation: Utf16String,
+ ) -> WebIdlResult<()> {
+ // 1. If the given value is not identical to any of the values that the <blend-mode> or the <composite-mode>
+ // properties are defined to take, then return.
+ // 2. Otherwise, set this's current compositing and blending operator to the given value.
+ if let Some(operator) = composite_operation_named(&global_composite_operation) {
+ self.drawing_state_mut().current_compositing_and_blending_operator = operator;
+ }
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs
new file mode 100644
index 00000000000..17d7df57987
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_image.rs
@@ -0,0 +1,388 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasdrawimage
+
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libcompositing_rust::display_list::commands::CanvasId;
+use libgfx_rust::image_frame::ImageFrameHandle;
+use libgfx_rust::{FloatRect, IntRect, ScalingMode};
+
+use super::image_bitmap::ImageBitmap;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::canvas_2d::canvas::{CanvasImageSourceKind, Usability, capture_video_frame};
+use crate::canvas_2d::context::{CanvasKind, ContextState, RenderingContext2D};
+use crate::canvas_2d::float;
+use crate::canvas_2d::host::{LentImageFrame, LentVideoFrameHold};
+
+/// The union CanvasImageSource of HTML/Canvas/CanvasDrawImage.idl, whose members the bindings convert.
+#[derive(Clone, Copy)]
+pub(crate) enum CanvasImageSource {
+ HTMLImageElement(CppInterface),
+ SVGImageElement(CppInterface),
+ HTMLVideoElement(CppInterface),
+ HTMLCanvasElement(CppInterface),
+ ImageBitmap(Ref<ImageBitmap>),
+ OffscreenCanvas(CppInterface),
+}
+
+impl CanvasImageSource {
+ /// The source and its kind, if it is implemented in C++.
+ fn cpp_source(self) -> Option<(CppInterface, CanvasImageSourceKind)> {
+ match self {
+ Self::HTMLImageElement(source) => Some((source, CanvasImageSourceKind::HTMLImageElement)),
+ Self::SVGImageElement(source) => Some((source, CanvasImageSourceKind::SVGImageElement)),
+ Self::HTMLVideoElement(source) => Some((source, CanvasImageSourceKind::HTMLVideoElement)),
+ Self::HTMLCanvasElement(source) => Some((source, CanvasImageSourceKind::HTMLCanvasElement)),
+ Self::OffscreenCanvas(source) => Some((source, CanvasImageSourceKind::OffscreenCanvas)),
+ Self::ImageBitmap(_) => None,
+ }
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
+ /// Whether the image is good, or an exception.
+ pub(crate) fn check_usability(self) -> WebIdlResult<bool> {
+ let usability = match self.cpp_source() {
+ Some((source, kind)) => kind.check_usability(source),
+ None => {
+ let Self::ImageBitmap(image_bitmap) = self else {
+ unreachable!("an image source that is not implemented in C++ is an ImageBitmap");
+ };
+ // FIXME: VideoFrame
+ if image_bitmap.is_detached() {
+ Usability::InvalidState(Utf16String::from_ascii(b"Image bitmap is detached"))
+ } else {
+ Usability::Good
+ }
+ }
+ };
+ match usability {
+ Usability::Good => Ok(true),
+ Usability::Bad => Ok(false),
+ Usability::InvalidState(message) => Err(Exception::Dom("InvalidStateError", message)),
+ }
+ }
+
+ /// The width and the height of the image, as the operations that do not take its size use them.
+ pub(crate) fn size(self) -> (i32, i32) {
+ match self.cpp_source() {
+ Some((source, kind)) => kind.size(source),
+ None => {
+ let Self::ImageBitmap(image_bitmap) = self else {
+ unreachable!("an image source that is not implemented in C++ is an ImageBitmap");
+ };
+ match image_bitmap.frame() {
+ Some(frame) => (frame.width(), frame.height()),
+ None => (
+ i32::try_from(image_bitmap.width_of_bitmap()).unwrap_or(i32::MAX),
+ i32::try_from(image_bitmap.height_of_bitmap()).unwrap_or(i32::MAX),
+ ),
+ }
+ }
+ }
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#the-image-argument-is-not-origin-clean
+ pub(crate) fn is_not_origin_clean(self) -> bool {
+ match self.cpp_source() {
+ Some((source, kind)) => kind.is_not_origin_clean(source),
+ // FIXME: image's bitmap's origin-clean flag is false.
+ None => false,
+ }
+ }
+
+ /// The frame of an image, a canvas or an ImageBitmap, if it has one. A canvas is read back for it, which flushes
+ /// the commands of every canvas.
+ pub(crate) fn frame(self) -> Option<ImageFrameHandle> {
+ match self {
+ Self::ImageBitmap(image_bitmap) => image_bitmap.frame(),
+ Self::HTMLVideoElement(_) => unreachable!("a video is drawn by its frames, which it holds"),
+ _ => {
+ let (source, kind) = self.cpp_source().expect("the image source is implemented in C++");
+ kind.frame(source)
+ }
+ }
+ }
+}
+
+/// The source rectangle of a draw in whole pixels, each of its numbers rounded as Gfx::Rect<float>::to_rounded<int>()
+/// rounds them: to the nearest integer, ties to even, and to the smallest int for a number that no int is.
+#[allow(
+ clippy::cast_possible_truncation,
+ reason = "the number is rounded and in the range of an int"
+)]
+fn rounded_rect(rect: FloatRect) -> IntRect {
+ let round = |value: f32| {
+ let rounded = value.round_ties_even();
+ if rounded.is_nan() || !(-2_147_483_648.0..2_147_483_648.0).contains(&rounded) {
+ return i32::MIN;
+ }
+ rounded as i32
+ };
+ IntRect {
+ x: round(rect.x),
+ y: round(rect.y),
+ width: round(rect.width),
+ height: round(rect.height),
+ }
+}
+
+impl ContextState {
+ /// 4.12.5.1.15 Drawing images, https://html.spec.whatwg.org/multipage/canvas.html#drawing-images
+ #[allow(clippy::too_many_arguments, reason = "the arguments of drawImage()")]
+ pub(crate) fn draw_image_internal(
+ &self,
+ image: CanvasImageSource,
+ mut source_x: f32,
+ mut source_y: f32,
+ mut source_width: f32,
+ mut source_height: f32,
+ mut destination_x: f32,
+ mut destination_y: f32,
+ mut destination_width: f32,
+ mut destination_height: f32,
+ ) -> WebIdlResult<()> {
+ // 1. If any of the arguments are infinite or NaN, then return.
+ let arguments = [
+ source_x,
+ source_y,
+ source_width,
+ source_height,
+ destination_x,
+ destination_y,
+ destination_width,
+ destination_height,
+ ];
+ if !arguments.iter().all(|argument| argument.is_finite()) {
+ return Ok(());
+ }
+
+ // 2. Let usability be the result of checking the usability of image.
+ // 3. If usability is bad, then return (without drawing anything).
+ if !image.check_usability()? {
+ return Ok(());
+ }
+
+ // 4. Establish the source and destination rectangles as follows:
+ // If not specified, the dw and dh arguments must default to the values of sw and sh, interpreted such that
+ // one CSS pixel in the image is treated as one unit in the output bitmap's coordinate space.
+ // If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's natural
+ // width in image pixels, and the image's natural height in image pixels, respectively.
+ // If the image has no natural dimensions, then the concrete object size must be used instead, as
+ // determined using the CSS "Concrete Object Size Resolution" algorithm, with the specified size having
+ // neither a definite width nor height, nor any additional constraints, the object's natural properties
+ // being those of the image argument, and the default object size being the size of the output bitmap.
+ // NOTE: Implemented in drawImage() overloads
+ if source_width < 0.0 {
+ source_x += source_width;
+ source_width = source_width.abs();
+ }
+ if source_height < 0.0 {
+ source_y += source_height;
+ source_height = source_height.abs();
+ }
+ if destination_width < 0.0 {
+ destination_x += destination_width;
+ destination_width = destination_width.abs();
+ }
+ if destination_height < 0.0 {
+ destination_y += destination_height;
+ destination_height = destination_height.abs();
+ }
+
+ // The source rectangle is the rectangle whose corners are the four points (sx, sy), (sx+sw, sy),
+ // (sx+sw, sy+sh), (sx, sy+sh).
+ let source_rect = FloatRect::new(source_x, source_y, source_width, source_height);
+ // The destination rectangle is the rectangle whose corners are the four points (dx, dy), (dx+dw, dy),
+ // (dx+dw, dy+dh), (dx, dy+dh).
+ let destination_rect = FloatRect::new(destination_x, destination_y, destination_width, destination_height);
+ // FIXME: When the source rectangle is outside the source image, the source rectangle must be clipped to the
+ // source image and the destination rectangle must be clipped in the same proportion.
+
+ // 5. If one of the sw or sh arguments is zero, then return. Nothing is painted.
+ if source_width == 0.0 || source_height == 0.0 {
+ return Ok(());
+ }
+
+ // 6. Paint the region of the image argument specified by the source rectangle on the region of the rendering
+ // context's output bitmap specified by the destination rectangle, after applying the current
+ // transformation matrix to the destination rectangle.
+ let scaling_mode = if self.drawing_state().image_smoothing_enabled {
+ // FIXME: Honor the image smoothing quality.
+ ScalingMode::BilinearMipmap
+ } else {
+ ScalingMode::NearestNeighbor
+ };
+ let source_rect = rounded_rect(source_rect);
+
+ // 7. If image is not origin-clean, then set the CanvasRenderingContext2D's origin-clean flag to false.
+ let update_origin_clean = || {
+ if image.is_not_origin_clean() {
+ self.set_origin_clean(false);
+ }
+ };
+
+ // A canvas is drawn by its id. A 2D source needs no eager synchronization: its recorded commands precede this
+ // DrawCanvas in the shared ordered stream, so the replay sees them by construction. WebGL frames are presented
+ // by a separate message and the source's registry surface is its live drawing buffer, so the source is
+ // presented now and the DrawCanvas is flushed right after it, before a later WebGL frame can overtake the
+ // reference.
+ if let CanvasImageSource::HTMLCanvasElement(source) | CanvasImageSource::OffscreenCanvas(source) = image {
+ let kind = image.cpp_source().expect("a canvas is implemented in C++").1;
+ if let Some((source_canvas_id, source_is_2d)) = kind.canvas_id(source) {
+ if self.recorder_is_ready() {
+ let state = self.drawing_state();
+ self.record(|recorder| {
+ recorder.draw_canvas(
+ CanvasId(source_canvas_id),
+ destination_rect,
+ source_rect,
+ scaling_mode,
+ &Self::compositing(&state),
+ );
+ });
+ drop(state);
+ self.did_draw();
+ if !source_is_2d {
+ self.record(|recorder| recorder.flush());
+ }
+ }
+ update_origin_clean();
+ return Ok(());
+ }
+ }
+
+ if let CanvasImageSource::HTMLVideoElement(video) = image {
+ let Some(captured_frame) = capture_video_frame(video) else {
+ return Ok(());
+ };
+ if self.recorder_is_ready() {
+ let state = self.drawing_state();
+ self.record(|recorder| {
+ recorder.draw_video_frame(
+ &LentVideoFrameHold(captured_frame.hold()),
+ captured_frame.sink_handle,
+ captured_frame.generation,
+ destination_rect,
+ source_rect,
+ scaling_mode,
+ &Self::compositing(&state),
+ );
+ });
+ drop(state);
+ self.did_draw();
+ }
+ update_origin_clean();
+ return Ok(());
+ }
+
+ let Some(frame) = image.frame() else {
+ return Ok(());
+ };
+
+ // NOTE: Reading a canvas back for its frame may flush the shared command stream, so the recorder is readied
+ // only afterwards.
+ if self.recorder_is_ready() {
+ let state = self.drawing_state();
+ let frame = LentImageFrame(NonNull::new(frame.as_raw().cast_mut()).expect("an image frame has a frame"));
+ self.record(|recorder| {
+ recorder.draw_image_frame(
+ &frame,
+ destination_rect,
+ source_rect,
+ scaling_mode,
+ &Self::compositing(&state),
+ );
+ });
+ drop(state);
+ self.did_draw();
+ }
+
+ // 7. If image is not origin-clean, then set the CanvasRenderingContext2D's origin-clean flag to false.
+ update_origin_clean();
+
+ Ok(())
+ }
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-drawimage
+ pub(crate) fn draw_image(
+ &self,
+ _: &mut CallContext,
+ image: CanvasImageSource,
+ dx: f64,
+ dy: f64,
+ ) -> WebIdlResult<()> {
+ // If not specified, the dw and dh arguments must default to the values of sw and sh, interpreted such that one
+ // CSS pixel in the image is treated as one unit in the output bitmap's coordinate space.
+ // If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's natural
+ // width in image pixels, and the image's natural height in image pixels, respectively.
+ let (dx, dy) = (float(dx), float(dy));
+ let (width, height) = image.size();
+ let (width, height) = (int_to_float(width), int_to_float(height));
+ self.draw_image_internal(image, 0.0, 0.0, width, height, dx, dy, width, height)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-drawimage
+ #[allow(clippy::too_many_arguments, reason = "the arguments of drawImage()")]
+ pub(crate) fn draw_image_with_size(
+ &self,
+ _: &mut CallContext,
+ image: CanvasImageSource,
+ dx: f64,
+ dy: f64,
+ dw: f64,
+ dh: f64,
+ ) -> WebIdlResult<()> {
+ // If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's natural
+ // width in image pixels, and the image's natural height in image pixels, respectively.
+ let (dx, dy, dw, dh) = (float(dx), float(dy), float(dw), float(dh));
+ let (width, height) = image.size();
+ let (width, height) = (int_to_float(width), int_to_float(height));
+ self.draw_image_internal(image, 0.0, 0.0, width, height, dx, dy, dw, dh)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-drawimage
+ #[allow(clippy::too_many_arguments, reason = "the arguments of drawImage()")]
+ pub(crate) fn draw_image_with_source_rectangle(
+ &self,
+ _: &mut CallContext,
+ image: CanvasImageSource,
+ sx: f64,
+ sy: f64,
+ sw: f64,
+ sh: f64,
+ dx: f64,
+ dy: f64,
+ dw: f64,
+ dh: f64,
+ ) -> WebIdlResult<()> {
+ self.draw_image_internal(
+ image,
+ float(sx),
+ float(sy),
+ float(sw),
+ float(sh),
+ float(dx),
+ float(dy),
+ float(dw),
+ float(dh),
+ )
+ }
+}
+
+#[allow(
+ clippy::cast_precision_loss,
+ reason = "a size of an image becomes a float, as the C++ had it"
+)]
+fn int_to_float(value: i32) -> f32 {
+ value as f32
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_path.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_path.rs
new file mode 100644
index 00000000000..fbc8bbfc909
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_draw_path.rs
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasdrawpath
+
+use libgfx_rust::path::OwnedPath;
+use libgfx_rust::{AffineTransform, FloatPoint, WindingRule};
+
+use super::path2d::Path2D;
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+use crate::canvas_2d::float;
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvasfillrule
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum CanvasFillRule {
+ Nonzero,
+ Evenodd,
+}
+
+impl From<CanvasFillRule> for WindingRule {
+ fn from(fill_rule: CanvasFillRule) -> Self {
+ match fill_rule {
+ CanvasFillRule::Nonzero => Self::Nonzero,
+ CanvasFillRule::Evenodd => Self::EvenOdd,
+ }
+ }
+}
+
+/// The path of a Path2D, which nothing changes while a context draws with it, as no script runs meanwhile.
+fn path_of(path: &Ref<Path2D>) -> &OwnedPath {
+ // SAFETY: No script runs while the context uses the path.
+ unsafe { path.path_unguarded() }
+}
+
+/// Whether the point, in the coordinates that the transform maps from, is inside the path.
+fn is_point_in_path_internal(
+ path: &OwnedPath,
+ transform: AffineTransform,
+ x: f64,
+ y: f64,
+ fill_rule: CanvasFillRule,
+) -> bool {
+ let mut point = FloatPoint {
+ x: float(x),
+ y: float(y),
+ };
+ if let Some(inverse_transform) = transform.inverse() {
+ point = inverse_transform.map_point(point);
+ }
+ path.contains(point.x, point.y, WindingRule::from(fill_rule) as i32)
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-beginpath
+ pub(crate) fn begin_path(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.clear_path();
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-fill
+ pub(crate) fn fill(&self, _: &mut CallContext, fill_rule: CanvasFillRule) -> WebIdlResult<()> {
+ let path = self.path().clone();
+ self.fill_internal(&path, fill_rule.into());
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-fill
+ pub(crate) fn fill_path2d(
+ &self,
+ _: &mut CallContext,
+ path: Ref<Path2D>,
+ fill_rule: CanvasFillRule,
+ ) -> WebIdlResult<()> {
+ self.fill_internal(path_of(&path), fill_rule.into());
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-stroke
+ pub(crate) fn stroke(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ let path = self.path().clone();
+ self.stroke_internal(&path);
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-stroke
+ pub(crate) fn stroke_path2d(&self, _: &mut CallContext, path: Ref<Path2D>) -> WebIdlResult<()> {
+ self.stroke_internal(path_of(&path));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-clip
+ pub(crate) fn clip(&self, _: &mut CallContext, fill_rule: CanvasFillRule) -> WebIdlResult<()> {
+ let path = self.path().clone();
+ self.clip_internal(&path, fill_rule.into());
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-clip
+ pub(crate) fn clip_path2d(
+ &self,
+ _: &mut CallContext,
+ path: Ref<Path2D>,
+ fill_rule: CanvasFillRule,
+ ) -> WebIdlResult<()> {
+ self.clip_internal(path_of(&path), fill_rule.into());
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-ispointinpath
+ pub(crate) fn is_point_in_path(
+ &self,
+ _: &mut CallContext,
+ x: f64,
+ y: f64,
+ fill_rule: CanvasFillRule,
+ ) -> WebIdlResult<bool> {
+ let transform = self.drawing_state().transform;
+ Ok(is_point_in_path_internal(&self.path(), transform, x, y, fill_rule))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-ispointinpath
+ pub(crate) fn is_point_in_path2d(
+ &self,
+ _: &mut CallContext,
+ path: Ref<Path2D>,
+ x: f64,
+ y: f64,
+ fill_rule: CanvasFillRule,
+ ) -> WebIdlResult<bool> {
+ let transform = self.drawing_state().transform;
+ Ok(is_point_in_path_internal(path_of(&path), transform, x, y, fill_rule))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_fill_stroke_styles.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_fill_stroke_styles.rs
new file mode 100644
index 00000000000..49b981bcf2f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_fill_stroke_styles.rs
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasfillstrokestyles
+
+use ak::Utf16String;
+
+use super::canvas_draw_image::CanvasImageSource;
+use super::canvas_gradient::CanvasGradient;
+use super::canvas_pattern::CanvasPattern;
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+use crate::canvas_2d::drawing_state::{FillOrStrokeStyle, serialize_color};
+
+/// The union (DOMString or CanvasGradient or CanvasPattern) of HTML/Canvas/CanvasFillStrokeStyles.idl, the value of
+/// fillStyle and strokeStyle, whose members the bindings convert.
+pub(crate) enum DOMStringOrCanvasGradientOrCanvasPattern {
+ DOMString(Utf16String),
+ CanvasGradient(Ref<CanvasGradient>),
+ CanvasPattern(Ref<CanvasPattern>),
+}
+
+impl From<FillOrStrokeStyle> for DOMStringOrCanvasGradientOrCanvasPattern {
+ fn from(style: FillOrStrokeStyle) -> Self {
+ match style {
+ FillOrStrokeStyle::Color(color) => Self::DOMString(serialize_color(color)),
+ FillOrStrokeStyle::Gradient(gradient) => Self::CanvasGradient(gradient),
+ FillOrStrokeStyle::Pattern(pattern) => Self::CanvasPattern(pattern),
+ }
+ }
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-strokestyle
+ pub(crate) fn stroke_style(&self, _: &mut CallContext) -> WebIdlResult<DOMStringOrCanvasGradientOrCanvasPattern> {
+ Ok(self.drawing_state().stroke_style.into())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-strokestyle
+ pub(crate) fn set_stroke_style(
+ &self,
+ _: &mut CallContext,
+ style: DOMStringOrCanvasGradientOrCanvasPattern,
+ ) -> WebIdlResult<()> {
+ let style = match style {
+ // 1. If the given value is a string:
+ DOMStringOrCanvasGradientOrCanvasPattern::DOMString(string) => {
+ // 1. Let context be this's canvas attribute's value, if that is an element; otherwise null.
+
+ // 2. Let parsedValue be the result of parsing the given value with context if non-null.
+ // 3. If parsedValue is failure, then return.
+ let Some(parsed_value) = self.parse_a_css_color_value(&string) else {
+ return Ok(());
+ };
+
+ // 4. Set this's stroke style to parsedValue.
+ self.drawing_state_mut().stroke_style = FillOrStrokeStyle::Color(parsed_value);
+
+ // 5. Return.
+ return Ok(());
+ }
+ DOMStringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => FillOrStrokeStyle::Gradient(gradient),
+ DOMStringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => {
+ // FIXME: 2. If the given value is a CanvasPattern object that is marked as not origin-clean, then set
+ // this's origin-clean flag to false.
+ FillOrStrokeStyle::Pattern(pattern)
+ }
+ };
+
+ // 3. Set this's stroke style to the given value.
+ self.drawing_state_mut().stroke_style = style;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-fillstyle
+ pub(crate) fn fill_style(&self, _: &mut CallContext) -> WebIdlResult<DOMStringOrCanvasGradientOrCanvasPattern> {
+ Ok(self.drawing_state().fill_style.into())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-fillstyle
+ pub(crate) fn set_fill_style(
+ &self,
+ _: &mut CallContext,
+ style: DOMStringOrCanvasGradientOrCanvasPattern,
+ ) -> WebIdlResult<()> {
+ let style = match style {
+ // 1. If the given value is a string:
+ DOMStringOrCanvasGradientOrCanvasPattern::DOMString(string) => {
+ // 1. Let context be this's canvas attribute's value, if that is an element; otherwise null.
+
+ // 2. Let parsedValue be the result of parsing the given value with context if non-null.
+ // 3. If parsedValue is failure, then return.
+ let Some(parsed_value) = self.parse_a_css_color_value(&string) else {
+ return Ok(());
+ };
+
+ // 4. Set this's fill style to parsedValue.
+ self.drawing_state_mut().fill_style = FillOrStrokeStyle::Color(parsed_value);
+
+ // 5. Return.
+ return Ok(());
+ }
+ DOMStringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => FillOrStrokeStyle::Gradient(gradient),
+ DOMStringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => {
+ // FIXME: 2. If the given value is a CanvasPattern object that is marked as not origin-clean, then set
+ // this's origin-clean flag to false.
+ FillOrStrokeStyle::Pattern(pattern)
+ }
+ };
+
+ // 3. Set this's fill style to the given value.
+ self.drawing_state_mut().fill_style = style;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createlineargradient
+ pub(crate) fn create_linear_gradient(
+ &self,
+ cx: &mut CallContext,
+ x0: f64,
+ y0: f64,
+ x1: f64,
+ y1: f64,
+ ) -> WebIdlResult<Ref<CanvasGradient>> {
+ Ok(CanvasGradient::create_linear(cx.vm(), x0, y0, x1, y1))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createradialgradient
+ #[allow(clippy::too_many_arguments, reason = "the arguments of createRadialGradient()")]
+ pub(crate) fn create_radial_gradient(
+ &self,
+ cx: &mut CallContext,
+ x0: f64,
+ y0: f64,
+ r0: f64,
+ x1: f64,
+ y1: f64,
+ r1: f64,
+ ) -> WebIdlResult<Ref<CanvasGradient>> {
+ // If either of r0 or r1 are negative, then an "IndexSizeError" DOMException must be thrown.
+ if r0 < 0.0 {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"The r0 passed is less than 0",
+ )));
+ }
+ if r1 < 0.0 {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"The r1 passed is less than 0",
+ )));
+ }
+ Ok(CanvasGradient::create_radial(cx.vm(), x0, y0, r0, x1, y1, r1))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createconicgradient
+ pub(crate) fn create_conic_gradient(
+ &self,
+ cx: &mut CallContext,
+ start_angle: f64,
+ x: f64,
+ y: f64,
+ ) -> WebIdlResult<Ref<CanvasGradient>> {
+ Ok(CanvasGradient::create_conic(cx.vm(), start_angle, x, y))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createpattern
+ pub(crate) fn create_pattern(
+ &self,
+ cx: &mut CallContext,
+ image: CanvasImageSource,
+ repetition: Utf16String,
+ ) -> WebIdlResult<Option<Ref<CanvasPattern>>> {
+ CanvasPattern::create_for_image(cx.vm(), &image, &repetition)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_filters.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_filters.rs
new file mode 100644
index 00000000000..8a51d680527
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_filters.rs
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasfilters
+
+use std::rc::Rc;
+
+use ak::Utf16String;
+use libcompositing_rust::filter_bytes::filter_functions_graph;
+use libgfx_rust::filter::Filter;
+
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-filter
+ pub(crate) fn filter(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self
+ .drawing_state()
+ .filter_string
+ .clone()
+ .unwrap_or_else(|| Utf16String::from_ascii(b"none")))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-filter
+ pub(crate) fn set_filter(&self, _: &mut CallContext, filter: Utf16String) -> WebIdlResult<()> {
+ self.drawing_state_mut().filter = None;
+
+ // 1. If the given value is "none", then set this's current filter to "none" and return.
+ if filter == Utf16String::from_ascii(b"none") {
+ self.drawing_state_mut().filter_string = None;
+ return Ok(());
+ }
+
+ // 2. Let parsedValue be the result of parsing the given values as a <filter-value-list>. If any
+ // property-independent style sheet syntax like 'inherit' or 'initial' is present, then this parsing must
+ // return failure.
+ // 3. If parsedValue is failure, then return.
+ // NB: LibWeb's C++ parses the value and resolves its lengths and colors, and leaves out the references to SVG
+ // filters, which are not implemented.
+ let Some(functions) = self.canvas_handle().parse_filter(&filter, self.font_metrics_source()) else {
+ return Ok(());
+ };
+
+ // 4. Set this's current filter to the given value.
+ let graph = filter_functions_graph(functions.into_iter().map(Filter::from));
+ let mut state = self.drawing_state_mut();
+ state.filter = graph.map(|graph| Rc::from(graph.serialize()));
+ state.filter_string = Some(filter);
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_data.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_data.rs
new file mode 100644
index 00000000000..7b45fc0b166
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_data.rs
@@ -0,0 +1,410 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasimagedata
+//!
+//! The rectangles of these operations are computed in 64 bits from the IDL longs that they take, so that no sum or
+//! difference of them overflows, and every rectangle that reads or writes pixels is checked against the bounds of the
+//! pixels it reads or writes.
+
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libcompositing_rust::display_list::canvas_2d::Compositing;
+use libcompositing_rust::display_list::canvas_2d_recorder::AlphaType;
+use libgfx_rust::{AffineTransform, CompositingAndBlendingOperator, FloatRect, IntRect, ScalingMode};
+use libjs_rust::api::{ErrorKind, ErrorType};
+
+use super::image_data::{ImageData, ImageDataSettings};
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::canvas_2d::canvas::image_frame_from_pixels;
+use crate::canvas_2d::context::{CanvasKind, ContextState, RenderingContext2D};
+use crate::canvas_2d::host::LentImageFrame;
+
+/// The size of a pixel of an ImageData and of a readback, whose pixels are RGBA8888.
+const BYTES_PER_PIXEL: usize = 4;
+
+/// The absolute magnitude of a size, with that of the smallest long, which a long cannot represent, being the largest.
+fn absolute_magnitude(size: i32) -> u32 {
+ if size == i32::MIN {
+ i32::MAX.unsigned_abs()
+ } else {
+ size.unsigned_abs()
+ }
+}
+
+fn index_size_error_for_zero_size() -> Exception {
+ Exception::index_size_error(Utf16String::from_ascii(b"Width and height must not be zero"))
+}
+
+fn invalid_state_error(message: &[u8]) -> Exception {
+ Exception::Dom("InvalidStateError", Utf16String::from_ascii(message))
+}
+
+/// A number of pixels or bytes that is known not to be negative.
+fn to_usize(value: i64) -> usize {
+ usize::try_from(value).expect("the number is not negative")
+}
+
+/// A coordinate or a size that is known to fit in an int.
+fn to_i32(value: i64) -> i32 {
+ i32::try_from(value).expect("the number fits in an int")
+}
+
+impl ContextState {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context2d-putimagedata-common
+ /// The caller has readied the recorder.
+ #[allow(clippy::too_many_arguments, reason = "the arguments of putImageData()")]
+ fn put_pixels_from_an_image_data_onto_a_bitmap(
+ &self,
+ cx: &mut CallContext,
+ image_data: Ref<ImageData>,
+ dx: i32,
+ dy: i32,
+ dirty_x: i32,
+ dirty_y: i32,
+ dirty_width: i32,
+ dirty_height: i32,
+ ) -> WebIdlResult<()> {
+ // 1. Let buffer be imageData's data attribute value's [[ViewedArrayBuffer]] internal slot.
+ // 2. If IsDetachedBuffer(buffer) is true, then throw an "InvalidStateError" DOMException.
+ if image_data.is_detached() {
+ return Err(invalid_state_error(b"ImageData's underlying buffer is detached"));
+ }
+
+ let (width, height) = image_data.size();
+ let (width, height) = (i64::from(width), i64::from(height));
+ let (dx, dy) = (i64::from(dx), i64::from(dy));
+ let (mut dirty_x, mut dirty_y) = (i64::from(dirty_x), i64::from(dirty_y));
+ let (mut dirty_width, mut dirty_height) = (i64::from(dirty_width), i64::from(dirty_height));
+
+ // 3. If dirtyWidth is negative, then let dirtyX be dirtyX+dirtyWidth, and let dirtyWidth be equal to the
+ // absolute magnitude of dirtyWidth.
+ if dirty_width < 0 {
+ dirty_x += dirty_width;
+ dirty_width = -dirty_width;
+ }
+ // If dirtyHeight is negative, then let dirtyY be dirtyY+dirtyHeight, and let dirtyHeight be equal to the
+ // absolute magnitude of dirtyHeight.
+ if dirty_height < 0 {
+ dirty_y += dirty_height;
+ dirty_height = -dirty_height;
+ }
+
+ // 4. If dirtyX is negative, then let dirtyWidth be dirtyWidth+dirtyX, and let dirtyX be 0.
+ if dirty_x < 0 {
+ dirty_width += dirty_x;
+ dirty_x = 0;
+ }
+ // If dirtyY is negative, then let dirtyHeight be dirtyHeight+dirtyY, and let dirtyY be 0.
+ if dirty_y < 0 {
+ dirty_height += dirty_y;
+ dirty_y = 0;
+ }
+
+ // 5. If dirtyX+dirtyWidth is greater than the width attribute of the imageData argument, then let dirtyWidth
+ // be the value of that width attribute, minus the value of dirtyX.
+ if dirty_x + dirty_width > width {
+ dirty_width = width - dirty_x;
+ }
+ // If dirtyY+dirtyHeight is greater than the height attribute of the imageData argument, then let dirtyHeight
+ // be the value of that height attribute, minus the value of dirtyY.
+ if dirty_y + dirty_height > height {
+ dirty_height = height - dirty_y;
+ }
+
+ // 6. If, after those changes, either dirtyWidth or dirtyHeight are negative or zero, then return without
+ // affecting any bitmaps.
+ if dirty_width <= 0 || dirty_height <= 0 {
+ return Ok(());
+ }
+
+ // 7. For all integer values of x and y where dirtyX ≤ x < dirtyX+dirtyWidth and dirtyY ≤ y <
+ // dirtyY+dirtyHeight, set the pixel with coordinate (dx+x, dy+y) in bitmap to the color of the pixel at
+ // coordinate (x, y) in the imageData data structure's bitmap, converted from imageData's colorSpace to the
+ // color space of bitmap using 'relative-colorimetric' rendering intent.
+ let Some(pixels) = image_data.pixels() else {
+ return Err(invalid_state_error(
+ b"ImageData's underlying buffer is detached or out-of-bounds",
+ ));
+ };
+ // NB: Only the pixels that land inside the output bitmap are set, so only those are copied. The source
+ // rectangle is also kept inside imageData here, whatever the steps above computed, before its pixels are
+ // read.
+ let size = self.size();
+ let source_left = dirty_x.max(-dx).max(0);
+ let source_top = dirty_y.max(-dy).max(0);
+ let source_right = (dirty_x + dirty_width).min(i64::from(size.width) - dx).min(width);
+ let source_bottom = (dirty_y + dirty_height).min(i64::from(size.height) - dy).min(height);
+ if source_left >= source_right || source_top >= source_bottom {
+ return Ok(());
+ }
+ // NB: The destination rectangle is inside the output bitmap, so its coordinates fit in an int.
+ let destination_rect = IntRect {
+ x: to_i32(source_left + dx),
+ y: to_i32(source_top + dy),
+ width: to_i32(source_right - source_left),
+ height: to_i32(source_bottom - source_top),
+ };
+
+ // NOTE: The ImageData buffer is mutable from script and the recorded draw is only serialized at flush time, so
+ // the dirty pixels are copied now. The copy is shareable, so that flushing to the Compositor passes the
+ // pixels by file descriptor instead of copying them again.
+ let source_pitch = to_usize(width) * BYTES_PER_PIXEL;
+ let first_row_offset = to_usize(source_top) * source_pitch + to_usize(source_left) * BYTES_PER_PIXEL;
+ // SAFETY: The source rectangle is inside the width × height pixels of the ImageData, which pixels() vouched
+ // for, so its first pixel is too.
+ let first_row = unsafe { NonNull::new_unchecked(pixels.as_ptr().add(first_row_offset)) };
+ // SAFETY: The rows of the source rectangle are inside the pixels of the ImageData, and nothing runs script
+ // while they are copied.
+ let Some(frame) = (unsafe {
+ image_frame_from_pixels(first_row, source_pitch, destination_rect.width, destination_rect.height)
+ }) else {
+ return Err(cx
+ .vm()
+ .throw_completion::<()>(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
+ .expect_err("throwing a completion throws")
+ .into());
+ };
+
+ #[allow(
+ clippy::cast_precision_loss,
+ reason = "the rectangle is in floats, as the C++ had it"
+ )]
+ let destination = FloatRect::new(
+ destination_rect.x as f32,
+ destination_rect.y as f32,
+ destination_rect.width as f32,
+ destination_rect.height as f32,
+ );
+ let frame_rect = IntRect {
+ x: 0,
+ y: 0,
+ width: destination_rect.width,
+ height: destination_rect.height,
+ };
+ let lent_frame = LentImageFrame(NonNull::new(frame.as_raw().cast_mut()).expect("an image frame has a frame"));
+ self.record(|recorder| {
+ recorder.save();
+ recorder.set_transform(AffineTransform::identity());
+ // NB: Step 7 sets each destination pixel to the source pixel: putImageData replaces the pixels (including
+ // their alpha), rather than compositing them. The copy operator makes a transparent source pixel
+ // overwrite an opaque destination pixel, rather than leave it unchanged.
+ recorder.draw_image_frame(
+ &lent_frame,
+ destination,
+ frame_rect,
+ ScalingMode::NearestNeighbor,
+ &Compositing {
+ compositing_and_blending_operator: CompositingAndBlendingOperator::Copy,
+ ..Compositing::default()
+ },
+ );
+ recorder.restore();
+ });
+
+ self.did_draw();
+
+ Ok(())
+ }
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createimagedata
+ pub(crate) fn create_image_data(
+ &self,
+ cx: &mut CallContext,
+ sw: i32,
+ sh: i32,
+ settings: ImageDataSettings,
+ ) -> WebIdlResult<Ref<ImageData>> {
+ // 1. If one or both of sw and sh are zero, then throw an "IndexSizeError" DOMException.
+ if sw == 0 || sh == 0 {
+ return Err(index_size_error_for_zero_size());
+ }
+
+ // 2. Let newImageData be a new ImageData object.
+ // 3. Initialize newImageData given the absolute magnitude of sw, the absolute magnitude of sh, settings set to
+ // settings, and defaultColorSpace set to this's color space.
+ // 4. Initialize the image data of newImageData to transparent black.
+ // 5. Return newImageData.
+ ImageData::create(cx, absolute_magnitude(sw), absolute_magnitude(sh), Some(&settings))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createimagedata-imagedata
+ pub(crate) fn create_image_data_from(
+ &self,
+ cx: &mut CallContext,
+ image_data: Ref<ImageData>,
+ ) -> WebIdlResult<Ref<ImageData>> {
+ // 1. Let newImageData be a new ImageData object.
+ // 2. Initialize newImageData given the value of imageData's width attribute, the value of imageData's height
+ // attribute, and defaultColorSpace set to the value of imageData's colorSpace attribute.
+ // FIXME: Set defaultColorSpace to the value of image_data's colorSpace attribute
+ // 3. Initialize the image data of newImageData to transparent black.
+ // 4. Return newImageData.
+ let (width, height) = image_data.size();
+ ImageData::create(cx, width, height, None)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-getimagedata
+ pub(crate) fn get_image_data(
+ &self,
+ cx: &mut CallContext,
+ sx: i32,
+ sy: i32,
+ sw: i32,
+ sh: i32,
+ settings: ImageDataSettings,
+ ) -> WebIdlResult<Ref<ImageData>> {
+ // 1. If either the sw or sh arguments are zero, then throw an "IndexSizeError" DOMException.
+ if sw == 0 || sh == 0 {
+ return Err(index_size_error_for_zero_size());
+ }
+
+ // 2. If the CanvasRenderingContext2D's origin-clean flag is set to false, then throw a "SecurityError"
+ // DOMException.
+ if !self.origin_clean() {
+ return Err(Exception::Dom(
+ "SecurityError",
+ Utf16String::from_ascii(b"CanvasRenderingContext2D is not origin-clean"),
+ ));
+ }
+
+ // ImageData initialization requires positive width and height
+ // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#initialize-an-imagedata-object
+ let (width, height) = (absolute_magnitude(sw), absolute_magnitude(sh));
+
+ // 3. Let imageData be a new ImageData object.
+ // 4. Initialize imageData given sw, sh, settings set to settings, and defaultColorSpace set to this's color
+ // space.
+ let image_data = ImageData::create(cx, width, height, Some(&settings))?;
+
+ // 5. Let the source rectangle be the rectangle whose corners are the four points (sx, sy), (sx+sw, sy),
+ // (sx+sw, sy+sh), (sx, sy+sh).
+ // NOTE: The spec doesn't seem to define this behavior, but MDN does and the WPT tests assume it works this
+ // way. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData#sw
+ let source_x = i64::from(sx) + i64::from(sw.min(0));
+ let source_y = i64::from(sy) + i64::from(sh.min(0));
+ let size = self.size();
+ let left = source_x.max(0);
+ let top = source_y.max(0);
+ let right = (source_x + i64::from(width)).min(i64::from(size.width));
+ let bottom = (source_y + i64::from(height)).min(i64::from(size.height));
+ if left >= right || top >= bottom {
+ return Ok(image_data);
+ }
+ let readback_rect = IntRect {
+ x: to_i32(left),
+ y: to_i32(top),
+ width: to_i32(right - left),
+ height: to_i32(bottom - top),
+ };
+
+ // NOTE: If reading back from the Compositor fails (no backing storage or no connection), it's like copying
+ // only transparent black pixels (which is a no-op).
+ // NOTE: Internally we must use premultiplied alpha, but ImageData should hold unpremultiplied alpha. This
+ // conversion might result in a loss of precision, but is according to spec.
+ // See: https://html.spec.whatwg.org/multipage/canvas.html#premultiplied-alpha-and-the-2d-rendering-context
+ let Some(readback) = self.read_pixels(readback_rect, AlphaType::Unpremultiplied) else {
+ return Ok(image_data);
+ };
+
+ // 6. Set the pixel values of imageData to be the pixels of this's output bitmap in the area specified by the
+ // source rectangle in the bitmap's coordinate space units, converted from this's color space to imageData's
+ // colorSpace using 'relative-colorimetric' rendering intent.
+ // NB: The pixels of imageData are RGBA8888 and unpremultiplied.
+ let Some(readback_pixels) = readback.unpremultiplied_rgba_pixels() else {
+ return Ok(image_data);
+ };
+ if readback_pixels.width != readback_rect.width || readback_pixels.height != readback_rect.height {
+ return Ok(image_data);
+ }
+ let image_data_pixels = image_data.pixels().expect("a new ImageData has room for its pixels");
+
+ // The readback only covers the part of the source rectangle that is inside the output bitmap.
+ let destination_x = to_usize(left - source_x);
+ let destination_y = to_usize(top - source_y);
+ let destination_pitch = width as usize * BYTES_PER_PIXEL;
+ let row_size = to_usize(i64::from(readback_rect.width)) * BYTES_PER_PIXEL;
+ let rows = to_usize(i64::from(readback_rect.height));
+ assert!(destination_x * BYTES_PER_PIXEL + row_size <= destination_pitch);
+ assert!(destination_y + rows <= height as usize);
+ assert!(row_size <= readback_pixels.pitch);
+ for row in 0..rows {
+ // SAFETY: The row is inside both the readback and the pixels of the new ImageData, as asserted above, and
+ // the two do not overlap.
+ unsafe {
+ let source = readback_pixels.first_row.as_ptr().add(row * readback_pixels.pitch);
+ let destination = image_data_pixels
+ .as_ptr()
+ .add((destination_y + row) * destination_pitch + destination_x * BYTES_PER_PIXEL);
+ core::ptr::copy_nonoverlapping(source, destination, row_size);
+ }
+ }
+
+ // 7. Set the pixels values of imageData for areas of the source rectangle that are outside of the output
+ // bitmap to transparent black.
+ // NOTE: No-op, already done during creation.
+
+ // 8. Return imageData.
+ Ok(image_data)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-putimagedata-short
+ pub(crate) fn put_image_data(
+ &self,
+ cx: &mut CallContext,
+ image_data: Ref<ImageData>,
+ dx: i32,
+ dy: i32,
+ ) -> WebIdlResult<()> {
+ // The putImageData(imageData, dx, dy) method steps are to put pixels from an ImageData onto a bitmap, given
+ // imageData, this's output bitmap, dx, dy, 0, 0, imageData's width, and imageData's height.
+ if !self.recorder_is_ready() {
+ return Ok(());
+ }
+ let (width, height) = image_data.size();
+ // NB: An ImageData's size fits in a long, as nothing creates a larger one.
+ let (width, height) = (
+ i32::try_from(width).unwrap_or(i32::MAX),
+ i32::try_from(height).unwrap_or(i32::MAX),
+ );
+ self.put_pixels_from_an_image_data_onto_a_bitmap(cx, image_data, dx, dy, 0, 0, width, height)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-putimagedata
+ #[allow(clippy::too_many_arguments, reason = "the arguments of putImageData()")]
+ pub(crate) fn put_image_data_with_dirty_rectangle(
+ &self,
+ cx: &mut CallContext,
+ image_data: Ref<ImageData>,
+ dx: i32,
+ dy: i32,
+ dirty_x: i32,
+ dirty_y: i32,
+ dirty_width: i32,
+ dirty_height: i32,
+ ) -> WebIdlResult<()> {
+ // The putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) method steps are to put pixels
+ // from an ImageData onto a bitmap, given imageData, this's output bitmap, dx, dy, dirtyX, dirtyY, dirtyWidth,
+ // and dirtyHeight.
+ if !self.recorder_is_ready() {
+ return Ok(());
+ }
+ self.put_pixels_from_an_image_data_onto_a_bitmap(
+ cx,
+ image_data,
+ dx,
+ dy,
+ dirty_x,
+ dirty_y,
+ dirty_width,
+ dirty_height,
+ )
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_smoothing.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_smoothing.rs
new file mode 100644
index 00000000000..97fcb1c1c09
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_image_smoothing.rs
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasimagesmoothing
+
+use super::canvas_rendering_context2d::ImageSmoothingQuality;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-imagesmoothingenabled
+ pub(crate) fn image_smoothing_enabled(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.drawing_state().image_smoothing_enabled)
+ }
+
+ pub(crate) fn set_image_smoothing_enabled(&self, _: &mut CallContext, enabled: bool) -> WebIdlResult<()> {
+ self.drawing_state_mut().image_smoothing_enabled = enabled;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-imagesmoothingquality
+ pub(crate) fn image_smoothing_quality(&self, _: &mut CallContext) -> WebIdlResult<ImageSmoothingQuality> {
+ Ok(self.drawing_state().image_smoothing_quality)
+ }
+
+ pub(crate) fn set_image_smoothing_quality(
+ &self,
+ _: &mut CallContext,
+ quality: ImageSmoothingQuality,
+ ) -> WebIdlResult<()> {
+ self.drawing_state_mut().image_smoothing_quality = quality;
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path_drawing_styles.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path_drawing_styles.rs
new file mode 100644
index 00000000000..49e58e2ce80
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path_drawing_styles.rs
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvaspathdrawingstyles
+
+use super::canvas_rendering_context2d::{CanvasLineCap, CanvasLineJoin};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+use crate::canvas_2d::float;
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linewidth
+ pub(crate) fn line_width(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ // On getting, it must return the current value.
+ Ok(f64::from(self.drawing_state().line_width))
+ }
+
+ pub(crate) fn set_line_width(&self, _: &mut CallContext, line_width: f64) -> WebIdlResult<()> {
+ // On setting, zero, negative, infinite, and NaN values must be ignored, leaving the value unchanged;
+ let line_width = float(line_width);
+ if line_width <= 0.0 || !line_width.is_finite() {
+ return Ok(());
+ }
+ // other values must change the current value to the new value.
+ self.drawing_state_mut().line_width = line_width;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linecap
+ pub(crate) fn line_cap(&self, _: &mut CallContext) -> WebIdlResult<CanvasLineCap> {
+ Ok(self.drawing_state().line_cap)
+ }
+
+ pub(crate) fn set_line_cap(&self, _: &mut CallContext, line_cap: CanvasLineCap) -> WebIdlResult<()> {
+ self.drawing_state_mut().line_cap = line_cap;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linejoin
+ pub(crate) fn line_join(&self, _: &mut CallContext) -> WebIdlResult<CanvasLineJoin> {
+ Ok(self.drawing_state().line_join)
+ }
+
+ pub(crate) fn set_line_join(&self, _: &mut CallContext, line_join: CanvasLineJoin) -> WebIdlResult<()> {
+ self.drawing_state_mut().line_join = line_join;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-miterlimit
+ pub(crate) fn miter_limit(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(f64::from(self.drawing_state().miter_limit))
+ }
+
+ pub(crate) fn set_miter_limit(&self, _: &mut CallContext, miter_limit: f64) -> WebIdlResult<()> {
+ // On setting, zero, negative, infinite, and NaN values must be ignored, leaving the value unchanged;
+ let miter_limit = float(miter_limit);
+ if miter_limit <= 0.0 || !miter_limit.is_finite() {
+ return Ok(());
+ }
+ // other values must change the current value to the new value.
+ self.drawing_state_mut().miter_limit = miter_limit;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-setlinedash
+ pub(crate) fn set_line_dash(&self, _: &mut CallContext, mut segments: Vec<f64>) -> WebIdlResult<()> {
+ // 1. If any value in segments is not finite (e.g. an Infinity or a NaN value), or if any value is negative
+ // (less than zero), then return (without throwing an exception; user agents could show a message on a
+ // developer console, though, as that would be helpful for debugging).
+ if segments.iter().any(|segment| !segment.is_finite() || *segment < 0.0) {
+ return Ok(());
+ }
+
+ // 2. If the number of elements in segments is odd, then let segments be the concatenation of two copies of
+ // segments.
+ if segments.len() % 2 == 1 {
+ segments.extend_from_within(..);
+ }
+
+ // 3. Set the object's dash list to segments.
+ self.drawing_state_mut().dash_list = segments;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-getlinedash
+ pub(crate) fn get_line_dash(&self, _: &mut CallContext) -> WebIdlResult<Vec<f64>> {
+ // When the getLineDash() method is invoked, it must return a sequence whose values are the values of the
+ // object's dash list, in the same order.
+ Ok(self.drawing_state().dash_list.clone())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linedashoffset
+ pub(crate) fn line_dash_offset(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(f64::from(self.drawing_state().line_dash_offset))
+ }
+
+ pub(crate) fn set_line_dash_offset(&self, _: &mut CallContext, line_dash_offset: f64) -> WebIdlResult<()> {
+ // On setting, infinite and NaN values must be ignored, leaving the value unchanged;
+ let line_dash_offset = float(line_dash_offset);
+ if !line_dash_offset.is_finite() {
+ return Ok(());
+ }
+ // other values must change the current value to the new value.
+ self.drawing_state_mut().line_dash_offset = line_dash_offset;
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
index 52a025aede5..a97e4b591d6 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs
@@ -8,15 +8,75 @@
use core::cell::Cell;
+use ak::Utf16String;
+use libcompositing_rust::display_list::canvas_2d::Compositing;
+use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, Recorder};
use libcompositing_rust::display_list::commands::Canvas2DPatternRepetition;
-use libgfx_rust::AffineTransform;
use libgfx_rust::image_frame::ImageFrameHandle;
+use libgfx_rust::{AffineTransform, CompositingAndBlendingOperator, FloatRect, IntRect, IntSize, ScalingMode};
use libjs_rust::api::{Trace, Vm};
+use super::canvas_draw_image::CanvasImageSource;
+use crate::bindings::conversions::CppInterface;
use crate::bindings::interface::{Ref, Wrappable, allocate};
-use crate::bindings::{CallContext, WebIdlResult};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::canvas_2d::canvas::{CanvasImageSourceKind, capture_video_frame, video_transport};
+use crate::canvas_2d::host::LentVideoFrameHold;
use crate::geometry::dom_matrix_read_only::{DOMMatrix2DInit, validate_and_fixup_2d};
+/// The repetition that a value of the repetition argument of createPattern() names exactly, if it names one.
+fn parse_repetition(repetition: &Utf16String) -> Option<Canvas2DPatternRepetition> {
+ [
+ ("repeat", Canvas2DPatternRepetition::Repeat),
+ ("repeat-x", Canvas2DPatternRepetition::RepeatX),
+ ("repeat-y", Canvas2DPatternRepetition::RepeatY),
+ ("no-repeat", Canvas2DPatternRepetition::NoRepeat),
+ ]
+ .into_iter()
+ .find(|(name, _)| *repetition == Utf16String::from_ascii(name.as_bytes()))
+ .map(|(_, repetition)| repetition)
+}
+
+/// A pattern outlives any one video frame, so it reads the frame back instead of holding it.
+fn read_back_current_video_frame(video: CppInterface) -> Option<ImageFrameHandle> {
+ let captured_frame = capture_video_frame(video)?;
+ let transport = video_transport(video)?;
+ let mut recorder = Recorder::new(transport);
+
+ let (width, height) = CanvasImageSourceKind::HTMLVideoElement.size(video);
+ let frame_rect = IntRect {
+ x: 0,
+ y: 0,
+ width,
+ height,
+ };
+ if width <= 0 || height <= 0 || !recorder.create_context(IntSize { width, height }, true) {
+ return None;
+ }
+
+ #[allow(
+ clippy::cast_precision_loss,
+ reason = "the rectangle is in floats, as the C++ had it"
+ )]
+ let destination = FloatRect::new(0.0, 0.0, width as f32, height as f32);
+ recorder.draw_video_frame(
+ &LentVideoFrameHold(captured_frame.hold()),
+ captured_frame.sink_handle,
+ captured_frame.generation,
+ destination,
+ frame_rect,
+ ScalingMode::NearestNeighbor,
+ &Compositing {
+ compositing_and_blending_operator: CompositingAndBlendingOperator::Copy,
+ ..Compositing::default()
+ },
+ );
+ recorder.flush();
+ let bitmap = recorder.read_back_pixels(frame_rect, AlphaType::Premultiplied);
+ recorder.destroy_context();
+ Some(bitmap?.into_image_frame())
+}
+
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct CanvasPattern {
@@ -45,6 +105,47 @@ impl CanvasPattern {
)
}
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createpattern
+ pub(crate) fn create_for_image(
+ vm: &Vm,
+ image: &CanvasImageSource,
+ repetition: &Utf16String,
+ ) -> WebIdlResult<Option<Ref<Self>>> {
+ // 1. Let usability be the result of checking the usability of image.
+ // 2. If usability is bad, then return null.
+ // 3. Assert: usability is good.
+ if !image.check_usability()? {
+ return Ok(None);
+ }
+
+ // 4. If repetition is the empty string, then set it to "repeat".
+ // 5. If repetition is not identical to one of "repeat", "repeat-x", "repeat-y", or "no-repeat", then throw a
+ // "SyntaxError" DOMException.
+ let repetition = if repetition.is_empty() {
+ Some(Canvas2DPatternRepetition::Repeat)
+ } else {
+ parse_repetition(repetition)
+ };
+ let Some(repetition) = repetition else {
+ return Err(Exception::syntax_error(Utf16String::from_ascii(
+ b"Repetition value is not valid",
+ )));
+ };
+
+ // 6. Let pattern be a new CanvasPattern object with the image image and the repetition behavior given by
+ // repetition.
+ let frame = match *image {
+ CanvasImageSource::HTMLVideoElement(video) => read_back_current_video_frame(video),
+ _ => image.frame(),
+ };
+ let pattern = Self::create(vm, frame, repetition);
+
+ // FIXME: 7. If image is not origin-clean, then mark pattern as not origin-clean.
+
+ // 8. Return pattern.
+ Ok(Some(pattern))
+ }
+
pub(crate) fn image(&self) -> Option<&ImageFrameHandle> {
self.image.as_ref()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rect.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rect.rs
new file mode 100644
index 00000000000..be13428ac1d
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rect.rs
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasrect
+
+use libgfx_rust::path::{OwnedPath, PathBuilder};
+use libgfx_rust::{FloatRect, WindingRule};
+
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+use crate::canvas_2d::float;
+
+/// The outline of a rectangle, as a closed subpath that goes around it clockwise from its top left corner.
+fn rect_path(x: f32, y: f32, width: f32, height: f32) -> OwnedPath {
+ let mut path = PathBuilder::new();
+ path.move_to(x, y);
+ path.line_to(x + width, y);
+ path.line_to(x + width, y + height);
+ path.line_to(x, y + height);
+ path.line_to(x, y);
+ path.build()
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-clearrect
+ pub(crate) fn clear_rect(&self, _: &mut CallContext, x: f64, y: f64, w: f64, h: f64) -> WebIdlResult<()> {
+ let (x, y, w, h) = (float(x), float(y), float(w), float(h));
+
+ // 1. If any of the arguments are infinite or NaN, then return.
+ if !x.is_finite() || !y.is_finite() || !w.is_finite() || !h.is_finite() {
+ return Ok(());
+ }
+
+ let color = self.clear_color();
+ if self.record_if_ready(|recorder| recorder.clear_rect(FloatRect::new(x, y, w, h), color)) {
+ self.did_draw();
+ }
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-fillrect
+ pub(crate) fn fill_rect(&self, _: &mut CallContext, x: f64, y: f64, w: f64, h: f64) -> WebIdlResult<()> {
+ self.fill_internal(&rect_path(float(x), float(y), float(w), float(h)), WindingRule::EvenOdd);
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-strokerect
+ pub(crate) fn stroke_rect(&self, _: &mut CallContext, x: f64, y: f64, w: f64, h: f64) -> WebIdlResult<()> {
+ self.stroke_internal(&rect_path(float(x), float(y), float(w), float(h)));
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rendering_context2d.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rendering_context2d.rs
new file mode 100644
index 00000000000..92066502ba7
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rendering_context2d.rs
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasrenderingcontext2d
+
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, OnScreen, RenderingContext2D};
+
+pub(crate) type CanvasRenderingContext2D = RenderingContext2D<OnScreen>;
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#imagesmoothingquality
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum ImageSmoothingQuality {
+ Low,
+ Medium,
+ High,
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvaslinecap
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum CanvasLineCap {
+ Butt,
+ Round,
+ Square,
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvaslinejoin
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum CanvasLineJoin {
+ Round,
+ Bevel,
+ Miter,
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvastextalign
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum CanvasTextAlign {
+ Start,
+ End,
+ Left,
+ Right,
+ Center,
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvastextbaseline
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum CanvasTextBaseline {
+ Top,
+ Hanging,
+ Middle,
+ Alphabetic,
+ Ideographic,
+ Bottom,
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvasdirection
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum CanvasDirection {
+ Ltr,
+ Rtl,
+ Inherit,
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-canvas
+ /// https://html.spec.whatwg.org/multipage/canvas.html#offscreencontext2d-canvas
+ pub(crate) fn canvas(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.canvas_handle().wrapper(cx.realm()))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rendering_context2d_settings.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rendering_context2d_settings.rs
new file mode 100644
index 00000000000..1d50e00145e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_rendering_context2d_settings.rs
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasrenderingcontext2dsettings
+
+use super::predefined_color_space::PredefinedColorSpace;
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvascolortype, in the order of
+/// Web::Bindings::CanvasColorType, which C++ passes as its underlying value.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub(crate) enum CanvasColorType {
+ Unorm8,
+ Float16,
+}
+
+impl CanvasColorType {
+ /// The color type whose underlying value C++ passes, if it is one.
+ pub(crate) fn from_u8(value: u8) -> Option<Self> {
+ match value {
+ 0 => Some(Self::Unorm8),
+ 1 => Some(Self::Float16),
+ _ => None,
+ }
+ }
+}
+
+/// https://html.spec.whatwg.org/multipage/canvas.html#canvasrenderingcontext2dsettings
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct CanvasRenderingContext2DSettings {
+ pub(crate) alpha: bool,
+ pub(crate) desynchronized: bool,
+ pub(crate) color_space: PredefinedColorSpace,
+ pub(crate) color_type: CanvasColorType,
+ pub(crate) will_read_frequently: bool,
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_settings.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_settings.rs
new file mode 100644
index 00000000000..3776a26aa87
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_settings.rs
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvassettings
+
+use super::canvas_rendering_context2d_settings::CanvasRenderingContext2DSettings;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-canvas-getcontextattributes
+ pub(crate) fn get_context_attributes(&self, _: &mut CallContext) -> WebIdlResult<CanvasRenderingContext2DSettings> {
+ Ok(self.context_attributes)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_shadow_styles.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_shadow_styles.rs
new file mode 100644
index 00000000000..6a02d280265
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_shadow_styles.rs
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasshadowstyles
+
+use ak::Utf16String;
+
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+use crate::canvas_2d::drawing_state::serialize_color;
+use crate::canvas_2d::float;
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowoffsetx
+ pub(crate) fn shadow_offset_x(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(f64::from(self.drawing_state().shadow_offset_x))
+ }
+
+ pub(crate) fn set_shadow_offset_x(&self, _: &mut CallContext, offset_x: f64) -> WebIdlResult<()> {
+ let offset_x = float(offset_x);
+ if offset_x.is_finite() {
+ self.drawing_state_mut().shadow_offset_x = offset_x;
+ }
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowoffsety
+ pub(crate) fn shadow_offset_y(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(f64::from(self.drawing_state().shadow_offset_y))
+ }
+
+ pub(crate) fn set_shadow_offset_y(&self, _: &mut CallContext, offset_y: f64) -> WebIdlResult<()> {
+ let offset_y = float(offset_y);
+ if offset_y.is_finite() {
+ self.drawing_state_mut().shadow_offset_y = offset_y;
+ }
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
+ pub(crate) fn shadow_blur(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(f64::from(self.drawing_state().shadow_blur))
+ }
+
+ pub(crate) fn set_shadow_blur(&self, _: &mut CallContext, blur_radius: f64) -> WebIdlResult<()> {
+ // On setting, the attribute must be set to the new value, except if the value is negative, infinite or NaN,
+ // in which case the new value must be ignored.
+ let blur_radius = float(blur_radius);
+ if blur_radius < 0.0 || !blur_radius.is_finite() {
+ return Ok(());
+ }
+ self.drawing_state_mut().shadow_blur = blur_radius;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowcolor
+ pub(crate) fn shadow_color(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(serialize_color(self.drawing_state().shadow_color))
+ }
+
+ pub(crate) fn set_shadow_color(&self, _: &mut CallContext, color: Utf16String) -> WebIdlResult<()> {
+ // 1. Let context be this's canvas attribute's value, if that is an element; otherwise null.
+
+ // 2. Let parsedValue be the result of parsing the given value with context if non-null.
+ // 3. If parsedValue is failure, then return.
+ let Some(parsed_value) = self.parse_a_css_color_value(&color) else {
+ return Ok(());
+ };
+
+ // 4. Set this's shadow color to parsedValue.
+ self.drawing_state_mut().shadow_color = parsed_value;
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_state.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_state.rs
new file mode 100644
index 00000000000..aac27821b19
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_state.rs
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasstate
+
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, CanvasRecorder, RenderingContext2D};
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-save
+ pub(crate) fn save(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ // The save() method steps are to push a copy of the current drawing state onto the drawing state stack.
+ self.push_drawing_state();
+
+ self.record_if_ready(CanvasRecorder::save);
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-restore
+ 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.
+ if !self.pop_drawing_state() {
+ return Ok(());
+ }
+
+ self.record_if_ready(CanvasRecorder::restore);
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-reset
+ pub(crate) fn reset(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ // The reset() method steps are to reset the rendering context to its default state.
+ self.reset_to_default_state();
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-iscontextlost
+ pub(crate) fn is_context_lost(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ // The isContextLost() method steps are to return this's context lost.
+ Ok(self.context_is_lost())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text.rs
new file mode 100644
index 00000000000..8369d9541f1
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text.rs
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvastext
+
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libcompositing_rust::display_list::commands::DisplayListGlyph;
+use libgfx_rust::path::{OwnedPath, PathBuilder};
+use libgfx_rust::{CompositingAndBlendingOperator, FloatPoint, WindingRule};
+
+use super::text_metrics::{TextMeasurements, TextMetrics};
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::context::{CanvasKind, ContextState, RenderingContext2D, paint_of};
+use crate::canvas_2d::float;
+use crate::canvas_2d::host::LentFont;
+use crate::canvas_2d::text::{baseline_offset, path_of_runs, replace_ascii_whitespace, shape_text, text_transform};
+use crate::html::canvas_rendering_context2d::CanvasTextBaseline;
+
+impl ContextState {
+ /// The outlines of the glyphs of the text, drawn at the point.
+ fn text_path(&self, text: &[u16], x: f32, y: f32, max_width: Option<f64>) -> OwnedPath {
+ if max_width.is_some_and(|max_width| max_width <= 0.0) {
+ return PathBuilder::new().build();
+ }
+
+ let font = self.current_font();
+ let letter_spacing = self.resolved_letter_spacing();
+ let runs = shape_text(&font.cascade, text, FloatPoint { x, y }, letter_spacing);
+ let path = path_of_runs(&runs);
+ let text_width: f32 = runs.iter().map(|run| run.width).sum();
+ let transform = text_transform(&self.drawing_state(), &font.cascade.first(), text_width, max_width);
+ path.copy_transformed(transform.values)
+ }
+}
+
+/// Whether the arguments of fillText() or strokeText() let it draw.
+fn are_finite(x: f32, y: f32, max_width: Option<f64>) -> bool {
+ x.is_finite() && y.is_finite() && max_width.is_none_or(f64::is_finite)
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-filltext
+ pub(crate) fn fill_text(
+ &self,
+ _: &mut CallContext,
+ text: Utf16String,
+ x: f64,
+ y: f64,
+ max_width: Option<f64>,
+ ) -> WebIdlResult<()> {
+ let (x, y) = (float(x), float(y));
+ if !are_finite(x, y, max_width) {
+ return Ok(());
+ }
+ let text = text.to_utf16();
+
+ // Complex text effects continue to use the combined outline so they are applied once to the entire text,
+ // including runs that use different fallback fonts.
+ let has_shadow = {
+ let state = self.drawing_state();
+ state.shadow_blur != 0.0 || state.shadow_offset_x != 0.0 || state.shadow_offset_y != 0.0
+ };
+ if max_width.is_some() || has_shadow {
+ self.fill_internal(&self.text_path(&text, x, y, max_width), WindingRule::Nonzero);
+ return Ok(());
+ }
+
+ let font = self.current_font();
+ let letter_spacing = self.resolved_letter_spacing();
+ let runs = shape_text(&font.cascade, &text, FloatPoint { x: 0.0, y: 0.0 }, letter_spacing);
+ let [run] = runs.as_slice() else {
+ self.fill_internal(&self.text_path(&text, x, y, max_width), WindingRule::Nonzero);
+ return Ok(());
+ };
+ if run.font.is_invisible() {
+ self.fill_internal(&self.text_path(&text, x, y, max_width), WindingRule::Nonzero);
+ return Ok(());
+ }
+
+ if !self.recorder_is_ready() {
+ return Ok(());
+ }
+ {
+ let state = self.drawing_state();
+ if !state.fill_style.is_visible()
+ && state.current_compositing_and_blending_operator == CompositingAndBlendingOperator::SourceOver
+ {
+ return Ok(());
+ }
+ }
+ let glyphs: Vec<DisplayListGlyph> = run
+ .glyphs
+ .iter()
+ .filter(|glyph| glyph.should_paint)
+ .map(|glyph| DisplayListGlyph {
+ position: FloatPoint { x: glyph.x, y: glyph.y },
+ glyph_id: glyph.glyph_id,
+ })
+ .collect();
+ let first_font = font.cascade.first();
+ let state = self.drawing_state();
+ let translation = text_transform(&state, &first_font, run.width, None).map_point(FloatPoint { x, y });
+ let lent_font = LentFont(NonNull::new(run.font.as_raw().cast_mut()).expect("a font has a font"));
+ self.record(|recorder| {
+ let paint = paint_of(recorder, &state.fill_style);
+ recorder.draw_glyph_run(
+ &lent_font,
+ &glyphs,
+ translation,
+ &paint,
+ &ContextState::compositing(&state),
+ );
+ });
+ drop(state);
+ self.did_draw();
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-stroketext
+ pub(crate) fn stroke_text(
+ &self,
+ _: &mut CallContext,
+ text: Utf16String,
+ x: f64,
+ y: f64,
+ max_width: Option<f64>,
+ ) -> WebIdlResult<()> {
+ let (x, y) = (float(x), float(y));
+ if !are_finite(x, y, max_width) {
+ return Ok(());
+ }
+ self.stroke_internal(&self.text_path(&text.to_utf16(), x, y, max_width));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-measuretext
+ pub(crate) fn measure_text(&self, cx: &mut CallContext, text: Utf16String) -> WebIdlResult<Ref<TextMetrics>> {
+ // The measureText(text) method steps are to run the text preparation algorithm, passing it text and the object
+ // implementing the CanvasText interface, and then using the returned inline box return a new TextMetrics
+ // object with members behaving as described in the following list:
+
+ // https://html.spec.whatwg.org/multipage/canvas.html#text-preparation-algorithm
+ // 1. If maxWidth was provided but is less than or equal to zero or equal to NaN, then return an empty array.
+ // 2. Replace all ASCII whitespace in text with U+0020 SPACE characters.
+ let replaced_text = replace_ascii_whitespace(&text.to_utf16());
+
+ // 3. Let font be the current font of target, as given by that object's font attribute.
+ let font = self.current_font();
+ let letter_spacing = self.resolved_letter_spacing();
+ let runs = shape_text(
+ &font.cascade,
+ &replaced_text,
+ FloatPoint { x: 0.0, y: 0.0 },
+ letter_spacing,
+ );
+
+ // FIXME: 4. Let language be the target's language.
+ // FIXME: 5. If language is "inherit": ...
+ // FIXME: 6. If language is the empty string, then set language to explicitly unknown.
+ // FIXME: 7. Apply the appropriate step from the following list to determine the value of direction: ...
+
+ // 8. Form a hypothetical infinitely-wide CSS line box containing a single inline box containing the text text,
+ // with the CSS content language set to language, and with its CSS properties set as follows: ...
+ // FIXME: Actually use a LineBox here instead of, you know, using the default font and measuring its size
+ // (which is not the spec at all).
+ let mut width = 0.0_f32;
+ for run in &runs {
+ width += run.width;
+ }
+
+ // 9. If maxWidth was provided and the hypothetical width of the inline box in the hypothetical line box is
+ // greater than maxWidth CSS pixels, then change font to have a more condensed font (if one is available or
+ // if a reasonably readable one can be synthesized by applying a horizontal scale factor to the font) or a
+ // smaller font, and return to the previous step.
+ // FIXME: 10. The anchor point is a point on the inline box, and the physical alignment is one of the values
+ // left, right, and center. These variables are determined by the textAlign and textBaseline values.
+ // 11. Let result be an array constructed by iterating over each glyph in the inline box from left to right (if
+ // any), adding to the array, for each glyph, the shape of the glyph as it is in the inline box, positioned
+ // on a coordinate space using CSS pixels with its origin at the anchor point.
+ // 12. Return result, physical alignment, and the inline box.
+ // NB: The inline box is at the origin, as wide as the text.
+ let (box_left, box_right) = (0.0_f32, width);
+
+ // FIXME: Use the font that was used to create the glyphs of the runs.
+ let first_font = font.cascade.first();
+ let ascent = first_font.facts().ascent;
+ let descent = first_font.facts().descent;
+ let hanging_baseline = ascent * 0.8;
+ let text_baseline: CanvasTextBaseline = self.drawing_state().text_baseline;
+ let baseline_offset = baseline_offset(text_baseline, &first_font);
+
+ let measurements = TextMeasurements {
+ // width attribute: The width of that inline box, in CSS pixels. (The text's advance width.)
+ width: f64::from(width),
+ // actualBoundingBoxLeft attribute: The distance parallel to the baseline from the alignment point given by
+ // the textAlign attribute to the left side of the bounding rectangle of the given text, in CSS pixels;
+ // positive numbers indicating a distance going left from the given alignment point.
+ actual_bounding_box_left: f64::from(-box_left),
+ // actualBoundingBoxRight attribute: The distance parallel to the baseline from the alignment point given
+ // by the textAlign attribute to the right side of the bounding rectangle of the given text, in CSS pixels;
+ // positive numbers indicating a distance going right from the given alignment point.
+ actual_bounding_box_right: f64::from(box_right),
+ // fontBoundingBoxAscent attribute: The distance from the horizontal line indicated by the textBaseline
+ // attribute to the ascent metric of the first available font, in CSS pixels; positive numbers indicating
+ // a distance going up from the given baseline.
+ font_bounding_box_ascent: f64::from(ascent - baseline_offset),
+ // fontBoundingBoxDescent attribute: The distance from the horizontal line indicated by the textBaseline
+ // attribute to the descent metric of the first available font, in CSS pixels; positive numbers indicating
+ // a distance going down from the given baseline.
+ font_bounding_box_descent: f64::from(descent + baseline_offset),
+ // actualBoundingBoxAscent attribute: The distance from the horizontal line indicated by the textBaseline
+ // attribute to the top of the bounding rectangle of the given text, in CSS pixels; positive numbers
+ // indicating a distance going up from the given baseline.
+ actual_bounding_box_ascent: f64::from(ascent - baseline_offset),
+ // actualBoundingBoxDescent attribute: The distance from the horizontal line indicated by the textBaseline
+ // attribute to the bottom of the bounding rectangle of the given text, in CSS pixels; positive numbers
+ // indicating a distance going down from the given baseline.
+ actual_bounding_box_descent: f64::from(descent + baseline_offset),
+ // emHeightAscent attribute: The distance from the horizontal line indicated by the textBaseline attribute
+ // to the highest top of the em squares in the inline box, in CSS pixels; positive numbers indicating that
+ // the given baseline is below the top of that em square (so this value will usually be positive). Zero if
+ // the given baseline is the top of that em square; half the font size if the given baseline is the middle
+ // of that em square.
+ em_height_ascent: f64::from(ascent - baseline_offset),
+ // emHeightDescent attribute: The distance from the horizontal line indicated by the textBaseline attribute
+ // to the lowest bottom of the em squares in the inline box, in CSS pixels; positive numbers indicating
+ // that the given baseline is above the bottom of that em square. (Zero if the given baseline is the bottom
+ // of that em square.)
+ em_height_descent: f64::from(descent + baseline_offset),
+ // hangingBaseline attribute: The distance from the horizontal line indicated by the textBaseline attribute
+ // to the hanging baseline of the inline box, in CSS pixels; positive numbers indicating that the given
+ // baseline is below the hanging baseline. (Zero if the given baseline is the hanging baseline.)
+ hanging_baseline: f64::from(hanging_baseline - baseline_offset),
+ // alphabeticBaseline attribute: The distance from the horizontal line indicated by the textBaseline
+ // attribute to the alphabetic baseline of the inline box, in CSS pixels; positive numbers indicating that
+ // the given baseline is below the alphabetic baseline. (Zero if the given baseline is the alphabetic
+ // baseline.)
+ alphabetic_baseline: f64::from(-baseline_offset),
+ // ideographicBaseline attribute: The distance from the horizontal line indicated by the textBaseline
+ // attribute to the ideographic-under baseline of the inline box, in CSS pixels; positive numbers
+ // indicating that the given baseline is below the ideographic-under baseline. (Zero if the given baseline
+ // is the ideographic-under baseline.)
+ ideographic_baseline: f64::from(-descent - baseline_offset),
+ };
+
+ Ok(TextMetrics::create(cx.vm(), measurements))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text_drawing_styles.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text_drawing_styles.rs
new file mode 100644
index 00000000000..21e8fb0eac3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text_drawing_styles.rs
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvastextdrawingstyles
+
+use ak::Utf16String;
+
+use super::canvas_rendering_context2d::{CanvasDirection, CanvasTextAlign, CanvasTextBaseline};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::canvas::parse_length;
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D};
+use crate::canvas_2d::drawing_state::LetterSpacing;
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-font
+ pub(crate) fn font(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // On getting, the font attribute must return the serialized form of the current font of the context (with no
+ // 'line-height' component).
+ // NB: When the context has no font yet, that is the font it starts with.
+ Ok(self.drawing_state().font.as_ref().map_or_else(
+ || Utf16String::from_ascii(b"10px sans-serif"),
+ |font| font.serialized.clone(),
+ ))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-font
+ pub(crate) fn set_font(&self, _: &mut CallContext, font: Utf16String) -> WebIdlResult<()> {
+ // The font IDL attribute, on setting, must be parsed as a CSS <'font'> value (but without supporting
+ // property-independent style sheet syntax like 'inherit'), and the resulting font must be assigned to the
+ // context, with the 'line-height' component forced to 'normal', with the 'font-size' component converted to
+ // CSS pixels, and with system fonts being computed to explicit values.
+ // If the new value is syntactically incorrect (including using property-independent style sheet syntax like
+ // 'inherit' or 'initial'), then it must be ignored, without assigning a new font value.
+ // NB: LibWeb's C++ parses the value and resolves it against the canvas.
+ self.assign_font(&font);
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textalign
+ pub(crate) fn text_align(&self, _: &mut CallContext) -> WebIdlResult<CanvasTextAlign> {
+ Ok(self.drawing_state().text_align)
+ }
+
+ pub(crate) fn set_text_align(&self, _: &mut CallContext, text_align: CanvasTextAlign) -> WebIdlResult<()> {
+ self.drawing_state_mut().text_align = text_align;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textbaseline
+ pub(crate) fn text_baseline(&self, _: &mut CallContext) -> WebIdlResult<CanvasTextBaseline> {
+ Ok(self.drawing_state().text_baseline)
+ }
+
+ pub(crate) fn set_text_baseline(&self, _: &mut CallContext, text_baseline: CanvasTextBaseline) -> WebIdlResult<()> {
+ self.drawing_state_mut().text_baseline = text_baseline;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-direction
+ pub(crate) fn direction(&self, _: &mut CallContext) -> WebIdlResult<CanvasDirection> {
+ Ok(self.drawing_state().direction)
+ }
+
+ pub(crate) fn set_direction(&self, _: &mut CallContext, direction: CanvasDirection) -> WebIdlResult<()> {
+ self.drawing_state_mut().direction = direction;
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-letterspacing
+ pub(crate) fn letter_spacing(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The letterSpacing getter steps are to return the serialized form of this's letter spacing.
+ Ok(self.drawing_state().letter_spacing.as_ref().map_or_else(
+ || Utf16String::from_ascii(b"0px"),
+ |letter_spacing| letter_spacing.serialized.clone(),
+ ))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-letterspacing
+ pub(crate) fn set_letter_spacing(&self, _: &mut CallContext, letter_spacing: Utf16String) -> WebIdlResult<()> {
+ // 1. Let parsed be the result of parsing the given value as a CSS <length>.
+ // 2. If parsed is failure, then return.
+ let Some((length, serialized)) = parse_length(&letter_spacing) else {
+ return Ok(());
+ };
+
+ // 3. Set this's letter spacing to parsed.
+ self.drawing_state_mut().letter_spacing = Some(LetterSpacing { length, serialized });
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs
new file mode 100644
index 00000000000..3f27eb21518
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvastransform
+//!
+//! The current default path is kept in the coordinates of the current transformation matrix, so an operation that
+//! changes the matrix transforms the path by the inverse of the change.
+
+use libgfx_rust::AffineTransform;
+
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::canvas_2d::canvas::create_dom_matrix;
+use crate::canvas_2d::context::{CanvasKind, RenderingContext2D, multiply_transforms, rotated, scaled, translated};
+use crate::canvas_2d::float;
+use crate::geometry::dom_matrix_read_only::{DOMMatrix2DInit, validate_and_fixup_2d};
+
+fn all_finite(values: &[f64]) -> bool {
+ values.iter().all(|value| value.is_finite())
+}
+
+impl<K: CanvasKind> RenderingContext2D<K> {
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-scale
+ pub(crate) fn scale(&self, _: &mut CallContext, x: f64, y: f64) -> WebIdlResult<()> {
+ let (x, y) = (float(x), float(y));
+ if !x.is_finite() || !y.is_finite() {
+ return Ok(());
+ }
+ {
+ let mut state = self.drawing_state_mut();
+ 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)),
+ ));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-translate
+ pub(crate) fn translate(&self, _: &mut CallContext, x: f64, y: f64) -> WebIdlResult<()> {
+ let (x, y) = (float(x), float(y));
+ if !x.is_finite() || !y.is_finite() {
+ return Ok(());
+ }
+ {
+ let mut state = self.drawing_state_mut();
+ state.transform = translated(state.transform, x, y);
+ }
+ self.flush_transform();
+ self.transform_path(translated(AffineTransform::identity(), -x, -y));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-rotate
+ pub(crate) fn rotate(&self, _: &mut CallContext, radians: f64) -> WebIdlResult<()> {
+ let radians = float(radians);
+ if !radians.is_finite() {
+ return Ok(());
+ }
+ {
+ let mut state = self.drawing_state_mut();
+ state.transform = rotated(state.transform, radians);
+ }
+ self.flush_transform();
+ self.transform_path(rotated(AffineTransform::identity(), -radians));
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-transform
+ #[allow(clippy::too_many_arguments, reason = "the arguments of transform()")]
+ pub(crate) fn transform(
+ &self,
+ _: &mut CallContext,
+ a: f64,
+ b: f64,
+ c: f64,
+ d: f64,
+ e: f64,
+ f: f64,
+ ) -> WebIdlResult<()> {
+ self.multiply_transform(a, b, c, d, e, f);
+ Ok(())
+ }
+
+ fn multiply_transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
+ // 1. If any of the arguments are infinite or NaN, then return.
+ if !all_finite(&[a, b, c, d, e, f]) {
+ return;
+ }
+
+ // 2. Replace the current transformation matrix with the result of multiplying the current transformation
+ // matrix with the matrix described by:
+ // a c e
+ // b d f
+ // 0 0 1
+ let transform = AffineTransform::new(float(a), float(b), float(c), float(d), float(e), float(f));
+ {
+ let mut state = self.drawing_state_mut();
+ state.transform = multiply_transforms(state.transform, transform);
+ }
+
+ if let Some(inverse) = transform.inverse() {
+ self.transform_path(inverse);
+ }
+ self.flush_transform();
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-gettransform
+ pub(crate) fn get_transform(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ let transform = self.drawing_state().transform;
+ Ok(create_dom_matrix(cx.realm(), transform))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-settransform
+ #[allow(clippy::too_many_arguments, reason = "the arguments of setTransform()")]
+ pub(crate) fn set_transform(
+ &self,
+ _: &mut CallContext,
+ a: f64,
+ b: f64,
+ c: f64,
+ d: f64,
+ e: f64,
+ f: f64,
+ ) -> WebIdlResult<()> {
+ // 1. If any of the arguments are infinite or NaN, then return.
+ if !all_finite(&[a, b, c, d, e, f]) {
+ return Ok(());
+ }
+
+ // 2. Reset the current transformation matrix to the matrix described by:
+ // a c e
+ // b d f
+ // 0 0 1
+ // NB: That is the identity matrix multiplied with the matrix.
+ self.drawing_state_mut().transform = AffineTransform::identity();
+ self.flush_transform();
+ self.multiply_transform(a, b, c, d, e, f);
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-settransform-matrix
+ pub(crate) fn set_transform_to_matrix(&self, _: &mut CallContext, transform: DOMMatrix2DInit) -> WebIdlResult<()> {
+ // 1. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.
+ let matrix = validate_and_fixup_2d(&transform)?;
+
+ // 2. If one or more of matrix's m11 element, m12 element, m21 element, m22 element, m41 element, or m42
+ // element are infinite or NaN, then return.
+ if !matrix.is_finite() {
+ return Ok(());
+ }
+
+ // 3. Reset the current transformation matrix to matrix.
+ let original_transform = {
+ let mut state = self.drawing_state_mut();
+ core::mem::replace(&mut state.transform, matrix.to_affine_transform())
+ };
+
+ self.transform_path(original_transform);
+
+ self.flush_transform();
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-resettransform
+ pub(crate) fn reset_transform(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ // The resetTransform() method, when invoked, must reset the current transformation matrix to the identity
+ // matrix.
+ self.drawing_state_mut().transform = AffineTransform::identity();
+ self.flush_transform();
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index 2de06231ceb..ddc53f11ffe 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -4,30 +4,18 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The C ABI through which the 2D canvas contexts of LibWeb's C++ create the objects of this module and read them,
-//! which the C++ classes of the interfaces declare (Libraries/LibWeb/HTML/CanvasGradient.cpp and the others). A cell
-//! is the cell of an object of the interface that the name of the function says.
+//! The C ABI through which LibWeb's C++ creates and reads the ImageData and ImageBitmap objects that it handles,
+//! which Libraries/LibWeb/HTML/ImageData.cpp and Libraries/LibWeb/HTML/ImageBitmap.cpp declare. A cell is the cell of
+//! an object of the interface that the name of the function says.
use core::ffi::c_void;
use core::ptr::NonNull;
-use ak::Utf16String;
-use libcompositing_rust::display_list::canvas_2d::Paint;
-use libcompositing_rust::display_list::canvas_2d_recorder::FfiCanvas2DPaint;
-use libcompositing_rust::display_list::commands::{Canvas2DPaintKind, Canvas2DPatternRepetition};
-use libgfx_rust::AffineTransform;
use libgfx_rust::image_frame::ImageFrameHandle;
-use libgfx_rust::path::PathMut;
use libjs_rust::api::{RawNativeFunctionResult, Value, Vm};
-use super::canvas_gradient::CanvasGradient;
-use super::canvas_path::{self, CanvasPathError, RoundRectRadius};
-use super::canvas_pattern::CanvasPattern;
use super::image_bitmap::ImageBitmap;
-use super::image_data::{ImageData, ImageDataSettings};
-use super::path2d::Path2D;
-use super::predefined_color_space::PredefinedColorSpace;
-use super::text_metrics::{TextMeasurements, TextMetrics};
+use super::image_data::ImageData;
use crate::bindings::CallContext;
use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments};
@@ -52,380 +40,7 @@ unsafe fn object_from_abi<'a, T: Interface>(cell: *mut c_void) -> &'a T {
unsafe { &*object.as_ptr() }
}
-/// Writes the paint into what C++ lends the recorder.
-fn lend_paint<'a>(paint: Paint<'a>, out_paint: &mut FfiCanvas2DPaint<'a>) {
- match paint {
- Paint::Color(color) => {
- out_paint.kind = Canvas2DPaintKind::Color;
- out_paint.color = color;
- }
- Paint::LinearGradient {
- start_point,
- end_point,
- color_stops,
- } => {
- out_paint.kind = Canvas2DPaintKind::LinearGradient;
- out_paint.start_point = start_point;
- out_paint.end_point = end_point;
- out_paint.color_stop_colors = ak::Span::new(color_stops.colors);
- out_paint.color_stop_positions = ak::Span::new(color_stops.positions);
- }
- Paint::RadialGradient {
- start_center,
- start_radius,
- end_center,
- end_radius,
- color_stops,
- } => {
- out_paint.kind = Canvas2DPaintKind::RadialGradient;
- out_paint.start_point = start_center;
- out_paint.start_radius = start_radius;
- out_paint.end_point = end_center;
- out_paint.end_radius = end_radius;
- out_paint.color_stop_colors = ak::Span::new(color_stops.colors);
- out_paint.color_stop_positions = ak::Span::new(color_stops.positions);
- }
- Paint::ConicGradient {
- center,
- start_angle,
- color_stops,
- } => {
- out_paint.kind = Canvas2DPaintKind::ConicGradient;
- out_paint.start_point = center;
- out_paint.start_angle = start_angle;
- out_paint.color_stop_colors = ak::Span::new(color_stops.colors);
- out_paint.color_stop_positions = ak::Span::new(color_stops.positions);
- }
- Paint::Pattern { .. } => unreachable!("a pattern lends its image, which a paint names by an id"),
- }
-}
-
-/// # Safety
-///
-/// `vm` must be the live VM.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_gradient_create_linear(
- vm: *mut c_void,
- x0: f64,
- y0: f64,
- x1: f64,
- y1: f64,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- cell_into_abi(CanvasGradient::create_linear(vm, x0, y0, x1, y1))
-}
-
-/// # Safety
-///
-/// `vm` must be the live VM.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_gradient_create_radial(
- vm: *mut c_void,
- x0: f64,
- y0: f64,
- r0: f64,
- x1: f64,
- y1: f64,
- r1: f64,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- cell_into_abi(CanvasGradient::create_radial(vm, x0, y0, r0, x1, y1, r1))
-}
-
-/// # Safety
-///
-/// `vm` must be the live VM.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_gradient_create_conic(
- vm: *mut c_void,
- start_angle: f64,
- x: f64,
- y: f64,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- cell_into_abi(CanvasGradient::create_conic(vm, start_angle, x, y))
-}
-
-/// # Safety
-///
-/// `gradient` must be a live cell.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_gradient_is_visible(gradient: *mut c_void) -> bool {
- // SAFETY: The caller passes a live cell.
- unsafe { object_from_abi::<CanvasGradient>(gradient) }.is_visible()
-}
-
-/// Lends the recorder the geometry and the stops of the gradient.
-///
-/// # Safety
-///
-/// `gradient` must be a live cell, which outlives the use of the paint, and nothing may add a stop to it meanwhile.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_gradient_lend_paint<'a>(
- gradient: *mut c_void,
- out_paint: &mut FfiCanvas2DPaint<'a>,
-) {
- // SAFETY: The caller passes a live cell, which outlives 'a.
- let gradient: &'a CanvasGradient = unsafe { object_from_abi(gradient) };
- // SAFETY: The caller adds no stop while the paint is in use.
- lend_paint(unsafe { gradient.paint_unguarded() }, out_paint);
-}
-
-/// # Safety
-///
-/// `vm` must be the live VM.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_text_metrics_create(vm: *mut c_void, measurements: &TextMeasurements) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- cell_into_abi(TextMetrics::create(vm, *measurements))
-}
-
-/// `frame` is a Gfx::DecodedImageFrame that the caller lends for the call, which the pattern keeps a copy of, or null.
-///
-/// # Safety
-///
-/// `vm` must be the live VM, and `frame` a live frame or null.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_pattern_create(
- vm: *mut c_void,
- frame: *const c_void,
- repetition: Canvas2DPatternRepetition,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- // SAFETY: The caller passes a live frame.
- let image = (!frame.is_null()).then(|| unsafe { ImageFrameHandle::retain(frame) });
- cell_into_abi(CanvasPattern::create(vm, image, repetition))
-}
-
-/// Lends the recorder the image, the repetition and the transformation matrix of the pattern.
-///
-/// # Safety
-///
-/// `pattern` must be a live cell, which outlives the use of the paint.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_pattern_lend_paint(pattern: *mut c_void, out_paint: &mut FfiCanvas2DPaint<'_>) {
- // SAFETY: The caller passes a live cell, which keeps the image alive while the paint is in use.
- let pattern: &CanvasPattern = unsafe { object_from_abi(pattern) };
- out_paint.kind = Canvas2DPaintKind::Pattern;
- out_paint.pattern_repetition = pattern.repetition();
- out_paint.pattern_image = pattern.image().map_or(core::ptr::null(), ImageFrameHandle::as_raw);
- if let Some(transform) = pattern.transform() {
- out_paint.has_pattern_transform = true;
- out_paint.pattern_transform = transform;
- }
-}
-
-/// What an operation of a canvas path threw, which `CanvasPathResult` of Libraries/LibWeb/HTML/Canvas/CanvasPath.cpp
-/// mirrors.
-#[derive(Clone, Copy)]
-#[repr(u8)]
-pub enum CanvasPathResultKind {
- Ok,
- IndexSizeError,
- RangeError,
-}
-
-/// The result of an operation of a canvas path, with the message of its exception, an AK::Utf16String that the
-/// caller takes over, unless the operation threw none.
-#[repr(C)]
-pub struct CanvasPathResult {
- kind: CanvasPathResultKind,
- message: usize,
-}
-
-impl From<Result<(), CanvasPathError>> for CanvasPathResult {
- fn from(result: Result<(), CanvasPathError>) -> Self {
- match result {
- Ok(()) => Self {
- kind: CanvasPathResultKind::Ok,
- message: 0,
- },
- Err(error) => Self {
- kind: if error.is_range_error() {
- CanvasPathResultKind::RangeError
- } else {
- CanvasPathResultKind::IndexSizeError
- },
- message: Utf16String::from_utf8(&error.message()).into_raw(),
- },
- }
- }
-}
-
-// NB: `path` of every operation below is a Gfx::Path that the caller lends mutably for the call.
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_close_path(path: *mut c_void) {
- // SAFETY: The caller lends a live path.
- canvas_path::close_path(&mut unsafe { PathMut::from_raw(path) });
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_move_to(path: *mut c_void, x: f32, y: f32) {
- // SAFETY: The caller lends a live path.
- canvas_path::move_to(&mut unsafe { PathMut::from_raw(path) }, x, y);
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_line_to(path: *mut c_void, x: f32, y: f32) {
- // SAFETY: The caller lends a live path.
- canvas_path::line_to(&mut unsafe { PathMut::from_raw(path) }, x, y);
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_quadratic_curve_to(path: *mut c_void, cpx: f32, cpy: f32, x: f32, y: f32) {
- // SAFETY: The caller lends a live path.
- canvas_path::quadratic_curve_to(&mut unsafe { PathMut::from_raw(path) }, cpx, cpy, x, y);
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_bezier_curve_to(
- path: *mut c_void,
- cp1x: f64,
- cp1y: f64,
- cp2x: f64,
- cp2y: f64,
- x: f64,
- y: f64,
-) {
- // SAFETY: The caller lends a live path.
- canvas_path::bezier_curve_to(&mut unsafe { PathMut::from_raw(path) }, cp1x, cp1y, cp2x, cp2y, x, y);
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_arc_to(
- path: *mut c_void,
- transform: &AffineTransform,
- x1: f64,
- y1: f64,
- x2: f64,
- y2: f64,
- radius: f64,
-) -> CanvasPathResult {
- // SAFETY: The caller lends a live path.
- canvas_path::arc_to(
- &mut unsafe { PathMut::from_raw(path) },
- *transform,
- x1,
- y1,
- x2,
- y2,
- radius,
- )
- .into()
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_rect(path: *mut c_void, x: f64, y: f64, w: f64, h: f64) {
- // SAFETY: The caller lends a live path.
- canvas_path::rect(&mut unsafe { PathMut::from_raw(path) }, x, y, w, h);
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_round_rect(
- path: *mut c_void,
- x: f64,
- y: f64,
- w: f64,
- h: f64,
- radii: ak::Span<'_, RoundRectRadius>,
-) -> CanvasPathResult {
- // SAFETY: The caller lends a live path.
- canvas_path::round_rect(&mut unsafe { PathMut::from_raw(path) }, x, y, w, h, radii.as_slice()).into()
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_arc(
- path: *mut c_void,
- x: f32,
- y: f32,
- radius: f32,
- start_angle: f32,
- end_angle: f32,
- counterclockwise: bool,
-) -> CanvasPathResult {
- // SAFETY: The caller lends a live path.
- let mut path = unsafe { PathMut::from_raw(path) };
- canvas_path::arc(&mut path, x, y, radius, start_angle, end_angle, counterclockwise).into()
-}
-
-/// # Safety
-///
-/// `path` must be a live Gfx::Path.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_canvas_path_ellipse(
- path: *mut c_void,
- x: f32,
- y: f32,
- radius_x: f32,
- radius_y: f32,
- rotation: f32,
- start_angle: f32,
- end_angle: f32,
- counterclockwise: bool,
-) -> CanvasPathResult {
- // SAFETY: The caller lends a live path.
- let mut path = unsafe { PathMut::from_raw(path) };
- canvas_path::ellipse(
- &mut path,
- x,
- y,
- radius_x,
- radius_y,
- rotation,
- start_angle,
- end_angle,
- counterclockwise,
- )
- .into()
-}
-
-/// The Gfx::Path of the Path2D, which the caller borrows.
-///
-/// # Safety
-///
-/// `path` must be a live cell, which outlives the use of the Gfx::Path, and nothing may change the path meanwhile.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_path2d_path(path: *mut c_void) -> *const c_void {
- // SAFETY: The caller passes a live cell.
- let path: &Path2D = unsafe { object_from_abi(path) };
- // SAFETY: The caller keeps the path from changing while it reads it.
- unsafe { path.path_unguarded() }.as_raw()
-}
-
-/// Creates an ImageData of the size, with transparent black pixels, in the realm, as the 2D contexts do, and stores
+/// Creates an ImageData of the size, with transparent black pixels and the sRGB color space, in the realm, and stores
/// its cell, or throws what initializing an ImageData throws.
///
/// # Safety
@@ -437,17 +52,12 @@ pub unsafe extern "C" fn web_image_data_create(
realm: *mut c_void,
width: u32,
height: u32,
- has_color_space: bool,
- color_space: PredefinedColorSpace,
out_image_data: &mut *mut c_void,
) -> RawNativeFunctionResult {
// SAFETY: The caller passes the live VM and a live realm.
let (vm, realm) = unsafe { realm_arguments(vm, realm) };
let mut cx = CallContext::new(vm, realm);
- let settings = ImageDataSettings {
- color_space: has_color_space.then_some(color_space),
- };
- let result = ImageData::create(&mut cx, width, height, Some(&settings)).map(|image_data| {
+ let result = ImageData::create(&mut cx, width, height, None).map(|image_data| {
*out_image_data = cell_into_abi(image_data);
Value::UNDEFINED
});
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index beca718088c..2deca7e1c34 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -4,9 +4,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The objects that the 2D canvas contexts draw with, the images that they and WebGL read and write the pixels of, and
-//! the operations of a path that Path2D and the contexts share. The contexts are still LibWeb's C++, which creates and
-//! reads these objects and builds its paths through the C ABI of `exports`.
+//! The 2D canvas contexts, with the attributes and operations of each of their mixins in the module of its IDL file,
+//! the objects that they draw with, the images that they and WebGL read and write the pixels of, and the operations of
+//! a path that Path2D and the contexts share. The state that the contexts share is in crate::canvas_2d.
pub(crate) mod canvas_path;
pub(crate) mod color_stops;
@@ -14,16 +14,52 @@ pub(crate) mod predefined_color_space;
// What follows runs on the JS runtime, which the tests of the crate do not link.
#[cfg(not(test))]
+pub(crate) mod canvas_compositing;
+#[cfg(not(test))]
+pub(crate) mod canvas_draw_image;
+#[cfg(not(test))]
+pub(crate) mod canvas_draw_path;
+#[cfg(not(test))]
+pub(crate) mod canvas_fill_stroke_styles;
+#[cfg(not(test))]
+pub(crate) mod canvas_filters;
+#[cfg(not(test))]
pub(crate) mod canvas_gradient;
#[cfg(not(test))]
+pub(crate) mod canvas_image_data;
+#[cfg(not(test))]
+pub(crate) mod canvas_image_smoothing;
+#[cfg(not(test))]
+pub(crate) mod canvas_path_drawing_styles;
+#[cfg(not(test))]
pub(crate) mod canvas_pattern;
#[cfg(not(test))]
+pub(crate) mod canvas_rect;
+#[cfg(not(test))]
+pub(crate) mod canvas_rendering_context2d;
+#[cfg(not(test))]
+pub(crate) mod canvas_rendering_context2d_settings;
+#[cfg(not(test))]
+pub(crate) mod canvas_settings;
+#[cfg(not(test))]
+pub(crate) mod canvas_shadow_styles;
+#[cfg(not(test))]
+pub(crate) mod canvas_state;
+#[cfg(not(test))]
+pub(crate) mod canvas_text;
+#[cfg(not(test))]
+pub(crate) mod canvas_text_drawing_styles;
+#[cfg(not(test))]
+pub(crate) mod canvas_transform;
+#[cfg(not(test))]
pub(crate) mod exports;
#[cfg(not(test))]
pub(crate) mod image_bitmap;
#[cfg(not(test))]
pub(crate) mod image_data;
#[cfg(not(test))]
+pub(crate) mod offscreen_canvas_rendering_context2d;
+#[cfg(not(test))]
pub(crate) mod path2d;
#[cfg(not(test))]
pub(crate) mod text_metrics;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/offscreen_canvas_rendering_context2d.rs b/Libraries/LibWeb/Bindings/Rust/src/html/offscreen_canvas_rendering_context2d.rs
new file mode 100644
index 00000000000..8bc830141c3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/offscreen_canvas_rendering_context2d.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#offscreencanvasrenderingcontext2d
+
+use crate::canvas_2d::context::{Offscreen, RenderingContext2D};
+
+pub(crate) type OffscreenCanvasRenderingContext2D = RenderingContext2D<Offscreen>;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/text_metrics.rs b/Libraries/LibWeb/Bindings/Rust/src/html/text_metrics.rs
index 519a7cf44f1..0d4130a0009 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/text_metrics.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/text_metrics.rs
@@ -11,9 +11,8 @@ use libjs_rust::api::{Trace, Vm};
use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
-/// The measurements of a text, in CSS pixels, which measureText() takes, as the members of TextMetrics describe them.
+/// The measurements of a text, in CSS pixels, as the members of TextMetrics describe them.
#[derive(Clone, Copy, Debug, Default)]
-#[repr(C)]
pub(crate) struct TextMeasurements {
// x-direction
pub(crate) width: f64,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index c51bbcc43eb..9e1593eb4a6 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -30,6 +30,14 @@ pub(crate) mod ak_format;
reason = "the generated bindings use only the conversions their interfaces need"
)]
pub(crate) mod bindings;
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
pub(crate) mod canvas_2d;
#[cfg_attr(
not(web_idl_bindings),
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 7c178662c41..57faa9606fe 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -439,20 +439,11 @@ set(SOURCES
HTML/BeforeUnloadEvent.cpp
HTML/BroadcastChannel.cpp
HTML/BrowsingContext.cpp
- HTML/Canvas/AbstractCanvasMixin.cpp
HTML/Canvas/Canvas2DContextBase.cpp
- HTML/Canvas/Canvas2DRecorder.cpp
HTML/Canvas/CanvasHost.cpp
HTML/Canvas/CanvasDrawImage.cpp
- HTML/Canvas/CanvasFillStrokeStyles.cpp
- HTML/Canvas/CanvasPath.cpp
- HTML/Canvas/CanvasState.cpp
- HTML/Canvas/CanvasTextDrawingStyles.cpp
- HTML/Canvas/DrawingState.cpp
HTML/Canvas/RemoteCanvas2DTransportFFI.cpp
HTML/Canvas/SerializeBitmap.cpp
- HTML/CanvasGradient.cpp
- HTML/CanvasPattern.cpp
HTML/CanvasRenderingContext2D.cpp
HTML/CheckUnloadingCanceledState.cpp
HTML/CloseEvent.cpp
@@ -627,7 +618,6 @@ set(SOURCES
HTML/Parser/HTMLTokenizer.cpp
HTML/Parser/IncrementalDocumentParser.cpp
HTML/Parser/SpeculativeHTMLParser.cpp
- HTML/Path2D.cpp
HTML/Plugin.cpp
HTML/PluginArray.cpp
HTML/PolicyContainers.cpp
@@ -678,7 +668,6 @@ set(SOURCES
HTML/TagNames.cpp
HTML/TextDirective.cpp
HTML/TextDirectiveGenerator.cpp
- HTML/TextMetrics.cpp
HTML/TextTrack.cpp
HTML/TextTrackCue.cpp
HTML/TextTrackCueList.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 2947a732903..755a388fc6d 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -805,7 +805,6 @@ class Navigator;
class OffscreenCanvas;
class OffscreenCanvasRenderingContext2D;
class PageTransitionEvent;
-class Path2D;
class Plugin;
class PluginArray;
class PopoverTargetAttributes;
@@ -825,7 +824,6 @@ class Storage;
class StructuredSerializeReader;
class StructuredSerializeWriter;
class SubmitEvent;
-class TextMetrics;
class TextTrack;
class TextTrackCue;
class TextTrackCueList;
diff --git a/Libraries/LibWeb/HTML/Canvas/AbstractCanvasMixin.cpp b/Libraries/LibWeb/HTML/Canvas/AbstractCanvasMixin.cpp
deleted file mode 100644
index 5d01aed07cd..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/AbstractCanvasMixin.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "AbstractCanvasMixin.h"
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/Parser/RustSyntaxParsing.h>
-#include <LibWeb/CSS/ValueType.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/ValueParserRustFFI.h>
-
-namespace Web::HTML {
-
-// https://drafts.csswg.org/css-color-4/#parse-a-css-color-value
-Optional<Color> AbstractCanvasMixin::parse_a_css_color_value(Utf16View value) const
-{
- // To parse a CSS <color> value, given a string input, and an optional context element element:
-
- // 1. Parse input as a <color>. If the result is failure, return failure; otherwise, let color be the result.
- RefPtr<CSS::StyleValue const> color;
- Optional<Color> resolved_color;
- bool found_cached_value = false;
- bool const input_is_cacheable = value.length_in_code_units() <= max_color_cache_input_length;
- if (input_is_cacheable) {
- for (size_t index = 0; index < m_color_cache.size(); ++index) {
- if (m_color_cache[index].input != value)
- continue;
-
- color = m_color_cache[index].parsed_value;
- resolved_color = m_color_cache[index].resolved_color;
- found_cached_value = true;
-
- if (index != m_color_cache.size() - 1) {
- auto entry = move(m_color_cache[index]);
- m_color_cache.remove(index);
- m_color_cache.append(move(entry));
- }
- break;
- }
- }
-
- if (!found_cached_value) {
- auto parsed_color = CSS::Parser::ValueParserFFI::rust_parse_simple_color(CSS::Parser::ffi_utf16_view(value));
- if (parsed_color.success)
- resolved_color = Color(parsed_color.red, parsed_color.green, parsed_color.blue, parsed_color.alpha);
- if (!resolved_color.has_value())
- color = parse_css_type(CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue }, value, CSS::ValueType::Color);
-
- if (input_is_cacheable) {
- if (m_color_cache.size() == max_color_cache_size)
- m_color_cache.remove(0);
- m_color_cache.append({ Utf16String::from_utf16(value), color, resolved_color });
- }
- }
-
- if (resolved_color.has_value())
- return resolved_color;
-
- if (!color)
- return {};
-
- // 2. Let used color be the result of resolving color to a used color. If the value of other properties on the
- // element a <color> is on is required to do the resolution (such as resolving a currentcolor or system color),
- // use element if it was passed, or the initial values of the properties if not.
-
- // AD-HOC: The spec tells us to use the element's properties as context but doesn't tell us how to resolve other
- // context dependent values (e.g. viewport relative lengths). This also differs from how font-relative
- // lengths are absolutized (i.e. using the canvas' font rather than the element's) in other canvas values
- // (e.g. letterSpacing) so we instead use a computation context based on the drawing state. See
- // https://github.com/whatwg/html/issues/12505.
- auto computation_context = computation_context_for_drawing_state();
-
- auto used_color = color->absolutized(computation_context)->to_color(canvas_host().canvas_color_resolution_style()).value();
-
- // 3. Return used color.
- return used_color;
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/AbstractCanvasMixin.h b/Libraries/LibWeb/HTML/Canvas/AbstractCanvasMixin.h
deleted file mode 100644
index 3477d70c84e..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/AbstractCanvasMixin.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Utf16View.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/Canvas/Canvas2DRecorder.h>
-#include <LibWeb/HTML/Canvas/CanvasHost.h>
-#include <LibWeb/HTML/Canvas/DrawingState.h>
-
-#pragma once
-
-namespace Web::HTML {
-
-class AbstractCanvasMixin {
-protected:
- virtual CanvasHost& canvas_host() const = 0;
- virtual DrawingState& drawing_state() = 0;
- virtual DrawingState const& drawing_state() const = 0;
- virtual JS::Realm& my_realm() = 0;
- virtual Gfx::Path& mutable_path() = 0;
- // The recorder of the canvas, ready to record, or null if the canvas cannot draw.
- virtual Canvas2DRecorder* canvas_recorder() = 0;
- virtual CSS::ComputationContext computation_context_for_drawing_state() const = 0;
- virtual void set_font(Utf16View font) = 0;
- virtual float resolved_letter_spacing() const = 0;
- Optional<Color> parse_a_css_color_value(Utf16View value) const;
-
-private:
- // Context-independent simple colors store a resolved color. Other colors store their parsed style value so they
- // can be resolved against the current canvas context on every use. A cache entry with neither is a parse failure.
- struct ColorCacheEntry {
- Utf16String input;
- RefPtr<CSS::StyleValue const> parsed_value;
- Optional<Color> resolved_color;
- };
-
- static constexpr size_t max_color_cache_size = 8;
- static constexpr size_t max_color_cache_input_length = 128;
- mutable Vector<ColorCacheEntry> m_color_cache;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index a768fdfe3d6..71d2e873174 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -2,6 +2,8 @@
* Copyright (c) 2020-2024, Andreas Kling <[email protected]>
* Copyright (c) 2021-2022, Linus Groh <[email protected]>
* Copyright (c) 2023, MacDue <[email protected]>
+ * Copyright (c) 2023, Bastiaan van der Plaat <[email protected]>
+ * Copyright (c) 2023-2026, Callum Law <[email protected]>
* Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
* Copyright (c) 2024, Lucien Fiorini <[email protected]>
* Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
@@ -9,389 +11,280 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Checked.h>
-#include <AK/NumericLimits.h>
-#include <AK/OwnPtr.h>
#include <AK/Utf16StringBuilder.h>
+#include <LibCompositing/RustFFI.h>
+#include <LibCompositing/Video/VideoFrameHold.h>
+#include <LibGfx/AffineTransform.h>
#include <LibGfx/Bitmap.h>
-#include <LibGfx/CompositingAndBlendingOperator.h>
#include <LibGfx/DecodedImageFrame.h>
-#include <LibGfx/Rect.h>
-#include <LibGfx/TextAlignment.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibJS/Runtime/ValueInlines.h>
-#include <LibWeb/Bindings/DOMRectReadOnly.h>
+#include <LibGfx/FontCascadeList.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/FontComputer.h>
+#include <LibWeb/CSS/FontResolution.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/PropertyID.h>
+#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleValues/FilterStyleValue.h>
+#include <LibWeb/CSS/StyleValues/FontStyleStyleValue.h>
+#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
+#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
+#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
+#include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
#include <LibWeb/CSS/StyleValues/URLStyleValue.h>
+#include <LibWeb/CSS/ValueType.h>
#include <LibWeb/Compositor/CompositorHost.h>
+#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Event.h>
+#include <LibWeb/Geometry/DOMMatrix.h>
#include <LibWeb/HTML/Canvas/Canvas2DContextBase.h>
+#include <LibWeb/HTML/Canvas/CanvasDrawImage.h>
#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>
+#include <LibWeb/HTML/CanvasRenderingContext2D.h>
#include <LibWeb/HTML/DecodedImageData.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/HTMLCanvasElement.h>
#include <LibWeb/HTML/HTMLImageElement.h>
-#include <LibWeb/HTML/HTMLMediaElement.h>
#include <LibWeb/HTML/HTMLVideoElement.h>
#include <LibWeb/HTML/ImageBitmap.h>
-#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/ImageRequest.h>
#include <LibWeb/HTML/OffscreenCanvas.h>
#include <LibWeb/HTML/OffscreenCanvasRenderingContext2D.h>
-#include <LibWeb/HTML/Path2D.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/TextMetrics.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/Layout/ImageProvider.h>
#include <LibWeb/Page/Page.h>
-#include <LibWeb/Painting/PaintingRustBridge.h>
+#include <LibWeb/Platform/FontPlugin.h>
+#include <LibWeb/SVG/SVGAnimatedLength.h>
#include <LibWeb/SVG/SVGImageElement.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/Infra/CharacterTypes.h>
+#include <LibWebCommon/Bindings/PredefinedColorSpace.h>
namespace Web::HTML {
-Canvas2DContextBase::Canvas2DContextBase(JS::Realm& realm, Gfx::IntSize initial_size, Bindings::CanvasRenderingContext2DSettings context_attributes)
- : CanvasPath(static_cast<CanvasState const&>(*this))
- , m_size(initial_size)
- , m_context_attributes(move(context_attributes))
- , m_realm(realm)
-{
-}
-
-Canvas2DContextBase::~Canvas2DContextBase() = default;
-
-void Canvas2DContextBase::finalize()
-{
- discard_backing_storage();
- Base::finalize();
+namespace {
+
+// `ContextCreationArguments` of Bindings/Rust/src/canvas_2d/exports.rs.
+struct ContextCreationArguments {
+ void* canvas { nullptr };
+ void* canvas_host { nullptr };
+ bool canvas_is_offscreen { false };
+ i32 width { 0 };
+ i32 height { 0 };
+ bool alpha { true };
+ bool desynchronized { false };
+ Bindings::PredefinedColorSpace color_space { Bindings::PredefinedColorSpace::Srgb };
+ Bindings::CanvasColorType color_type { Bindings::CanvasColorType::Unorm8 };
+ bool will_read_frequently { false };
+};
+
+// `FontMetricsSource` of Bindings/Rust/src/canvas_2d/canvas.rs: the font of the context, if it has one yet.
+struct FontMetricsSource {
+ Gfx::FontCascadeList const* cascade { nullptr };
+ // The size of the font, as the raw value of a CSSPixels.
+ i32 font_size { 0 };
+};
+
+// `ResolvedFontAbi` of Bindings/Rust/src/canvas_2d/canvas.rs.
+struct ResolvedFont {
+ // A Gfx::FontCascadeList with a reference that Rust takes over.
+ Gfx::FontCascadeList const* cascade { nullptr };
+ u64 environment_generation { 0 };
+ i32 font_size { 0 };
+ // An AK::Utf16String that Rust takes over.
+ FlatPtr serialized { 0 };
+};
+
+// `CanvasImageSourceKind` of Bindings/Rust/src/canvas_2d/canvas.rs: the sources of images that are implemented in C++.
+enum class CanvasImageSourceKind : u8 {
+ HTMLImageElement,
+ SVGImageElement,
+ HTMLVideoElement,
+ HTMLCanvasElement,
+ OffscreenCanvas,
+};
+
+// `CapturedVideoFrameAbi` of Bindings/Rust/src/canvas_2d/canvas.rs.
+struct CapturedVideoFrame {
+ // A Compositing::VideoFrameHold with a reference that Rust takes over.
+ Compositing::VideoFrameHold* hold { nullptr };
+ u64 sink_handle { 0 };
+ u64 generation { 0 };
+};
+
+}
+
+// NB: The color space and the color type cross the bridge as their underlying values, which canvas_2d/exports.rs
+// reads in this order.
+static_assert(sizeof(Bindings::PredefinedColorSpace) == sizeof(u8));
+static_assert(to_underlying(Bindings::PredefinedColorSpace::Srgb) == 0);
+static_assert(to_underlying(Bindings::PredefinedColorSpace::DisplayP3Linear) == 3);
+static_assert(sizeof(Bindings::CanvasColorType) == sizeof(u8));
+static_assert(to_underlying(Bindings::CanvasColorType::Unorm8) == 0);
+static_assert(to_underlying(Bindings::CanvasColorType::Float16) == 1);
+static_assert(sizeof(Gfx::AffineTransform) == 6 * sizeof(float));
+static_assert(sizeof(Gfx::IntRect) == 4 * sizeof(int));
+
+extern "C" {
+
+// Defined in Bindings/Rust/src/canvas_2d/exports.rs. A context is the cell of a context of either kind.
+void* web_canvas_2d_context_create(JSVM*, ContextCreationArguments const*);
+void* web_canvas_2d_context_canvas_host(void const* context);
+bool web_canvas_2d_context_origin_clean(void const* context);
+void web_canvas_2d_context_set_size(void* context, i32 width, i32 height);
+void web_canvas_2d_context_reset_to_default_state(void* context);
+void web_canvas_2d_context_ensure_backing_storage(void* context);
+void web_canvas_2d_context_discard_backing_storage(void* context);
+bool web_canvas_2d_context_has_backing_storage(void const* context);
+void web_canvas_2d_context_drop_cached_readback(void* context);
+bool web_canvas_2d_context_is_lost(void const* context);
+void web_canvas_2d_context_set_lost(void* context, bool lost);
+void web_canvas_2d_context_prepare_for_compositing(void* context);
+bool web_canvas_2d_context_canvas_id(void const* context, u64* out_canvas_id);
+void* web_canvas_2d_context_read_pixels(void* context, Gfx::IntRect rect, u8 alpha_type);
+bool web_canvas_2d_context_draw_image_bitmap(void* context, void* image_bitmap, float x, float y);
+
+// What the Rust implementation asks of LibWeb, declared in Bindings/Rust/src/canvas_2d/canvas.rs.
+void web_canvas_2d_canvas_did_change_content(void* canvas_host);
+void web_canvas_2d_canvas_did_create_backing_storage(void* canvas_host);
+void* web_canvas_2d_canvas_create_transport(void* canvas_host);
+void* web_canvas_2d_canvas_wrapper(void* canvas, bool canvas_is_offscreen, void* realm);
+void* web_canvas_2d_canvas_relevant_realm(void* canvas_host);
+u64 web_canvas_2d_canvas_font_environment_generation(void* canvas_host);
+bool web_canvas_2d_canvas_resolve_font(void* canvas, bool canvas_is_offscreen, FlatPtr font, ResolvedFont* out_font);
+void web_canvas_2d_canvas_resolve_color(void* canvas_host, CSS::StyleValue const* color, FontMetricsSource, Gfx::Color* out_color);
+float web_canvas_2d_canvas_resolve_length(void* canvas_host, CSS::StyleValue const* length, FontMetricsSource);
+bool web_canvas_2d_canvas_parse_filter(void* canvas_host, FlatPtr filter, FontMetricsSource, void* functions, void (*append_function)(void*, Compositing::RustFFI::FfiFilterFunction const*));
+CSS::StyleValue const* web_canvas_2d_parse_color(FlatPtr color);
+CSS::StyleValue const* web_canvas_2d_parse_length(FlatPtr length, FlatPtr* out_serialized);
+void web_canvas_2d_style_value_ref(CSS::StyleValue const*);
+void web_canvas_2d_style_value_unref(CSS::StyleValue const*);
+void* web_canvas_2d_create_dom_matrix(void* realm, Gfx::AffineTransform const*);
+Gfx::DecodedImageFrame* web_canvas_2d_image_frame_from_pixels(u8 const* first_row, size_t pitch, i32 width, i32 height);
+u8 web_canvas_2d_check_usability_of_image(void* source_wrapper, CanvasImageSourceKind, FlatPtr* out_message);
+void 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);
+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*);
+
+// What Bindings/Rust/src/html/canvas_gradient.rs asks of LibWeb.
+bool web_canvas_gradient_parse_color(FlatPtr color, Gfx::Color* out_color);
+}
+
+static void* cell_of(Canvas2DContextBase const& context)
+{
+ return const_cast<Canvas2DContextBase*>(&context);
+}
+
+Canvas2DContextBase& Canvas2DContextBase::create(CanvasHost& canvas_host, GC::Cell& canvas, bool canvas_is_offscreen, CanvasRenderingContext2DSettings const& context_attributes)
+{
+ auto size = canvas_host.bitmap_size_for_canvas();
+ ContextCreationArguments arguments {
+ .canvas = &canvas,
+ .canvas_host = &canvas_host,
+ .canvas_is_offscreen = canvas_is_offscreen,
+ .width = size.width(),
+ .height = size.height(),
+ .alpha = context_attributes.alpha,
+ .desynchronized = context_attributes.desynchronized,
+ .color_space = context_attributes.color_space,
+ .color_type = context_attributes.color_type,
+ .will_read_frequently = context_attributes.will_read_frequently,
+ };
+ return *static_cast<Canvas2DContextBase*>(web_canvas_2d_context_create(JS::HostABI::vm_to_abi(JS::VM::the()), &arguments));
}
-void Canvas2DContextBase::visit_edges(Cell::Visitor& visitor)
+CanvasHost& Canvas2DContextBase::canvas_host() const
{
- Base::visit_edges(visitor);
- CanvasState::visit_edges(visitor);
- visitor.visit(m_realm);
+ return *static_cast<CanvasHost*>(web_canvas_2d_context_canvas_host(cell_of(*this)));
}
-GC::Ptr<Bindings::Wrappable> Canvas2DContextBase::relevant_global_impl() const
+bool Canvas2DContextBase::origin_clean() const
{
- return canvas_host().canvas_relevant_global_impl();
+ return web_canvas_2d_context_origin_clean(cell_of(*this));
}
-size_t Canvas2DContextBase::external_memory_size() const
+void Canvas2DContextBase::set_size(Gfx::IntSize const& size)
{
- auto size = Base::external_memory_size();
- if (m_cached_readback)
- size = JS::saturating_add_external_memory_size(size, m_cached_readback->size_in_bytes());
- if (!has_backing_storage())
- return size;
-
- auto surface_size = m_size;
- if (surface_size.is_empty())
- return size;
-
- Checked<size_t> pixel_size = static_cast<size_t>(surface_size.width());
- pixel_size *= static_cast<size_t>(surface_size.height());
- pixel_size *= sizeof(u32);
- if (pixel_size.has_overflow())
- return NumericLimits<size_t>::max();
- return JS::saturating_add_external_memory_size(size, pixel_size.value());
+ web_canvas_2d_context_set_size(this, size.width(), size.height());
}
-Gfx::Path Canvas2DContextBase::rect_path(float x, float y, float width, float height)
+void Canvas2DContextBase::reset_to_default_state()
{
- auto top_left = Gfx::FloatPoint(x, y);
- auto top_right = Gfx::FloatPoint(x + width, y);
- auto bottom_left = Gfx::FloatPoint(x, y + height);
- auto bottom_right = Gfx::FloatPoint(x + width, y + height);
-
- Gfx::Path path;
- path.move_to(top_left);
- path.line_to(top_right);
- path.line_to(bottom_right);
- path.line_to(bottom_left);
- path.line_to(top_left);
- return path;
+ web_canvas_2d_context_reset_to_default_state(this);
}
-void Canvas2DContextBase::fill_rect(float x, float y, float width, float height)
+void Canvas2DContextBase::prepare_for_compositing()
{
- fill_internal(rect_path(x, y, width, height), Gfx::WindingRule::EvenOdd);
+ web_canvas_2d_context_prepare_for_compositing(this);
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-clearrect
-void Canvas2DContextBase::clear_rect(float x, float y, float width, float height)
+void Canvas2DContextBase::ensure_backing_storage()
{
- // 1. If any of the arguments are infinite or NaN, then return.
- if (!isfinite(x) || !isfinite(y) || !isfinite(width) || !isfinite(height))
- return;
-
- if (auto* recorder = canvas_recorder()) {
- auto rect = Gfx::FloatRect(x, y, width, height);
- recorder->clear_rect(rect, clear_color());
- did_draw(rect);
- }
+ web_canvas_2d_context_ensure_backing_storage(this);
}
-void Canvas2DContextBase::stroke_rect(float x, float y, float width, float height)
+void Canvas2DContextBase::discard_backing_storage()
{
- stroke_internal(rect_path(x, y, width, height));
+ web_canvas_2d_context_discard_backing_storage(this);
}
-// 4.12.5.1.14 Drawing images, https://html.spec.whatwg.org/multipage/canvas.html#drawing-images
-WebIDL::ExceptionOr<void> Canvas2DContextBase::draw_image_internal(CanvasImageSource const& image, float source_x, float source_y, float source_width, float source_height, float destination_x, float destination_y, float destination_width, float destination_height)
+Optional<Compositing::CanvasId> Canvas2DContextBase::canvas_id() const
{
- // 1. If any of the arguments are infinite or NaN, then return.
- if (!isfinite(source_x) || !isfinite(source_y) || !isfinite(source_width) || !isfinite(source_height) || !isfinite(destination_x) || !isfinite(destination_y) || !isfinite(destination_width) || !isfinite(destination_height))
- return {};
-
- // 2. Let usability be the result of checking the usability of image.
- auto usability = TRY(check_usability_of_image(image));
-
- // 3. If usability is bad, then return (without drawing anything).
- if (usability == CanvasImageSourceUsability::Bad)
- return {};
-
- auto source_bitmap_rect = Gfx::IntRect { {}, canvas_image_source_dimensions(image) };
-
- // 4. Establish the source and destination rectangles as follows:
- // If not specified, the dw and dh arguments must default to the values of sw and sh, interpreted such that one CSS pixel in the image is treated as one unit in the output bitmap's coordinate space.
- // If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's intrinsic width in image pixels, and the image's intrinsic height in image pixels, respectively.
- // If the image has no intrinsic dimensions, then the concrete object size must be used instead, as determined using the CSS "Concrete Object Size Resolution" algorithm, with the specified size having
- // neither a definite width nor height, nor any additional constraints, the object's intrinsic properties being those of the image argument, and the default object size being the size of the output bitmap.
- // The source rectangle is the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).
- // The destination rectangle is the rectangle whose corners are the four points (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).
- // NOTE: Implemented in drawImage() overloads
- if (source_width < 0) {
- source_x += source_width;
- source_width = abs(source_width);
- }
- if (source_height < 0) {
- source_y += source_height;
- source_height = abs(source_height);
- }
- if (destination_width < 0) {
- destination_x += destination_width;
- destination_width = abs(destination_width);
- }
- if (destination_height < 0) {
- destination_y += destination_height;
- destination_height = abs(destination_height);
- }
-
- // The source rectangle is the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).
- auto source_rect = Gfx::FloatRect { source_x, source_y, source_width, source_height };
- // The destination rectangle is the rectangle whose corners are the four points (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).
- auto destination_rect = Gfx::FloatRect { destination_x, destination_y, destination_width, destination_height };
- // When the source rectangle is outside the source image, the source rectangle must be clipped
- // to the source image and the destination rectangle must be clipped in the same proportion.
- auto clipped_source = source_rect.intersected(source_bitmap_rect.to_type<float>());
- auto clipped_destination = destination_rect;
- if (clipped_source != source_rect) {
- clipped_destination.set_width(clipped_destination.width() * (clipped_source.width() / source_rect.width()));
- clipped_destination.set_height(clipped_destination.height() * (clipped_source.height() / source_rect.height()));
- }
-
- // 5. If one of the sw or sh arguments is zero, then return. Nothing is painted.
- if (source_width == 0 || source_height == 0)
- return {};
-
- // 6. Paint the region of the image argument specified by the source rectangle on the region of the rendering context's output bitmap specified by the destination rectangle, after applying the current transformation matrix to the destination rectangle.
- auto scaling_mode = Gfx::ScalingMode::NearestNeighbor;
- if (drawing_state().image_smoothing_enabled) {
- // FIXME: Honor drawing_state().image_smoothing_quality
- scaling_mode = Gfx::ScalingMode::BilinearMipmap;
- }
-
- auto draw_canvas_by_id = [&](Compositing::CanvasId source_canvas_id, bool source_is_2d) {
- if (auto* recorder = canvas_recorder()) {
- recorder->draw_canvas(source_canvas_id, destination_rect, source_rect.to_rounded<int>(), scaling_mode, compositing_for_drawing_state());
- did_draw(destination_rect);
- if (!source_is_2d)
- recorder->flush();
- }
-
- // 7. If image is not origin-clean, then set the CanvasRenderingContext2D's origin-clean flag to false.
- if (image_is_not_origin_clean(image))
- m_origin_clean = false;
- };
-
- if (auto const* source_canvas = image.get_pointer<GC::Ref<HTMLCanvasElement>>(); source_canvas && !(*source_canvas)->is_placeholder()) {
- // A 2D source needs no eager synchronization: its recorded commands
- // precede this DrawCanvas in the shared ordered stream, so the replay
- // sees them by construction. WebGL frames are presented by a separate
- // message and the source's registry surface is its live drawing buffer,
- // so present the source now and flush the DrawCanvas right after it,
- // before a later WebGL frame can overtake the reference.
- bool const source_is_2d = (*source_canvas)->canvas_rendering_context_2d() != nullptr;
- (*source_canvas)->ensure_backing_storage();
- if (!source_is_2d)
- (*source_canvas)->prepare_for_compositing();
- if (auto source_canvas_id = (*source_canvas)->canvas_id(); source_canvas_id.has_value()) {
- draw_canvas_by_id(*source_canvas_id, source_is_2d);
- return {};
- }
- }
-
- if (auto const* source_canvas = image.get_pointer<GC::Ref<OffscreenCanvas>>()) {
- if (auto const* source_context = (*source_canvas)->context().get_pointer<GC::Ref<OffscreenCanvasRenderingContext2D>>()) {
- (*source_context)->ensure_backing_storage();
- if (auto source_canvas_id = (*source_context)->canvas_id(); source_canvas_id.has_value()) {
- draw_canvas_by_id(*source_canvas_id, true);
- return {};
- }
- }
- }
-
- if (auto const* source_video = image.get_pointer<GC::Ref<HTMLVideoElement>>()) {
- auto captured_frame = (*source_video)->capture_current_video_frame();
- if (!captured_frame.has_value())
- return {};
- if (auto* recorder = canvas_recorder()) {
- recorder->draw_video_frame(*captured_frame, destination_rect, source_rect.to_rounded<int>(), scaling_mode, compositing_for_drawing_state());
- did_draw(destination_rect);
- }
- if (image_is_not_origin_clean(image))
- m_origin_clean = false;
- return {};
- }
-
- auto frame = canvas_image_source_frame(image);
- if (!frame.has_value())
+ u64 canvas_id = 0;
+ if (!web_canvas_2d_context_canvas_id(cell_of(*this), &canvas_id))
return {};
-
- // NOTE: The readback fallback inside canvas_image_source_frame() may flush the
- // shared command stream, so the recorder is readied only afterwards.
- if (auto* recorder = canvas_recorder()) {
- recorder->draw_image_frame(*frame, destination_rect, source_rect.to_rounded<int>(), scaling_mode, compositing_for_drawing_state());
- did_draw(destination_rect);
- }
-
- // 7. If image is not origin-clean, then set the CanvasRenderingContext2D's origin-clean flag to false.
- if (image_is_not_origin_clean(image))
- m_origin_clean = false;
-
- return {};
-}
-
-void Canvas2DContextBase::did_draw(Gfx::FloatRect const&)
-{
- m_cached_readback = nullptr;
- // FIXME: Make use of the rect to reduce the invalidated area when possible.
- canvas_host().did_change_canvas_content();
-}
-
-Canvas2DRecorder* Canvas2DContextBase::canvas_recorder()
-{
- if (is_context_lost())
- return nullptr;
- ensure_backing_storage();
- if (!has_backing_storage())
- return nullptr;
- m_recorder->prepare_to_record();
- return m_recorder.ptr();
-}
-
-bool Canvas2DContextBase::ensure_remote_canvas_context()
-{
- if (m_recorder)
- return true;
-
- auto& page = canvas_host().canvas_page();
- if (!page.has_compositor_host())
- return false;
- auto transport = page.compositor_host().create_canvas_2d_transport();
- if (!transport)
- return false;
-
- // FIXME: implement context attribute .color_space
- // FIXME: implement context attribute .color_type
- // FIXME: implement context attribute .desynchronized
- // FIXME: implement context attribute .will_read_frequently
- auto recorder = Canvas2DRecorder::create(transport.release_nonnull());
- if (!recorder->create_context(m_size, m_context_attributes.alpha))
- return false;
- m_recorder = move(recorder);
- return true;
+ return Compositing::CanvasId { canvas_id };
}
RefPtr<Gfx::Bitmap> Canvas2DContextBase::read_pixels(Gfx::IntRect const& rect, Gfx::AlphaType alpha_type)
{
- if (!has_backing_storage())
+ auto* bitmap = static_cast<Gfx::Bitmap*>(web_canvas_2d_context_read_pixels(this, rect, to_underlying(alpha_type)));
+ if (!bitmap)
return nullptr;
-
- // OPTIMIZATION: A remote readback requires a synchronous compositor IPC.
- // Reuse the snapshot while no drawing command has changed its pixels.
- if (m_cached_readback && m_cached_readback_rect == rect && m_cached_readback->alpha_type() == alpha_type)
- return m_cached_readback;
-
- m_recorder->flush();
- auto pixels = m_recorder->read_back_pixels(rect, alpha_type);
- if (pixels) {
- m_cached_readback = pixels;
- m_cached_readback_rect = rect;
- }
- return pixels;
+ return adopt_ref(*bitmap);
}
-void Canvas2DContextBase::set_size(Gfx::IntSize const& size)
+bool Canvas2DContextBase::draw_image(ImageBitmap& image_bitmap, float x, float y)
{
- if (m_size == size)
- return;
- m_size = size;
- discard_backing_storage();
+ return web_canvas_2d_context_draw_image_bitmap(this, &image_bitmap, x, y);
}
-void Canvas2DContextBase::prepare_for_compositing()
-{
- if (!has_backing_storage())
- return;
- m_recorder->present();
-}
-
-Optional<Compositing::CanvasId> Canvas2DContextBase::canvas_id() const
-{
- if (!m_recorder)
- return {};
- return m_recorder->canvas_id();
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#context-loss
+// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-context-lost
void Canvas2DContextBase::notify_backing_storage_lost()
{
- if (!has_backing_storage())
+ if (!web_canvas_2d_context_has_backing_storage(this))
return;
- m_cached_readback = nullptr;
+ web_canvas_2d_context_drop_cached_readback(this);
// When the user agent detects that the backing storage associated with a canvas context has been lost, then it
// must queue a global task on the DOM manipulation task source given canvas's relevant global object to run
// these steps:
- queue_global_task(HTML::Task::Source::DOMManipulation, realm().global_object(), GC::create_function(heap(), [this] {
+ queue_global_task(HTML::Task::Source::DOMManipulation, canvas_host().canvas_relevant_global_object(), GC::create_function(GC::Heap::the(), [context = GC::Ref { *this }] {
// 1. Let canvas be context's canvas element.
+ auto& canvas = context->canvas_host();
+
// 2. If context's context lost is true, then abort these steps.
- if (is_context_lost())
+ if (web_canvas_2d_context_is_lost(context.ptr()))
return;
// 3. Set context's context lost to true.
- set_context_lost(true);
+ web_canvas_2d_context_set_lost(context.ptr(), true);
// AD-HOC: Release the remote context backing the lost storage.
- discard_backing_storage();
+ context->discard_backing_storage();
// 4. Reset the rendering context to its default state given context.
- reset_to_default_state();
+ context->reset_to_default_state();
// 5. Let shouldRestore be the result of firing an event named contextlost at canvas, with the cancelable
// attribute initialized to true.
DOM::EventInit context_lost_event_init;
context_lost_event_init.cancelable = true;
- bool should_restore = canvas_host().canvas_event_target().dispatch_event(DOM::Event::create(realm().global_object(), HTML::EventNames::contextlost, context_lost_event_init));
+ bool should_restore = canvas.canvas_event_target().dispatch_event(DOM::Event::create(canvas.canvas_relevant_global_object(), HTML::EventNames::contextlost, context_lost_event_init));
// 6. If shouldRestore is false, then abort these steps.
if (!should_restore)
@@ -399,831 +292,436 @@ void Canvas2DContextBase::notify_backing_storage_lost()
// 7. Attempt to restore context by creating a backing storage using context's attributes and associating
// them with context. If this fails, then abort these steps.
- ensure_backing_storage();
- if (!has_backing_storage())
+ context->ensure_backing_storage();
+ if (!web_canvas_2d_context_has_backing_storage(context.ptr()))
return;
// 8. Set context's context lost to false.
- set_context_lost(false);
+ web_canvas_2d_context_set_lost(context.ptr(), false);
// 9. Fire an event named contextrestored at canvas.
- canvas_host().canvas_event_target().dispatch_event(DOM::Event::create(realm().global_object(), HTML::EventNames::contextrestored));
+ canvas.canvas_event_target().dispatch_event(DOM::Event::create(canvas.canvas_relevant_global_object(), HTML::EventNames::contextrestored));
}));
}
-void Canvas2DContextBase::ensure_backing_storage()
+static CanvasHost& host_from(void* canvas_host)
{
- if (has_backing_storage() || m_size.is_empty())
- return;
- if (!ensure_remote_canvas_context())
- return;
-
- canvas_host().did_create_canvas_backing_storage();
+ return *static_cast<CanvasHost*>(canvas_host);
}
-void Canvas2DContextBase::discard_backing_storage()
+void web_canvas_2d_canvas_did_change_content(void* canvas_host)
{
- m_cached_readback = nullptr;
- if (m_recorder) {
- // Flush the shared stream before destroying the context: it may still
- // hold commands targeting this canvas, and DrawCanvas commands from
- // other canvases referencing it, which must replay while it is alive.
- m_recorder->flush();
- m_recorder->destroy_context();
- m_recorder = nullptr;
- }
+ host_from(canvas_host).did_change_canvas_content();
}
-Gfx::Path Canvas2DContextBase::text_path(Utf16View text, float x, float y, Optional<double> max_width)
+void web_canvas_2d_canvas_did_create_backing_storage(void* canvas_host)
{
- if (max_width.has_value() && max_width.value() <= 0)
- return {};
-
- auto const& font_cascade_list = this->font_cascade_list();
- auto glyph_runs = Gfx::shape_text({ x, y }, text, *font_cascade_list, resolved_letter_spacing());
- Gfx::Path path;
- float text_width = 0;
- for (auto const& glyph_run : glyph_runs) {
- path.glyph_run(glyph_run);
- text_width += glyph_run->width();
- }
- return path.copy_transformed(text_transform(text_width, max_width));
+ host_from(canvas_host).did_create_canvas_backing_storage();
}
-Gfx::AffineTransform Canvas2DContextBase::text_transform(float text_width, Optional<double> max_width)
+static void* transport_for(Page& page)
{
- auto const& drawing_state = this->drawing_state();
- auto const& font = font_cascade_list()->first();
- Gfx::AffineTransform transform = {};
-
- // https://html.spec.whatwg.org/multipage/canvas.html#text-preparation-algorithm:
- // 9. If maxWidth was provided and the hypothetical width of the inline box in the hypothetical line box
- // is greater than maxWidth CSS pixels, then change font to have a more condensed font (if one is
- // available or if a reasonably readable one can be synthesized by applying a horizontal scale
- // factor to the font) or a smaller font, and return to the previous step.
- if (max_width.has_value() && text_width > float(*max_width)) {
- auto horizontal_scale = float(*max_width) / text_width;
- transform = Gfx::AffineTransform {}.scale({ horizontal_scale, 1 });
- text_width *= horizontal_scale;
- }
-
- // Apply text align
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textalign
- // The direction property affects how "start" and "end" are interpreted:
- // - "ltr" or "inherit" (default): start=left, end=right
- // - "rtl": start=right, end=left
-
- // Determine if we're in RTL mode
- bool is_rtl = drawing_state.direction == Bindings::CanvasDirection::Rtl;
-
- // Center alignment is the same regardless of direction
- if (drawing_state.text_align == Bindings::CanvasTextAlign::Center) {
- transform = Gfx::AffineTransform {}.set_translation({ -text_width / 2, 0 }).multiply(transform);
- }
- // Handle "start" alignment
- else if (drawing_state.text_align == Bindings::CanvasTextAlign::Start) {
- // In RTL, "start" means right-aligned (translate by full width)
- if (is_rtl) {
- transform = Gfx::AffineTransform {}.set_translation({ -text_width, 0 }).multiply(transform);
- }
- // In LTR, "start" means left-aligned (no translation needed - default)
- }
- // Handle "end" alignment
- else if (drawing_state.text_align == Bindings::CanvasTextAlign::End) {
- // In RTL, "end" means left-aligned (no translation needed)
- if (!is_rtl) {
- // In LTR, "end" means right-aligned (translate by full width)
- transform = Gfx::AffineTransform {}.set_translation({ -text_width, 0 }).multiply(transform);
- }
- }
- // Explicit "left" and "right" alignments ignore direction
- else if (drawing_state.text_align == Bindings::CanvasTextAlign::Right) {
- transform = Gfx::AffineTransform {}.set_translation({ -text_width, 0 }).multiply(transform);
- }
- // Left is the default - no translation needed
-
- // Apply text baseline
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textbaseline
- auto const& font_pixel_metrics = font.pixel_metrics();
- auto baseline_y_offset = [&] {
- switch (drawing_state.text_baseline) {
- case Bindings::CanvasTextBaseline::Top:
- return font_pixel_metrics.ascent;
- case Bindings::CanvasTextBaseline::Hanging:
- return font_pixel_metrics.ascent * 0.8f;
- case Bindings::CanvasTextBaseline::Middle:
- return (font_pixel_metrics.ascent - font_pixel_metrics.descent) / 2.0f;
- case Bindings::CanvasTextBaseline::Alphabetic:
- return 0.0f;
- case Bindings::CanvasTextBaseline::Ideographic:
- case Bindings::CanvasTextBaseline::Bottom:
- return -font_pixel_metrics.descent;
- }
- VERIFY_NOT_REACHED();
- }();
-
- if (baseline_y_offset != 0.f)
- transform = Gfx::AffineTransform {}.set_translation({ 0, baseline_y_offset }).multiply(transform);
-
- return transform;
+ if (!page.has_compositor_host())
+ return nullptr;
+ auto transport = page.compositor_host().create_canvas_2d_transport();
+ if (!transport)
+ return nullptr;
+ return &transport.release_nonnull().leak_ref();
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-filltext
-void Canvas2DContextBase::fill_text(Utf16View text, float x, float y, Optional<double> max_width)
+void* web_canvas_2d_canvas_create_transport(void* canvas_host)
{
- if (!isfinite(x) || !isfinite(y) || (max_width.has_value() && !isfinite(max_width.value())))
- return;
-
- auto& state = drawing_state();
- // Complex text effects continue to use the combined outline so they are applied
- // once to the entire text, including runs that use different fallback fonts.
- if (max_width.has_value() || state.shadow_blur != 0 || state.shadow_offset_x != 0 || state.shadow_offset_y != 0) {
- fill_internal(text_path(text, x, y, max_width), Gfx::WindingRule::Nonzero);
- return;
- }
-
- auto font_cascade = font_cascade_list();
- auto glyph_runs = Gfx::shape_text({}, text, *font_cascade, resolved_letter_spacing());
- if (glyph_runs.size() != 1 || glyph_runs.first()->font().is_invisible()) {
- fill_internal(text_path(text, x, y, max_width), Gfx::WindingRule::Nonzero);
- return;
- }
-
- auto* recorder = canvas_recorder();
- if (!recorder)
- return;
- if (!state.fill_style.is_visible() && state.current_compositing_and_blending_operator == Gfx::CompositingAndBlendingOperator::SourceOver)
- return;
- auto const& glyph_run = glyph_runs.first();
- Vector<Compositing::DisplayListGlyph> glyphs;
- glyphs.ensure_capacity(glyph_run->glyphs().size());
- for (auto const& glyph : glyph_run->glyphs()) {
- if (glyph.should_paint)
- glyphs.unchecked_append({ .position = glyph.position, .glyph_id = glyph.glyph_id });
- }
- auto translation = text_transform(glyph_run->width(), {}).map(Gfx::FloatPoint { x, y });
- recorder->draw_glyph_run(glyph_run->font(), glyphs, translation, state.fill_style, compositing_for_drawing_state());
- did_draw({});
+ return transport_for(host_from(canvas_host).canvas_page());
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-stroketext
-void Canvas2DContextBase::stroke_text(Utf16View text, float x, float y, Optional<double> max_width)
+void* web_canvas_2d_canvas_wrapper(void* canvas, bool canvas_is_offscreen, void* realm_pointer)
{
- if (!isfinite(x) || !isfinite(y) || (max_width.has_value() && !isfinite(max_width.value())))
- return;
-
- stroke_internal(text_path(text, x, y, max_width));
+ auto& realm = *static_cast<JS::Realm*>(realm_pointer);
+ auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
+ auto* cell = static_cast<GC::Cell*>(canvas);
+ if (canvas_is_offscreen)
+ return Bindings::wrap(wrapper_world, realm, GC::Ref { *static_cast<OffscreenCanvas*>(cell) }).ptr();
+ return Bindings::wrap(wrapper_world, realm, GC::Ref { *static_cast<HTMLCanvasElement*>(cell) }).ptr();
}
-void Canvas2DContextBase::begin_path()
+void* web_canvas_2d_canvas_relevant_realm(void* canvas_host)
{
- path().clear();
+ return &host_from(canvas_host).canvas_relevant_global_object().shape().realm();
}
-static Gfx::Path::CapStyle to_gfx_cap(Bindings::CanvasLineCap const& cap_style)
+u64 web_canvas_2d_canvas_font_environment_generation(void* canvas_host)
{
- switch (cap_style) {
- case Bindings::CanvasLineCap::Butt:
- return Gfx::Path::CapStyle::Butt;
- case Bindings::CanvasLineCap::Round:
- return Gfx::Path::CapStyle::Round;
- case Bindings::CanvasLineCap::Square:
- return Gfx::Path::CapStyle::Square;
- }
- VERIFY_NOT_REACHED();
+ return host_from(canvas_host).canvas_font_computer().environment_generation();
}
-static Gfx::Path::JoinStyle to_gfx_join(Bindings::CanvasLineJoin const& join_style)
+// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-font
+template<typename CanvasType>
+static bool resolve_font(CanvasType& canvas_element, Utf16View font, ResolvedFont& out_font)
{
- switch (join_style) {
- case Bindings::CanvasLineJoin::Round:
- return Gfx::Path::JoinStyle::Round;
- case Bindings::CanvasLineJoin::Bevel:
- return Gfx::Path::JoinStyle::Bevel;
- case Bindings::CanvasLineJoin::Miter:
- return Gfx::Path::JoinStyle::Miter;
- }
+ // The font IDL attribute, on setting, must be parsed as a CSS <'font'> value (but without supporting property-independent style sheet syntax like 'inherit'),
+ // and the resulting font must be assigned to the context, with the 'line-height' component forced to 'normal', with the 'font-size' component converted to CSS pixels,
+ // and with system fonts being computed to explicit values.
- VERIFY_NOT_REACHED();
-}
-
-static bool transparent_source_paint_can_be_ignored(Gfx::CompositingAndBlendingOperator compositing_and_blending_operator)
-{
- // https://html.spec.whatwg.org/multipage/canvas.html#drawing-model
- // Composite B within the clipping region over the current output bitmap using the current compositing and blending operator.
- return compositing_and_blending_operator == Gfx::CompositingAndBlendingOperator::SourceOver;
-}
+ auto const parsing_context = [&]() {
+ if constexpr (SameAs<CanvasType, HTML::HTMLCanvasElement>)
+ return CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::OnScreenCanvasContextFontValue };
+ return CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue };
+ }();
-// https://html.spec.whatwg.org/multipage/canvas.html#the-canvas-settings:concept-canvas-alpha
-Gfx::Color Canvas2DContextBase::clear_color() const
-{
- return m_context_attributes.alpha ? Gfx::Color::Transparent : Gfx::Color::Black;
-}
+ auto font_style_value_result = parse_css_value(parsing_context, font, CSS::PropertyID::Font);
-Canvas2DCompositing Canvas2DContextBase::compositing_for_drawing_state() const
-{
- auto const& state = drawing_state();
- return {
- .filter = state.filter.has_value() ? &state.filter.value() : nullptr,
- .global_alpha = state.global_alpha,
- .compositing_and_blending_operator = state.current_compositing_and_blending_operator,
- };
-}
+ // If the new value is syntactically incorrect (including using property-independent style sheet syntax like 'inherit' or 'initial'), then it must be ignored, without assigning a new font value.
+ // NOTE: ShorthandStyleValue should be the only valid option here. We implicitly VERIFY this below.
+ if (!font_style_value_result || !font_style_value_result->is_shorthand())
+ return false;
-void Canvas2DContextBase::stroke_internal(Gfx::Path path)
-{
- auto* recorder = canvas_recorder();
- if (!recorder)
- return;
+ // Load font with font style value properties
+ auto const& font_style_value = font_style_value_result->as_shorthand();
- auto& state = drawing_state();
- if (!state.stroke_style.is_visible() && transparent_source_paint_can_be_ignored(state.current_compositing_and_blending_operator))
- return;
+ auto computed_math_depth = CSS::InitialValues::math_depth();
- auto line_cap = to_gfx_cap(state.line_cap);
- auto line_join = to_gfx_join(state.line_join);
- // FIXME: Need a Vector<float> for rendering dash_array, but state.dash_list is Vector<double>.
- // Maybe possible to avoid creating copies?
- auto dash_array = Vector<float> {};
- dash_array.ensure_capacity(state.dash_list.size());
- for (auto const& dash : state.dash_list) {
- dash_array.append(static_cast<float>(dash));
- }
- paint_shadow_for_stroke_internal(path, line_cap, line_join, dash_array);
- auto bounding_box = path.bounding_box();
- recorder->stroke_path(path, state.stroke_style,
- {
- .thickness = state.line_width,
- .cap_style = line_cap,
- .join_style = line_join,
- .miter_limit = state.miter_limit,
- .dash_array = dash_array,
- .dash_offset = state.line_dash_offset,
- },
- compositing_for_drawing_state());
+ // FIXME: We will need to absolutize this once we support ident() functions
+ auto font_family = font_style_value.longhand(CSS::PropertyID::FontFamily);
- did_draw(bounding_box);
-}
+ Optional<DOM::AbstractElement> inheritance_parent;
-void Canvas2DContextBase::stroke()
-{
- stroke_internal(path().clone());
-}
+ if constexpr (SameAs<CanvasType, HTML::HTMLCanvasElement>) {
+ // NB: Once pending style work is settled, the canvas's installed style is current, unless it is below
+ // display:none, where style updates leave it stale. Only then is its style computed again.
+ auto& document = canvas_element.document();
+ Layout::ForcedReadScope read { document };
+ document.update_style_for_element(DOM::AbstractElement { canvas_element }, DOM::Document::StyleUpdateMode::OnlyIfNeeded);
+ auto style_record = canvas_element.style_record_identity();
+ if (!style_record || has_flag(document.style_computer().style_engine().style_record_dependency_flags(read, style_record), CSS::StyleRecordDependencyFlag::InDisplayNoneSubtree))
+ document.update_style_for_element(DOM::AbstractElement { canvas_element });
-void Canvas2DContextBase::stroke(Path2D const& path)
-{
- stroke_internal(path.path().clone());
-}
+ if (canvas_element.navigable() && canvas_element.is_connected()) {
+ // NOTE: Since we can't set a math depth directly here we always use the inherited value for the computed value
+ computed_math_depth = canvas_element.template style_group<CSS::ComputedValues::FontValues>()->math_depth;
-static constexpr Gfx::WindingRule bindings_to_gfx_fill_rule(Bindings::CanvasFillRule fill_rule)
-{
- switch (fill_rule) {
- case Bindings::CanvasFillRule::Nonzero:
- return Gfx::WindingRule::Nonzero;
- case Bindings::CanvasFillRule::Evenodd:
- return Gfx::WindingRule::EvenOdd;
+ // NOTE: The canvas itself is considered the inheritance parent
+ inheritance_parent = canvas_element;
+ }
}
- VERIFY_NOT_REACHED();
-}
-void Canvas2DContextBase::fill_internal(Gfx::Path path, Gfx::WindingRule winding_rule)
-{
- auto* recorder = canvas_recorder();
- if (!recorder)
- return;
+ auto computation_context = canvas_element.canvas_font_computation_context();
- auto& state = this->drawing_state();
- if (!state.fill_style.is_visible() && transparent_source_paint_can_be_ignored(state.current_compositing_and_blending_operator))
- return;
+ auto const& computed_font_size = CSS::StyleComputer::compute_font_size(font_style_value.longhand(CSS::PropertyID::FontSize)->absolutized(computation_context), computed_math_depth, inheritance_parent, CSSPixels { 10 });
+ auto const& computed_font_style = CSS::StyleComputer::compute_font_style(font_style_value.longhand(CSS::PropertyID::FontStyle)->absolutized(computation_context));
+ auto const& computed_font_weight = CSS::StyleComputer::compute_font_weight(font_style_value.longhand(CSS::PropertyID::FontWeight)->absolutized(computation_context), inheritance_parent);
+ auto const& computed_font_width = CSS::StyleComputer::compute_font_width(font_style_value.longhand(CSS::PropertyID::FontWidth)->absolutized(computation_context));
+ // NB: This doesn't require absolutization since only the font-variant-caps longhand can be set and that can only be
+ // a keyword value
+ auto const& computed_font_variant = font_style_value.longhand(CSS::PropertyID::FontVariant).release_nonnull();
- paint_shadow_for_fill_internal(path, winding_rule);
-
- auto bounding_box = path.bounding_box();
- recorder->fill_path(path, state.fill_style, winding_rule, compositing_for_drawing_state());
-
- did_draw(bounding_box);
-}
-
-void Canvas2DContextBase::fill(Bindings::CanvasFillRule fill_rule)
-{
- fill_internal(path().clone(), bindings_to_gfx_fill_rule(fill_rule));
-}
-
-void Canvas2DContextBase::fill(Path2D& path, Bindings::CanvasFillRule fill_rule)
-{
- fill_internal(path.path().clone(), bindings_to_gfx_fill_rule(fill_rule));
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createimagedata
-WebIDL::ExceptionOr<GC::Ref<ImageData>> Canvas2DContextBase::create_image_data(int width, int height, Optional<Bindings::ImageDataSettings> const& settings) const
-{
- // 1. If one or both of sw and sh are zero, then throw an "IndexSizeError" DOMException.
- if (width == 0 || height == 0)
- return WebIDL::IndexSizeError::create(realm(), "Width and height must not be zero"_utf16);
+ auto resolved_font_style_value = CSS::ShorthandStyleValue::create(
+ CSS::PropertyID::Font,
+ {
+ // Set explicitly https://drafts.csswg.org/css-fonts/#font-prop
+ CSS::PropertyID::FontFamily,
+ CSS::PropertyID::FontSize,
+ CSS::PropertyID::FontWidth,
+ CSS::PropertyID::FontStyle,
+ CSS::PropertyID::FontVariant,
+ CSS::PropertyID::FontWeight,
+ CSS::PropertyID::LineHeight,
+
+ // Reset implicitly https://drafts.csswg.org/css-fonts/#font-prop
+ CSS::PropertyID::FontFeatureSettings,
+ CSS::PropertyID::FontKerning,
+ CSS::PropertyID::FontLanguageOverride,
+ CSS::PropertyID::FontOpticalSizing,
+ // FIXME: PropertyID::FontSizeAdjust,
+ CSS::PropertyID::FontVariationSettings,
+ },
+ {
+ // Set explicitly
+ *font_family,
+ computed_font_size,
+ computed_font_width,
+ computed_font_style,
+ computed_font_variant,
+ computed_font_weight,
+ property_initial_value(CSS::PropertyID::LineHeight), // NB: line-height is forced to normal (i.e. the initial value)
+
+ // Reset implicitly
+ property_initial_value(CSS::PropertyID::FontFeatureSettings), // font-feature-settings
+ property_initial_value(CSS::PropertyID::FontKerning), // font-kerning,
+ property_initial_value(CSS::PropertyID::FontLanguageOverride), // font-language-override
+ property_initial_value(CSS::PropertyID::FontOpticalSizing), // font-optical-sizing,
+ // FIXME: font-size-adjust,
+ property_initial_value(CSS::PropertyID::FontVariationSettings), // font-variation-settings
+ });
- int abs_width = width == NumericLimits<int>::min() ? NumericLimits<int>::max() : abs(width);
- int abs_height = height == NumericLimits<int>::min() ? NumericLimits<int>::max() : abs(height);
+ CSS::FontResolutionFeatureValues feature_values;
+ if (auto caps = computed_font_variant->as_shorthand().longhand(CSS::PropertyID::FontVariantCaps); caps->to_keyword() == CSS::Keyword::SmallCaps)
+ feature_values[to_underlying(CSS::FontResolutionFeatureInput::FontVariantCaps)] = caps;
- // 2. Let newImageData be a new ImageData object.
- // 3. Initialize newImageData given the absolute magnitude of sw, the absolute magnitude of sh, settings set to settings, and defaultColorSpace set to this's color space.
- auto image_data = TRY(ImageData::create(realm(), abs_width, abs_height, settings));
+ // https://drafts.csswg.org/css-font-loading/#font-source
+ auto& font_computer = canvas_element.canvas_font_computer();
- // 4. Initialize the image data of newImageData to transparent black.
- // ... this is handled by ImageData::create()
+ auto font_size = computed_font_size->as_length().length().absolute_length_to_px();
+ auto cascade = CSS::resolve_font_for_style_values(font_computer,
+ {
+ .font_families = CSS::computed_font_families_from_style_value(*font_family),
+ .font_optical_sizing = CSS::FontOpticalSizing::Auto,
+ .font_size = font_size,
+ .font_slope = computed_font_style->as_font_style().to_font_slope(),
+ .font_weight = computed_font_weight->as_number().number(),
+ .font_width = computed_font_width->as_percentage().percentage(),
+ .feature_values = move(feature_values),
+ .font_feature_values_scope = {},
+ });
- // 5. Return newImageData.
- return image_data;
+ out_font = {
+ .cascade = &cascade.leak_ref(),
+ .environment_generation = font_computer.environment_generation(),
+ .font_size = font_size.raw_value(),
+ // On getting, the font attribute must return the serialized form of the current font of the context (with no 'line-height' component).
+ .serialized = resolved_font_style_value->to_utf16_string(CSS::SerializationMode::ResolvedValue).into_raw(),
+ };
+ return true;
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createimagedata-imagedata
-WebIDL::ExceptionOr<GC::Ref<ImageData>> Canvas2DContextBase::create_image_data(ImageData const& image_data) const
+bool web_canvas_2d_canvas_resolve_font(void* canvas, bool canvas_is_offscreen, FlatPtr font, ResolvedFont* out_font)
{
- // 1. Let newImageData be a new ImageData object.
- // 2. Initialize newImageData given the value of imageData's width attribute, the value of imageData's height attribute, and defaultColorSpace set to the value of imageData's colorSpace attribute.
- // FIXME: Set defaultColorSpace to the value of image_data's colorSpace attribute
- // 3. Initialize the image data of newImageData to transparent black.
- // NOTE: No-op, already done during creation.
- // 4. Return newImageData.
- return TRY(ImageData::create(realm(), image_data.width(), image_data.height()));
+ auto font_string = Utf16String::from_raw(font);
+ auto* cell = static_cast<GC::Cell*>(canvas);
+ if (canvas_is_offscreen)
+ return resolve_font(*static_cast<OffscreenCanvas*>(cell), font_string.utf16_view(), *out_font);
+ return resolve_font(*static_cast<HTMLCanvasElement*>(cell), font_string.utf16_view(), *out_font);
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-getimagedata
-WebIDL::ExceptionOr<GC::Ptr<ImageData>> Canvas2DContextBase::get_image_data(int x, int y, int width, int height, Optional<Bindings::ImageDataSettings> const& settings)
+// What the CSS values of a context are resolved with: the viewport of the canvas, and the font of the context.
+static CSS::ComputationContext computation_context_for(CanvasHost& canvas_host, FontMetricsSource font)
{
- // 1. If either the sw or sh arguments are zero, then throw an "IndexSizeError" DOMException.
- if (width == 0 || height == 0)
- return WebIDL::IndexSizeError::create(realm(), "Width and height must not be zero"_utf16);
-
- // 2. If the CanvasRenderingContext2D's origin-clean flag is set to false, then throw a "SecurityError" DOMException.
- if (!m_origin_clean)
- return WebIDL::SecurityError::create(realm(), "CanvasRenderingContext2D is not origin-clean"_utf16);
-
- // ImageData initialization requires positive width and height
- // https://html.spec.whatwg.org/multipage/canvas.html#initialize-an-imagedata-object
- int abs_width = width == NumericLimits<int>::min() ? NumericLimits<int>::max() : abs(width);
- int abs_height = height == NumericLimits<int>::min() ? NumericLimits<int>::max() : abs(height);
-
- // 3. Let imageData be a new ImageData object.
- // 4. Initialize imageData given sw, sh, settings set to settings, and defaultColorSpace set to this's color space.
- auto image_data = TRY(ImageData::create(realm(), abs_width, abs_height, settings));
-
- // 5. Let the source rectangle be the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).
- auto source_rect = Gfx::Rect { x, y, abs_width, abs_height };
-
- // NOTE: The spec doesn't seem to define this behavior, but MDN does and the WPT tests
- // assume it works this way.
- // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData#sw
- if (width < 0 || height < 0) {
- source_rect = source_rect.translated(min(width, 0), min(height, 0));
- }
- auto source_rect_intersected = source_rect.intersected(Gfx::IntRect { {}, m_size });
- if (source_rect_intersected.is_empty())
- return image_data;
-
- // NOTE: If reading back from the Compositor fails (no backing storage or no connection),
- // it's like copying only transparent black pixels (which is a no-op).
- // NOTE: Internally we must use premultiplied alpha, but ImageData should hold unpremultiplied alpha. This conversion
- // might result in a loss of precision, but is according to spec.
- // See: https://html.spec.whatwg.org/multipage/canvas.html#premultiplied-alpha-and-the-2d-rendering-context
- auto pixels = read_pixels(source_rect_intersected, Gfx::AlphaType::Unpremultiplied);
- if (!pixels)
- return image_data;
-
- // 6. Set the pixel values of imageData to be the pixels of this's output bitmap in the area specified by the source rectangle in the bitmap's coordinate space units, converted from this's color space to imageData's colorSpace using 'relative-colorimetric' rendering intent.
- // NB: The pixels of imageData are RGBA8888 and unpremultiplied.
- auto* image_data_pixels = image_data->pixels();
- VERIFY(image_data_pixels);
- if (pixels->format() != Gfx::BitmapFormat::RGBA8888 || pixels->alpha_type() != Gfx::AlphaType::Unpremultiplied || pixels->size() != source_rect_intersected.size())
- return image_data;
-
- // The readback only covers the part of the source rectangle that is inside the output bitmap.
- auto destination_location = source_rect_intersected.location() - source_rect.location();
- auto destination_pitch = static_cast<size_t>(image_data->width()) * sizeof(u32);
- auto row_size = static_cast<size_t>(pixels->width()) * sizeof(u32);
- for (int y = 0; y < pixels->height(); ++y) {
- auto* destination_row = image_data_pixels + (destination_location.y() + y) * destination_pitch + destination_location.x() * sizeof(u32);
- memcpy(destination_row, pixels->scanline_u8(y), row_size);
- }
-
- // 7. Set the pixels values of imageData for areas of the source rectangle that are outside of the output bitmap to transparent black.
- // NOTE: No-op, already done during creation.
-
- // 8. Return imageData.
- return image_data;
-}
+ auto font_metrics = [&]() {
+ // https://html.spec.whatwg.org/multipage/canvas.html#text-styles
+ // NB: We lazily initialize the font, so if it hasn't been set yet we generate the font metrics based on the default font
+ if (!font.cascade) {
+ // When the object implementing the CanvasTextDrawingStyles interface is created, the font of the context must be set to 10px sans-serif.
+ return CSS::Length::FontMetrics { 10, Platform::FontPlugin::the().default_font(8)->pixel_metrics(), CSS::InitialValues::line_height() };
+ }
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-putimagedata-short
-WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_data, int dx, int dy)
-{
- // The putImageData(imageData, dx, dy) method steps are to put pixels from an ImageData onto a bitmap,
- // given imageData, this's output bitmap, dx, dy, 0, 0, imageData's width, and imageData's height.
- if (auto* recorder = canvas_recorder())
- TRY(put_pixels_from_an_image_data_onto_a_bitmap(image_data, *recorder, dx, dy, 0, 0, image_data.width(), image_data.height()));
+ auto const& first_font = font.cascade->first_available_font();
+ return CSS::Length::FontMetrics { CSSPixels::from_raw(font.font_size), first_font.pixel_metrics(), CSS::InitialValues::line_height() };
+ }();
- return {};
+ return {
+ .length_resolution_context = {
+ .viewport_rect = canvas_host.canvas_viewport_rect(),
+ .font_metrics = font_metrics,
+ .root_font_metrics = font_metrics },
+
+ // NB: We don't require an abstract element because tree counting and random() functions aren't allowed in
+ // non-font canvas context values
+ .abstract_element = {},
+
+ // FIXME: The spec doesn't specify what color scheme should be used here but other browsers always use light so
+ // we do too for compatibility. See https://github.com/whatwg/html/issues/12505
+ .color_scheme = CSS::PreferredColorScheme::Light
+ };
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-putimagedata
-WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_data, int x, int y, int dirty_x, int dirty_y, int dirty_width, int dirty_height)
+void web_canvas_2d_canvas_resolve_color(void* canvas_host, CSS::StyleValue const* color, FontMetricsSource font, Gfx::Color* out_color)
{
- // The putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) method steps are to put pixels
- // from an ImageData onto a bitmap, given imageData, this's output bitmap, dx, dy, dirtyX, dirtyY, dirtyWidth, and
- // dirtyHeight.
- if (auto* recorder = canvas_recorder())
- TRY(put_pixels_from_an_image_data_onto_a_bitmap(image_data, *recorder, x, y, dirty_x, dirty_y, dirty_width, dirty_height));
-
- return {};
+ auto& host = host_from(canvas_host);
+ auto computation_context = computation_context_for(host, font);
+ *out_color = color->absolutized(computation_context)->to_color(host.canvas_color_resolution_style()).value();
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context2d-putimagedata-common
-WebIDL::ExceptionOr<void> Canvas2DContextBase::put_pixels_from_an_image_data_onto_a_bitmap(ImageData& image_data, Canvas2DRecorder& recorder, int dx, int dy, int dirty_x_argument, int dirty_y_argument, int dirty_width_argument, int dirty_height_argument)
+float web_canvas_2d_canvas_resolve_length(void* canvas_host, CSS::StyleValue const* length, FontMetricsSource font)
{
- // 1. Let buffer be imageData's data attribute value's [[ViewedArrayBuffer]] internal slot.
- // 2. If IsDetachedBuffer(buffer) is true, then throw an "InvalidStateError" DOMException
- if (image_data.is_detached())
- return WebIDL::InvalidStateError::create("ImageData's underlying buffer is detached"_utf16);
-
- // NB: The arguments are IDL longs. Do the arithmetic below in 64 bits, so that it neither overflows nor loses
- // precision.
- i64 dirty_x = dirty_x_argument;
- i64 dirty_y = dirty_y_argument;
- i64 dirty_width = dirty_width_argument;
- i64 dirty_height = dirty_height_argument;
-
- // 3. If dirtyWidth is negative, then let dirtyX be dirtyX+dirtyWidth, and let dirtyWidth be equal to the
- // absolute magnitude of dirtyWidth.
- if (dirty_width < 0) {
- dirty_x += dirty_width;
- dirty_width = -dirty_width;
- }
- // If dirtyHeight is negative, then let dirtyY be dirtyY+dirtyHeight, and let dirtyHeight be equal to the absolute
- // magnitude of dirtyHeight.
- if (dirty_height < 0) {
- dirty_y += dirty_height;
- dirty_height = -dirty_height;
- }
-
- // 4. If dirtyX is negative, then let dirtyWidth be dirtyWidth+dirtyX, and let dirtyX be 0.
- if (dirty_x < 0) {
- dirty_width += dirty_x;
- dirty_x = 0;
- }
-
- // If dirtyY is negative, then let dirtyHeight be dirtyHeight+dirtyY, and let dirtyY be 0.
- if (dirty_y < 0) {
- dirty_height += dirty_y;
- dirty_y = 0;
- }
-
- // 5. If dirtyX+dirtyWidth is greater than the width attribute of the imageData argument, then let dirtyWidth be
- // the value of that width attribute, minus the value of dirtyX.
- if (dirty_x + dirty_width > image_data.width()) {
- dirty_width = image_data.width() - dirty_x;
- }
- // If dirtyY+dirtyHeight is greater than the height attribute of the imageData argument, then let dirtyHeight be
- // the value of that height attribute, minus the value of dirtyY.
- if (dirty_y + dirty_height > image_data.height()) {
- dirty_height = image_data.height() - dirty_y;
- }
-
- // 6. If, after those changes, either dirtyWidth or dirtyHeight are negative or zero, then return without affecting
- // any bitmaps.
- if (dirty_width <= 0 || dirty_height <= 0)
- return {};
-
- // 7. For all integer values of x and y where dirtyX ≤ x < dirtyX+dirtyWidth and dirtyY ≤ y < dirtyY+dirtyHeight,
- // set the pixel with coordinate (dx+x, dy+y) in bitmap to the color of the pixel at coordinate (x, y) in the
- // imageData data structure's bitmap, converted from imageData's colorSpace to the color space of bitmap using
- // 'relative-colorimetric' rendering intent.
- auto* source_pixels = image_data.pixels();
- if (!source_pixels)
- return WebIDL::InvalidStateError::create("ImageData's underlying buffer is detached or out-of-bounds"_utf16);
- // NB: Only the pixels that land inside the output bitmap are set, so only copy those. Also keep the source
- // rectangle inside imageData here, whatever the steps above computed, before reading its pixels.
- i64 source_left = max(max(dirty_x, -static_cast<i64>(dx)), static_cast<i64>(0));
- i64 source_top = max(max(dirty_y, -static_cast<i64>(dy)), static_cast<i64>(0));
- i64 source_right = min(min(dirty_x + dirty_width, static_cast<i64>(m_size.width()) - dx), static_cast<i64>(image_data.width()));
- i64 source_bottom = min(min(dirty_y + dirty_height, static_cast<i64>(m_size.height()) - dy), static_cast<i64>(image_data.height()));
- if (source_left >= source_right || source_top >= source_bottom)
- return {};
- // NB: The destination rectangle is inside the output bitmap, so its coordinates fit in an int.
- auto destination_rect = Gfx::IntRect {
- static_cast<int>(source_left + dx),
- static_cast<int>(source_top + dy),
- static_cast<int>(source_right - source_left),
- static_cast<int>(source_bottom - source_top),
- };
-
- // NOTE: The ImageData buffer is mutable from script and the recorded draw is only
- // serialized at flush time, so snapshot the dirty pixels at call time. The
- // snapshot is shareable so that flushing to the Compositor passes the pixels
- // by file descriptor instead of copying them again.
- auto source_pitch = static_cast<size_t>(image_data.width()) * sizeof(u32);
- auto bitmap_snapshot = TRY_OR_THROW_OOM(realm().vm(), Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Unpremultiplied, destination_rect.size()));
- for (int y = 0; y < destination_rect.height(); ++y)
- __builtin_memcpy(bitmap_snapshot->scanline(y), source_pixels + static_cast<size_t>(source_top + y) * source_pitch + static_cast<size_t>(source_left) * sizeof(u32), static_cast<size_t>(destination_rect.width()) * sizeof(Gfx::RawPixel));
- auto dst_rect = destination_rect.to_type<float>();
- recorder.save();
- recorder.set_transform({});
- // NB: Step 7 sets each destination pixel to the source pixel: putImageData replaces the pixels (including their
- // alpha), rather than compositing them. Use the Copy operator — so a transparent source pixel overwrites an
- // opaque destination pixel, rather than leaving it unchanged.
- recorder.draw_image_frame(Gfx::DecodedImageFrame { *bitmap_snapshot, Gfx::AlphaType::Unpremultiplied }, dst_rect, bitmap_snapshot->rect(), Gfx::ScalingMode::NearestNeighbor,
- { .compositing_and_blending_operator = Gfx::CompositingAndBlendingOperator::Copy });
- recorder.restore();
-
- did_draw(dst_rect);
-
- return {};
+ auto absolutized_length = CSS::Length::from_style_value(length->absolutized(computation_context_for(host_from(canvas_host), font)), {});
+ return static_cast<float>(absolutized_length.absolute_length_to_px().to_double());
}
-// https://html.spec.whatwg.org/multipage/canvas.html#reset-the-rendering-context-to-its-default-state
-void Canvas2DContextBase::reset_to_default_state()
+// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-filter
+bool web_canvas_2d_canvas_parse_filter(void* canvas_host, FlatPtr filter, FontMetricsSource font, void* functions, void (*append_function)(void*, Compositing::RustFFI::FfiFilterFunction const*))
{
- auto* recorder = has_backing_storage() ? canvas_recorder() : nullptr;
-
- // 1. Clear canvas's bitmap to transparent black.
- if (recorder)
- recorder->clear_rect(Gfx::FloatRect { {}, m_size.to_type<float>() }, clear_color());
-
- // 2. Empty the list of subpaths in context's current default path.
- path().clear();
+ auto& host = host_from(canvas_host);
+ auto filter_string = Utf16String::from_raw(filter);
+ CSS::Parser::Parser parser { CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue } };
- // 3. Clear the context's drawing state stack.
- clear_drawing_state_stack();
+ // 2. Let parsedValue be the result of parsing the given values as a <filter-value-list>.
+ // If any property-independent style sheet syntax like 'inherit' or 'initial' is present,
+ // then this parsing must return failure.
+ auto style_value = parser.parse_as_css_value(filter_string.utf16_view(), CSS::PropertyID::Filter);
+ if (!style_value || !style_value->is_value_list())
+ return false;
- // 4. Reset everything that drawing state consists of to their initial values.
- reset_drawing_state();
+ auto absolutized_style_value = style_value->absolutized(computation_context_for(host, font));
+ for (auto& item : absolutized_style_value->as_value_list().values()) {
+ if (item->is_url()) {
+ // FIXME: Resolve the SVG filter
+ dbgln("FIXME: SVG filters are not implemented for Canvas2D");
+ continue;
+ }
- if (recorder) {
- recorder->reset();
- did_draw(Gfx::FloatRect { {}, m_size.to_type<float>() });
+ auto const& filter_value = item->as_filter();
+ Compositing::RustFFI::FfiFilterFunction function {};
+ switch (filter_value.kind()) {
+ case CSS::FilterStyleValue::Kind::Blur: {
+ auto const& blur_filter = static_cast<CSS::BlurFilterStyleValue const&>(filter_value);
+ function.kind = Compositing::RustFFI::FfiFilterFunctionKind::Blur;
+ function.amount = blur_filter.resolved_radius();
+ break;
+ }
+ case CSS::FilterStyleValue::Kind::Color: {
+ auto const& color = static_cast<CSS::ColorFilterStyleValue const&>(filter_value);
+ function.kind = Compositing::RustFFI::FfiFilterFunctionKind::Color;
+ function.color_operation = color.operation();
+ function.amount = color.resolved_amount();
+ break;
+ }
+ case CSS::FilterStyleValue::Kind::HueRotate: {
+ auto const& hue_rotate = static_cast<CSS::HueRotateFilterStyleValue const&>(filter_value);
+ function.kind = Compositing::RustFFI::FfiFilterFunctionKind::HueRotate;
+ function.amount = hue_rotate.angle_degrees();
+ break;
+ }
+ case CSS::FilterStyleValue::Kind::DropShadow: {
+ auto const& drop_shadow = static_cast<CSS::DropShadowFilterStyleValue const&>(filter_value);
+ function.kind = Compositing::RustFFI::FfiFilterFunctionKind::DropShadow;
+ function.offset_x = static_cast<float>(CSS::Length::from_style_value(drop_shadow.offset_x(), {}).absolute_length_to_px());
+ function.offset_y = static_cast<float>(CSS::Length::from_style_value(drop_shadow.offset_y(), {}).absolute_length_to_px());
+ if (drop_shadow.radius())
+ function.amount = static_cast<float>(CSS::Length::from_style_value(*drop_shadow.radius(), {}).absolute_length_to_px());
+ function.color = drop_shadow.color() ? drop_shadow.color()->to_color(host.canvas_color_resolution_style()).value_or(Gfx::Color::Black) : Gfx::Color::Black;
+ break;
+ }
+ }
+ append_function(functions, &function);
}
+ return true;
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-measuretext
-GC::Ref<TextMetrics> Canvas2DContextBase::measure_text(Utf16View text)
+CSS::StyleValue const* web_canvas_2d_parse_color(FlatPtr color)
{
- // The measureText(text) method steps are to run the text preparation
- // algorithm, passing it text and the object implementing the CanvasText
- // interface, and then using the returned inline box return a new
- // TextMetrics object with members behaving as described in the following
- // list:
- auto prepared_text = prepare_text(text);
- TextMeasurements metrics;
- // FIXME: Use the font that was used to create the glyphs in prepared_text.
- auto const& font = font_cascade_list()->first();
- auto const& font_pixel_metrics = font.pixel_metrics();
- auto const ascent = font_pixel_metrics.ascent;
- auto const descent = font_pixel_metrics.descent;
- auto const hanging_baseline = ascent * 0.8f;
-
- float baseline_offset = 0;
- switch (drawing_state().text_baseline) {
- case Bindings::CanvasTextBaseline::Top:
- baseline_offset = ascent;
- break;
- case Bindings::CanvasTextBaseline::Hanging:
- baseline_offset = hanging_baseline;
- break;
- case Bindings::CanvasTextBaseline::Middle:
- baseline_offset = (ascent - descent) / 2.0f;
- break;
- case Bindings::CanvasTextBaseline::Alphabetic:
- baseline_offset = 0;
- break;
- case Bindings::CanvasTextBaseline::Ideographic:
- case Bindings::CanvasTextBaseline::Bottom:
- baseline_offset = -descent;
- break;
- }
-
- // width attribute: The width of that inline box, in CSS pixels. (The text's advance width.)
- metrics.width = prepared_text.bounding_box.width();
- // actualBoundingBoxLeft attribute: The distance parallel to the baseline from the alignment point given by the textAlign attribute to the left side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going left from the given alignment point.
- metrics.actual_bounding_box_left = -prepared_text.bounding_box.left();
- // actualBoundingBoxRight attribute: The distance parallel to the baseline from the alignment point given by the textAlign attribute to the right side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going right from the given alignment point.
- metrics.actual_bounding_box_right = prepared_text.bounding_box.right();
- // fontBoundingBoxAscent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the ascent metric of the first available font, in CSS pixels; positive numbers indicating a distance going up from the given baseline.
- metrics.font_bounding_box_ascent = ascent - baseline_offset;
- // fontBoundingBoxDescent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the descent metric of the first available font, in CSS pixels; positive numbers indicating a distance going down from the given baseline.
- metrics.font_bounding_box_descent = descent + baseline_offset;
- // actualBoundingBoxAscent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the top of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going up from the given baseline.
- metrics.actual_bounding_box_ascent = ascent - baseline_offset;
- // actualBoundingBoxDescent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the bottom of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going down from the given baseline.
- metrics.actual_bounding_box_descent = descent + baseline_offset;
- // emHeightAscent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the highest top of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the top of that em square (so this value will usually be positive). Zero if the given baseline is the top of that em square; half the font size if the given baseline is the middle of that em square.
- metrics.em_height_ascent = ascent - baseline_offset;
- // emHeightDescent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the lowest bottom of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is above the bottom of that em square. (Zero if the given baseline is the bottom of that em square.)
- metrics.em_height_descent = descent + baseline_offset;
- // hangingBaseline attribute: The distance from the horizontal line indicated by the textBaseline attribute to the hanging baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the hanging baseline. (Zero if the given baseline is the hanging baseline.)
- metrics.hanging_baseline = hanging_baseline - baseline_offset;
- // alphabeticBaseline attribute: The distance from the horizontal line indicated by the textBaseline attribute to the alphabetic baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the alphabetic baseline. (Zero if the given baseline is the alphabetic baseline.)
- metrics.alphabetic_baseline = -baseline_offset;
- // ideographicBaseline attribute: The distance from the horizontal line indicated by the textBaseline attribute to the ideographic-under baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the ideographic-under baseline. (Zero if the given baseline is the ideographic-under baseline.)
- metrics.ideographic_baseline = -descent - baseline_offset;
-
- return TextMetrics::create(metrics);
+ auto color_string = Utf16String::from_raw(color);
+ auto parsed_color = parse_css_type(CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue }, color_string.utf16_view(), CSS::ValueType::Color);
+ if (!parsed_color)
+ return nullptr;
+ return &parsed_color.release_nonnull().leak_ref();
}
-RefPtr<Gfx::FontCascadeList const> Canvas2DContextBase::font_cascade_list()
+// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-letterspacing
+CSS::StyleValue const* web_canvas_2d_parse_length(FlatPtr length, FlatPtr* out_serialized)
{
- // When font style value is empty load default font
- if (!drawing_state().font_style_value) {
- set_font(u"10px sans-serif"sv);
- }
-
- // NB: Drawing states, including saved states, retain their cascades across font loads and font-display
- // transitions. Refresh them lazily so cached invisible fallback glyphs and metrics cannot outlive
- // the font environment that selected them.
- if (drawing_state().font_environment_generation != canvas_host().canvas_font_computer().environment_generation()) {
- auto font = drawing_state().font_style_value->to_utf16_string(CSS::SerializationMode::ResolvedValue);
- set_font(font);
- }
- return drawing_state().current_font_cascade_list;
+ auto length_string = Utf16String::from_raw(length);
+ auto parsed = parse_css_type(CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue }, length_string.utf16_view(), CSS::ValueType::Length);
+ if (!parsed)
+ return nullptr;
+ Utf16StringBuilder builder;
+ parsed->serialize(builder, CSS::SerializationMode::Normal);
+ *out_serialized = builder.to_string().into_raw();
+ return &parsed.release_nonnull().leak_ref();
}
-// https://html.spec.whatwg.org/multipage/canvas.html#text-preparation-algorithm
-Canvas2DContextBase::PreparedText Canvas2DContextBase::prepare_text(Utf16View text, float max_width)
+void web_canvas_2d_style_value_ref(CSS::StyleValue const* style_value)
{
- // 1. If maxWidth was provided but is less than or equal to zero or equal to NaN, then return an empty array.
- if (max_width <= 0 || max_width != max_width) {
- return {};
- }
-
- // 2. Replace all ASCII whitespace in text with U+0020 SPACE characters.
- Utf16StringBuilder builder { text.length_in_code_units() };
- for (auto c : text) {
- builder.append_code_point(Infra::is_ascii_whitespace(c) ? ' ' : c);
- }
- auto replaced_text = builder.to_string();
-
- // 3. Let font be the current font of target, as given by that object's font attribute.
- auto glyph_runs = Gfx::shape_text({ 0, 0 }, replaced_text.utf16_view(), *font_cascade_list(), resolved_letter_spacing());
-
- // FIXME: 4. Let language be the target's language.
- // FIXME: 5. If language is "inherit":
- // ...
- // FIXME: 6. If language is the empty string, then set language to explicitly unknown.
-
- // FIXME: 7. Apply the appropriate step from the following list to determine the value of direction:
- // ...
-
- // 8. Form a hypothetical infinitely-wide CSS line box containing a single inline box containing the text text,
- // with the CSS content language set to language, and with its CSS properties set as follows:
- // 'direction' -> direction
- // 'font' -> font
- // 'font-kerning' -> target's fontKerning
- // 'font-stretch' -> target's fontStretch
- // 'font-variant-caps' -> target's fontVariantCaps
- // 'letter-spacing' -> target's letterSpacing
- // SVG text-rendering -> target's textRendering
- // 'white-space' -> 'pre'
- // 'word-spacing' -> target's wordSpacing
- // ...and with all other properties set to their initial values.
- // FIXME: Actually use a LineBox here instead of, you know, using the default font and measuring its size (which is not the spec at all).
- // FIXME: Once we have CanvasTextDrawingStyles, add the CSS attributes.
- float height = 0;
- float width = 0;
- for (auto const& glyph_run : glyph_runs) {
- height = max(height, glyph_run->font().pixel_size());
- width += glyph_run->width();
- }
-
- // 9. If maxWidth was provided and the hypothetical width of the inline box in the hypothetical line box is greater than maxWidth CSS pixels, then change font to have a more condensed font (if one is available or if a reasonably readable one can be synthesized by applying a horizontal scale factor to the font) or a smaller font, and return to the previous step.
- // FIXME: Record the font size used for this piece of text, and actually retry with a smaller size if needed.
-
- // FIXME: 10. The anchor point is a point on the inline box, and the physical alignment is one of the values left, right,
- // and center. These variables are determined by the textAlign and textBaseline values as follows:
- // ...
-
- // 11. Let result be an array constructed by iterating over each glyph in the inline box from left to right (if
- // any), adding to the array, for each glyph, the shape of the glyph as it is in the inline box, positioned on
- // a coordinate space using CSS pixels with its origin is at the anchor point.
- PreparedText prepared_text { move(glyph_runs), Gfx::TextAlignment::CenterLeft, { 0, 0, width, height } };
-
- // 12. Return result, physical alignment, and the inline box.
- return prepared_text;
+ style_value->ref();
}
-void Canvas2DContextBase::clip_internal(Gfx::Path const& path, Gfx::WindingRule winding_rule)
+void web_canvas_2d_style_value_unref(CSS::StyleValue const* style_value)
{
- auto* recorder = canvas_recorder();
- if (!recorder)
- return;
-
- recorder->clip_path(path, winding_rule);
+ style_value->unref();
}
-void Canvas2DContextBase::clip(Bindings::CanvasFillRule fill_rule)
+// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-gettransform
+void* web_canvas_2d_create_dom_matrix(void* realm_pointer, Gfx::AffineTransform const* transform)
{
- clip_internal(path(), bindings_to_gfx_fill_rule(fill_rule));
+ auto& realm = *static_cast<JS::Realm*>(realm_pointer);
+ Geometry::DOMMatrix2DInit init = { transform->a(), transform->b(), transform->c(), transform->d(), transform->e(), transform->f() };
+ auto matrix = Geometry::DOMMatrix::create_from_dom_matrix_2d_init(init);
+ return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, matrix).ptr();
}
-void Canvas2DContextBase::clip(Path2D& path, Bindings::CanvasFillRule fill_rule)
+Gfx::DecodedImageFrame* web_canvas_2d_image_frame_from_pixels(u8 const* first_row, size_t pitch, i32 width, i32 height)
{
- clip_internal(path.path(), bindings_to_gfx_fill_rule(fill_rule));
+ // NB: The bitmap is shareable, so that flushing to the Compositor passes the pixels by file descriptor instead of
+ // copying them again.
+ auto bitmap = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Unpremultiplied, { width, height });
+ if (bitmap.is_error())
+ return nullptr;
+ auto row_size = static_cast<size_t>(width) * sizeof(Gfx::RawPixel);
+ for (int y = 0; y < height; ++y)
+ __builtin_memcpy(bitmap.value()->scanline(y), first_row + static_cast<size_t>(y) * pitch, row_size);
+ return new Gfx::DecodedImageFrame { *bitmap.release_value(), Gfx::AlphaType::Unpremultiplied };
+}
+
+static CanvasImageSource image_source_from(void* source_wrapper, CanvasImageSourceKind kind)
+{
+ auto& wrapper = *static_cast<JS::Object*>(source_wrapper);
+ switch (kind) {
+ case CanvasImageSourceKind::HTMLImageElement:
+ return GC::Ref { Bindings::impl_from<HTMLImageElement>(wrapper) };
+ case CanvasImageSourceKind::SVGImageElement:
+ return GC::Ref { Bindings::impl_from<SVG::SVGImageElement>(wrapper) };
+ case CanvasImageSourceKind::HTMLVideoElement:
+ return GC::Ref { Bindings::impl_from<HTMLVideoElement>(wrapper) };
+ case CanvasImageSourceKind::HTMLCanvasElement:
+ return GC::Ref { Bindings::impl_from<HTMLCanvasElement>(wrapper) };
+ case CanvasImageSourceKind::OffscreenCanvas:
+ return GC::Ref { Bindings::impl_from<OffscreenCanvas>(wrapper) };
+ }
+ VERIFY_NOT_REACHED();
}
-static bool is_point_in_path_internal(Gfx::Path path, Gfx::AffineTransform const& transform, double x, double y, Bindings::CanvasFillRule fill_rule)
-{
- auto point = Gfx::FloatPoint(x, y);
- if (auto inverse_transform = transform.inverse(); inverse_transform.has_value())
- point = inverse_transform->map(point);
- return path.contains(point, bindings_to_gfx_fill_rule(fill_rule));
-}
+// The values of `Usability` of Bindings/Rust/src/canvas_2d/canvas.rs.
+static constexpr u8 usability_good = 0;
+static constexpr u8 usability_bad = 1;
+static constexpr u8 usability_invalid_state = 2;
-static bool image_provider_is_usable_for_canvas(Layout::ImageProvider const& image_provider)
+u8 web_canvas_2d_check_usability_of_image(void* source_wrapper, CanvasImageSourceKind kind, FlatPtr* out_message)
{
- if (!image_provider.is_image_available())
- return false;
-
- auto intrinsic_width = image_provider.intrinsic_width();
- auto intrinsic_height = image_provider.intrinsic_height();
- return intrinsic_width.has_value() && intrinsic_height.has_value()
- && *intrinsic_width > 0 && *intrinsic_height > 0;
+ auto usability = check_usability_of_image(image_source_from(source_wrapper, kind));
+ if (usability.is_exception()) {
+ auto exception = usability.release_error();
+ auto& dom_exception = exception.get<GC::Ref<WebIDL::DOMException>>();
+ VERIFY(dom_exception->name() == "InvalidStateError"_utf16_fly_string);
+ *out_message = Utf16String { dom_exception->message() }.into_raw();
+ return usability_invalid_state;
+ }
+ return usability.value() == CanvasImageSourceUsability::Good ? usability_good : usability_bad;
}
-bool Canvas2DContextBase::is_point_in_path(double x, double y, Bindings::CanvasFillRule fill_rule)
+void web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind kind, i32* out_width, i32* out_height)
{
- return is_point_in_path_internal(path(), drawing_state().transform, x, y, fill_rule);
-}
+ auto image_provider_intrinsic_size = [](Layout::ImageProvider const& image_provider) -> Optional<Gfx::IntSize> {
+ auto intrinsic_width = image_provider.intrinsic_width();
+ auto intrinsic_height = image_provider.intrinsic_height();
+ if (!intrinsic_width.has_value() || !intrinsic_height.has_value())
+ return {};
+ return Gfx::IntSize { intrinsic_width->to_int(), intrinsic_height->to_int() };
+ };
-bool Canvas2DContextBase::is_point_in_path(Path2D const& path, double x, double y, Bindings::CanvasFillRule fill_rule)
-{
- return is_point_in_path_internal(path.path(), drawing_state().transform, x, y, fill_rule);
-}
+ auto size = image_source_from(source_wrapper, kind).visit([&](GC::Ref<HTMLImageElement> source) -> Gfx::IntSize {
+ if (auto intrinsic_size = image_provider_intrinsic_size(*source); intrinsic_size.has_value())
+ return *intrinsic_size;
-// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
-WebIDL::ExceptionOr<CanvasImageSourceUsability> check_usability_of_image(CanvasImageSource const& image)
-{
- // 1. Switch on image:
- auto usability = TRY(image.visit(
- // HTMLOrSVGImageElement
- [](GC::Ref<HTMLImageElement> image_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
- // If image's current request's state is broken, then throw an "InvalidStateError" DOMException.
- if (image_element->current_request().state() == HTML::ImageRequest::State::Broken)
- return WebIDL::InvalidStateError::create("Image element state is broken"_utf16);
-
- // If image is not fully decodable, or has an intrinsic width or intrinsic height
- // (or both) equal to zero, then return bad.
- if (!image_provider_is_usable_for_canvas(*image_element))
- return { CanvasImageSourceUsability::Bad };
- return Optional<CanvasImageSourceUsability> {};
- },
- // FIXME: Don't duplicate this for HTMLImageElement and SVGImageElement.
- [](GC::Ref<SVG::SVGImageElement> image_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
- // FIXME: If image's current request's state is broken, then throw an "InvalidStateError" DOMException.
-
- // If image is not fully decodable, or has an intrinsic width or intrinsic height
- // (or both) equal to zero, then return bad.
- if (!image_provider_is_usable_for_canvas(*image_element))
- return { CanvasImageSourceUsability::Bad };
- return Optional<CanvasImageSourceUsability> {};
- },
+ // FIXME: This is very janky and not correct.
+ return { source->width(), source->height() }; }, [&](GC::Ref<SVG::SVGImageElement> source) -> Gfx::IntSize {
+ if (auto intrinsic_size = image_provider_intrinsic_size(*source); intrinsic_size.has_value())
+ return *intrinsic_size;
- [](GC::Ref<HTML::HTMLVideoElement> video_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
- // If image's readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return bad.
- if (video_element->ready_state() == HTML::HTMLMediaElement::ReadyState::HaveNothing || video_element->ready_state() == HTML::HTMLMediaElement::ReadyState::HaveMetadata) {
- return { CanvasImageSourceUsability::Bad };
- }
- return Optional<CanvasImageSourceUsability> {};
- },
+ // FIXME: This is very janky and not correct.
+ auto maybe_width = source->width()->anim_val()->value();
+ auto maybe_height = source->height()->anim_val()->value();
- // OffscreenCanvas
- [](GC::Ref<OffscreenCanvas> offscreen_canvas) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
- // If image has either a horizontal dimension or a vertical dimension equal to zero, then throw an "InvalidStateError" DOMException.
- if (offscreen_canvas->width() == 0 || offscreen_canvas->height() == 0)
- return WebIDL::InvalidStateError::create("OffscreenCanvas width or height is zero"_utf16);
- return Optional<CanvasImageSourceUsability> {};
- },
- // HTMLCanvasElement
- [](GC::Ref<HTMLCanvasElement> canvas_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
- // If image has either a horizontal dimension or a vertical dimension equal to zero, then throw an "InvalidStateError" DOMException.
- if (canvas_element->width() == 0 || canvas_element->height() == 0)
- return WebIDL::InvalidStateError::create("Canvas width or height is zero"_utf16);
- return Optional<CanvasImageSourceUsability> {};
- },
+ auto width = maybe_width.is_exception() ? 0 : maybe_width.release_value();
+ auto height = maybe_height.is_exception() ? 0 : maybe_height.release_value();
- // ImageBitmap
- // FIXME: VideoFrame
- [](GC::Ref<ImageBitmap> image_bitmap) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
- if (image_bitmap->is_detached())
- return WebIDL::InvalidStateError::create("Image bitmap is detached"_utf16);
- return Optional<CanvasImageSourceUsability> {};
- }));
- if (usability.has_value())
- return usability.release_value();
-
- // 2. Return good.
- return { CanvasImageSourceUsability::Good };
+ return { width, height }; }, [](GC::Ref<HTMLCanvasElement> source) -> Gfx::IntSize { return { source->width(), source->height() }; }, [](GC::Ref<OffscreenCanvas> source) -> Gfx::IntSize { return source->bitmap_size_for_canvas(); }, [](GC::Ref<HTMLVideoElement> source) -> Gfx::IntSize { return { source->video_width(), source->video_height() }; }, [](GC::Ref<ImageBitmap>) -> Gfx::IntSize { VERIFY_NOT_REACHED(); });
+ *out_width = size.width();
+ *out_height = size.height();
}
// https://html.spec.whatwg.org/multipage/canvas.html#the-image-argument-is-not-origin-clean
-bool image_is_not_origin_clean(CanvasImageSource const& image)
+bool web_canvas_2d_image_is_not_origin_clean(void* source_wrapper, CanvasImageSourceKind kind)
{
// An object image is not origin-clean if, switching on image's type:
- return image.visit(
+ return image_source_from(source_wrapper, kind).visit(
// HTMLOrSVGImageElement
[](GC::Ref<HTMLImageElement> image) {
// image's current request's image data is CORS-cross-origin.
@@ -1242,343 +740,104 @@ bool image_is_not_origin_clean(CanvasImageSource const& image)
// image's bitmap's origin-clean flag is false.
return !canvas->is_origin_clean();
},
- // ImageBitmap
- [](GC::Ref<ImageBitmap> const&) {
- // FIXME: image's bitmap's origin-clean flag is false.
- return false;
+ [](GC::Ref<ImageBitmap> const&) -> bool {
+ VERIFY_NOT_REACHED();
});
}
-bool Canvas2DContextBase::image_smoothing_enabled() const
-{
- return drawing_state().image_smoothing_enabled;
-}
-
-void Canvas2DContextBase::set_image_smoothing_enabled(bool enabled)
-{
- drawing_state().image_smoothing_enabled = enabled;
-}
-
-Bindings::ImageSmoothingQuality Canvas2DContextBase::image_smoothing_quality() const
-{
- return drawing_state().image_smoothing_quality;
-}
-
-void Canvas2DContextBase::set_image_smoothing_quality(Bindings::ImageSmoothingQuality quality)
-{
- drawing_state().image_smoothing_quality = quality;
-}
-
-float Canvas2DContextBase::global_alpha() const
-{
- return drawing_state().global_alpha;
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-globalalpha
-void Canvas2DContextBase::set_global_alpha(float alpha)
-{
- // 1. If the given value is either infinite, NaN, or not in the range 0.0 to 1.0, then return.
- if (!isfinite(alpha) || alpha < 0.0f || alpha > 1.0f) {
- return;
- }
- // 2. Otherwise, set this's global alpha to the given value.
- drawing_state().global_alpha = alpha;
-}
-
-#define ENUMERATE_COMPOSITE_OPERATIONS(E) \
- E("normal"_utf16, u"normal"sv, Normal) \
- E("multiply"_utf16, u"multiply"sv, Multiply) \
- E("screen"_utf16, u"screen"sv, Screen) \
- E("overlay"_utf16, u"overlay"sv, Overlay) \
- E("darken"_utf16, u"darken"sv, Darken) \
- E("lighten"_utf16, u"lighten"sv, Lighten) \
- E("color-dodge"_utf16, u"color-dodge"sv, ColorDodge) \
- E("color-burn"_utf16, u"color-burn"sv, ColorBurn) \
- E("hard-light"_utf16, u"hard-light"sv, HardLight) \
- E("soft-light"_utf16, u"soft-light"sv, SoftLight) \
- E("difference"_utf16, u"difference"sv, Difference) \
- E("exclusion"_utf16, u"exclusion"sv, Exclusion) \
- E("hue"_utf16, u"hue"sv, Hue) \
- E("saturation"_utf16, u"saturation"sv, Saturation) \
- E("color"_utf16, u"color"sv, Color) \
- E("luminosity"_utf16, u"luminosity"sv, Luminosity) \
- E("clear"_utf16, u"clear"sv, Clear) \
- E("copy"_utf16, u"copy"sv, Copy) \
- E("source-over"_utf16, u"source-over"sv, SourceOver) \
- E("destination-over"_utf16, u"destination-over"sv, DestinationOver) \
- E("source-in"_utf16, u"source-in"sv, SourceIn) \
- E("destination-in"_utf16, u"destination-in"sv, DestinationIn) \
- E("source-out"_utf16, u"source-out"sv, SourceOut) \
- E("destination-out"_utf16, u"destination-out"sv, DestinationOut) \
- E("source-atop"_utf16, u"source-atop"sv, SourceATop) \
- E("destination-atop"_utf16, u"destination-atop"sv, DestinationATop) \
- E("xor"_utf16, u"xor"sv, Xor) \
- E("lighter"_utf16, u"lighter"sv, Lighter) \
- E("plus-darker"_utf16, u"plus-darker"sv, PlusDarker) \
- E("plus-lighter"_utf16, u"plus-lighter"sv, PlusLighter)
-
-Utf16String Canvas2DContextBase::global_composite_operation() const
-{
- auto current_compositing_and_blending_operator = drawing_state().current_compositing_and_blending_operator;
- switch (current_compositing_and_blending_operator) {
-#undef __ENUMERATE
-#define __ENUMERATE(operation_string, operation_view, compositing_and_blending_operator) \
- case Gfx::CompositingAndBlendingOperator::compositing_and_blending_operator: \
- return operation_string;
- ENUMERATE_COMPOSITE_OPERATIONS(__ENUMERATE)
-#undef __ENUMERATE
- default:
- VERIFY_NOT_REACHED();
- }
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-globalcompositeoperation
-void Canvas2DContextBase::set_global_composite_operation(Utf16View global_composite_operation)
+// The id of the canvas that a canvas or an OffscreenCanvas draws into, readied to be drawn, if it is drawn by its id.
+bool web_canvas_2d_image_source_canvas_id(void* source_wrapper, CanvasImageSourceKind kind, u64* out_canvas_id, bool* out_source_is_2d)
{
- // 1. If the given value is not identical to any of the values that the <blend-mode> or the <composite-mode> properties are defined to take, then return.
- // 2. Otherwise, set this's current compositing and blending operator to the given value.
-#undef __ENUMERATE
-#define __ENUMERATE(operation_string, operation_view, compositing_and_blending_operator) \
- if (global_composite_operation == operation_view) { \
- drawing_state().current_compositing_and_blending_operator = Gfx::CompositingAndBlendingOperator::compositing_and_blending_operator; \
- return; \
+ auto& wrapper = *static_cast<JS::Object*>(source_wrapper);
+ Optional<Compositing::CanvasId> source_canvas_id;
+ if (kind == CanvasImageSourceKind::HTMLCanvasElement) {
+ auto& source_canvas = Bindings::impl_from<HTMLCanvasElement>(wrapper);
+ if (source_canvas.is_placeholder())
+ return false;
+ bool const source_is_2d = source_canvas.canvas_rendering_context_2d() != nullptr;
+ source_canvas.ensure_backing_storage();
+ if (!source_is_2d)
+ source_canvas.prepare_for_compositing();
+ source_canvas_id = source_canvas.canvas_id();
+ *out_source_is_2d = source_is_2d;
+ } else if (kind == CanvasImageSourceKind::OffscreenCanvas) {
+ auto& source_canvas = Bindings::impl_from<OffscreenCanvas>(wrapper);
+ auto const* source_context = source_canvas.context().get_pointer<GC::Ref<OffscreenCanvasRenderingContext2D>>();
+ if (!source_context)
+ return false;
+ (*source_context)->ensure_backing_storage();
+ source_canvas_id = (*source_context)->canvas_id();
+ *out_source_is_2d = true;
}
- ENUMERATE_COMPOSITE_OPERATIONS(__ENUMERATE)
-#undef __ENUMERATE
-}
-
-float Canvas2DContextBase::shadow_offset_x() const
-{
- return drawing_state().shadow_offset_x;
-}
-
-void Canvas2DContextBase::set_shadow_offset_x(float offset_x)
-{
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowoffsetx
- if (!isfinite(offset_x))
- return;
-
- drawing_state().shadow_offset_x = offset_x;
-}
-
-float Canvas2DContextBase::shadow_offset_y() const
-{
- return drawing_state().shadow_offset_y;
-}
-
-void Canvas2DContextBase::set_shadow_offset_y(float offset_y)
-{
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowoffsety
- if (!isfinite(offset_y))
- return;
-
- drawing_state().shadow_offset_y = offset_y;
-}
-
-float Canvas2DContextBase::shadow_blur() const
-{
- return drawing_state().shadow_blur;
+ if (!source_canvas_id.has_value())
+ return false;
+ *out_canvas_id = source_canvas_id->value();
+ return true;
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
-void Canvas2DContextBase::set_shadow_blur(float blur_radius)
+Gfx::DecodedImageFrame* web_canvas_2d_image_source_frame(void* source_wrapper, CanvasImageSourceKind kind)
{
- // On setting, the attribute must be set to the new value,
- // except if the value is negative, infinite or NaN, in which case the new value must be ignored.
- if (blur_radius < 0 || isinf(blur_radius) || isnan(blur_radius))
- return;
+ 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 {};
- drawing_state().shadow_blur = blur_radius;
-}
+ Gfx::IntSize size;
+ auto intrinsic_width = element->intrinsic_width();
+ auto intrinsic_height = element->intrinsic_height();
+ if (intrinsic_width.has_value() && intrinsic_height.has_value())
+ size = { intrinsic_width->to_int(), intrinsic_height->to_int() };
-Utf16String Canvas2DContextBase::shadow_color() const
-{
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowcolor
- auto serialized_color = drawing_state().shadow_color.to_string(Gfx::Color::HTMLCompatibleSerialization::Yes);
- return Utf16String::from_ascii_without_validation(serialized_color.bytes());
+ return image_data->default_frame(size); }, [](GC::Ref<HTMLCanvasElement> const& canvas) -> Optional<Gfx::DecodedImageFrame> {
+ canvas->prepare_for_compositing();
+ auto bitmap = canvas->get_bitmap_from_surface();
+ if (!bitmap)
+ return {};
+ return Gfx::DecodedImageFrame { *bitmap }; }, [](GC::Ref<OffscreenCanvas> const& source) -> Optional<Gfx::DecodedImageFrame> {
+ auto bitmap = source->get_bitmap_from_surface();
+ if (!bitmap)
+ return {};
+ return Gfx::DecodedImageFrame { *bitmap }; }, [](OneOf<GC::Ref<HTMLVideoElement>, GC::Ref<ImageBitmap>> auto const&) -> Optional<Gfx::DecodedImageFrame> { VERIFY_NOT_REACHED(); });
+ if (!frame.has_value())
+ return nullptr;
+ return new Gfx::DecodedImageFrame { frame.release_value() };
}
-void Canvas2DContextBase::set_shadow_color(Utf16View color)
+bool web_canvas_2d_capture_video_frame(void* source_wrapper, CapturedVideoFrame* out_frame)
{
- // 1. Let context be this's canvas attribute's value, if that is an element; otherwise null.
-
- // 2. Let parsedValue be the result of parsing the given value with context if non-null.
- auto parsed_value = parse_a_css_color_value(color);
-
- // 3. If parsedValue is failure, then return.
- if (!parsed_value.has_value())
- return;
-
- // 4. Set this's shadow color to parsedValue.
- drawing_state().shadow_color = parsed_value.value();
-}
-// A shadow is drawn through the filter with its operator, but without the global alpha, which its color holds.
-static Canvas2DCompositing shadow_compositing(DrawingState const& state)
-{
- return {
- .filter = state.filter.has_value() ? &state.filter.value() : nullptr,
- .global_alpha = 1,
- .compositing_and_blending_operator = state.current_compositing_and_blending_operator,
+ auto& video = Bindings::impl_from<HTMLVideoElement>(*static_cast<JS::Object*>(source_wrapper));
+ auto captured_frame = video.capture_current_video_frame();
+ if (!captured_frame.has_value())
+ return false;
+ VERIFY(captured_frame->hold);
+ *out_frame = {
+ .hold = &captured_frame->hold.release_nonnull().leak_ref(),
+ .sink_handle = captured_frame->sink_handle.value(),
+ .generation = captured_frame->generation,
};
+ return true;
}
-void Canvas2DContextBase::paint_shadow_for_fill_internal(Gfx::Path const& path, Gfx::WindingRule winding_rule)
+void* web_canvas_2d_video_transport(void* source_wrapper)
{
- auto* recorder = canvas_recorder();
- if (!recorder)
- return;
-
- auto& state = this->drawing_state();
- if (state.shadow_blur == 0.0f && state.shadow_offset_x == 0.0f && state.shadow_offset_y == 0.0f)
- return;
-
- if (state.current_compositing_and_blending_operator == Gfx::CompositingAndBlendingOperator::Copy)
- return;
-
- auto alpha = state.global_alpha * (state.shadow_color.alpha() / 255.0f);
- auto fill_style_color = state.fill_style.as_color();
- if (fill_style_color.has_value() && fill_style_color->alpha() > 0)
- alpha = (fill_style_color->alpha() / 255.0f) * state.global_alpha;
- if (alpha == 0.0f)
- return;
-
- recorder->save();
-
- Gfx::AffineTransform transform;
- transform.translate(state.shadow_offset_x, state.shadow_offset_y);
- transform.multiply(state.transform);
- recorder->set_transform(transform);
- recorder->fill_path_shadow(path, state.shadow_color.with_opacity(alpha), winding_rule, state.shadow_blur, shadow_compositing(state));
-
- recorder->restore();
-
- did_draw(path.bounding_box());
+ auto& video = Bindings::impl_from<HTMLVideoElement>(*static_cast<JS::Object*>(source_wrapper));
+ return transport_for(video.document().page());
}
-void Canvas2DContextBase::paint_shadow_for_stroke_internal(Gfx::Path const& path, Gfx::Path::CapStyle line_cap, Gfx::Path::JoinStyle line_join, Vector<float> const& dash_array)
+void web_canvas_2d_video_frame_hold_unref(Compositing::VideoFrameHold* hold)
{
- auto* recorder = canvas_recorder();
- if (!recorder)
- return;
-
- auto& state = drawing_state();
-
- if (state.current_compositing_and_blending_operator == Gfx::CompositingAndBlendingOperator::Copy)
- return;
-
- if (state.shadow_blur == 0.0f && state.shadow_offset_x == 0.0f && state.shadow_offset_y == 0.0f)
- return;
-
- auto alpha = state.global_alpha * (state.shadow_color.alpha() / 255.0f);
- auto fill_style_color = state.fill_style.as_color();
- if (fill_style_color.has_value() && fill_style_color->alpha() > 0)
- alpha = (fill_style_color->alpha() / 255.0f) * state.global_alpha;
- if (alpha == 0.0f)
- return;
-
- recorder->save();
-
- Gfx::AffineTransform transform;
- transform.translate(state.shadow_offset_x, state.shadow_offset_y);
- transform.multiply(state.transform);
- recorder->set_transform(transform);
- recorder->stroke_path_shadow(path, state.shadow_color.with_opacity(alpha),
- {
- .thickness = state.line_width,
- .cap_style = line_cap,
- .join_style = line_join,
- .miter_limit = state.miter_limit,
- .dash_array = dash_array,
- .dash_offset = state.line_dash_offset,
- },
- state.shadow_blur, shadow_compositing(state));
-
- recorder->restore();
-
- did_draw(path.bounding_box());
-}
-
-Utf16String Canvas2DContextBase::filter() const
-{
- if (!drawing_state().filter_string.has_value()) {
- return "none"_utf16;
- }
-
- return drawing_state().filter_string.value();
+ hold->unref();
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-filter
-void Canvas2DContextBase::set_filter(Utf16View filter)
+// https://drafts.csswg.org/css-color/#parse-a-css-color-value
+bool web_canvas_gradient_parse_color(FlatPtr color, Gfx::Color* out_color)
{
- drawing_state().filter.clear();
-
- // 1. If the given value is "none", then set this's current filter to "none" and return.
- if (filter == u"none"sv) {
- drawing_state().filter_string.clear();
- return;
- }
-
- CSS::Parser::Parser parser { CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue } };
-
- // 2. Let parsedValue be the result of parsing the given values as a <filter-value-list>.
- // If any property-independent style sheet syntax like 'inherit' or 'initial' is present,
- // then this parsing must return failure.
- auto style_value = parser.parse_as_css_value(filter, CSS::PropertyID::Filter);
-
- if (style_value && style_value->is_value_list()) {
- auto absolutized_style_value = style_value->absolutized(computation_context_for_drawing_state());
- auto filter_value_list = absolutized_style_value->as_value_list().values();
-
- // 4. Set this's current filter to the given value.
- Vector<Compositing::RustFFI::FfiFilterFunction> functions;
- for (auto& item : filter_value_list) {
- if (item->is_url()) {
- // FIXME: Resolve the SVG filter
- dbgln("FIXME: SVG filters are not implemented for Canvas2D");
- continue;
- }
-
- auto const& filter_value = item->as_filter();
- Compositing::RustFFI::FfiFilterFunction function {};
- switch (filter_value.kind()) {
- case CSS::FilterStyleValue::Kind::Blur: {
- auto const& blur_filter = static_cast<CSS::BlurFilterStyleValue const&>(filter_value);
- function.kind = Compositing::RustFFI::FfiFilterFunctionKind::Blur;
- function.amount = blur_filter.resolved_radius();
- break;
- }
- case CSS::FilterStyleValue::Kind::Color: {
- auto const& color = static_cast<CSS::ColorFilterStyleValue const&>(filter_value);
- function.kind = Compositing::RustFFI::FfiFilterFunctionKind::Color;
- function.color_operation = color.operation();
- function.amount = color.resolved_amount();
- break;
- }
- case CSS::FilterStyleValue::Kind::HueRotate: {
- auto const& hue_rotate = static_cast<CSS::HueRotateFilterStyleValue const&>(filter_value);
- function.kind = Compositing::RustFFI::FfiFilterFunctionKind::HueRotate;
- function.amount = hue_rotate.angle_degrees();
- break;
- }
- case CSS::FilterStyleValue::Kind::DropShadow: {
- auto const& drop_shadow = static_cast<CSS::DropShadowFilterStyleValue const&>(filter_value);
- function.kind = Compositing::RustFFI::FfiFilterFunctionKind::DropShadow;
- function.offset_x = static_cast<float>(CSS::Length::from_style_value(drop_shadow.offset_x(), {}).absolute_length_to_px());
- function.offset_y = static_cast<float>(CSS::Length::from_style_value(drop_shadow.offset_y(), {}).absolute_length_to_px());
- if (drop_shadow.radius())
- function.amount = static_cast<float>(CSS::Length::from_style_value(*drop_shadow.radius(), {}).absolute_length_to_px());
- function.color = drop_shadow.color() ? drop_shadow.color()->to_color(canvas_host().canvas_color_resolution_style()).value_or(Gfx::Color::Black) : Gfx::Color::Black;
- break;
- }
- }
- functions.append(function);
- }
- drawing_state().filter = Painting::filter_from_functions(functions);
-
- drawing_state().filter_string = Utf16String::from_utf16(filter);
- }
-
- // 3. If parsedValue is failure, then return.
+ auto color_string = Utf16String::from_raw(color);
+ auto const maybe_color = parse_css_value(CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue }, color_string.utf16_view(), CSS::PropertyID::Color);
+ if (maybe_color.is_null() || !maybe_color->has_color())
+ return false;
+ *out_color = maybe_color->to_color({}).value();
+ return true;
}
}
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h
index 4bf0b5dd3f5..16c0ff5722f 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h
@@ -9,191 +9,48 @@
#pragma once
#include <AK/Optional.h>
-#include <AK/OwnPtr.h>
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
-#include <LibCompositing/Types.h>
+#include <AK/RefPtr.h>
+#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
+#include <LibGfx/Bitmap.h>
#include <LibGfx/Forward.h>
-#include <LibGfx/Path.h>
-#include <LibGfx/TextLayout.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/HTML/Canvas/CanvasCompositing.h>
-#include <LibWeb/HTML/Canvas/CanvasDrawImage.h>
-#include <LibWeb/HTML/Canvas/CanvasDrawPath.h>
-#include <LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h>
-#include <LibWeb/HTML/Canvas/CanvasFilters.h>
-#include <LibWeb/HTML/Canvas/CanvasImageData.h>
-#include <LibWeb/HTML/Canvas/CanvasImageSmoothing.h>
-#include <LibWeb/HTML/Canvas/CanvasPath.h>
-#include <LibWeb/HTML/Canvas/CanvasPathDrawingStyles.h>
-#include <LibWeb/HTML/Canvas/CanvasRect.h>
+#include <LibGfx/Rect.h>
+#include <LibGfx/Size.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
#include <LibWeb/HTML/Canvas/CanvasSettings.h>
-#include <LibWeb/HTML/Canvas/CanvasShadowStyles.h>
-#include <LibWeb/HTML/Canvas/CanvasState.h>
-#include <LibWeb/HTML/Canvas/CanvasText.h>
-#include <LibWeb/HTML/Canvas/CanvasTransform.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::HTML {
-class Canvas2DContextBase
- : public Bindings::GCAllocatedWrappable
- , public CanvasPath
- , public CanvasState
- , public CanvasTransform
- , public CanvasFillStrokeStyles
- , public CanvasShadowStyles
- , public CanvasFilters
- , public CanvasRect
- , public CanvasDrawPath
- , public CanvasText
- , public CanvasDrawImage
- , public CanvasImageData
- , public CanvasImageSmoothing
- , public CanvasCompositing
- , public CanvasSettings
- , public CanvasPathDrawingStyles {
-
- WEB_NON_IDL_WRAPPABLE(Canvas2DContextBase, Bindings::GCAllocatedWrappable);
-
+// The C++ side of a CanvasRenderingContext2D or an OffscreenCanvasRenderingContext2D, which are implemented in Rust
+// (Libraries/LibWeb/Bindings/Rust/src/canvas_2d and the modules of their IDL files in .../src/html): what the rest of
+// LibWeb calls, and what the Rust code calls back.
+class WEB_API Canvas2DContextBase : public Bindings::RustInterfaceCell {
public:
- virtual ~Canvas2DContextBase() override;
+ CanvasHost& canvas_host() const;
// https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-clean
- bool origin_clean() const { return m_origin_clean; }
-
- virtual void fill_rect(float x, float y, float width, float height) override;
- virtual void stroke_rect(float x, float y, float width, float height) override;
- virtual void clear_rect(float x, float y, float width, float height) override;
-
- virtual WebIDL::ExceptionOr<void> draw_image_internal(CanvasImageSource const&, float source_x, float source_y, float source_width, float source_height, float destination_x, float destination_y, float destination_width, float destination_height) override;
-
- virtual void begin_path() override;
- virtual void stroke() override;
- virtual void stroke(Path2D const& path) override;
-
- virtual void fill_text(Utf16View, float x, float y, Optional<double> max_width) override;
- virtual void stroke_text(Utf16View, float x, float y, Optional<double> max_width) override;
-
- virtual void fill(Bindings::CanvasFillRule) override;
- virtual void fill(Path2D& path, Bindings::CanvasFillRule) override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(int width, int height, Optional<Bindings::ImageDataSettings> const& settings = {}) const override;
- virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(ImageData const& image_data) const override;
- virtual WebIDL::ExceptionOr<GC::Ptr<ImageData>> get_image_data(int x, int y, int width, int height, Optional<Bindings::ImageDataSettings> const& settings = {}) override;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y) override;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y, int dirty_x, int dirty_y, int dirty_width, int dirty_height) override;
- WebIDL::ExceptionOr<void> put_pixels_from_an_image_data_onto_a_bitmap(ImageData&, Canvas2DRecorder&, int dx, int dy, int dirty_x, int dirty_y, int dirty_width, int dirty_height);
-
- virtual void reset_to_default_state() override;
-
- virtual Bindings::CanvasRenderingContext2DSettings get_context_attributes() const override { return m_context_attributes; }
-
- virtual GC::Ref<TextMetrics> measure_text(Utf16View) override;
-
- virtual void clip(Bindings::CanvasFillRule) override;
- virtual void clip(Path2D& path, Bindings::CanvasFillRule) override;
-
- virtual bool is_point_in_path(double x, double y, Bindings::CanvasFillRule) override;
- virtual bool is_point_in_path(Path2D const& path, double x, double y, Bindings::CanvasFillRule) override;
-
- virtual bool image_smoothing_enabled() const override;
- virtual void set_image_smoothing_enabled(bool) override;
- virtual Bindings::ImageSmoothingQuality image_smoothing_quality() const override;
- virtual void set_image_smoothing_quality(Bindings::ImageSmoothingQuality) override;
-
- virtual float global_alpha() const override;
- virtual void set_global_alpha(float) override;
-
- virtual Utf16String global_composite_operation() const override;
- virtual void set_global_composite_operation(Utf16View) override;
-
- virtual Utf16String filter() const override;
- virtual void set_filter(Utf16View) override;
-
- virtual float shadow_offset_x() const override;
- virtual void set_shadow_offset_x(float) override;
- virtual float shadow_offset_y() const override;
- virtual void set_shadow_offset_y(float) override;
- virtual float shadow_blur() const override;
- virtual void set_shadow_blur(float) override;
- virtual Utf16String shadow_color() const override;
- virtual void set_shadow_color(Utf16View) override;
+ bool origin_clean() const;
void set_size(Gfx::IntSize const&);
+ void reset_to_default_state();
void prepare_for_compositing();
void ensure_backing_storage();
-
void discard_backing_storage();
+ // https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-context-lost
void notify_backing_storage_lost();
Optional<Compositing::CanvasId> canvas_id() const;
RefPtr<Gfx::Bitmap> read_pixels(Gfx::IntRect const&, Gfx::AlphaType = Gfx::AlphaType::Premultiplied);
-protected:
- Canvas2DContextBase(JS::Realm&, Gfx::IntSize initial_size, Bindings::CanvasRenderingContext2DSettings);
-
- virtual void finalize() override;
- virtual void visit_edges(Cell::Visitor&) override;
- virtual size_t external_memory_size() const override;
- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
-
- [[nodiscard]] Canvas2DRecorder* canvas_recorder() override;
- JS::Realm& my_realm() override { return realm(); }
- JS::Realm& realm() const { return *m_realm; }
- Gfx::Path& mutable_path() override { return path(); }
-
- struct PreparedText {
- Vector<NonnullRefPtr<Gfx::GlyphRun>> glyph_runs;
- Gfx::TextAlignment physical_alignment;
- Gfx::FloatRect bounding_box;
- };
-
- void did_draw(Gfx::FloatRect const&);
-
- RefPtr<Gfx::FontCascadeList const> font_cascade_list();
-
- PreparedText prepare_text(Utf16View, float max_width = INFINITY);
-
- [[nodiscard]] Gfx::Path rect_path(float x, float y, float width, float height);
- Gfx::AffineTransform text_transform(float text_width, Optional<double> max_width);
- [[nodiscard]] Gfx::Path text_path(Utf16View, float x, float y, Optional<double> max_width);
-
- Gfx::Color clear_color() const;
- // How a draw composites under the current drawing state.
- Canvas2DCompositing compositing_for_drawing_state() const;
-
- void stroke_internal(Gfx::Path);
- void fill_internal(Gfx::Path, Gfx::WindingRule);
- void clip_internal(Gfx::Path const&, Gfx::WindingRule);
- void paint_shadow_for_fill_internal(Gfx::Path const&, Gfx::WindingRule);
- void paint_shadow_for_stroke_internal(Gfx::Path const&, Gfx::Path::CapStyle, Gfx::Path::JoinStyle, Vector<float> const&);
+ // Draws the ImageBitmap at the point as drawImage() does, and returns whether that threw nothing.
+ bool draw_image(ImageBitmap&, float x, float y);
- bool ensure_remote_canvas_context();
-
- bool has_backing_storage() const { return m_recorder != nullptr; }
-
- OwnPtr<Canvas2DRecorder> m_recorder;
- RefPtr<Gfx::Bitmap> m_cached_readback;
- Gfx::IntRect m_cached_readback_rect;
-
- // https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-clean
- bool m_origin_clean { true };
-
- Gfx::IntSize m_size;
- Bindings::CanvasRenderingContext2DSettings m_context_attributes;
- GC::Ref<JS::Realm> m_realm;
-};
-
-enum class CanvasImageSourceUsability {
- Bad,
- Good,
+protected:
+ static Canvas2DContextBase& create(CanvasHost&, GC::Cell& canvas, bool canvas_is_offscreen, CanvasRenderingContext2DSettings const&);
};
-WebIDL::ExceptionOr<CanvasImageSourceUsability> check_usability_of_image(CanvasImageSource const&);
-bool image_is_not_origin_clean(CanvasImageSource const&);
-
}
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp
deleted file mode 100644
index 81a81d006b2..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Noncopyable.h>
-#include <AK/Vector.h>
-#include <LibCompositing/DisplayList/DisplayListCommandsGenerated.h>
-#include <LibCompositing/RustFFI.h>
-#include <LibGfx/Bitmap.h>
-#include <LibGfx/DecodedImageFrame.h>
-#include <LibGfx/Filter.h>
-#include <LibGfx/Font/Font.h>
-#include <LibWeb/HTML/Canvas/Canvas2DRecorder.h>
-#include <LibWeb/HTML/Canvas/DrawingState.h>
-#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>
-
-namespace Web::HTML {
-
-using Compositing::RustFFI::FfiCanvas2DCompositing;
-using Compositing::RustFFI::FfiCanvas2DPaint;
-using Compositing::RustFFI::FfiCanvas2DStroke;
-
-// NB: `AlphaType` of display_list/canvas_2d_recorder.rs is a u8 with the values of Gfx::AlphaType.
-static_assert(to_underlying(Gfx::AlphaType::Premultiplied) == 0);
-static_assert(to_underlying(Gfx::AlphaType::Unpremultiplied) == 1);
-
-// The C ABI of Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs.
-extern "C" {
-RustCanvas2DRecorder* web_canvas_2d_recorder_create(void* transport);
-void web_canvas_2d_recorder_destroy(RustCanvas2DRecorder*);
-bool web_canvas_2d_recorder_create_context(RustCanvas2DRecorder*, i32 width, i32 height, bool alpha);
-bool web_canvas_2d_recorder_canvas_id(RustCanvas2DRecorder const*, u64* out_canvas_id);
-void web_canvas_2d_recorder_destroy_context(RustCanvas2DRecorder*);
-void web_canvas_2d_recorder_flush(RustCanvas2DRecorder*);
-void* web_canvas_2d_recorder_read_back_pixels(RustCanvas2DRecorder*, Gfx::IntRect rect, u8 alpha_type);
-void web_canvas_2d_recorder_present(RustCanvas2DRecorder*);
-void web_canvas_2d_recorder_prepare_to_record(RustCanvas2DRecorder*);
-void web_canvas_2d_recorder_fill_path(RustCanvas2DRecorder*, ReadonlyBytes path, FfiCanvas2DPaint const*, Gfx::WindingRule, float blur_radius, FfiCanvas2DCompositing const*);
-void web_canvas_2d_recorder_stroke_path(RustCanvas2DRecorder*, ReadonlyBytes path, FfiCanvas2DPaint const*, FfiCanvas2DStroke const*, float blur_radius, FfiCanvas2DCompositing const*);
-void web_canvas_2d_recorder_draw_glyph_run(RustCanvas2DRecorder*, void const* font, ReadonlySpan<Compositing::DisplayListGlyph>, Gfx::FloatPoint translation, FfiCanvas2DPaint const*, FfiCanvas2DCompositing const*);
-void web_canvas_2d_recorder_clear_rect(RustCanvas2DRecorder*, Gfx::FloatRect rect, Gfx::Color);
-void web_canvas_2d_recorder_draw_image_frame(RustCanvas2DRecorder*, void const* frame, Gfx::FloatRect dst_rect, Gfx::IntRect src_rect, Gfx::ScalingMode, FfiCanvas2DCompositing const*);
-void web_canvas_2d_recorder_draw_canvas(RustCanvas2DRecorder*, u64 source_canvas_id, Gfx::FloatRect dst_rect, Gfx::IntRect src_rect, Gfx::ScalingMode, FfiCanvas2DCompositing const*);
-void web_canvas_2d_recorder_draw_video_frame(RustCanvas2DRecorder*, void* hold, u64 video_sink_handle, u64 generation, Gfx::FloatRect dst_rect, Gfx::IntRect src_rect, Gfx::ScalingMode, FfiCanvas2DCompositing const*);
-void web_canvas_2d_recorder_set_transform(RustCanvas2DRecorder*, Gfx::AffineTransform const*);
-void web_canvas_2d_recorder_save(RustCanvas2DRecorder*);
-void web_canvas_2d_recorder_restore(RustCanvas2DRecorder*);
-void web_canvas_2d_recorder_clip_path(RustCanvas2DRecorder*, ReadonlyBytes path, Gfx::WindingRule);
-void web_canvas_2d_recorder_reset(RustCanvas2DRecorder*);
-void web_canvas_2d_recorder_clear_canvas(RustCanvas2DRecorder*, Gfx::Color);
-
-// Defined in Bindings/Rust/src/html/exports.rs.
-void web_canvas_gradient_lend_paint(void* gradient, FfiCanvas2DPaint* out_paint);
-void web_canvas_pattern_lend_paint(void* pattern, FfiCanvas2DPaint* out_paint);
-}
-
-namespace {
-
-// A fill or stroke style as the recorder borrows it. A gradient lends its color stops and a pattern its image, which
-// stay as they are while the recorder borrows them.
-class LentPaint {
- AK_MAKE_NONCOPYABLE(LentPaint);
- AK_MAKE_NONMOVABLE(LentPaint);
-
-public:
- explicit LentPaint(Gfx::Color color)
- {
- m_paint.kind = Compositing::Canvas2DPaintKind::Color;
- m_paint.color = color;
- }
-
- explicit LentPaint(FillOrStrokeStyle const& style)
- {
- style.variant().visit(
- [&](Gfx::Color color) {
- m_paint.kind = Compositing::Canvas2DPaintKind::Color;
- m_paint.color = color;
- },
- [&](GC::Ref<CanvasGradient> gradient) {
- web_canvas_gradient_lend_paint(gradient.ptr(), &m_paint);
- },
- [&](GC::Ref<CanvasPattern> pattern) {
- web_canvas_pattern_lend_paint(pattern.ptr(), &m_paint);
- });
- }
-
- FfiCanvas2DPaint const* ptr() const { return &m_paint; }
-
-private:
- FfiCanvas2DPaint m_paint {
- .kind = Compositing::Canvas2DPaintKind::Color,
- .pattern_repetition = Compositing::Canvas2DPatternRepetition::Repeat,
- .has_pattern_transform = false,
- .color = {},
- .start_point = {},
- .end_point = {},
- .start_radius = 0,
- .end_radius = 0,
- .start_angle = 0,
- .color_stop_colors = {},
- .color_stop_positions = {},
- .pattern_image = nullptr,
- .pattern_transform = {},
- };
-};
-
-}
-
-static FfiCanvas2DCompositing lend(Canvas2DCompositing const& compositing)
-{
- return {
- .filter = compositing.filter ? compositing.filter->serialized_bytes() : ReadonlyBytes {},
- .has_filter = compositing.filter != nullptr,
- .global_alpha = compositing.global_alpha,
- .compositing_and_blending_operator = compositing.compositing_and_blending_operator,
- };
-}
-
-static FfiCanvas2DStroke lend(Canvas2DStroke const& stroke)
-{
- return {
- .thickness = stroke.thickness,
- .cap_style = stroke.cap_style,
- .join_style = stroke.join_style,
- .miter_limit = stroke.miter_limit,
- .dash_array = stroke.dash_array,
- .dash_offset = stroke.dash_offset,
- };
-}
-
-NonnullOwnPtr<Canvas2DRecorder> Canvas2DRecorder::create(NonnullRefPtr<RemoteCanvas2DTransport> transport)
-{
- return adopt_own(*new Canvas2DRecorder(web_canvas_2d_recorder_create(&transport.leak_ref())));
-}
-
-Canvas2DRecorder::Canvas2DRecorder(RustCanvas2DRecorder* recorder)
- : m_recorder(recorder)
-{
- VERIFY(m_recorder);
-}
-
-Canvas2DRecorder::~Canvas2DRecorder()
-{
- web_canvas_2d_recorder_destroy(m_recorder);
-}
-
-bool Canvas2DRecorder::create_context(Gfx::IntSize size, bool alpha)
-{
- return web_canvas_2d_recorder_create_context(m_recorder, size.width(), size.height(), alpha);
-}
-
-Optional<Compositing::CanvasId> Canvas2DRecorder::canvas_id() const
-{
- u64 canvas_id = 0;
- if (!web_canvas_2d_recorder_canvas_id(m_recorder, &canvas_id))
- return {};
- return Compositing::CanvasId { canvas_id };
-}
-
-void Canvas2DRecorder::destroy_context()
-{
- web_canvas_2d_recorder_destroy_context(m_recorder);
-}
-
-void Canvas2DRecorder::flush()
-{
- web_canvas_2d_recorder_flush(m_recorder);
-}
-
-RefPtr<Gfx::Bitmap> Canvas2DRecorder::read_back_pixels(Gfx::IntRect const& rect, Gfx::AlphaType alpha_type)
-{
- auto* bitmap = web_canvas_2d_recorder_read_back_pixels(m_recorder, rect, to_underlying(alpha_type));
- if (!bitmap)
- return nullptr;
- return adopt_ref(*static_cast<Gfx::Bitmap*>(bitmap));
-}
-
-void Canvas2DRecorder::present()
-{
- web_canvas_2d_recorder_present(m_recorder);
-}
-
-void Canvas2DRecorder::prepare_to_record()
-{
- web_canvas_2d_recorder_prepare_to_record(m_recorder);
-}
-
-void Canvas2DRecorder::fill_path(Gfx::Path const& path, FillOrStrokeStyle const& style, Gfx::WindingRule winding_rule, Canvas2DCompositing const& compositing)
-{
- auto path_bytes = path.serialize_to_bytes();
- LentPaint paint { style };
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_fill_path(m_recorder, path_bytes.span(), paint.ptr(), winding_rule, 0, &lent_compositing);
-}
-
-void Canvas2DRecorder::fill_path_shadow(Gfx::Path const& path, Gfx::Color color, Gfx::WindingRule winding_rule, float blur_radius, Canvas2DCompositing const& compositing)
-{
- auto path_bytes = path.serialize_to_bytes();
- LentPaint paint { color };
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_fill_path(m_recorder, path_bytes.span(), paint.ptr(), winding_rule, blur_radius, &lent_compositing);
-}
-
-void Canvas2DRecorder::stroke_path(Gfx::Path const& path, FillOrStrokeStyle const& style, Canvas2DStroke const& stroke, Canvas2DCompositing const& compositing)
-{
- auto path_bytes = path.serialize_to_bytes();
- LentPaint paint { style };
- auto lent_stroke = lend(stroke);
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_stroke_path(m_recorder, path_bytes.span(), paint.ptr(), &lent_stroke, 0, &lent_compositing);
-}
-
-void Canvas2DRecorder::stroke_path_shadow(Gfx::Path const& path, Gfx::Color color, Canvas2DStroke const& stroke, float blur_radius, Canvas2DCompositing const& compositing)
-{
- auto path_bytes = path.serialize_to_bytes();
- LentPaint paint { color };
- auto lent_stroke = lend(stroke);
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_stroke_path(m_recorder, path_bytes.span(), paint.ptr(), &lent_stroke, blur_radius, &lent_compositing);
-}
-
-void Canvas2DRecorder::draw_glyph_run(Gfx::Font const& font, ReadonlySpan<Compositing::DisplayListGlyph> glyphs, Gfx::FloatPoint translation, FillOrStrokeStyle const& style, Canvas2DCompositing const& compositing)
-{
- LentPaint paint { style };
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_draw_glyph_run(m_recorder, &font, glyphs, translation, paint.ptr(), &lent_compositing);
-}
-
-void Canvas2DRecorder::clear_rect(Gfx::FloatRect const& rect, Gfx::Color color)
-{
- web_canvas_2d_recorder_clear_rect(m_recorder, rect, color);
-}
-
-void Canvas2DRecorder::draw_image_frame(Gfx::DecodedImageFrame const& frame, Gfx::FloatRect const& dst_rect, Gfx::IntRect const& src_rect, Gfx::ScalingMode scaling_mode, Canvas2DCompositing const& compositing)
-{
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_draw_image_frame(m_recorder, &frame, dst_rect, src_rect, scaling_mode, &lent_compositing);
-}
-
-void Canvas2DRecorder::draw_canvas(Compositing::CanvasId source_canvas_id, Gfx::FloatRect const& dst_rect, Gfx::IntRect const& src_rect, Gfx::ScalingMode scaling_mode, Canvas2DCompositing const& compositing)
-{
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_draw_canvas(m_recorder, source_canvas_id.value(), dst_rect, src_rect, scaling_mode, &lent_compositing);
-}
-
-void Canvas2DRecorder::draw_video_frame(Compositing::CapturedVideoFrame const& captured_frame, Gfx::FloatRect const& dst_rect, Gfx::IntRect const& src_rect, Gfx::ScalingMode scaling_mode, Canvas2DCompositing const& compositing)
-{
- VERIFY(captured_frame.hold);
- auto lent_compositing = lend(compositing);
- web_canvas_2d_recorder_draw_video_frame(m_recorder, captured_frame.hold.ptr(), captured_frame.sink_handle.value(), captured_frame.generation, dst_rect, src_rect, scaling_mode, &lent_compositing);
-}
-
-void Canvas2DRecorder::set_transform(Gfx::AffineTransform const& transform)
-{
- web_canvas_2d_recorder_set_transform(m_recorder, &transform);
-}
-
-void Canvas2DRecorder::save()
-{
- web_canvas_2d_recorder_save(m_recorder);
-}
-
-void Canvas2DRecorder::restore()
-{
- web_canvas_2d_recorder_restore(m_recorder);
-}
-
-void Canvas2DRecorder::clip_path(Gfx::Path const& path, Gfx::WindingRule winding_rule)
-{
- auto path_bytes = path.serialize_to_bytes();
- web_canvas_2d_recorder_clip_path(m_recorder, path_bytes.span(), winding_rule);
-}
-
-void Canvas2DRecorder::reset()
-{
- web_canvas_2d_recorder_reset(m_recorder);
-}
-
-void Canvas2DRecorder::clear_canvas(Gfx::Color color)
-{
- web_canvas_2d_recorder_clear_canvas(m_recorder, color);
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.h b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.h
deleted file mode 100644
index b4e9d68b261..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Noncopyable.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/RefPtr.h>
-#include <AK/Span.h>
-#include <LibCompositing/DisplayList/DisplayListCommandsGenerated.h>
-#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
-#include <LibCompositing/Video/VideoFrameHold.h>
-#include <LibGfx/Color.h>
-#include <LibGfx/CompositingAndBlendingOperator.h>
-#include <LibGfx/Forward.h>
-#include <LibGfx/Path.h>
-#include <LibGfx/Rect.h>
-#include <LibGfx/ScalingMode.h>
-#include <LibGfx/WindingRule.h>
-#include <LibWeb/Forward.h>
-
-namespace Gfx {
-
-class Filter;
-
-}
-
-namespace Web::HTML {
-
-struct FillOrStrokeStyle;
-struct RustCanvas2DRecorder;
-
-// How a draw composites onto the canvas.
-struct Canvas2DCompositing {
- Gfx::Filter const* filter { nullptr };
- float global_alpha { 1 };
- Gfx::CompositingAndBlendingOperator compositing_and_blending_operator { Gfx::CompositingAndBlendingOperator::SourceOver };
-};
-
-struct Canvas2DStroke {
- float thickness { 1 };
- Gfx::Path::CapStyle cap_style { Gfx::Path::CapStyle::Butt };
- Gfx::Path::JoinStyle join_style { Gfx::Path::JoinStyle::Miter };
- float miter_limit { 10 };
- ReadonlySpan<float> dash_array;
- float dash_offset { 0 };
-};
-
-// The recorder of a 2D canvas, which Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs implements: it writes the
-// commands of the canvas as records of the display list tape into the stream that the canvases of WebContent share,
-// and reaches the Compositor through the transport that it owns.
-class Canvas2DRecorder {
- AK_MAKE_NONCOPYABLE(Canvas2DRecorder);
- AK_MAKE_NONMOVABLE(Canvas2DRecorder);
-
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- static NonnullOwnPtr<Canvas2DRecorder> create(NonnullRefPtr<RemoteCanvas2DTransport>);
- ~Canvas2DRecorder();
-
- bool create_context(Gfx::IntSize, bool alpha);
- Optional<Compositing::CanvasId> canvas_id() const;
- void destroy_context();
- void flush();
- // Unpremultiplied pixels come back as RGBA8888 and premultiplied pixels as BGRA8888.
- RefPtr<Gfx::Bitmap> read_back_pixels(Gfx::IntRect const&, Gfx::AlphaType);
- void present();
- // Sends the shared stream once it holds a batch, so that what is recorded next travels with its resources.
- void prepare_to_record();
-
- void fill_path(Gfx::Path const&, FillOrStrokeStyle const&, Gfx::WindingRule, Canvas2DCompositing const&);
- // A shadow: a fill in a solid color, blurred by the blur radius.
- void fill_path_shadow(Gfx::Path const&, Gfx::Color, Gfx::WindingRule, float blur_radius, Canvas2DCompositing const&);
- void stroke_path(Gfx::Path const&, FillOrStrokeStyle const&, Canvas2DStroke const&, Canvas2DCompositing const&);
- void stroke_path_shadow(Gfx::Path const&, Gfx::Color, Canvas2DStroke const&, float blur_radius, Canvas2DCompositing const&);
- void draw_glyph_run(Gfx::Font const&, ReadonlySpan<Compositing::DisplayListGlyph>, Gfx::FloatPoint translation, FillOrStrokeStyle const&, Canvas2DCompositing const&);
- void clear_rect(Gfx::FloatRect const&, Gfx::Color);
- void draw_image_frame(Gfx::DecodedImageFrame const&, Gfx::FloatRect const& dst_rect, Gfx::IntRect const& src_rect, Gfx::ScalingMode, Canvas2DCompositing const&);
- void draw_canvas(Compositing::CanvasId source_canvas_id, Gfx::FloatRect const& dst_rect, Gfx::IntRect const& src_rect, Gfx::ScalingMode, Canvas2DCompositing const&);
- void draw_video_frame(Compositing::CapturedVideoFrame const&, Gfx::FloatRect const& dst_rect, Gfx::IntRect const& src_rect, Gfx::ScalingMode, Canvas2DCompositing const&);
- void set_transform(Gfx::AffineTransform const&);
- void save();
- void restore();
- void clip_path(Gfx::Path const&, Gfx::WindingRule);
- void reset();
- void clear_canvas(Gfx::Color);
-
-private:
- explicit Canvas2DRecorder(RustCanvas2DRecorder*);
-
- RustCanvas2DRecorder* m_recorder { nullptr };
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasCompositing.h b/Libraries/LibWeb/HTML/Canvas/CanvasCompositing.h
deleted file mode 100644
index 8082c19c937..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasCompositing.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2023, MacDue <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvascompositing
-class CanvasCompositing {
-public:
- virtual ~CanvasCompositing() = default;
-
- virtual float global_alpha() const = 0;
- virtual void set_global_alpha(float) = 0;
-
- virtual Utf16String global_composite_operation() const = 0;
- virtual void set_global_composite_operation(Utf16View) = 0;
-
-protected:
- CanvasCompositing() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
index e4239d72c61..993c3caf3be 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
@@ -5,121 +5,88 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGfx/Bitmap.h>
-#include <LibGfx/DecodedImageFrame.h>
#include <LibWeb/HTML/Canvas/CanvasDrawImage.h>
-#include <LibWeb/HTML/DecodedImageData.h>
+#include <LibWeb/HTML/HTMLMediaElement.h>
#include <LibWeb/HTML/ImageBitmap.h>
-#include <LibWeb/SVG/SVGAnimatedLength.h>
+#include <LibWeb/HTML/ImageRequest.h>
+#include <LibWeb/Layout/ImageProvider.h>
namespace Web::HTML {
-Gfx::IntSize canvas_image_source_dimensions(CanvasImageSource const& image)
+static bool image_provider_is_usable_for_canvas(Layout::ImageProvider const& image_provider)
{
- auto image_provider_intrinsic_size = [](Layout::ImageProvider const& image_provider) -> Optional<Gfx::IntSize> {
- auto intrinsic_width = image_provider.intrinsic_width();
- auto intrinsic_height = image_provider.intrinsic_height();
- if (!intrinsic_width.has_value() || !intrinsic_height.has_value())
- return {};
- return Gfx::IntSize { intrinsic_width->to_int(), intrinsic_height->to_int() };
- };
+ if (!image_provider.is_image_available())
+ return false;
- return image.visit(
- [&](GC::Ref<HTMLImageElement> source) -> Gfx::IntSize {
- if (auto intrinsic_size = image_provider_intrinsic_size(*source); intrinsic_size.has_value())
- return *intrinsic_size;
-
- // FIXME: This is very janky and not correct.
- return { source->width(), source->height() };
- },
- [&](GC::Ref<SVG::SVGImageElement> source) -> Gfx::IntSize {
- if (auto intrinsic_size = image_provider_intrinsic_size(*source); intrinsic_size.has_value())
- return *intrinsic_size;
-
- // FIXME: This is very janky and not correct.
- auto maybe_width = source->width()->anim_val()->value();
- auto maybe_height = source->height()->anim_val()->value();
-
- auto width = maybe_width.is_exception() ? 0 : maybe_width.release_value();
- auto height = maybe_height.is_exception() ? 0 : maybe_height.release_value();
-
- return { width, height };
- },
- [](GC::Ref<HTMLCanvasElement> source) -> Gfx::IntSize {
- return { source->width(), source->height() };
- },
- [](GC::Ref<ImageBitmap> source) -> Gfx::IntSize {
- if (auto* bitmap = source->bitmap())
- return bitmap->size();
- return { source->width(), source->height() };
- },
- [](GC::Ref<OffscreenCanvas> source) -> Gfx::IntSize {
- return source->bitmap_size_for_canvas();
- },
- [](GC::Ref<HTMLVideoElement> source) -> Gfx::IntSize {
- return { source->video_width(), source->video_height() };
- });
+ auto intrinsic_width = image_provider.intrinsic_width();
+ auto intrinsic_height = image_provider.intrinsic_height();
+ return intrinsic_width.has_value() && intrinsic_height.has_value()
+ && *intrinsic_width > 0 && *intrinsic_height > 0;
}
-Optional<Gfx::DecodedImageFrame> canvas_image_source_frame(CanvasImageSource const& image)
+// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
+WebIDL::ExceptionOr<CanvasImageSourceUsability> check_usability_of_image(CanvasImageSource const& image)
{
- return image.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 {};
+ // 1. Switch on image:
+ auto usability = TRY(image.visit(
+ // HTMLOrSVGImageElement
+ [](GC::Ref<HTMLImageElement> image_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
+ // If image's current request's state is broken, then throw an "InvalidStateError" DOMException.
+ if (image_element->current_request().state() == HTML::ImageRequest::State::Broken)
+ return WebIDL::InvalidStateError::create("Image element state is broken"_utf16);
- Gfx::IntSize size;
- auto intrinsic_width = element->intrinsic_width();
- auto intrinsic_height = element->intrinsic_height();
- if (intrinsic_width.has_value() && intrinsic_height.has_value())
- size = { intrinsic_width->to_int(), intrinsic_height->to_int() };
+ // If image is not fully decodable, then return bad.
+ // If image has a natural width or natural height (or both) equal to zero, then return bad.
+ if (!image_provider_is_usable_for_canvas(*image_element))
+ return { CanvasImageSourceUsability::Bad };
+ return Optional<CanvasImageSourceUsability> {};
+ },
+ // FIXME: Don't duplicate this for HTMLImageElement and SVGImageElement.
+ [](GC::Ref<SVG::SVGImageElement> image_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
+ // FIXME: If image's current request's state is broken, then throw an "InvalidStateError" DOMException.
- return image_data->default_frame(size);
+ // If image is not fully decodable, then return bad.
+ // If image has a natural width or natural height (or both) equal to zero, then return bad.
+ if (!image_provider_is_usable_for_canvas(*image_element))
+ return { CanvasImageSourceUsability::Bad };
+ return Optional<CanvasImageSourceUsability> {};
},
- [](GC::Ref<HTMLCanvasElement> const& canvas) -> Optional<Gfx::DecodedImageFrame> {
- canvas->prepare_for_compositing();
- auto bitmap = canvas->get_bitmap_from_surface();
- if (!bitmap)
- return {};
- return Gfx::DecodedImageFrame { *bitmap };
+
+ [](GC::Ref<HTML::HTMLVideoElement> video_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
+ // If image's readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return bad.
+ if (video_element->ready_state() == HTML::HTMLMediaElement::ReadyState::HaveNothing || video_element->ready_state() == HTML::HTMLMediaElement::ReadyState::HaveMetadata) {
+ return { CanvasImageSourceUsability::Bad };
+ }
+ return Optional<CanvasImageSourceUsability> {};
},
- [](GC::Ref<ImageBitmap> const& source) -> Optional<Gfx::DecodedImageFrame> {
- return source->frame();
+
+ // OffscreenCanvas
+ [](GC::Ref<OffscreenCanvas> offscreen_canvas) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
+ // If image has either a horizontal dimension or a vertical dimension equal to zero, then throw an "InvalidStateError" DOMException.
+ if (offscreen_canvas->width() == 0 || offscreen_canvas->height() == 0)
+ return WebIDL::InvalidStateError::create("OffscreenCanvas width or height is zero"_utf16);
+ return Optional<CanvasImageSourceUsability> {};
},
- [](GC::Ref<OffscreenCanvas> const& source) -> Optional<Gfx::DecodedImageFrame> {
- auto bitmap = source->get_bitmap_from_surface();
- if (!bitmap)
- return {};
- return Gfx::DecodedImageFrame { *bitmap };
+ // HTMLCanvasElement
+ [](GC::Ref<HTMLCanvasElement> canvas_element) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
+ // If image has either a horizontal dimension or a vertical dimension equal to zero, then throw an "InvalidStateError" DOMException.
+ if (canvas_element->width() == 0 || canvas_element->height() == 0)
+ return WebIDL::InvalidStateError::create("Canvas width or height is zero"_utf16);
+ return Optional<CanvasImageSourceUsability> {};
},
- [](GC::Ref<HTMLVideoElement> const&) -> Optional<Gfx::DecodedImageFrame> {
- VERIFY_NOT_REACHED();
- });
-}
-WebIDL::ExceptionOr<void> CanvasDrawImage::draw_image(CanvasImageSource const& image, float destination_x, float destination_y)
-{
- // If not specified, the dw and dh arguments must default to the values of sw and sh, interpreted such that one CSS pixel in the image is treated as one unit in the output bitmap's coordinate space.
- // If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's intrinsic width in image pixels, and the image's intrinsic height in image pixels, respectively.
- // If the image has no intrinsic dimensions, then the concrete object size must be used instead, as determined using the CSS "Concrete Object Size Resolution" algorithm, with the specified size having
- // neither a definite width nor height, nor any additional constraints, the object's intrinsic properties being those of the image argument, and the default object size being the size of the output bitmap.
- auto size = canvas_image_source_dimensions(image);
- return draw_image_internal(image, 0, 0, size.width(), size.height(), destination_x, destination_y, size.width(), size.height());
-}
+ // ImageBitmap
+ // FIXME: VideoFrame
+ [](GC::Ref<ImageBitmap> image_bitmap) -> WebIDL::ExceptionOr<Optional<CanvasImageSourceUsability>> {
+ if (image_bitmap->is_detached())
+ return WebIDL::InvalidStateError::create("Image bitmap is detached"_utf16);
+ return Optional<CanvasImageSourceUsability> {};
+ }));
+ if (usability.has_value())
+ return usability.release_value();
-WebIDL::ExceptionOr<void> CanvasDrawImage::draw_image(CanvasImageSource const& image, float destination_x, float destination_y, float destination_width, float destination_height)
-{
- // If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's intrinsic width in image pixels, and the image's intrinsic height in image pixels, respectively.
- // If the image has no intrinsic dimensions, then the concrete object size must be used instead, as determined using the CSS "Concrete Object Size Resolution" algorithm, with the specified size having
- // neither a definite width nor height, nor any additional constraints, the object's intrinsic properties being those of the image argument, and the default object size being the size of the output bitmap.
- auto size = canvas_image_source_dimensions(image);
- return draw_image_internal(image, 0, 0, size.width(), size.height(), destination_x, destination_y, destination_width, destination_height);
-}
-
-WebIDL::ExceptionOr<void> CanvasDrawImage::draw_image(CanvasImageSource const& image, float source_x, float source_y, float source_width, float source_height, float destination_x, float destination_y, float destination_width, float destination_height)
-{
- return draw_image_internal(image, source_x, source_y, source_width, source_height, destination_x, destination_y, destination_width, destination_height);
+ // 2. Return good.
+ return { CanvasImageSourceUsability::Good };
}
}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.h b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.h
index 8a897abfc65..3a25d886c51 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.h
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.h
@@ -7,9 +7,6 @@
#pragma once
-#include <AK/Optional.h>
-#include <LibGfx/DecodedImageFrame.h>
-#include <LibGfx/Size.h>
#include <LibWeb/Forward.h>
#include <LibWeb/HTML/HTMLCanvasElement.h>
#include <LibWeb/HTML/HTMLImageElement.h>
@@ -24,22 +21,12 @@ namespace Web::HTML {
// NOTE: This is the Variant created by the IDL wrapper generator, and needs to be updated accordingly.
using CanvasImageSource = Variant<GC::Ref<HTMLImageElement>, GC::Ref<SVG::SVGImageElement>, GC::Ref<HTMLCanvasElement>, GC::Ref<ImageBitmap>, GC::Ref<OffscreenCanvas>, GC::Ref<HTMLVideoElement>>;
-Gfx::IntSize canvas_image_source_dimensions(CanvasImageSource const&);
-Optional<Gfx::DecodedImageFrame> canvas_image_source_frame(CanvasImageSource const&);
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasdrawimage
-class CanvasDrawImage {
-public:
- virtual ~CanvasDrawImage() = default;
-
- WebIDL::ExceptionOr<void> draw_image(CanvasImageSource const&, float destination_x, float destination_y);
- WebIDL::ExceptionOr<void> draw_image(CanvasImageSource const&, float destination_x, float destination_y, float destination_width, float destination_height);
- WebIDL::ExceptionOr<void> draw_image(CanvasImageSource const&, float source_x, float source_y, float source_width, float source_height, float destination_x, float destination_y, float destination_width, float destination_height);
-
- virtual WebIDL::ExceptionOr<void> draw_image_internal(CanvasImageSource const&, float source_x, float source_y, float source_width, float source_height, float destination_x, float destination_y, float destination_width, float destination_height) = 0;
-
-protected:
- CanvasDrawImage() = default;
+enum class CanvasImageSourceUsability {
+ Bad,
+ Good,
};
+// https://html.spec.whatwg.org/multipage/canvas.html#check-the-usability-of-the-image-argument
+WebIDL::ExceptionOr<CanvasImageSourceUsability> check_usability_of_image(CanvasImageSource const&);
+
}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.idl b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.idl
index e986fdc12a0..258813337bd 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.idl
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.idl
@@ -10,7 +10,7 @@ typedef (HTMLImageElement or
// https://html.spec.whatwg.org/multipage/canvas.html#canvasdrawimage
interface mixin CanvasDrawImage {
- undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy);
- undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
- undefined drawImage(CanvasImageSource image, unrestricted double sx, unrestricted double sy, unrestricted double sw, unrestricted double sh, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
+ [ImplementedAs=draw_image] undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy);
+ [ImplementedAs=draw_image_with_size] undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
+ [ImplementedAs=draw_image_with_source_rectangle] undefined drawImage(CanvasImageSource image, unrestricted double sx, unrestricted double sy, unrestricted double sw, unrestricted double sh, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
};
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawPath.h b/Libraries/LibWeb/HTML/Canvas/CanvasDrawPath.h
deleted file mode 100644
index e7fde171899..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawPath.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <LibWeb/Bindings/CanvasDrawPath.h>
-#include <LibWeb/HTML/Path2D.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasdrawpath
-class CanvasDrawPath {
-public:
- virtual ~CanvasDrawPath() = default;
-
- virtual void begin_path() = 0;
-
- virtual void fill(Bindings::CanvasFillRule) = 0;
- virtual void fill(Path2D& path, Bindings::CanvasFillRule) = 0;
-
- virtual void stroke() = 0;
- virtual void stroke(Path2D const& path) = 0;
-
- virtual void clip(Bindings::CanvasFillRule) = 0;
- virtual void clip(Path2D& path, Bindings::CanvasFillRule) = 0;
-
- virtual bool is_point_in_path(double x, double y, Bindings::CanvasFillRule) = 0;
- virtual bool is_point_in_path(Path2D const& path, double x, double y, Bindings::CanvasFillRule) = 0;
-
-protected:
- CanvasDrawPath() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawPath.idl b/Libraries/LibWeb/HTML/Canvas/CanvasDrawPath.idl
index 86923a7aa57..9eccb25f3c6 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawPath.idl
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawPath.idl
@@ -5,14 +5,14 @@ enum CanvasFillRule { "nonzero", "evenodd" };
interface mixin CanvasDrawPath {
// path API (see also CanvasPath)
undefined beginPath();
- undefined fill(optional CanvasFillRule fillRule = "nonzero");
- undefined fill(Path2D path, optional CanvasFillRule fillRule = "nonzero");
- undefined stroke();
- undefined stroke(Path2D path);
- undefined clip(optional CanvasFillRule fillRule = "nonzero");
- undefined clip(Path2D path, optional CanvasFillRule fillRule = "nonzero");
- boolean isPointInPath(unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
- boolean isPointInPath(Path2D path, unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
+ [ImplementedAs=fill] undefined fill(optional CanvasFillRule fillRule = "nonzero");
+ [ImplementedAs=fill_path2d] undefined fill(Path2D path, optional CanvasFillRule fillRule = "nonzero");
+ [ImplementedAs=stroke] undefined stroke();
+ [ImplementedAs=stroke_path2d] undefined stroke(Path2D path);
+ [ImplementedAs=clip] undefined clip(optional CanvasFillRule fillRule = "nonzero");
+ [ImplementedAs=clip_path2d] undefined clip(Path2D path, optional CanvasFillRule fillRule = "nonzero");
+ [ImplementedAs=is_point_in_path] boolean isPointInPath(unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
+ [ImplementedAs=is_point_in_path2d] boolean isPointInPath(Path2D path, unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
[FIXME] boolean isPointInStroke(unrestricted double x, unrestricted double y);
[FIXME] boolean isPointInStroke(Path2D path, unrestricted double x, unrestricted double y);
};
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.cpp
deleted file mode 100644
index d6012ef38ca..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.cpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (c) 2020-2022, Andreas Kling <[email protected]>
- * Copyright (c) 2021-2022, Linus Groh <[email protected]>
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- * Copyright (c) 2023, MacDue <[email protected]>
- * Copyright (c) 2025, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CanvasFillStrokeStyles.h"
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/PropertyID.h>
-#include <LibWeb/HTML/CanvasGradient.h>
-#include <LibWeb/HTML/CanvasPattern.h>
-#include <LibWeb/HTML/CanvasRenderingContext2D.h>
-#include <LibWeb/HTML/HTMLCanvasElement.h>
-#include <LibWeb/HTML/OffscreenCanvas.h>
-#include <LibWeb/HTML/OffscreenCanvasRenderingContext2D.h>
-
-namespace Web::HTML {
-
-void CanvasFillStrokeStyles::set_fill_style(FillOrStrokeStyleVariant style)
-{
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-fillstyle
- style.visit(
- // 1. If the given value is a string, then:
- [&](Utf16String const& string) {
- // 1. Let context be this's canvas attribute's value, if that is an element; otherwise null.
-
- // 2. Let parsedValue be the result of parsing the given value with context if non-null.
- auto parsed_value = parse_a_css_color_value(string);
-
- // 3. If parsedValue is failure, then return.
-
- if (!parsed_value.has_value())
- return;
-
- // 4. Set this's fill style to parsedValue.
- drawing_state().fill_style = parsed_value.value();
-
- // 5. Return.
- return;
- },
- [&](auto fill_or_stroke_style) {
- // FIXME: 2. If the given value is a CanvasPattern object that is marked as not origin-clean, then set this's origin-clean flag to false.
-
- // 3. Set this's fill style to the given value.
- drawing_state().fill_style = GC::Ref { *fill_or_stroke_style };
- });
-}
-
-CanvasFillStrokeStyles::FillOrStrokeStyleVariant CanvasFillStrokeStyles::fill_style() const
-{
- return drawing_state().fill_style.to_js_fill_or_stroke_style();
-}
-
-void CanvasFillStrokeStyles::set_stroke_style(FillOrStrokeStyleVariant style)
-{
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-strokestyle
-
- style.visit(
- // 1. If the given value is a string, then:
- [&](Utf16String const& string) {
- // 1. Let context be this's canvas attribute's value, if that is an element; otherwise null.
-
- // 2. Let parsedValue be the result of parsing the given value with context if non-null.
- auto parsed_value = parse_a_css_color_value(string);
-
- // 3. If parsedValue is failure, then return.
- if (!parsed_value.has_value())
- return;
-
- // 4. Set this's stroke style to parsedValue.
- drawing_state().stroke_style = parsed_value.value();
-
- // 5. Return.
- return;
- },
- [&](auto fill_or_stroke_style) {
- // FIXME: 2. If the given value is a CanvasPattern object that is marked as not origin-clean, then set this's origin-clean flag to false.
-
- // 3. Set this's stroke style to the given value.
- drawing_state().stroke_style = GC::Ref { *fill_or_stroke_style };
- });
-}
-
-CanvasFillStrokeStyles::FillOrStrokeStyleVariant CanvasFillStrokeStyles::stroke_style() const
-{
- return drawing_state().stroke_style.to_js_fill_or_stroke_style();
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createradialgradient
-WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> CanvasFillStrokeStyles::create_radial_gradient(double x0, double y0, double r0, double x1, double y1, double r1)
-{
- // If either of r0 or r1 are negative, then an "IndexSizeError" DOMException must be thrown.
- if (r0 < 0)
- return WebIDL::IndexSizeError::create("The r0 passed is less than 0"_utf16);
- if (r1 < 0)
- return WebIDL::IndexSizeError::create("The r1 passed is less than 0"_utf16);
-
- return CanvasGradient::create_radial(x0, y0, r0, x1, y1, r1);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createlineargradient
-WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> CanvasFillStrokeStyles::create_linear_gradient(double x0, double y0, double x1, double y1)
-{
- return CanvasGradient::create_linear(x0, y0, x1, y1);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createconicgradient
-WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> CanvasFillStrokeStyles::create_conic_gradient(double start_angle, double x, double y)
-{
- return CanvasGradient::create_conic(start_angle, x, y);
-}
-
-WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> CanvasFillStrokeStyles::create_pattern(CanvasImageSource const& image, Utf16FlyString const& repetition)
-{
- return CanvasPattern::create(image, repetition);
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h b/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h
deleted file mode 100644
index 40a07c04bc4..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2020-2022, Andreas Kling <[email protected]>
- * Copyright (c) 2021-2022, Linus Groh <[email protected]>
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- * Copyright (c) 2023, MacDue <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/Canvas/AbstractCanvasMixin.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasfillstrokestyles
-class CanvasFillStrokeStyles : protected virtual AbstractCanvasMixin {
-public:
- ~CanvasFillStrokeStyles() = default;
- using FillOrStrokeStyleVariant = Variant<Utf16String, GC::Ref<CanvasGradient>, GC::Ref<CanvasPattern>>;
-
- void set_fill_style(FillOrStrokeStyleVariant style);
- FillOrStrokeStyleVariant fill_style() const;
-
- void set_stroke_style(FillOrStrokeStyleVariant style);
- FillOrStrokeStyleVariant stroke_style() const;
-
- WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> create_radial_gradient(double x0, double y0, double r0, double x1, double y1, double r1);
- WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> create_linear_gradient(double x0, double y0, double x1, double y1);
- WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> create_conic_gradient(double start_angle, double x, double y);
- WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> create_pattern(CanvasImageSource const& image, Utf16FlyString const& repetition);
-
-protected:
- CanvasFillStrokeStyles() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasFilters.h b/Libraries/LibWeb/HTML/Canvas/CanvasFilters.h
deleted file mode 100644
index f0ce56634e6..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasFilters.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2024, Lucien Fiorini <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasfilters
-class CanvasFilters {
-public:
- ~CanvasFilters() = default;
-
- virtual Utf16String filter() const = 0;
- virtual void set_filter(Utf16View filter) = 0;
-
-protected:
- CanvasFilters() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasImageData.h b/Libraries/LibWeb/HTML/Canvas/CanvasImageData.h
deleted file mode 100644
index 8d4b33d8b45..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasImageData.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/HTML/ImageData.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasimagedata
-class CanvasImageData {
-public:
- virtual ~CanvasImageData() = default;
-
- virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(int width, int height, Optional<ImageData::Settings> const& settings = {}) const = 0;
- virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(ImageData const&) const = 0;
- virtual WebIDL::ExceptionOr<GC::Ptr<ImageData>> get_image_data(int x, int y, int width, int height, Optional<ImageData::Settings> const& settings = {}) = 0;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y) = 0;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y, int dirty_x, int dirty_y, int dirty_width, int dirty_height) = 0;
-
-protected:
- CanvasImageData() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasImageData.idl b/Libraries/LibWeb/HTML/Canvas/CanvasImageData.idl
index b36409c8213..d917b391b3a 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasImageData.idl
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasImageData.idl
@@ -1,10 +1,10 @@
// https://html.spec.whatwg.org/multipage/canvas.html#canvasimagedata
interface mixin CanvasImageData {
- ImageData createImageData([EnforceRange] long sw, [EnforceRange] long sh, optional ImageDataSettings settings = {});
- ImageData createImageData(ImageData imageData);
+ [ImplementedAs=create_image_data] ImageData createImageData([EnforceRange] long sw, [EnforceRange] long sh, optional ImageDataSettings settings = {});
+ [ImplementedAs=create_image_data_from] ImageData createImageData(ImageData imageData);
ImageData getImageData([EnforceRange] long sx, [EnforceRange] long sy, [EnforceRange] long sw, [EnforceRange] long sh, optional ImageDataSettings settings = {});
- undefined putImageData(ImageData imageData, [EnforceRange] long dx, [EnforceRange] long dy);
- undefined putImageData(ImageData imageData, [EnforceRange] long dx, [EnforceRange] long dy, [EnforceRange] long dirtyX, [EnforceRange] long dirtyY, [EnforceRange] long dirtyWidth, [EnforceRange] long dirtyHeight);
+ [ImplementedAs=put_image_data] undefined putImageData(ImageData imageData, [EnforceRange] long dx, [EnforceRange] long dy);
+ [ImplementedAs=put_image_data_with_dirty_rectangle] undefined putImageData(ImageData imageData, [EnforceRange] long dx, [EnforceRange] long dy, [EnforceRange] long dirtyX, [EnforceRange] long dirtyY, [EnforceRange] long dirtyWidth, [EnforceRange] long dirtyHeight);
};
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasImageSmoothing.h b/Libraries/LibWeb/HTML/Canvas/CanvasImageSmoothing.h
deleted file mode 100644
index e8664cba7ed..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasImageSmoothing.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2023, Andreas Kling <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/ImageData.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasimagesmoothing
-class CanvasImageSmoothing {
-public:
- virtual ~CanvasImageSmoothing() = default;
-
- virtual bool image_smoothing_enabled() const = 0;
- virtual void set_image_smoothing_enabled(bool) = 0;
- virtual ImageSmoothingQuality image_smoothing_quality() const = 0;
- virtual void set_image_smoothing_quality(ImageSmoothingQuality) = 0;
-
-protected:
- CanvasImageSmoothing() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasPath.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasPath.cpp
deleted file mode 100644
index fcdbfc738ca..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasPath.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (c) 2020-2022, Andreas Kling <[email protected]>
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/HTML/Canvas/CanvasPath.h>
-
-namespace Web::HTML {
-
-namespace {
-
-// `CanvasPathResultKind` and `CanvasPathResult` of Bindings/Rust/src/html/exports.rs.
-enum class CanvasPathResultKind : u8 {
- Ok,
- IndexSizeError,
- RangeError,
-};
-
-struct CanvasPathResult {
- CanvasPathResultKind kind;
- // An AK::Utf16String that the caller takes over, unless the kind is Ok.
- FlatPtr message;
-};
-
-}
-
-// NB: `RoundRectRadius` of Bindings/Rust/src/html/canvas_path.rs is two doubles in this order.
-static_assert(sizeof(CanvasRoundRectRadius) == 2 * sizeof(double));
-static_assert(offsetof(CanvasRoundRectRadius, y) == sizeof(double));
-
-// Defined in Bindings/Rust/src/html/exports.rs. The path is lent mutably for the call.
-extern "C" {
-void web_canvas_path_close_path(Gfx::Path*);
-void web_canvas_path_move_to(Gfx::Path*, float x, float y);
-void web_canvas_path_line_to(Gfx::Path*, float x, float y);
-void web_canvas_path_quadratic_curve_to(Gfx::Path*, float cpx, float cpy, float x, float y);
-void web_canvas_path_bezier_curve_to(Gfx::Path*, double cp1x, double cp1y, double cp2x, double cp2y, double x, double y);
-CanvasPathResult web_canvas_path_arc_to(Gfx::Path*, Gfx::AffineTransform const*, double x1, double y1, double x2, double y2, double radius);
-void web_canvas_path_rect(Gfx::Path*, double x, double y, double w, double h);
-CanvasPathResult web_canvas_path_round_rect(Gfx::Path*, double x, double y, double w, double h, ReadonlySpan<CanvasRoundRectRadius> radii);
-CanvasPathResult web_canvas_path_arc(Gfx::Path*, float x, float y, float radius, float start_angle, float end_angle, bool counter_clockwise);
-CanvasPathResult web_canvas_path_ellipse(Gfx::Path*, float x, float y, float radius_x, float radius_y, float rotation, float start_angle, float end_angle, bool counter_clockwise);
-}
-
-static WebIDL::ExceptionOr<void> to_exception_or(CanvasPathResult result)
-{
- switch (result.kind) {
- case CanvasPathResultKind::Ok:
- return {};
- case CanvasPathResultKind::IndexSizeError:
- return WebIDL::IndexSizeError::create(Utf16String::adopt_raw(result.message));
- case CanvasPathResultKind::RangeError:
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, Utf16String::adopt_raw(result.message) };
- }
- VERIFY_NOT_REACHED();
-}
-
-Gfx::AffineTransform CanvasPath::active_transform() const
-{
- if (m_canvas_state.has_value())
- return m_canvas_state->drawing_state().transform;
- return {};
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-closepath
-void CanvasPath::close_path()
-{
- web_canvas_path_close_path(&m_path);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-moveto
-void CanvasPath::move_to(float x, float y)
-{
- web_canvas_path_move_to(&m_path, x, y);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-lineto
-void CanvasPath::line_to(float x, float y)
-{
- web_canvas_path_line_to(&m_path, x, y);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-quadraticcurveto
-void CanvasPath::quadratic_curve_to(float cpx, float cpy, float x, float y)
-{
- web_canvas_path_quadratic_curve_to(&m_path, cpx, cpy, x, y);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-beziercurveto
-void CanvasPath::bezier_curve_to(double cp1x, double cp1y, double cp2x, double cp2y, double x, double y)
-{
- web_canvas_path_bezier_curve_to(&m_path, cp1x, cp1y, cp2x, cp2y, x, y);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-arc
-WebIDL::ExceptionOr<void> CanvasPath::arc(float x, float y, float radius, float start_angle, float end_angle, bool counter_clockwise)
-{
- return to_exception_or(web_canvas_path_arc(&m_path, x, y, radius, start_angle, end_angle, counter_clockwise));
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-ellipse
-WebIDL::ExceptionOr<void> CanvasPath::ellipse(float x, float y, float radius_x, float radius_y, float rotation, float start_angle, float end_angle, bool counter_clockwise)
-{
- return to_exception_or(web_canvas_path_ellipse(&m_path, x, y, radius_x, radius_y, rotation, start_angle, end_angle, counter_clockwise));
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-arcto
-WebIDL::ExceptionOr<void> CanvasPath::arc_to(double x1, double y1, double x2, double y2, double radius)
-{
- auto transform = active_transform();
- return to_exception_or(web_canvas_path_arc_to(&m_path, &transform, x1, y1, x2, y2, radius));
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-rect
-void CanvasPath::rect(double x, double y, double w, double h)
-{
- web_canvas_path_rect(&m_path, x, y, w, h);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-roundrect
-WebIDL::ExceptionOr<void> CanvasPath::round_rect(double x, double y, double w, double h, Variant<double, Bindings::DOMPointInit, Vector<Variant<double, Bindings::DOMPointInit>>> const& radii)
-{
- auto append_radius = [](Vector<CanvasRoundRectRadius>& radius_list, Variant<double, Bindings::DOMPointInit> const& radius) {
- if (radius.has<double>()) {
- auto radius_as_double = radius.get<double>();
- radius_list.append({ radius_as_double, radius_as_double });
- return;
- }
-
- auto const& radius_as_dom_point = radius.get<Bindings::DOMPointInit>();
- radius_list.append({ radius_as_dom_point.x, radius_as_dom_point.y });
- };
-
- Vector<CanvasRoundRectRadius> radius_list;
- if (radii.has<double>()) {
- auto radius = radii.get<double>();
- radius_list.append({ radius, radius });
- } else if (radii.has<Bindings::DOMPointInit>()) {
- auto const& radius = radii.get<Bindings::DOMPointInit>();
- radius_list.append({ radius.x, radius.y });
- } else {
- for (auto const& radius : radii.get<Vector<Variant<double, Bindings::DOMPointInit>>>())
- append_radius(radius_list, radius);
- }
-
- return round_rect(x, y, w, h, radius_list);
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-roundrect
-WebIDL::ExceptionOr<void> CanvasPath::round_rect(double x, double y, double w, double h, ReadonlySpan<CanvasRoundRectRadius> radii)
-{
- return to_exception_or(web_canvas_path_round_rect(&m_path, x, y, w, h, radii));
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasPath.h b/Libraries/LibWeb/HTML/Canvas/CanvasPath.h
deleted file mode 100644
index ac9a714f314..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasPath.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Span.h>
-#include <AK/Variant.h>
-#include <AK/Vector.h>
-#include <LibGfx/Path.h>
-#include <LibWeb/Bindings/DOMPointReadOnly.h>
-#include <LibWeb/Geometry/DOMPointReadOnly.h>
-#include <LibWeb/HTML/Canvas/CanvasState.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::HTML {
-
-// A radius of roundRect(), which `RoundRectRadius` of Bindings/Rust/src/html/canvas_path.rs mirrors.
-struct CanvasRoundRectRadius {
- double x { 0 };
- double y { 0 };
-};
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvaspath
-// The path of a 2D context, which the operations of the mixin in Bindings/Rust/src/html/canvas_path.rs build on.
-class CanvasPath {
-public:
- virtual ~CanvasPath() = default;
-
- void close_path();
-
- void move_to(float x, float y);
- void line_to(float x, float y);
- void quadratic_curve_to(float cx, float cy, float x, float y);
- void bezier_curve_to(double cp1x, double cp1y, double cp2x, double cp2y, double x, double y);
- WebIDL::ExceptionOr<void> arc_to(double x1, double y1, double x2, double y2, double radius);
- void rect(double x, double y, double w, double h);
- WebIDL::ExceptionOr<void> round_rect(double x, double y, double w, double h, Variant<double, Bindings::DOMPointInit, Vector<Variant<double, Bindings::DOMPointInit>>> const& radii);
- WebIDL::ExceptionOr<void> round_rect(double x, double y, double w, double h, ReadonlySpan<CanvasRoundRectRadius> radii);
- WebIDL::ExceptionOr<void> arc(float x, float y, float radius, float start_angle, float end_angle, bool counter_clockwise);
- WebIDL::ExceptionOr<void> ellipse(float x, float y, float radius_x, float radius_y, float rotation, float start_angle, float end_angle, bool counter_clockwise);
-
- Gfx::Path& path() { return m_path; }
- Gfx::Path const& path() const { return m_path; }
-
-protected:
- CanvasPath() = default;
-
- explicit CanvasPath(CanvasState const& canvas_state)
- : m_canvas_state(canvas_state)
- {
- }
-
-private:
- Gfx::AffineTransform active_transform() const;
-
- Optional<CanvasState const&> m_canvas_state;
- Gfx::Path m_path;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasPathDrawingStyles.h b/Libraries/LibWeb/HTML/Canvas/CanvasPathDrawingStyles.h
deleted file mode 100644
index 953dde6096b..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasPathDrawingStyles.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/Canvas/AbstractCanvasMixin.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvaspathdrawingstyles
-class CanvasPathDrawingStyles : protected virtual AbstractCanvasMixin {
-public:
- ~CanvasPathDrawingStyles() = default;
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linewidth
- void set_line_width(float line_width)
- {
- // On setting, zero, negative, infinite, and NaN values must be ignored, leaving the value unchanged;
- if (line_width <= 0 || !isfinite(line_width))
- return;
- // other values must change the current value to the new value.
- drawing_state().line_width = line_width;
- }
- float line_width() const
- {
- // On getting, it must return the current value.
- return drawing_state().line_width;
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linecap
- void set_line_cap(CanvasLineCap line_cap)
- {
- // On setting, the current value must be changed to the new value.
- drawing_state().line_cap = line_cap;
- }
- CanvasLineCap line_cap() const
- {
- // On getting, it must return the current value.
- return drawing_state().line_cap;
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linejoin
- void set_line_join(CanvasLineJoin line_join)
- {
- // On setting, the current value must be changed to the new value.
- drawing_state().line_join = line_join;
- }
- CanvasLineJoin line_join() const
- {
- // On getting, it must return the current value.
- return drawing_state().line_join;
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-miterlimit
- void set_miter_limit(float miter_limit)
- {
- // On setting, zero, negative, infinite, and NaN values must be ignored, leaving the value unchanged;
- if (miter_limit <= 0 || !isfinite(miter_limit))
- return;
- // other values must change the current value to the new value.
- drawing_state().miter_limit = miter_limit;
- }
- float miter_limit() const
- {
- // On getting, it must return the current value.
- return drawing_state().miter_limit;
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-setlinedash
- void set_line_dash(Vector<double> segments)
- {
- // The setLineDash(segments) method, when invoked, must run these steps:
-
- // 1. If any value in segments is not finite (e.g. an Infinity or a NaN value), or if any value is negative (less than zero), then return
- // (without throwing an exception; user agents could show a message on a developer console, though, as that would be helpful for debugging).
- for (auto const& segment : segments) {
- if (!isfinite(segment) || segment < 0)
- return;
- }
-
- // 2. If the number of elements in segments is odd, then let segments be the concatenation of two copies of segments.
- if (segments.size() % 2 == 1)
- segments.extend(segments);
-
- // 3. Set the object's dash list to segments.
- drawing_state().dash_list = move(segments);
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-getlinedash
- Vector<double> get_line_dash()
- {
- // When the getLineDash() method is invoked, it must return a sequence whose values are the values of the object's dash list, in the same order.
- return drawing_state().dash_list;
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-linedashoffset
- void set_line_dash_offset(float line_dash_offset)
- {
- // On setting, infinite and NaN values must be ignored, leaving the value unchanged;
- if (!isfinite(line_dash_offset))
- return;
- // other values must change the current value to the new value.
- drawing_state().line_dash_offset = line_dash_offset;
- }
- float line_dash_offset() const
- {
- // On getting, it must return the current value.
- return drawing_state().line_dash_offset;
- }
-
-protected:
- CanvasPathDrawingStyles() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasRect.h b/Libraries/LibWeb/HTML/Canvas/CanvasRect.h
deleted file mode 100644
index 4ff12891c83..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasRect.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasrect
-class CanvasRect {
-public:
- virtual ~CanvasRect() = default;
-
- virtual void fill_rect(float x, float y, float width, float height) = 0;
- virtual void stroke_rect(float x, float y, float width, float height) = 0;
- virtual void clear_rect(float x, float y, float width, float height) = 0;
-
-protected:
- CanvasRect() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasSettings.h b/Libraries/LibWeb/HTML/Canvas/CanvasSettings.h
index f83bd53a717..04840547418 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasSettings.h
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasSettings.h
@@ -6,22 +6,10 @@
#pragma once
-#include <AK/Types.h>
#include <LibWeb/Bindings/CanvasRenderingContext2DSettings.h>
namespace Web::HTML {
using CanvasRenderingContext2DSettings = Bindings::CanvasRenderingContext2DSettings;
-// https://html.spec.whatwg.org/multipage/canvas.html#canvassettings
-class CanvasSettings {
-public:
- virtual ~CanvasSettings() = default;
-
- virtual CanvasRenderingContext2DSettings get_context_attributes() const = 0;
-
-protected:
- CanvasSettings() = default;
-};
-
}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.h b/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.h
deleted file mode 100644
index c9570976a93..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasShadowStyles.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2024, İbrahim UYSAL <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <LibWeb/HTML/Canvas/CanvasState.h>
-#include <LibWeb/HTML/CanvasGradient.h>
-#include <LibWeb/HTML/CanvasPattern.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasshadowstyles
-class CanvasShadowStyles {
-public:
- ~CanvasShadowStyles() = default;
-
- virtual float shadow_offset_x() const = 0;
- virtual void set_shadow_offset_x(float offsetX) = 0;
-
- virtual float shadow_offset_y() const = 0;
- virtual void set_shadow_offset_y(float offsetY) = 0;
-
- virtual float shadow_blur() const = 0;
- virtual void set_shadow_blur(float offsetY) = 0;
-
- virtual Utf16String shadow_color() const = 0;
- virtual void set_shadow_color(Utf16View color) = 0;
-
-protected:
- CanvasShadowStyles() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasState.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasState.cpp
deleted file mode 100644
index 47b1fe9d0c3..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasState.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2021-2022, Linus Groh <[email protected]>
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- * Copyright (c) 2023, MacDue <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/CSS/ComputedValues.h>
-#include <LibWeb/CSS/PropertyID.h>
-#include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
-#include <LibWeb/HTML/Canvas/CanvasState.h>
-#include <LibWeb/HTML/LocalNavigable.h>
-#include <LibWeb/Platform/FontPlugin.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-save
-void CanvasState::save()
-{
- // The save() method steps are to push a copy of the current drawing state onto the drawing state stack.
- m_drawing_state_stack.append(m_drawing_state);
-
- if (auto* recorder = canvas_recorder())
- recorder->save();
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-restore
-void CanvasState::restore()
-{
- // 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.
- if (m_drawing_state_stack.is_empty())
- return;
- m_drawing_state = m_drawing_state_stack.take_last();
-
- if (auto* recorder = canvas_recorder())
- recorder->restore();
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-reset
-void CanvasState::reset()
-{
- // The reset() method steps are to reset the rendering context to its default state.
- reset_to_default_state();
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-iscontextlost
-bool CanvasState::is_context_lost()
-{
- // The isContextLost() method steps are to return this's context lost.
- return m_context_lost;
-}
-
-CSS::ComputationContext CanvasState::computation_context_for_drawing_state() const
-{
- auto font_metrics = [&]() {
- // https://html.spec.whatwg.org/multipage/canvas.html#text-styles
- // NB: We lazily initialize the font, so if it hasn't been set yet we generate the font metrics based on the default font
- if (!m_drawing_state.font_style_value) {
- // When the object implementing the CanvasTextDrawingStyles interface is created, the font of the context must be set to 10px sans-serif.
- return CSS::Length::FontMetrics { 10, Platform::FontPlugin::the().default_font(8)->pixel_metrics(), CSS::InitialValues::line_height() };
- }
-
- VERIFY(m_drawing_state.current_font_cascade_list);
- auto const& first_font = m_drawing_state.current_font_cascade_list->first_available_font();
- auto font_size_value = m_drawing_state.font_style_value->as_shorthand().longhand(CSS::PropertyID::FontSize);
- auto font_size = font_size_value->as_length().length().absolute_length_to_px();
-
- return CSS::Length::FontMetrics { font_size, first_font.pixel_metrics(), CSS::InitialValues::line_height() };
- }();
-
- return {
- .length_resolution_context = {
- .viewport_rect = canvas_host().canvas_viewport_rect(),
- .font_metrics = font_metrics,
- .root_font_metrics = font_metrics },
-
- // NB: We don't require an abstract element because tree counting and random() functions aren't allowed in
- // non-font canvas context values
- .abstract_element = {},
-
- // FIXME: The spec doesn't specify what color scheme should be used here but other browsers always use light so
- // we do too for compatibility. See https://github.com/whatwg/html/issues/12505
- .color_scheme = CSS::PreferredColorScheme::Light
- };
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasState.h b/Libraries/LibWeb/HTML/Canvas/CanvasState.h
deleted file mode 100644
index a91429f1f0c..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasState.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- * Copyright (c) 2023, MacDue <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/HTML/Canvas/AbstractCanvasMixin.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasstate
-class CanvasState : protected virtual AbstractCanvasMixin {
-public:
- virtual ~CanvasState() = default;
-
- void save();
- void restore();
- void reset();
- bool is_context_lost();
-
- DrawingState& drawing_state() override { return m_drawing_state; }
- DrawingState const& drawing_state() const override { return m_drawing_state; }
-
- CSS::ComputationContext computation_context_for_drawing_state() const override;
-
- void clear_drawing_state_stack() { m_drawing_state_stack.clear(); }
- void reset_drawing_state() { m_drawing_state = {}; }
-
- virtual void reset_to_default_state() = 0;
-
- void visit_edges(GC::Cell::Visitor& visitor)
- {
- m_drawing_state.visit_edges(visitor);
- for (auto& state : m_drawing_state_stack) {
- state.visit_edges(visitor);
- }
- }
-
-protected:
- CanvasState() = default;
-
- void set_context_lost(bool context_lost) { m_context_lost = context_lost; }
-
-private:
- DrawingState m_drawing_state;
- Vector<DrawingState> m_drawing_state_stack;
-
- // https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-context-lost
- bool m_context_lost { false };
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasText.h b/Libraries/LibWeb/HTML/Canvas/CanvasText.h
deleted file mode 100644
index 2f1ee9d44ec..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasText.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Utf16View.h>
-#include <LibWeb/HTML/TextMetrics.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvastext
-class CanvasText {
-public:
- virtual ~CanvasText() = default;
-
- virtual void fill_text(Utf16View, float x, float y, Optional<double> max_width) = 0;
- virtual void stroke_text(Utf16View, float x, float y, Optional<double> max_width) = 0;
- virtual GC::Ref<TextMetrics> measure_text(Utf16View) = 0;
-
-protected:
- CanvasText() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.cpp
deleted file mode 100644
index df6c74b17a1..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.cpp
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Copyright (c) 2023, Bastiaan van der Plaat <[email protected]>
- * Copyright (c) 2023, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CanvasTextDrawingStyles.h"
-#include <LibWeb/CSS/ComputedValues.h>
-#include <LibWeb/CSS/FontComputer.h>
-#include <LibWeb/CSS/FontResolution.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/PropertyID.h>
-#include <LibWeb/CSS/StyleComputer.h>
-#include <LibWeb/CSS/StyleValues/FontStyleStyleValue.h>
-#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
-#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
-#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
-#include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/CanvasRenderingContext2D.h>
-#include <LibWeb/HTML/OffscreenCanvas.h>
-#include <LibWeb/HTML/OffscreenCanvasRenderingContext2D.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-
-namespace Web::HTML {
-
-template<typename CanvasType>
-Utf16String CanvasTextDrawingStyles<CanvasType>::font() const
-{
- // When font style value is empty return default string
- if (!drawing_state().font_style_value) {
- return "10px sans-serif"_utf16;
- }
-
- // On getting, the font attribute must return the serialized form of the current font of the context (with no 'line-height' component).
- return drawing_state().font_style_value->to_utf16_string(CSS::SerializationMode::ResolvedValue);
-}
-
-template<typename CanvasType>
-void CanvasTextDrawingStyles<CanvasType>::set_font(Utf16View font)
-{
- // The font IDL attribute, on setting, must be parsed as a CSS <'font'> value (but without supporting property-independent style sheet syntax like 'inherit'),
- // and the resulting font must be assigned to the context, with the 'line-height' component forced to 'normal', with the 'font-size' component converted to CSS pixels,
- // and with system fonts being computed to explicit values.
-
- auto const parsing_context = [&]() {
- if constexpr (SameAs<CanvasType, HTML::HTMLCanvasElement>)
- return CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::OnScreenCanvasContextFontValue };
- return CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue };
- }();
-
- auto font_style_value_result = parse_css_value(parsing_context, font, CSS::PropertyID::Font);
-
- // If the new value is syntactically incorrect (including using property-independent style sheet syntax like 'inherit' or 'initial'), then it must be ignored, without assigning a new font value.
- // NOTE: ShorthandStyleValue should be the only valid option here. We implicitly VERIFY this below.
- if (!font_style_value_result || !font_style_value_result->is_shorthand()) {
- return;
- }
-
- // Load font with font style value properties
- auto const& font_style_value = font_style_value_result->as_shorthand();
- auto& canvas_element = static_cast<CanvasType&>(this->canvas_host());
-
- auto computed_math_depth = CSS::InitialValues::math_depth();
-
- // FIXME: We will need to absolutize this once we support ident() functions
- auto font_family = font_style_value.longhand(CSS::PropertyID::FontFamily);
-
- Optional<DOM::AbstractElement> inheritance_parent;
-
- if constexpr (SameAs<CanvasType, HTML::HTMLCanvasElement>) {
- // NB: Once pending style work is settled, the canvas's installed style is current, unless it is below
- // display:none, where style updates leave it stale. Only then is its style computed again.
- auto& document = canvas_element.document();
- Layout::ForcedReadScope read { document };
- document.update_style_for_element(DOM::AbstractElement { canvas_element }, DOM::Document::StyleUpdateMode::OnlyIfNeeded);
- auto style_record = canvas_element.style_record_identity();
- if (!style_record || has_flag(document.style_computer().style_engine().style_record_dependency_flags(read, style_record), CSS::StyleRecordDependencyFlag::InDisplayNoneSubtree))
- document.update_style_for_element(DOM::AbstractElement { canvas_element });
-
- if (canvas_element.navigable() && canvas_element.is_connected()) {
- // NOTE: Since we can't set a math depth directly here we always use the inherited value for the computed value
- computed_math_depth = canvas_element.template style_group<CSS::ComputedValues::FontValues>()->math_depth;
-
- // NOTE: The canvas itself is considered the inheritance parent
- inheritance_parent = canvas_element;
- }
- }
-
- auto computation_context = canvas_element.canvas_font_computation_context();
-
- auto const& computed_font_size = CSS::StyleComputer::compute_font_size(font_style_value.longhand(CSS::PropertyID::FontSize)->absolutized(computation_context), computed_math_depth, inheritance_parent, CSSPixels { 10 });
- auto const& computed_font_style = CSS::StyleComputer::compute_font_style(font_style_value.longhand(CSS::PropertyID::FontStyle)->absolutized(computation_context));
- auto const& computed_font_weight = CSS::StyleComputer::compute_font_weight(font_style_value.longhand(CSS::PropertyID::FontWeight)->absolutized(computation_context), inheritance_parent);
- auto const& computed_font_width = CSS::StyleComputer::compute_font_width(font_style_value.longhand(CSS::PropertyID::FontWidth)->absolutized(computation_context));
- // NB: This doesn't require absolutization since only the font-variant-caps longhand can be set and that can only be
- // a keyword value
- auto const& computed_font_variant = font_style_value.longhand(CSS::PropertyID::FontVariant).release_nonnull();
-
- drawing_state().font_style_value = CSS::ShorthandStyleValue::create(
- CSS::PropertyID::Font,
- {
- // Set explicitly https://drafts.csswg.org/css-fonts/#set-explicitly
- CSS::PropertyID::FontFamily,
- CSS::PropertyID::FontSize,
- CSS::PropertyID::FontWidth,
- CSS::PropertyID::FontStyle,
- CSS::PropertyID::FontVariant,
- CSS::PropertyID::FontWeight,
- CSS::PropertyID::LineHeight,
-
- // Reset implicitly https://drafts.csswg.org/css-fonts/#reset-implicitly
- CSS::PropertyID::FontFeatureSettings,
- CSS::PropertyID::FontKerning,
- CSS::PropertyID::FontLanguageOverride,
- CSS::PropertyID::FontOpticalSizing,
- // FIXME: PropertyID::FontSizeAdjust,
- CSS::PropertyID::FontVariationSettings,
- },
- {
- // Set explicitly
- *font_family,
- computed_font_size,
- computed_font_width,
- computed_font_style,
- computed_font_variant,
- computed_font_weight,
- property_initial_value(CSS::PropertyID::LineHeight), // NB: line-height is forced to normal (i.e. the initial value)
-
- // Reset implicitly
- property_initial_value(CSS::PropertyID::FontFeatureSettings), // font-feature-settings
- property_initial_value(CSS::PropertyID::FontKerning), // font-kerning,
- property_initial_value(CSS::PropertyID::FontLanguageOverride), // font-language-override
- property_initial_value(CSS::PropertyID::FontOpticalSizing), // font-optical-sizing,
- // FIXME: font-size-adjust,
- property_initial_value(CSS::PropertyID::FontVariationSettings), // font-variation-settings
- });
-
- CSS::FontResolutionFeatureValues feature_values;
- if (auto caps = computed_font_variant->as_shorthand().longhand(CSS::PropertyID::FontVariantCaps); caps->to_keyword() == CSS::Keyword::SmallCaps)
- feature_values[to_underlying(CSS::FontResolutionFeatureInput::FontVariantCaps)] = caps;
-
- // https://drafts.csswg.org/css-font-loading/#font-source
- auto& font_computer = canvas_element.canvas_font_computer();
-
- drawing_state().font_environment_generation = font_computer.environment_generation();
- drawing_state().current_font_cascade_list = CSS::resolve_font_for_style_values(font_computer,
- {
- .font_families = CSS::computed_font_families_from_style_value(*font_family),
- .font_optical_sizing = CSS::FontOpticalSizing::Auto,
- .font_size = computed_font_size->as_length().length().absolute_length_to_px(),
- .font_slope = computed_font_style->as_font_style().to_font_slope(),
- .font_weight = computed_font_weight->as_number().number(),
- .font_width = computed_font_width->as_percentage().percentage(),
- .feature_values = move(feature_values),
- .font_feature_values_scope = {},
- });
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-letterspacing
-template<typename CanvasType>
-Utf16String CanvasTextDrawingStyles<CanvasType>::letter_spacing() const
-{
- // The letterSpacing getter steps are to return the serialized form of this's letter spacing.
- Utf16StringBuilder builder;
- drawing_state().letter_spacing->serialize(builder, CSS::SerializationMode::Normal);
- return builder.to_string();
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-letterspacing
-template<typename CanvasType>
-void CanvasTextDrawingStyles<CanvasType>::set_letter_spacing(Utf16View letter_spacing)
-{
- // 1. Let parsed be the result of parsing the given value as a CSS <length>.
- auto parsed = parse_css_type(CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue }, letter_spacing, CSS::ValueType::Length);
-
- // 2. If parsed is failure, then return.
- if (!parsed)
- return;
-
- // 3. Set this's letter spacing to parsed.
- drawing_state().letter_spacing = parsed.release_nonnull();
-}
-
-template<typename CanvasType>
-float CanvasTextDrawingStyles<CanvasType>::resolved_letter_spacing() const
-{
- auto absolutized_length = CSS::Length::from_style_value(drawing_state().letter_spacing->absolutized(computation_context_for_drawing_state()), {});
-
- return static_cast<float>(absolutized_length.absolute_length_to_px().to_double());
-}
-
-template class CanvasTextDrawingStyles<HTMLCanvasElement>;
-template class CanvasTextDrawingStyles<HTML::OffscreenCanvas>;
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h b/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h
deleted file mode 100644
index 3621336ffb9..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2023, Bastiaan van der Plaat <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/Canvas/AbstractCanvasMixin.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvastextdrawingstyles
-template<typename CanvasType>
-class CanvasTextDrawingStyles : protected virtual AbstractCanvasMixin {
-public:
- ~CanvasTextDrawingStyles() = default;
- Utf16String font() const;
- void set_font(Utf16View font) override;
-
- CanvasTextAlign text_align() const { return drawing_state().text_align; }
- void set_text_align(CanvasTextAlign text_align) { drawing_state().text_align = text_align; }
-
- CanvasTextBaseline text_baseline() const { return drawing_state().text_baseline; }
- void set_text_baseline(CanvasTextBaseline text_baseline) { drawing_state().text_baseline = text_baseline; }
-
- CanvasDirection direction() const { return drawing_state().direction; }
- void set_direction(CanvasDirection direction) { drawing_state().direction = direction; }
-
- Utf16String letter_spacing() const;
- void set_letter_spacing(Utf16View);
- float resolved_letter_spacing() const override;
-
-protected:
- CanvasTextDrawingStyles() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasTransform.h b/Libraries/LibWeb/HTML/Canvas/CanvasTransform.h
deleted file mode 100644
index 2c082c647f7..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/CanvasTransform.h
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright (c) 2020-2022, Andreas Kling <[email protected]>
- * Copyright (c) 2021-2022, Linus Groh <[email protected]>
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Debug.h>
-#include <LibGfx/AffineTransform.h>
-#include <LibGfx/Path.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/HTML/Canvas/AbstractCanvasMixin.h>
-
-namespace Web::Bindings {
-
-struct DOMMatrix2DInit;
-
-}
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvastransform
-class CanvasTransform : protected virtual AbstractCanvasMixin {
-public:
- ~CanvasTransform() = default;
-
- void scale(float sx, float sy)
- {
- dbgln_if(CANVAS_RENDERING_CONTEXT_2D_DEBUG, "CanvasTransform::scale({}, {})", sx, sy);
- if (!isfinite(sx) || !isfinite(sy))
- return;
- drawing_state().transform.scale(sx, sy);
- flush_transform();
- mutable_path().transform(Gfx::AffineTransform().scale(1.0 / sx, 1.0 / sy));
- }
-
- void translate(float tx, float ty)
- {
- dbgln_if(CANVAS_RENDERING_CONTEXT_2D_DEBUG, "CanvasTransform::translate({}, {})", tx, ty);
- if (!isfinite(tx) || !isfinite(ty))
- return;
- drawing_state().transform.translate(tx, ty);
- flush_transform();
- mutable_path().transform(Gfx::AffineTransform().translate(-tx, -ty));
- }
-
- void rotate(float radians)
- {
- dbgln_if(CANVAS_RENDERING_CONTEXT_2D_DEBUG, "CanvasTransform::rotate({})", radians);
- if (!isfinite(radians))
- return;
- drawing_state().transform.rotate_radians(radians);
- flush_transform();
- mutable_path().transform(Gfx::AffineTransform().rotate_radians(-radians));
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-transform
- void transform(double a, double b, double c, double d, double e, double f)
- {
- // 1. If any of the arguments are infinite or NaN, then return.
- if (!isfinite(a) || !isfinite(b) || !isfinite(c) || !isfinite(d) || !isfinite(e) || !isfinite(f))
- return;
-
- // 2. Replace the current transformation matrix with the result of multiplying the current transformation matrix with the matrix described by:
- // a c e
- // b d f
- // 0 0 1
- auto transform = Gfx::AffineTransform(a, b, c, d, e, f);
- drawing_state().transform.multiply(transform);
-
- if (auto inverse = transform.inverse(); inverse.has_value()) {
- mutable_path().transform(inverse.value());
- }
- flush_transform();
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-gettransform
- WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> get_transform()
- {
- auto transform = drawing_state().transform;
- Geometry::DOMMatrix2DInit init = { transform.a(), transform.b(), transform.c(), transform.d(), transform.e(), transform.f() };
- return Geometry::DOMMatrix::create_from_dom_matrix_2d_init(init);
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-settransform
- void set_transform(double a, double b, double c, double d, double e, double f)
- {
- // 1. If any of the arguments are infinite or NaN, then return.
- if (!isfinite(a) || !isfinite(b) || !isfinite(c) || !isfinite(d) || !isfinite(e) || !isfinite(f))
- return;
-
- // 2. Reset the current transformation matrix to the identity matrix.
- drawing_state().transform = {};
- flush_transform();
-
- // 3. Invoke the transform(a, b, c, d, e, f) method with the same arguments.
- transform(a, b, c, d, e, f);
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-settransform-matrix
- WebIDL::ExceptionOr<void> set_transform(Geometry::DOMMatrix2DInit const& init)
- {
- // 1. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.
- auto matrix = Geometry::DOMMatrix::create_from_dom_matrix_2d_init(init);
-
- // 2. If one or more of matrix's m11 element, m12 element, m21 element, m22 element, m41 element, or m42 element are infinite or NaN, then return.
- if (!isfinite(matrix->m11()) || !isfinite(matrix->m12()) || !isfinite(matrix->m21()) || !isfinite(matrix->m22()) || !isfinite(matrix->m41()) || !isfinite(matrix->m42()))
- return {};
-
- auto original_transform = drawing_state().transform;
-
- // 3. Reset the current transformation matrix to matrix.
- auto transform = Gfx::AffineTransform { static_cast<float>(matrix->a()), static_cast<float>(matrix->b()), static_cast<float>(matrix->c()), static_cast<float>(matrix->d()), static_cast<float>(matrix->e()), static_cast<float>(matrix->f()) };
- drawing_state().transform = transform;
-
- mutable_path().transform(original_transform);
-
- flush_transform();
- return {};
- }
-
- WebIDL::ExceptionOr<void> set_transform(Bindings::DOMMatrix2DInit const& init)
- {
- return set_transform(TRY(Geometry::validate_and_fixup_dom_matrix_2d_init(init)));
- }
-
- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-resettransform
- void reset_transform()
- {
- // The resetTransform() method, when invoked, must reset the current transformation matrix to the identity matrix.
- drawing_state().transform = {};
- flush_transform();
- }
-
- void flush_transform()
- {
- if (auto* recorder = canvas_recorder())
- recorder->set_transform(drawing_state().transform);
- }
-
-protected:
- CanvasTransform() = default;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasTransform.idl b/Libraries/LibWeb/HTML/Canvas/CanvasTransform.idl
index b54403f56e6..f33b1609a56 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasTransform.idl
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasTransform.idl
@@ -6,7 +6,7 @@ interface mixin CanvasTransform {
undefined transform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f);
[NewObject] DOMMatrix getTransform();
- undefined setTransform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f);
- undefined setTransform(optional DOMMatrix2DInit transform = {});
+ [ImplementedAs=set_transform] undefined setTransform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f);
+ [ImplementedAs=set_transform_to_matrix] undefined setTransform(optional DOMMatrix2DInit transform = {});
undefined resetTransform();
};
diff --git a/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp b/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp
deleted file mode 100644
index fd01273fab8..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "DrawingState.h"
-
-namespace Web::HTML {
-
-bool FillOrStrokeStyle::is_visible() const
-{
- return m_fill_or_stroke_style.visit(
- [](Gfx::Color color) { return color.alpha() > 0; },
- [](GC::Ref<CanvasGradient> gradient) { return gradient->is_visible(); },
- [](GC::Ref<CanvasPattern>) { return true; });
-}
-
-Gfx::Color FillOrStrokeStyle::to_color_but_fixme_should_accept_any_paint_style() const
-{
- return as_color().value_or(Gfx::Color::Black);
-}
-
-Optional<Gfx::Color> FillOrStrokeStyle::as_color() const
-{
- if (auto* color = m_fill_or_stroke_style.get_pointer<Gfx::Color>())
- return *color;
- return {};
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/DrawingState.h b/Libraries/LibWeb/HTML/Canvas/DrawingState.h
deleted file mode 100644
index 3c5abd91b87..00000000000
--- a/Libraries/LibWeb/HTML/Canvas/DrawingState.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/CanvasRenderingContext2D.h>
-#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
-#include <LibWeb/HTML/CanvasGradient.h>
-#include <LibWeb/HTML/CanvasPattern.h>
-
-namespace Web::HTML {
-
-using FillOrStrokeVariant = Variant<Gfx::Color, GC::Ref<CanvasGradient>, GC::Ref<CanvasPattern>>;
-
-struct FillOrStrokeStyle {
- FillOrStrokeStyle(Gfx::Color color)
- : m_fill_or_stroke_style(color)
- {
- }
-
- FillOrStrokeStyle(GC::Ref<CanvasGradient> gradient)
- : m_fill_or_stroke_style(gradient)
- {
- }
-
- FillOrStrokeStyle(GC::Ref<CanvasPattern> pattern)
- : m_fill_or_stroke_style(pattern)
- {
- }
-
- FillOrStrokeVariant const& variant() const { return m_fill_or_stroke_style; }
-
- // Whether a draw with the style can change a pixel.
- bool is_visible() const;
-
- Optional<Gfx::Color> as_color() const;
- Gfx::Color to_color_but_fixme_should_accept_any_paint_style() const;
-
- using JsFillOrStrokeStyle = Variant<Utf16String, GC::Ref<CanvasGradient>, GC::Ref<CanvasPattern>>;
-
- JsFillOrStrokeStyle to_js_fill_or_stroke_style() const
- {
- return m_fill_or_stroke_style.visit(
- [&](Gfx::Color color) -> JsFillOrStrokeStyle {
- auto serialized_color = color.to_string(Gfx::Color::HTMLCompatibleSerialization::Yes);
- return Utf16String::from_ascii_without_validation(serialized_color.bytes());
- },
- [&](auto handle) -> JsFillOrStrokeStyle {
- return handle;
- });
- }
-
- void visit_edges(GC::Cell::Visitor& visitor)
- {
- visitor.visit(m_fill_or_stroke_style);
- }
-
-private:
- FillOrStrokeVariant m_fill_or_stroke_style;
-};
-
-// https://html.spec.whatwg.org/multipage/canvas.html#drawing-state
-struct DrawingState {
- Gfx::AffineTransform transform;
- FillOrStrokeStyle fill_style { Gfx::Color::Black };
- FillOrStrokeStyle stroke_style { Gfx::Color::Black };
- float shadow_offset_x { 0.0f };
- float shadow_offset_y { 0.0f };
- float shadow_blur { 0.0f };
- Gfx::Color shadow_color { Gfx::Color::Transparent };
- Optional<Gfx::Filter> filter;
- Optional<Utf16String> filter_string;
- float line_width { 1 };
- CanvasLineCap line_cap { CanvasLineCap::Butt };
- CanvasLineJoin line_join { CanvasLineJoin::Miter };
- float miter_limit { 10 };
- Vector<double> dash_list;
- float line_dash_offset { 0 };
- bool image_smoothing_enabled { true };
- ImageSmoothingQuality image_smoothing_quality { ImageSmoothingQuality::Low };
- float global_alpha = { 1 };
- Gfx::CompositingAndBlendingOperator current_compositing_and_blending_operator = Gfx::CompositingAndBlendingOperator::SourceOver;
- RefPtr<CSS::StyleValue const> font_style_value { nullptr };
- RefPtr<Gfx::FontCascadeList const> current_font_cascade_list { nullptr };
- u64 font_environment_generation { 0 };
- CanvasTextAlign text_align { CanvasTextAlign::Start };
- CanvasTextBaseline text_baseline { CanvasTextBaseline::Alphabetic };
- CanvasDirection direction { CanvasDirection::Inherit };
- NonnullRefPtr<CSS::StyleValue const> letter_spacing { CSS::LengthStyleValue::create(CSS::Length::make_px(0)) };
-
- void visit_edges(GC::Cell::Visitor& visitor)
- {
- fill_style.visit_edges(visitor);
- stroke_style.visit_edges(visitor);
- }
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp
index 5edb27772ec..231328778f6 100644
--- a/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/RemoteCanvas2DTransportFFI.cpp
@@ -16,7 +16,7 @@
// which declares these functions in host.rs.
//
// The recorder holds a transport and a bitmap as a pointer that owns one reference. A font, a decoded image frame and a
-// video frame hold are lent for the call that takes them.
+// video frame hold are lent for the call that takes them. The pixels of a bitmap that is read back are read in place.
namespace Web::HTML {
@@ -45,7 +45,11 @@ void web_canvas_2d_transport_record_present(void* transport);
size_t web_canvas_2d_transport_pending_command_count(void const* transport);
void web_canvas_2d_transport_flush(void* transport);
void* web_canvas_2d_transport_read_back_pixels(void* transport, i32 x, i32 y, i32 width, i32 height, u8 alpha_type);
+void web_canvas_2d_bitmap_ref(void* bitmap);
void web_canvas_2d_bitmap_unref(void* bitmap);
+size_t web_canvas_2d_bitmap_size_in_bytes(void* bitmap);
+bool web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(void* bitmap, u8 const** out_pixels, size_t* out_pitch, i32* out_width, i32* out_height);
+void* web_canvas_2d_image_frame_from_bitmap(void* bitmap);
}
static RemoteCanvas2DTransport& transport_from(void* transport)
@@ -121,9 +125,38 @@ void* web_canvas_2d_transport_read_back_pixels(void* transport, i32 x, i32 y, i3
return &bitmap.release_nonnull().leak_ref();
}
+void web_canvas_2d_bitmap_ref(void* bitmap)
+{
+ static_cast<Gfx::Bitmap*>(bitmap)->ref();
+}
+
void web_canvas_2d_bitmap_unref(void* bitmap)
{
static_cast<Gfx::Bitmap*>(bitmap)->unref();
}
+size_t web_canvas_2d_bitmap_size_in_bytes(void* bitmap)
+{
+ return static_cast<Gfx::Bitmap*>(bitmap)->size_in_bytes();
+}
+
+bool web_canvas_2d_bitmap_unpremultiplied_rgba_pixels(void* bitmap, u8 const** out_pixels, size_t* out_pitch, i32* out_width, i32* out_height)
+{
+ auto const& typed_bitmap = *static_cast<Gfx::Bitmap const*>(bitmap);
+ if (typed_bitmap.format() != Gfx::BitmapFormat::RGBA8888 || typed_bitmap.alpha_type() != Gfx::AlphaType::Unpremultiplied)
+ return false;
+ *out_pixels = typed_bitmap.scanline_u8(0);
+ *out_pitch = typed_bitmap.pitch();
+ *out_width = typed_bitmap.width();
+ *out_height = typed_bitmap.height();
+ return true;
+}
+
+// A Gfx::DecodedImageFrame of the bitmap, allocated with new, which takes over the reference to the bitmap.
+void* web_canvas_2d_image_frame_from_bitmap(void* bitmap)
+{
+ NonnullRefPtr<Gfx::Bitmap const> adopted_bitmap = adopt_ref(*static_cast<Gfx::Bitmap*>(bitmap));
+ return new Gfx::DecodedImageFrame { move(adopted_bitmap) };
+}
+
}
diff --git a/Libraries/LibWeb/HTML/CanvasGradient.cpp b/Libraries/LibWeb/HTML/CanvasGradient.cpp
deleted file mode 100644
index 163d52ef486..00000000000
--- a/Libraries/LibWeb/HTML/CanvasGradient.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2022, Andreas Kling <[email protected]>
- * Copyright (c) 2023, MacDue <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGfx/Color.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/PropertyID.h>
-#include <LibWeb/HTML/CanvasGradient.h>
-
-namespace Web::HTML {
-
-extern "C" {
-
-// Defined in Bindings/Rust/src/html/exports.rs.
-void* web_canvas_gradient_create_linear(JSVM*, double x0, double y0, double x1, double y1);
-void* web_canvas_gradient_create_radial(JSVM*, double x0, double y0, double r0, double x1, double y1, double r1);
-void* web_canvas_gradient_create_conic(JSVM*, double start_angle, double x, double y);
-bool web_canvas_gradient_is_visible(void* gradient);
-
-// What the Rust implementation asks of LibWeb, declared in Bindings/Rust/src/html/canvas_gradient.rs.
-bool web_canvas_gradient_parse_color(FlatPtr color, Gfx::Color* out_color);
-}
-
-static JSVM* vm()
-{
- return JS::HostABI::vm_to_abi(JS::VM::the());
-}
-
-GC::Ref<CanvasGradient> CanvasGradient::create_linear(double x0, double y0, double x1, double y1)
-{
- return *static_cast<CanvasGradient*>(web_canvas_gradient_create_linear(vm(), x0, y0, x1, y1));
-}
-
-GC::Ref<CanvasGradient> CanvasGradient::create_radial(double x0, double y0, double r0, double x1, double y1, double r1)
-{
- return *static_cast<CanvasGradient*>(web_canvas_gradient_create_radial(vm(), x0, y0, r0, x1, y1, r1));
-}
-
-GC::Ref<CanvasGradient> CanvasGradient::create_conic(double start_angle, double x, double y)
-{
- return *static_cast<CanvasGradient*>(web_canvas_gradient_create_conic(vm(), start_angle, x, y));
-}
-
-bool CanvasGradient::is_visible() const
-{
- return web_canvas_gradient_is_visible(const_cast<CanvasGradient*>(this));
-}
-
-// https://drafts.csswg.org/css-color/#parse-a-css-color-value
-bool web_canvas_gradient_parse_color(FlatPtr color, Gfx::Color* out_color)
-{
- auto color_string = Utf16String::from_raw(color);
- auto const maybe_color = parse_css_value(CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue }, color_string.utf16_view(), CSS::PropertyID::Color);
- if (maybe_color.is_null() || !maybe_color->has_color())
- return false;
- *out_color = maybe_color->to_color({}).value();
- return true;
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/CanvasGradient.h b/Libraries/LibWeb/HTML/CanvasGradient.h
deleted file mode 100644
index daa8f165db4..00000000000
--- a/Libraries/LibWeb/HTML/CanvasGradient.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2022, Andreas Kling <[email protected]>
- * Copyright (c) 2023, MacDue <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/CanvasGradient.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/Export.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvasgradient
-// The C++ side of a CanvasGradient, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what the
-// 2D contexts create and paint with.
-class WEB_API CanvasGradient final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(CanvasGradient, canvas_gradient)
-
-public:
- static GC::Ref<CanvasGradient> create_linear(double x0, double y0, double x1, double y1);
- static GC::Ref<CanvasGradient> create_radial(double x0, double y0, double r0, double x1, double y1, double r1);
- static GC::Ref<CanvasGradient> create_conic(double start_angle, double x, double y);
-
- // Whether one of the color stops is not transparent.
- bool is_visible() const;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/CanvasPattern.cpp b/Libraries/LibWeb/HTML/CanvasPattern.cpp
deleted file mode 100644
index 54ee2410015..00000000000
--- a/Libraries/LibWeb/HTML/CanvasPattern.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2023, MacDue <[email protected]>
- * Copyright (c) 2024, Aliaksandr Kalenik <[email protected]>
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGfx/DecodedImageFrame.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Compositor/CompositorHost.h>
-#include <LibWeb/HTML/Canvas/Canvas2DRecorder.h>
-#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>
-#include <LibWeb/HTML/CanvasPattern.h>
-#include <LibWeb/HTML/CanvasRenderingContext2D.h>
-#include <LibWeb/HTML/HTMLVideoElement.h>
-#include <LibWeb/Page/Page.h>
-
-namespace Web::HTML {
-
-extern "C" {
-
-// Defined in Bindings/Rust/src/html/exports.rs.
-void* web_canvas_pattern_create(JSVM*, Gfx::DecodedImageFrame const* frame, Compositing::Canvas2DPatternRepetition);
-}
-
-// A pattern outlives any one video frame, so it reads the frame back instead of holding it.
-static Optional<Gfx::DecodedImageFrame> read_back_current_video_frame(HTMLVideoElement& video)
-{
- auto captured_frame = video.capture_current_video_frame();
- if (!captured_frame.has_value())
- return {};
- auto& page = video.document().page();
- if (!page.has_compositor_host())
- return {};
- auto transport = page.compositor_host().create_canvas_2d_transport();
- if (!transport)
- return {};
- auto recorder = Canvas2DRecorder::create(transport.release_nonnull());
-
- Gfx::IntRect frame_rect { 0, 0, static_cast<int>(video.video_width()), static_cast<int>(video.video_height()) };
- if (frame_rect.is_empty() || !recorder->create_context(frame_rect.size(), true))
- return {};
-
- recorder->draw_video_frame(*captured_frame, frame_rect.to_type<float>(), frame_rect, Gfx::ScalingMode::NearestNeighbor,
- { .compositing_and_blending_operator = Gfx::CompositingAndBlendingOperator::Copy });
- recorder->flush();
- auto bitmap = recorder->read_back_pixels(frame_rect, Gfx::AlphaType::Premultiplied);
- recorder->destroy_context();
- if (!bitmap)
- return {};
- return Gfx::DecodedImageFrame { NonnullRefPtr<Gfx::Bitmap const> { bitmap.release_nonnull() } };
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createpattern
-WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> CanvasPattern::create(CanvasImageSource const& image, Utf16FlyString const& repetition)
-{
- auto parse_repetition = [&](auto value) -> Optional<Compositing::Canvas2DPatternRepetition> {
- if (value == u"repeat"sv)
- return Compositing::Canvas2DPatternRepetition::Repeat;
- if (value == u"repeat-x"sv)
- return Compositing::Canvas2DPatternRepetition::RepeatX;
- if (value == u"repeat-y"sv)
- return Compositing::Canvas2DPatternRepetition::RepeatY;
- if (value == u"no-repeat"sv)
- return Compositing::Canvas2DPatternRepetition::NoRepeat;
- return {};
- };
-
- // 1. Let usability be the result of checking the usability of image.
- auto usability = TRY(check_usability_of_image(image));
-
- // 2. If usability is bad, then return null.
- if (usability == CanvasImageSourceUsability::Bad)
- return GC::Ptr<CanvasPattern> {};
-
- // 3. Assert: usability is good.
- VERIFY(usability == CanvasImageSourceUsability::Good);
-
- // 4. If repetition is the empty string, then set it to "repeat".
- auto repetition_or_default = repetition.is_empty() ? "repeat"_utf16_fly_string : repetition;
-
- // 5. If repetition is not identical to one of "repeat", "repeat-x", "repeat-y", or "no-repeat",
- // then throw a "SyntaxError" DOMException.
- auto repetition_value = parse_repetition(repetition_or_default);
- if (!repetition_value.has_value())
- return WebIDL::SyntaxError::create("Repetition value is not valid"_utf16);
-
- // 6. Let pattern be a new CanvasPattern object with the image image and the repetition behavior given by repetition.
- Optional<Gfx::DecodedImageFrame> frame;
- if (auto const* video = image.get_pointer<GC::Ref<HTMLVideoElement>>())
- frame = read_back_current_video_frame(*video);
- else
- frame = canvas_image_source_frame(image);
- auto* pattern = static_cast<CanvasPattern*>(web_canvas_pattern_create(JS::HostABI::vm_to_abi(JS::VM::the()), frame.has_value() ? &frame.value() : nullptr, *repetition_value));
-
- // FIXME: 7. If image is not origin-clean, then mark pattern as not origin-clean.
-
- // 8. Return pattern.
- return GC::Ptr { pattern };
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/CanvasPattern.h b/Libraries/LibWeb/HTML/CanvasPattern.h
deleted file mode 100644
index 088e41468fe..00000000000
--- a/Libraries/LibWeb/HTML/CanvasPattern.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2023, MacDue <[email protected]>
- * Copyright (c) 2025, Shannon Booth <[email protected]>
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <LibWeb/Bindings/CanvasPattern.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/HTML/Canvas/CanvasDrawImage.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#canvaspattern
-// The C++ side of a CanvasPattern, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what the
-// 2D contexts create and paint with.
-class WEB_API CanvasPattern final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(CanvasPattern, canvas_pattern)
-
-public:
- static WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> create(CanvasImageSource const& image, Utf16FlyString const& repetition);
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp b/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp
index 3afd6fc2c5f..7057c5e2bbb 100644
--- a/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp
+++ b/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp
@@ -14,32 +14,9 @@
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(CanvasRenderingContext2D);
-
-GC::Ref<CanvasRenderingContext2D> CanvasRenderingContext2D::create(HTMLCanvasElement& element, HTML::CanvasRenderingContext2DSettings context_attributes)
-{
- auto& realm = HTML::relevant_realm(element);
- auto context = realm.create<CanvasRenderingContext2D>(realm, element, context_attributes);
- return context;
-}
-
-CanvasRenderingContext2D::CanvasRenderingContext2D(JS::Realm& realm, HTMLCanvasElement& element, HTML::CanvasRenderingContext2DSettings context_attributes)
- : Canvas2DContextBase(realm, element.bitmap_size_for_canvas(), move(context_attributes))
- , m_element(element)
-{
-}
-
-CanvasRenderingContext2D::~CanvasRenderingContext2D() = default;
-
-void CanvasRenderingContext2D::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_element);
-}
-
-GC::Ref<HTMLCanvasElement> CanvasRenderingContext2D::canvas_for_binding() const
+GC::Ref<CanvasRenderingContext2D> CanvasRenderingContext2D::create(HTMLCanvasElement& element, CanvasRenderingContext2DSettings const& context_attributes)
{
- return *m_element;
+ return static_cast<CanvasRenderingContext2D&>(Canvas2DContextBase::create(element, element, false, context_attributes));
}
}
diff --git a/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h b/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h
index 8f2b91c08ec..ece1ac4ea73 100644
--- a/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h
+++ b/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h
@@ -8,34 +8,17 @@
#pragma once
+#include <LibWeb/Bindings/CanvasRenderingContext2D.h>
#include <LibWeb/HTML/Canvas/Canvas2DContextBase.h>
-#include <LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h>
namespace Web::HTML {
-class CanvasRenderingContext2D
- : public Canvas2DContextBase
- , public CanvasTextDrawingStyles<HTMLCanvasElement> {
-
- WEB_WRAPPABLE(CanvasRenderingContext2D, Canvas2DContextBase);
- GC_DECLARE_ALLOCATOR(CanvasRenderingContext2D);
+// https://html.spec.whatwg.org/multipage/canvas.html#canvasrenderingcontext2d
+class WEB_API CanvasRenderingContext2D final : public Canvas2DContextBase {
+ WEB_RUST_INTERFACE(CanvasRenderingContext2D, canvas_rendering_context2d)
public:
- static GC::Ref<CanvasRenderingContext2D> create(HTMLCanvasElement&, HTML::CanvasRenderingContext2DSettings);
-
- virtual ~CanvasRenderingContext2D() override;
-
- GC::Ref<HTMLCanvasElement> canvas_for_binding() const;
-
-protected:
- virtual CanvasHost& canvas_host() const override { return *m_element; }
-
-private:
- CanvasRenderingContext2D(JS::Realm&, HTMLCanvasElement&, HTML::CanvasRenderingContext2DSettings);
-
- virtual void visit_edges(Cell::Visitor&) override;
-
- GC::Ref<HTMLCanvasElement> m_element;
+ static GC::Ref<CanvasRenderingContext2D> create(HTMLCanvasElement&, CanvasRenderingContext2DSettings const&);
};
}
diff --git a/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl b/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl
index 248bf616609..353836dd789 100644
--- a/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl
+++ b/Libraries/LibWeb/HTML/CanvasRenderingContext2D.idl
@@ -10,9 +10,9 @@ enum CanvasTextBaseline { "top", "hanging", "middle", "alphabetic", "ideographic
enum CanvasDirection { "ltr", "rtl", "inherit" };
// https://html.spec.whatwg.org/multipage/canvas.html#canvasrenderingcontext2d
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CanvasRenderingContext2D {
- [ImplementedAs=canvas_for_binding] readonly attribute HTMLCanvasElement canvas;
+ readonly attribute HTMLCanvasElement canvas;
};
CanvasRenderingContext2D includes CanvasSettings;
diff --git a/Libraries/LibWeb/HTML/ImageBitmap.cpp b/Libraries/LibWeb/HTML/ImageBitmap.cpp
index c82774ef555..14a726f4bb9 100644
--- a/Libraries/LibWeb/HTML/ImageBitmap.cpp
+++ b/Libraries/LibWeb/HTML/ImageBitmap.cpp
@@ -289,13 +289,6 @@ void ImageBitmap::close()
web_image_bitmap_close(this);
}
-Optional<Gfx::DecodedImageFrame> ImageBitmap::frame() const
-{
- if (auto const* frame = web_image_bitmap_frame(this))
- return *frame;
- return {};
-}
-
Gfx::Bitmap const* ImageBitmap::bitmap() const
{
if (auto const* frame = web_image_bitmap_frame(this))
diff --git a/Libraries/LibWeb/HTML/ImageBitmap.h b/Libraries/LibWeb/HTML/ImageBitmap.h
index abe846c3773..6b5b295c320 100644
--- a/Libraries/LibWeb/HTML/ImageBitmap.h
+++ b/Libraries/LibWeb/HTML/ImageBitmap.h
@@ -38,8 +38,9 @@ struct ImageBitmapSharedPixels {
// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagebitmap
// The C++ side of an ImageBitmap, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what
-// createImageBitmap(), OffscreenCanvas and WebDriver create, and the 2D contexts draw. ImageBitmap.cpp encodes and
-// decodes the bitmap data for the serialization and transfer steps of the Rust implementation.
+// createImageBitmap(), OffscreenCanvas and WebDriver create, and createImageBitmap() and StructuredSerialize read.
+// ImageBitmap.cpp encodes and decodes the bitmap data for the serialization and transfer steps of the Rust
+// implementation.
class WEB_API ImageBitmap final : public Bindings::RustInterfaceCell {
WEB_RUST_INTERFACE(ImageBitmap, image_bitmap)
@@ -56,8 +57,7 @@ public:
// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-close
void close();
- // The bitmap data, which the ImageBitmap keeps until it is closed or transferred.
- Optional<Gfx::DecodedImageFrame> frame() const;
+ // The bitmap of the bitmap data, which the ImageBitmap keeps until it is closed or transferred.
Gfx::Bitmap const* bitmap() const;
static size_t shared_pixels_size(Gfx::Bitmap const&);
diff --git a/Libraries/LibWeb/HTML/ImageData.cpp b/Libraries/LibWeb/HTML/ImageData.cpp
index 1bc8240113e..4aab76128f9 100644
--- a/Libraries/LibWeb/HTML/ImageData.cpp
+++ b/Libraries/LibWeb/HTML/ImageData.cpp
@@ -11,6 +11,7 @@
#include <LibWeb/Bindings/RustSerialization.h>
#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/StructuredSerialize.h>
+#include <LibWebCommon/Bindings/PredefinedColorSpace.h>
namespace Web::HTML {
@@ -22,7 +23,7 @@ static_assert(to_underlying(Bindings::PredefinedColorSpace::DisplayP3Linear) ==
extern "C" {
// Defined in Bindings/Rust/src/html/exports.rs.
-JSCompletion web_image_data_create(JSVM*, void* realm, u32 width, u32 height, bool has_color_space, Bindings::PredefinedColorSpace, void** out_image_data);
+JSCompletion web_image_data_create(JSVM*, void* realm, u32 width, u32 height, void** out_image_data);
u32 web_image_data_width(void const* image_data);
u32 web_image_data_height(void const* image_data);
bool web_image_data_is_detached(void const* image_data);
@@ -48,11 +49,10 @@ JSCompletion web_image_data_deserialize_color_space(Bindings::RustSerializationR
}
}
-WebIDL::ExceptionOr<GC::Ref<ImageData>> ImageData::create(JS::Realm& realm, u32 width, u32 height, Optional<Settings> const& settings)
+WebIDL::ExceptionOr<GC::Ref<ImageData>> ImageData::create(JS::Realm& realm, u32 width, u32 height)
{
- auto color_space = settings.has_value() ? settings->color_space : Optional<Bindings::PredefinedColorSpace> {};
void* image_data = nullptr;
- TRY(JS::HostABI::completion_from_abi<void>(web_image_data_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, width, height, color_space.has_value(), color_space.value_or(Bindings::PredefinedColorSpace::Srgb), &image_data)));
+ TRY(JS::HostABI::completion_from_abi<void>(web_image_data_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, width, height, &image_data)));
return GC::Ref { *static_cast<ImageData*>(image_data) };
}
diff --git a/Libraries/LibWeb/HTML/ImageData.h b/Libraries/LibWeb/HTML/ImageData.h
index 496449a94b5..164c6063c6b 100644
--- a/Libraries/LibWeb/HTML/ImageData.h
+++ b/Libraries/LibWeb/HTML/ImageData.h
@@ -19,16 +19,15 @@
namespace Web::HTML {
// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagedata
-// The C++ side of an ImageData, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what the 2D
-// contexts create, read and write the pixels of, and createImageBitmap() reads.
+// The C++ side of an ImageData, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what
+// createImageBitmap() reads.
class WEB_API ImageData final : public Bindings::RustInterfaceCell {
WEB_RUST_INTERFACE(ImageData, image_data)
public:
- using Settings = Bindings::ImageDataSettings;
-
- // A new ImageData of the size, with transparent black pixels, https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#initialize-an-imagedata-object
- static WebIDL::ExceptionOr<GC::Ref<ImageData>> create(JS::Realm&, u32 width, u32 height, Optional<Settings> const& = {});
+ // A new ImageData of the size, with transparent black pixels and the sRGB color space,
+ // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#initialize-an-imagedata-object
+ static WebIDL::ExceptionOr<GC::Ref<ImageData>> create(JS::Realm&, u32 width, u32 height);
u32 width() const;
u32 height() const;
diff --git a/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.cpp b/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.cpp
index f659b8c6097..98e6ead56ad 100644
--- a/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.cpp
+++ b/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.cpp
@@ -9,48 +9,17 @@
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(OffscreenCanvasRenderingContext2D);
+// Defined in Bindings/Rust/src/canvas_2d/exports.rs.
+extern "C" void web_canvas_2d_context_replace_bitmap_with_cleared_bitmap(void* context);
-GC::Ref<OffscreenCanvasRenderingContext2D> OffscreenCanvasRenderingContext2D::create(OffscreenCanvas& offscreen_canvas, HTML::CanvasRenderingContext2DSettings context_attributes)
+GC::Ref<OffscreenCanvasRenderingContext2D> OffscreenCanvasRenderingContext2D::create(OffscreenCanvas& offscreen_canvas, CanvasRenderingContext2DSettings const& context_attributes)
{
- auto& realm = offscreen_canvas.relevant_global_object().shape().realm();
- return realm.create<OffscreenCanvasRenderingContext2D>(realm, offscreen_canvas, move(context_attributes));
-}
-
-OffscreenCanvasRenderingContext2D::OffscreenCanvasRenderingContext2D(JS::Realm& realm, OffscreenCanvas& offscreen_canvas, HTML::CanvasRenderingContext2DSettings context_attributes)
- : Canvas2DContextBase(realm, offscreen_canvas.bitmap_size_for_canvas(), move(context_attributes))
- , m_canvas(offscreen_canvas)
-{
-}
-
-OffscreenCanvasRenderingContext2D::~OffscreenCanvasRenderingContext2D() = default;
-
-void OffscreenCanvasRenderingContext2D::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_canvas);
-}
-
-CanvasHost& OffscreenCanvasRenderingContext2D::canvas_host() const
-{
- return *m_canvas;
-}
-
-GC::Ref<OffscreenCanvas> OffscreenCanvasRenderingContext2D::canvas()
-{
- return m_canvas;
+ return static_cast<OffscreenCanvasRenderingContext2D&>(Canvas2DContextBase::create(offscreen_canvas, offscreen_canvas, true, context_attributes));
}
void OffscreenCanvasRenderingContext2D::replace_bitmap_with_cleared_bitmap()
{
- m_cached_readback = nullptr;
- m_origin_clean = true;
- if (!has_backing_storage())
- return;
- if (auto* recorder = canvas_recorder()) {
- recorder->clear_canvas(clear_color());
- did_draw({ {}, m_size.to_type<float>() });
- }
+ web_canvas_2d_context_replace_bitmap_with_cleared_bitmap(this);
}
}
diff --git a/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.h b/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.h
index e953ee0db04..3be18689210 100644
--- a/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.h
+++ b/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.h
@@ -6,35 +6,19 @@
#pragma once
+#include <LibWeb/Bindings/OffscreenCanvasRenderingContext2D.h>
#include <LibWeb/HTML/Canvas/Canvas2DContextBase.h>
-#include <LibWeb/HTML/Canvas/CanvasTextDrawingStyles.h>
namespace Web::HTML {
-class OffscreenCanvasRenderingContext2D
- : public Canvas2DContextBase
- , public CanvasTextDrawingStyles<OffscreenCanvas> {
-
- WEB_WRAPPABLE(OffscreenCanvasRenderingContext2D, Canvas2DContextBase);
- GC_DECLARE_ALLOCATOR(OffscreenCanvasRenderingContext2D);
+// https://html.spec.whatwg.org/multipage/canvas.html#offscreencanvasrenderingcontext2d
+class WEB_API OffscreenCanvasRenderingContext2D final : public Canvas2DContextBase {
+ WEB_RUST_INTERFACE(OffscreenCanvasRenderingContext2D, offscreen_canvas_rendering_context2d)
public:
- [[nodiscard]] static GC::Ref<OffscreenCanvasRenderingContext2D> create(OffscreenCanvas&, HTML::CanvasRenderingContext2DSettings);
- virtual ~OffscreenCanvasRenderingContext2D() override;
-
- GC::Ref<OffscreenCanvas> canvas();
+ static GC::Ref<OffscreenCanvasRenderingContext2D> create(OffscreenCanvas&, CanvasRenderingContext2DSettings const&);
void replace_bitmap_with_cleared_bitmap();
-
-protected:
- virtual CanvasHost& canvas_host() const override;
-
-private:
- OffscreenCanvasRenderingContext2D(JS::Realm&, OffscreenCanvas&, HTML::CanvasRenderingContext2DSettings);
-
- virtual void visit_edges(Cell::Visitor&) override;
-
- GC::Ref<OffscreenCanvas> m_canvas;
};
}
diff --git a/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.idl b/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.idl
index 09b1fc2030c..30f13ca9a2d 100644
--- a/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.idl
+++ b/Libraries/LibWeb/HTML/OffscreenCanvasRenderingContext2D.idl
@@ -1,5 +1,5 @@
// https://html.spec.whatwg.org/multipage/canvas.html#offscreencanvasrenderingcontext2d
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface OffscreenCanvasRenderingContext2D {
readonly attribute OffscreenCanvas canvas;
};
diff --git a/Libraries/LibWeb/HTML/Path2D.cpp b/Libraries/LibWeb/HTML/Path2D.cpp
deleted file mode 100644
index 950feeb2a17..00000000000
--- a/Libraries/LibWeb/HTML/Path2D.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- * Copyright (c) 2022, Andreas Kling <[email protected]>
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGfx/Path.h>
-#include <LibWeb/HTML/Path2D.h>
-
-namespace Web::HTML {
-
-// Defined in Bindings/Rust/src/html/exports.rs.
-extern "C" Gfx::Path const* web_path2d_path(void* path);
-
-Gfx::Path const& Path2D::path() const
-{
- return *web_path2d_path(const_cast<Path2D*>(this));
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/Path2D.h b/Libraries/LibWeb/HTML/Path2D.h
deleted file mode 100644
index f799c862399..00000000000
--- a/Libraries/LibWeb/HTML/Path2D.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2022, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibGfx/Forward.h>
-#include <LibWeb/Bindings/Path2D.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/Export.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/canvas.html#path2d
-// The C++ side of a Path2D, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what the 2D
-// contexts fill, stroke and clip with.
-class WEB_API Path2D final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(Path2D, path2d)
-
-public:
- // The path, which changes only when script calls a method of the Path2D.
- Gfx::Path const& path() const;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/TextMetrics.cpp b/Libraries/LibWeb/HTML/TextMetrics.cpp
deleted file mode 100644
index 59a8c5a8847..00000000000
--- a/Libraries/LibWeb/HTML/TextMetrics.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2021, sin-ack <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/HTML/TextMetrics.h>
-
-namespace Web::HTML {
-
-// NB: `TextMeasurements` of Bindings/Rust/src/html/text_metrics.rs is twelve doubles in this order.
-static_assert(sizeof(TextMeasurements) == 12 * sizeof(double));
-static_assert(offsetof(TextMeasurements, actual_bounding_box_right) == 2 * sizeof(double));
-static_assert(offsetof(TextMeasurements, ideographic_baseline) == 11 * sizeof(double));
-
-// Defined in Bindings/Rust/src/html/exports.rs.
-extern "C" void* web_text_metrics_create(JSVM*, TextMeasurements const*);
-
-GC::Ref<TextMetrics> TextMetrics::create(TextMeasurements const& measurements)
-{
- return *static_cast<TextMetrics*>(web_text_metrics_create(JS::HostABI::vm_to_abi(JS::VM::the()), &measurements));
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/TextMetrics.h b/Libraries/LibWeb/HTML/TextMetrics.h
deleted file mode 100644
index 32442286a5e..00000000000
--- a/Libraries/LibWeb/HTML/TextMetrics.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2021, sin-ack <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/Bindings/TextMetrics.h>
-#include <LibWeb/Export.h>
-
-namespace Web::HTML {
-
-// The measurements of a text, in CSS pixels, as the members of TextMetrics describe them. `TextMeasurements` of
-// Bindings/Rust/src/html/text_metrics.rs mirrors it.
-struct TextMeasurements {
- // x-direction
- double width { 0 };
- double actual_bounding_box_left { 0 };
- double actual_bounding_box_right { 0 };
-
- // y-direction
- double font_bounding_box_ascent { 0 };
- double font_bounding_box_descent { 0 };
- double actual_bounding_box_ascent { 0 };
- double actual_bounding_box_descent { 0 };
- double em_height_ascent { 0 };
- double em_height_descent { 0 };
- double hanging_baseline { 0 };
- double alphabetic_baseline { 0 };
- double ideographic_baseline { 0 };
-};
-
-// https://html.spec.whatwg.org/multipage/canvas.html#textmetrics
-// The C++ side of a TextMetrics, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what
-// measureText() returns.
-class WEB_API TextMetrics final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(TextMetrics, text_metrics)
-
-public:
- [[nodiscard]] static GC::Ref<TextMetrics> create(TextMeasurements const&);
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index 4a056bf5f45..7b4778208db 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -39,6 +39,7 @@
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventSource.h>
#include <LibWeb/HTML/HTMLImageElement.h>
+#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/OffscreenCanvas.h>
#include <LibWeb/HTML/PromiseRejectionEvent.h>
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index cd4d83fed15..8021e7355ef 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -2509,7 +2509,6 @@ fn main() -> Result<(), Box<dyn Error>> {
value_parser_config.export.include = vec![
"NativeCompilationPurpose".to_string(),
"FfiParseStatus".to_string(),
- "FfiSimpleColor".to_string(),
"FontFeatureValuesRuleKind".to_string(),
"FfiValueParsingContext".to_string(),
"FfiValueParsingContextKind".to_string(),
diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
index bfb980302b6..9efffc8fa4b 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
@@ -25,7 +25,7 @@ use crate::css::parser::arbitrary_substitution::{
substitution_function_presence_bits,
};
use crate::css::parser::calc_parser::{CalcParseError, parse_a_calc_function_node};
-use crate::css::parser::color_parser::{is_color_function_name, parse_color_value, parse_simple_color};
+use crate::css::parser::color_parser::{is_color_function_name, parse_color_value};
use crate::css::parser::component_value::{
ComponentKind, ComponentValue, consume_a_list_of_component_values, consume_a_small_list_of_component_values,
};
@@ -6237,34 +6237,6 @@ pub unsafe extern "C" fn rust_parse_entire_css_primitive_from_source(
}
}
-#[derive(Clone, Copy, Default)]
-#[repr(C)]
-pub struct FfiSimpleColor {
- pub success: bool,
- pub red: u8,
- pub green: u8,
- pub blue: u8,
- pub alpha: u8,
-}
-
-/// Parses the allocation-free subset used by the canvas color cache.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_parse_simple_color(source: FfiUtf16View) -> FfiSimpleColor {
- let Some(source) = source.units() else {
- return FfiSimpleColor::default();
- };
- let Some([red, green, blue, alpha]) = parse_simple_color(source) else {
- return FfiSimpleColor::default();
- };
- FfiSimpleColor {
- success: true,
- red,
- green,
- blue,
- alpha,
- }
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn rust_is_valid_animation_name_custom_ident(source: FfiUtf16View) -> bool {
let Some(source) = source.units() else {
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index f411a4c5b84..470279113a0 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -33,6 +33,18 @@ pub(crate) mod svg;
// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.
pub use svg::gfx_path_from_path_data;
+/// The red, green, blue and alpha of a CSS <color> in ASCII that needs nothing to be resolved against, or None for any
+/// other value, as the color cache of the 2D canvas contexts parses it.
+pub fn parse_simple_color_ascii(source: &[u8]) -> Option<[u8; 4]> {
+ css::parser::color_parser::parse_simple_color(source.into())
+}
+
+/// The red, green, blue and alpha of a CSS <color> in UTF-16 that needs nothing to be resolved against, or None for any
+/// other value, as the color cache of the 2D canvas contexts parses it.
+pub fn parse_simple_color_utf16(source: &[u16]) -> Option<[u8; 4]> {
+ css::parser::color_parser::parse_simple_color(source.into())
+}
+
// NB: Only C++ calls into the HTML tokenizer and parser, so nothing in this crate names them. Linking the crate keeps
// their extern "C" functions in the static library.
extern crate libweb_html_tokenizer;
diff --git a/Libraries/LibWeb/WebDriver/Screenshot.cpp b/Libraries/LibWeb/WebDriver/Screenshot.cpp
index 25486e6b4b2..0380af15fc4 100644
--- a/Libraries/LibWeb/WebDriver/Screenshot.cpp
+++ b/Libraries/LibWeb/WebDriver/Screenshot.cpp
@@ -72,7 +72,7 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_cont
HTML::TemporaryExecutionContext execution_context { element->document().relevant_settings_object() };
auto image_bitmap = HTML::ImageBitmap::create(bitmap);
- if (canvas->canvas_rendering_context_2d()->draw_image(image_bitmap, 0, 0).is_exception()) {
+ if (!canvas->canvas_rendering_context_2d()->draw_image(*image_bitmap, 0, 0)) {
callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "Failed to draw the screenshot to the canvas"sv));
return;
}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 27229f130df..7e1dd08403f 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -52,8 +52,8 @@ ALLOWED_REALM_MENTIONS = {
"FileAPI": (6, 11, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),
"Geometry": (8, 8, "geometry constructors and structured clone still materialize JS-facing geometry objects"),
"HTML": (
- 70,
- 211,
+ 64,
+ 203,
"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage",
),
"IndexedDB": (