Skip to content

Truly independent web browser

LibWeb: Implement CanvasGradient in Rust

Andreas Kling010ac20bda92
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_gradient.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_gradient.rs
new file mode 100644
index 00000000000..bba072607bd
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_gradient.rs
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#canvasgradient
+
+use core::cell::RefCell;
+
+use ak::Utf16String;
+use libcompositing_rust::display_list::canvas_2d::{ColorStops, Paint};
+use libgfx_rust::{Color, FloatPoint};
+use libjs_rust::api::{Trace, Vm};
+
+use super::color_stops::ColorStopList;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ /// Parses the color as the CSS color value of a canvas without an element to resolve it against, which LibWeb's
+ /// C++ does, and returns whether it is one. The string is a borrowed AK::Utf16String.
+ fn web_canvas_gradient_parse_color(color: usize, out_color: *mut Color) -> bool;
+}
+
+/// Where the colors of a gradient go, which the method of the context that created it decides. The points and the
+/// radii are in the coordinates that a draw is transformed from.
+#[derive(Clone, Copy)]
+enum GradientGeometry {
+ Linear {
+ start_point: FloatPoint,
+ end_point: FloatPoint,
+ },
+ Radial {
+ start_center: FloatPoint,
+ start_radius: f32,
+ end_center: FloatPoint,
+ end_radius: f32,
+ },
+ Conic {
+ center: FloatPoint,
+ start_angle: f32,
+ },
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CanvasGradient {
+ #[gc(untraced)]
+ geometry: GradientGeometry,
+ #[gc(untraced)]
+ color_stops: RefCell<ColorStopList>,
+}
+
+impl Wrappable for CanvasGradient {}
+
+#[allow(
+ clippy::cast_possible_truncation,
+ reason = "the gradient keeps its geometry in floats, as the C++ did"
+)]
+fn point(x: f64, y: f64) -> FloatPoint {
+ FloatPoint {
+ x: x as f32,
+ y: y as f32,
+ }
+}
+
+impl CanvasGradient {
+ fn create(vm: &Vm, geometry: GradientGeometry) -> Ref<Self> {
+ allocate(
+ vm,
+ Self {
+ geometry,
+ color_stops: RefCell::new(ColorStopList::default()),
+ },
+ )
+ }
+
+ /// The gradient of createLinearGradient(), https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createlineargradient
+ pub(crate) fn create_linear(vm: &Vm, x0: f64, y0: f64, x1: f64, y1: f64) -> Ref<Self> {
+ Self::create(
+ vm,
+ GradientGeometry::Linear {
+ start_point: point(x0, y0),
+ end_point: point(x1, y1),
+ },
+ )
+ }
+
+ /// The gradient of createRadialGradient(), whose radii the context has checked,
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createradialgradient
+ #[allow(
+ clippy::cast_possible_truncation,
+ reason = "the gradient keeps its geometry in floats, as the C++ did"
+ )]
+ pub(crate) fn create_radial(vm: &Vm, x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64) -> Ref<Self> {
+ Self::create(
+ vm,
+ GradientGeometry::Radial {
+ start_center: point(x0, y0),
+ start_radius: r0 as f32,
+ end_center: point(x1, y1),
+ end_radius: r1 as f32,
+ },
+ )
+ }
+
+ /// The gradient of createConicGradient(), https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createconicgradient
+ #[allow(
+ clippy::cast_possible_truncation,
+ reason = "the gradient keeps its geometry in floats, as the C++ did"
+ )]
+ pub(crate) fn create_conic(vm: &Vm, start_angle: f64, x: f64, y: f64) -> Ref<Self> {
+ Self::create(
+ vm,
+ GradientGeometry::Conic {
+ center: point(x, y),
+ start_angle: start_angle as f32,
+ },
+ )
+ }
+
+ /// Whether a draw with the gradient can change a pixel: whether one of its stops is not transparent.
+ pub(crate) fn is_visible(&self) -> bool {
+ self.color_stops.borrow().colors().iter().any(|color| color.alpha() > 0)
+ }
+
+ /// The paint of a draw with the gradient, which borrows the stops until the gradient changes.
+ ///
+ /// # Safety
+ ///
+ /// Nothing may add a stop to the gradient while the paint is in use.
+ pub(crate) unsafe fn paint_unguarded(&self) -> Paint<'_> {
+ // SAFETY: The caller keeps the stops from changing while the paint borrows them.
+ let color_stops = unsafe { self.color_stops.try_borrow_unguarded() }.expect("nothing adds a stop meanwhile");
+ self.paint_with_color_stops(color_stops)
+ }
+
+ fn paint_with_color_stops<'a>(&self, color_stops: &'a ColorStopList) -> Paint<'a> {
+ let color_stops = ColorStops {
+ colors: color_stops.colors(),
+ positions: color_stops.positions(),
+ };
+ match self.geometry {
+ GradientGeometry::Linear { start_point, end_point } => Paint::LinearGradient {
+ start_point,
+ end_point,
+ color_stops,
+ },
+ GradientGeometry::Radial {
+ start_center,
+ start_radius,
+ end_center,
+ end_radius,
+ } => Paint::RadialGradient {
+ start_center,
+ start_radius,
+ end_center,
+ end_radius,
+ color_stops,
+ },
+ GradientGeometry::Conic { center, start_angle } => Paint::ConicGradient {
+ center,
+ start_angle,
+ color_stops,
+ },
+ }
+ }
+
+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-canvasgradient-addcolorstop
+ pub(crate) fn add_color_stop(&self, _: &mut CallContext, offset: f64, color: Utf16String) -> WebIdlResult<()> {
+ // 1. If the offset is less than 0 or greater than 1, then throw an "IndexSizeError" DOMException.
+ if !(0.0..=1.0).contains(&offset) {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"CanvasGradient color stop offset out of bounds",
+ )));
+ }
+
+ // 2. Let parsed color be the result of parsing color.
+ // https://drafts.csswg.org/css-color/#parse-a-css-color-value
+ let mut parsed_color = Color(0);
+ // SAFETY: The string is live for the call, and the color is a local.
+ let is_color = unsafe { web_canvas_gradient_parse_color(color.raw_identity(), &raw mut parsed_color) };
+
+ // 3. If parsed color is failure, throw a "SyntaxError" DOMException.
+ if !is_color {
+ return Err(Exception::syntax_error(Utf16String::from_ascii(
+ b"Could not parse color for CanvasGradient",
+ )));
+ }
+
+ // 4. Place a new stop on the gradient, at offset offset relative to the whole gradient, and with the color
+ // parsed color.
+ // If multiple stops are added at the same offset on a gradient, then they must be placed in the order
+ // added, with the first one closest to the start of the gradient, and each subsequent one infinitesimally
+ // further along towards the end point (in effect causing all but the first and last stop added at each
+ // point to be ignored).
+ #[allow(
+ clippy::cast_possible_truncation,
+ reason = "the gradient keeps its stops in floats, as the C++ did"
+ )]
+ self.color_stops.borrow_mut().add(offset as f32, parsed_color);
+
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/color_stops.rs b/Libraries/LibWeb/Bindings/Rust/src/html/color_stops.rs
new file mode 100644
index 00000000000..9949a6e67f3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/color_stops.rs
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The color stops of a CanvasGradient, kept in the order of their positions. Stops at the same position stay in
+//! the order they were added in, as the spec says.
+
+use libgfx_rust::Color;
+
+/// The color stops, as the parallel arrays of colors and positions that a paint lends the recorder.
+#[derive(Debug, Default)]
+pub(crate) struct ColorStopList {
+ colors: Vec<Color>,
+ positions: Vec<f32>,
+}
+
+impl ColorStopList {
+ pub(crate) fn colors(&self) -> &[Color] {
+ &self.colors
+ }
+
+ pub(crate) fn positions(&self) -> &[f32] {
+ &self.positions
+ }
+
+ /// Places the stop after every stop at a position that is not greater than its own.
+ pub(crate) fn add(&mut self, position: f32, color: Color) {
+ let index = self.positions.partition_point(|&other| other <= position);
+ self.positions.insert(index, position);
+ self.colors.insert(index, color);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ColorStopList;
+ use libgfx_rust::Color;
+
+ #[test]
+ fn stops_are_sorted_by_position() {
+ let mut stops = ColorStopList::default();
+ stops.add(0.5, Color(1));
+ stops.add(0.0, Color(2));
+ stops.add(1.0, Color(3));
+ stops.add(0.25, Color(4));
+ assert_eq!(stops.positions(), [0.0, 0.25, 0.5, 1.0]);
+ assert_eq!(stops.colors(), [Color(2), Color(4), Color(1), Color(3)]);
+ }
+
+ #[test]
+ fn stops_at_one_position_stay_in_the_order_they_were_added() {
+ let mut stops = ColorStopList::default();
+ for color in 0..20 {
+ stops.add(0.5, Color(color));
+ }
+ assert_eq!(stops.colors(), (0..20).map(Color).collect::<Vec<_>>());
+ }
+
+ #[test]
+ fn stops_at_several_positions_stay_in_the_order_they_were_added() {
+ let mut stops = ColorStopList::default();
+ let positions = [0.5, 0.1, 0.5, 0.9, 0.5, 0.1, 0.5, 0.3, 0.5, 0.1, 0.7, 0.5];
+ for (color, position) in (0..).zip(positions) {
+ stops.add(position, Color(color));
+ }
+ assert_eq!(
+ stops.positions(),
+ [0.1, 0.1, 0.1, 0.3, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.7, 0.9]
+ );
+ assert_eq!(stops.colors(), [1, 5, 9, 7, 0, 2, 4, 6, 8, 11, 10, 3].map(Color));
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
new file mode 100644
index 00000000000..df1d7bfad9f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * 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.
+
+use core::ffi::c_void;
+
+use libcompositing_rust::display_list::canvas_2d::Paint;
+use libcompositing_rust::display_list::canvas_2d_recorder::FfiCanvas2DPaint;
+use libcompositing_rust::display_list::commands::Canvas2DPaintKind;
+use libjs_rust::api::Vm;
+
+use super::canvas_gradient::CanvasGradient;
+use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi};
+
+/// # Safety
+///
+/// `vm` must be the live VM.
+unsafe fn vm_from_abi<'vm>(vm: *mut c_void) -> &'vm Vm {
+ assert!(!vm.is_null(), "C++ passes the VM");
+ // SAFETY: The caller passes the live VM.
+ unsafe { &*vm.cast::<Vm>() }
+}
+
+/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of an object of the interface, and it must outlive `'a`.
+unsafe fn object_from_abi<'a, T: Interface>(cell: *mut c_void) -> &'a T {
+ // SAFETY: The caller passes a live cell of the interface.
+ let object: Ref<T> = unsafe { cell_from_abi(cell) };
+ // SAFETY: The caller keeps the cell alive for 'a.
+ 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);
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
new file mode 100644
index 00000000000..4d694d15361
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The objects that the 2D canvas contexts create and draw with. The contexts are still LibWeb's C++, which creates
+//! and reads these objects through the C ABI of `exports`.
+
+pub(crate) mod color_stops;
+
+// What follows runs on the JS runtime, which the tests of the crate do not link.
+#[cfg(not(test))]
+pub(crate) mod canvas_gradient;
+#[cfg(not(test))]
+pub(crate) mod exports;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 0f9fcb4b122..1c8a38e42ba 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -38,6 +38,15 @@ pub(crate) mod encoding;
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 html;
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
pub(crate) mod speech;
#[cfg_attr(
not(web_idl_bindings),
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index 5e43773a1f3..5cafa02f379 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -553,8 +553,7 @@ void Canvas2DContextBase::fill_text(Utf16View text, float x, float y, Optional<d
auto* recorder = canvas_recorder();
if (!recorder)
return;
- auto paint_style = state.fill_style.to_gfx_paint_style();
- if (!paint_style->is_visible() && state.current_compositing_and_blending_operator == Gfx::CompositingAndBlendingOperator::SourceOver)
+ 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;
@@ -564,7 +563,7 @@ void Canvas2DContextBase::fill_text(Utf16View text, float x, float y, Optional<d
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, *paint_style, compositing_for_drawing_state());
+ recorder->draw_glyph_run(glyph_run->font(), glyphs, translation, state.fill_style, compositing_for_drawing_state());
did_draw({});
}
@@ -639,8 +638,7 @@ void Canvas2DContextBase::stroke_internal(Gfx::Path path)
return;
auto& state = drawing_state();
- auto paint_style = state.stroke_style.to_gfx_paint_style();
- if (!paint_style->is_visible() && transparent_source_paint_can_be_ignored(state.current_compositing_and_blending_operator))
+ if (!state.stroke_style.is_visible() && transparent_source_paint_can_be_ignored(state.current_compositing_and_blending_operator))
return;
auto line_cap = to_gfx_cap(state.line_cap);
@@ -654,7 +652,7 @@ void Canvas2DContextBase::stroke_internal(Gfx::Path path)
}
paint_shadow_for_stroke_internal(path, line_cap, line_join, dash_array);
auto bounding_box = path.bounding_box();
- recorder->stroke_path(path, *paint_style,
+ recorder->stroke_path(path, state.stroke_style,
{
.thickness = state.line_width,
.cap_style = line_cap,
@@ -696,14 +694,13 @@ void Canvas2DContextBase::fill_internal(Gfx::Path path, Gfx::WindingRule winding
return;
auto& state = this->drawing_state();
- auto paint_style = state.fill_style.to_gfx_paint_style();
- if (!paint_style->is_visible() && transparent_source_paint_can_be_ignored(state.current_compositing_and_blending_operator))
+ if (!state.fill_style.is_visible() && transparent_source_paint_can_be_ignored(state.current_compositing_and_blending_operator))
return;
paint_shadow_for_fill_internal(path, winding_rule);
auto bounding_box = path.bounding_box();
- recorder->fill_path(path, *paint_style, winding_rule, compositing_for_drawing_state());
+ recorder->fill_path(path, state.fill_style, winding_rule, compositing_for_drawing_state());
did_draw(bounding_box);
}
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp
index 3db1c7b12d4..7449282684a 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp
@@ -15,6 +15,7 @@
#include <LibGfx/Font/Font.h>
#include <LibGfx/PaintStyle.h>
#include <LibWeb/HTML/Canvas/Canvas2DRecorder.h>
+#include <LibWeb/HTML/Canvas/DrawingState.h>
#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>
namespace Web::HTML {
@@ -56,11 +57,15 @@ 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);
}
namespace {
-// A paint style as the recorder borrows it, with the arrays and the pattern image it lends kept alive.
+// A fill or stroke style as the recorder borrows it, with the pattern image it lends kept alive. A gradient lends its
+// color stops, which do not change while the recorder borrows them.
class LentPaint {
AK_MAKE_NONCOPYABLE(LentPaint);
AK_MAKE_NONMOVABLE(LentPaint);
@@ -72,58 +77,34 @@ public:
m_paint.color = color;
}
- explicit LentPaint(Gfx::PaintStyle const& paint_style)
+ explicit LentPaint(FillOrStrokeStyle const& style)
{
- if (auto const* solid_color = as_if<Gfx::SolidColorPaintStyle>(paint_style)) {
- m_paint.kind = Compositing::Canvas2DPaintKind::Color;
- m_paint.color = solid_color->color();
- } else if (auto const* linear_gradient = as_if<Gfx::CanvasLinearGradientPaintStyle>(paint_style)) {
- m_paint.kind = Compositing::Canvas2DPaintKind::LinearGradient;
- m_paint.start_point = linear_gradient->start_point();
- m_paint.end_point = linear_gradient->end_point();
- lend_color_stops(*linear_gradient);
- } else if (auto const* radial_gradient = as_if<Gfx::CanvasRadialGradientPaintStyle>(paint_style)) {
- m_paint.kind = Compositing::Canvas2DPaintKind::RadialGradient;
- m_paint.start_point = radial_gradient->start_center();
- m_paint.start_radius = radial_gradient->start_radius();
- m_paint.end_point = radial_gradient->end_center();
- m_paint.end_radius = radial_gradient->end_radius();
- lend_color_stops(*radial_gradient);
- } else if (auto const* conic_gradient = as_if<Gfx::CanvasConicGradientPaintStyle>(paint_style)) {
- m_paint.kind = Compositing::Canvas2DPaintKind::ConicGradient;
- m_paint.start_point = conic_gradient->center();
- m_paint.start_angle = conic_gradient->start_angle();
- lend_color_stops(*conic_gradient);
- } else if (auto const* pattern = as_if<Gfx::CanvasPatternPaintStyle>(paint_style)) {
- m_paint.kind = Compositing::Canvas2DPaintKind::Pattern;
- m_paint.pattern_repetition = static_cast<Compositing::Canvas2DPatternRepetition>(to_underlying(pattern->repetition()));
- m_pattern_image = pattern->image();
- if (m_pattern_image.has_value())
- m_paint.pattern_image = &m_pattern_image.value();
- if (auto const& transform = pattern->transform(); transform.has_value()) {
- m_paint.has_pattern_transform = true;
- m_paint.pattern_transform = *transform;
- }
- } else {
- VERIFY_NOT_REACHED();
- }
+ 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> canvas_pattern) {
+ auto paint_style = canvas_pattern->to_gfx_paint_style();
+ auto const& pattern = as<Gfx::CanvasPatternPaintStyle>(*paint_style);
+ m_paint.kind = Compositing::Canvas2DPaintKind::Pattern;
+ m_paint.pattern_repetition = static_cast<Compositing::Canvas2DPatternRepetition>(to_underlying(pattern.repetition()));
+ m_pattern_image = pattern.image();
+ if (m_pattern_image.has_value())
+ m_paint.pattern_image = &m_pattern_image.value();
+ if (auto const& transform = pattern.transform(); transform.has_value()) {
+ m_paint.has_pattern_transform = true;
+ m_paint.pattern_transform = *transform;
+ }
+ });
}
FfiCanvas2DPaint const* ptr() const { return &m_paint; }
private:
- void lend_color_stops(Gfx::GradientPaintStyle const& gradient)
- {
- m_color_stop_colors.ensure_capacity(gradient.color_stops().size());
- m_color_stop_positions.ensure_capacity(gradient.color_stops().size());
- for (auto const& color_stop : gradient.color_stops()) {
- m_color_stop_colors.unchecked_append(color_stop.color);
- m_color_stop_positions.unchecked_append(color_stop.position);
- }
- m_paint.color_stop_colors = m_color_stop_colors.span();
- m_paint.color_stop_positions = m_color_stop_positions.span();
- }
-
FfiCanvas2DPaint m_paint {
.kind = Compositing::Canvas2DPaintKind::Color,
.pattern_repetition = Compositing::Canvas2DPatternRepetition::Repeat,
@@ -139,8 +120,6 @@ private:
.pattern_image = nullptr,
.pattern_transform = {},
};
- Vector<Gfx::Color, 8> m_color_stop_colors;
- Vector<float, 8> m_color_stop_positions;
Optional<Gfx::DecodedImageFrame> m_pattern_image;
};
@@ -225,10 +204,10 @@ void Canvas2DRecorder::prepare_to_record()
web_canvas_2d_recorder_prepare_to_record(m_recorder);
}
-void Canvas2DRecorder::fill_path(Gfx::Path const& path, Gfx::PaintStyle const& paint_style, Gfx::WindingRule winding_rule, Canvas2DCompositing const& compositing)
+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 { paint_style };
+ 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);
}
@@ -241,10 +220,10 @@ void Canvas2DRecorder::fill_path_shadow(Gfx::Path const& path, Gfx::Color color,
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, Gfx::PaintStyle const& paint_style, Canvas2DStroke const& stroke, Canvas2DCompositing const& 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 { paint_style };
+ 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);
@@ -259,9 +238,9 @@ void Canvas2DRecorder::stroke_path_shadow(Gfx::Path const& path, Gfx::Color colo
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, Gfx::PaintStyle const& paint_style, Canvas2DCompositing const& 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 { paint_style };
+ LentPaint paint { style };
auto lent_compositing = lend(compositing);
web_canvas_2d_recorder_draw_glyph_run(m_recorder, &font, glyphs, translation, paint.ptr(), &lent_compositing);
}
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.h b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.h
index 31caef5ab49..b4e9d68b261 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.h
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.h
@@ -27,12 +27,12 @@
namespace Gfx {
class Filter;
-class PaintStyle;
}
namespace Web::HTML {
+struct FillOrStrokeStyle;
struct RustCanvas2DRecorder;
// How a draw composites onto the canvas.
@@ -74,12 +74,12 @@ public:
// 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&, Gfx::PaintStyle const&, Gfx::WindingRule, Canvas2DCompositing const&);
+ 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&, Gfx::PaintStyle const&, Canvas2DStroke const&, 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, Gfx::PaintStyle const&, 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&);
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.cpp
index 524ed5795d1..d6012ef38ca 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasFillStrokeStyles.cpp
@@ -90,15 +90,25 @@ CanvasFillStrokeStyles::FillOrStrokeStyleVariant CanvasFillStrokeStyles::stroke_
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);
diff --git a/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp b/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp
index 8786777f7da..3c0389e2e61 100644
--- a/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp
@@ -8,17 +8,12 @@
namespace Web::HTML {
-NonnullRefPtr<Gfx::PaintStyle> FillOrStrokeStyle::to_gfx_paint_style()
+bool FillOrStrokeStyle::is_visible() const
{
return m_fill_or_stroke_style.visit(
- [&](Gfx::Color color) -> NonnullRefPtr<Gfx::PaintStyle> {
- if (!m_color_paint_style)
- m_color_paint_style = Gfx::SolidColorPaintStyle::create(color).release_value_but_fixme_should_propagate_errors();
- return *m_color_paint_style;
- },
- [&](auto handle) {
- return handle->to_gfx_paint_style();
- });
+ [](Gfx::Color color) { return color.alpha() > 0; },
+ [](GC::Ref<CanvasGradient> gradient) { return gradient->is_visible(); },
+ [](GC::Ref<CanvasPattern> pattern) { return pattern->to_gfx_paint_style()->is_visible(); });
}
Gfx::Color FillOrStrokeStyle::to_color_but_fixme_should_accept_any_paint_style() const
diff --git a/Libraries/LibWeb/HTML/Canvas/DrawingState.h b/Libraries/LibWeb/HTML/Canvas/DrawingState.h
index 58e9a1ef0e4..3c5abd91b87 100644
--- a/Libraries/LibWeb/HTML/Canvas/DrawingState.h
+++ b/Libraries/LibWeb/HTML/Canvas/DrawingState.h
@@ -31,7 +31,10 @@ struct FillOrStrokeStyle {
{
}
- NonnullRefPtr<Gfx::PaintStyle> to_gfx_paint_style();
+ 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;
@@ -57,7 +60,6 @@ struct FillOrStrokeStyle {
private:
FillOrStrokeVariant m_fill_or_stroke_style;
- RefPtr<Gfx::PaintStyle> m_color_paint_style { nullptr };
};
// https://html.spec.whatwg.org/multipage/canvas.html#drawing-state
diff --git a/Libraries/LibWeb/HTML/CanvasGradient.cpp b/Libraries/LibWeb/HTML/CanvasGradient.cpp
index 76eef0ea8d6..163d52ef486 100644
--- a/Libraries/LibWeb/HTML/CanvasGradient.cpp
+++ b/Libraries/LibWeb/HTML/CanvasGradient.cpp
@@ -5,77 +5,61 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/QuickSort.h>
-#include <LibGC/Heap.h>
+#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>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(CanvasGradient);
+extern "C" {
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createradialgradient
-WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> CanvasGradient::create_radial(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);
+// 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);
- auto radial_gradient = TRY_OR_THROW_OOM(JS::VM::the(), Gfx::CanvasRadialGradientPaintStyle::create(Gfx::FloatPoint { x0, y0 }, r0, Gfx::FloatPoint { x1, y1 }, r1));
- return GC::Heap::the().allocate<CanvasGradient>(*radial_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);
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createlineargradient
-WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> CanvasGradient::create_linear(double x0, double y0, double x1, double y1)
+static JSVM* vm()
{
- auto linear_gradient = TRY_OR_THROW_OOM(JS::VM::the(), Gfx::CanvasLinearGradientPaintStyle::create(Gfx::FloatPoint { x0, y0 }, Gfx::FloatPoint { x1, y1 }));
- return GC::Heap::the().allocate<CanvasGradient>(*linear_gradient);
+ return JS::HostABI::vm_to_abi(JS::VM::the());
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createconicgradient
-WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> CanvasGradient::create_conic(double start_angle, double x, double y)
+GC::Ref<CanvasGradient> CanvasGradient::create_linear(double x0, double y0, double x1, double y1)
{
- auto conic_gradient = TRY_OR_THROW_OOM(JS::VM::the(), Gfx::CanvasConicGradientPaintStyle::create(Gfx::FloatPoint { x, y }, start_angle));
- return GC::Heap::the().allocate<CanvasGradient>(*conic_gradient);
+ return *static_cast<CanvasGradient*>(web_canvas_gradient_create_linear(vm(), x0, y0, x1, y1));
}
-CanvasGradient::CanvasGradient(Gfx::GradientPaintStyle& gradient)
- : m_gradient(gradient)
+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));
}
-CanvasGradient::~CanvasGradient() = default;
-
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-canvasgradient-addcolorstop
-WebIDL::ExceptionOr<void> CanvasGradient::add_color_stop(double offset, Utf16String const& color)
+GC::Ref<CanvasGradient> CanvasGradient::create_conic(double start_angle, double x, double y)
{
- // 1. If the offset is less than 0 or greater than 1, then throw an "IndexSizeError" DOMException.
- if (offset < 0 || offset > 1)
- return WebIDL::IndexSizeError::create("CanvasGradient color stop offset out of bounds"_utf16);
+ return *static_cast<CanvasGradient*>(web_canvas_gradient_create_conic(vm(), start_angle, x, y));
+}
- // 2. Let parsed color be the result of parsing color.
- // https://drafts.csswg.org/css-color/#parse-a-css-color-value
- auto const maybe_color = parse_css_value(CSS::Parser::ParsingParams { CSS::Parser::SpecialContext::CanvasContextGenericValue }, color.utf16_view(), CSS::PropertyID::Color);
+bool CanvasGradient::is_visible() const
+{
+ return web_canvas_gradient_is_visible(const_cast<CanvasGradient*>(this));
+}
- // 3. If parsed color is failure, throw a "SyntaxError" DOMException.
+// 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 WebIDL::SyntaxError::create("Could not parse color for CanvasGradient"_utf16);
-
- auto const parsed_color = maybe_color->to_color({}).value();
-
- // 4. Place a new stop on the gradient, at offset offset relative to the whole gradient, and with the color parsed color.
- TRY_OR_THROW_OOM(JS::VM::the(), m_gradient->add_color_stop(offset, parsed_color));
-
- // FIXME: If multiple stops are added at the same offset on a gradient, then they must be placed in the order added,
- // with the first one closest to the start of the gradient, and each subsequent one infinitesimally further along
- // towards the end point (in effect causing all but the first and last stop added at each point to be ignored).
-
- return {};
+ 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
index 54e1f2908cf..daa8f165db4 100644
--- a/Libraries/LibWeb/HTML/CanvasGradient.h
+++ b/Libraries/LibWeb/HTML/CanvasGradient.h
@@ -7,32 +7,25 @@
#pragma once
-#include <AK/Utf16View.h>
-#include <LibGfx/PaintStyle.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/CanvasGradient.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Export.h>
namespace Web::HTML {
-class CanvasGradient final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CanvasGradient, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(CanvasGradient);
+// 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 WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> create_radial(double x0, double y0, double r0, double x1, double y1, double r1);
- static WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> create_linear(double x0, double y0, double x1, double y1);
- static WebIDL::ExceptionOr<GC::Ref<CanvasGradient>> create_conic(double start_angle, double x, double y);
+ 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);
- WebIDL::ExceptionOr<void> add_color_stop(double offset, Utf16String const& color);
-
- ~CanvasGradient();
-
- NonnullRefPtr<Gfx::PaintStyle> to_gfx_paint_style() { return m_gradient; }
-
-private:
- CanvasGradient(Gfx::GradientPaintStyle& gradient);
-
- NonnullRefPtr<Gfx::GradientPaintStyle> m_gradient;
+ // Whether one of the color stops is not transparent.
+ bool is_visible() const;
};
}
diff --git a/Libraries/LibWeb/HTML/CanvasGradient.idl b/Libraries/LibWeb/HTML/CanvasGradient.idl
index fb26d9691ec..13685fdf251 100644
--- a/Libraries/LibWeb/HTML/CanvasGradient.idl
+++ b/Libraries/LibWeb/HTML/CanvasGradient.idl
@@ -1,5 +1,5 @@
// https://html.spec.whatwg.org/multipage/canvas.html#canvasgradient
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface CanvasGradient {
// opaque object
undefined addColorStop(double offset, DOMString color);
diff --git a/Tests/LibWeb/Text/expected/canvas/gradient-add-color-stop-errors.txt b/Tests/LibWeb/Text/expected/canvas/gradient-add-color-stop-errors.txt
new file mode 100644
index 00000000000..653d5ad4c7b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/canvas/gradient-add-color-stop-errors.txt
@@ -0,0 +1,18 @@
+addColorStop(0, red): added
+addColorStop(1, blue): added
+addColorStop(0, green): added
+addColorStop(0.5, lime): added
+addColorStop(NaN, red): TypeError
+addColorStop(Infinity, red): TypeError
+addColorStop(-Infinity, red): TypeError
+addColorStop(-0.1, red): DOMException IndexSizeError (code 1)
+addColorStop(1.1, red): DOMException IndexSizeError (code 1)
+addColorStop(0.5, not a color): DOMException SyntaxError (code 12)
+addColorStop(0.5, currentcolor): added
+addColorStop on a plain object: TypeError
+addColorStop with one argument: TypeError
+gradient is a CanvasGradient: true
+toString tag: [object CanvasGradient]
+new CanvasGradient(): TypeError
+createRadialGradient with a negative radius: DOMException IndexSizeError
+createLinearGradient with NaN: TypeError
diff --git a/Tests/LibWeb/Text/expected/canvas/gradient-stops-at-one-offset-keep-their-order.txt b/Tests/LibWeb/Text/expected/canvas/gradient-stops-at-one-offset-keep-their-order.txt
new file mode 100644
index 00000000000..56f6e5c0617
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/canvas/gradient-stops-at-one-offset-keep-their-order.txt
@@ -0,0 +1,8 @@
+x=5: rgba(255, 0, 0, 255)
+x=20: rgba(255, 0, 0, 255)
+x=30: rgba(0, 255, 0, 255)
+x=45: rgba(0, 255, 0, 255)
+x=55: rgba(0, 0, 255, 255)
+x=70: rgba(0, 0, 255, 255)
+x=80: rgba(255, 255, 0, 255)
+x=95: rgba(255, 255, 0, 255)
diff --git a/Tests/LibWeb/Text/input/canvas/gradient-add-color-stop-errors.html b/Tests/LibWeb/Text/input/canvas/gradient-add-color-stop-errors.html
new file mode 100644
index 00000000000..f4c86098509
--- /dev/null
+++ b/Tests/LibWeb/Text/input/canvas/gradient-add-color-stop-errors.html
@@ -0,0 +1,59 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const context = document.createElement("canvas").getContext("2d");
+ const gradient = context.createLinearGradient(0, 0, 8, 0);
+
+ function tryAddColorStop(offset, color) {
+ try {
+ gradient.addColorStop(offset, color);
+ println(`addColorStop(${String(offset)}, ${color}): added`);
+ } catch (e) {
+ const kind = e instanceof DOMException ? `DOMException ${e.name} (code ${e.code})` : e.constructor.name;
+ println(`addColorStop(${String(offset)}, ${color}): ${kind}`);
+ }
+ }
+
+ tryAddColorStop(0, "red");
+ tryAddColorStop(1, "blue");
+ tryAddColorStop(-0, "green");
+ tryAddColorStop("0.5", "lime");
+ tryAddColorStop(NaN, "red");
+ tryAddColorStop(Infinity, "red");
+ tryAddColorStop(-Infinity, "red");
+ tryAddColorStop(-0.1, "red");
+ tryAddColorStop(1.1, "red");
+ tryAddColorStop(0.5, "not a color");
+ tryAddColorStop(0.5, "currentcolor");
+
+ try {
+ CanvasGradient.prototype.addColorStop.call({}, 0, "red");
+ } catch (e) {
+ println(`addColorStop on a plain object: ${e.constructor.name}`);
+ }
+ try {
+ gradient.addColorStop(0);
+ } catch (e) {
+ println(`addColorStop with one argument: ${e.constructor.name}`);
+ }
+
+ println(`gradient is a CanvasGradient: ${gradient instanceof CanvasGradient}`);
+ println(`toString tag: ${Object.prototype.toString.call(gradient)}`);
+ try {
+ new CanvasGradient();
+ } catch (e) {
+ println(`new CanvasGradient(): ${e.constructor.name}`);
+ }
+ try {
+ context.createRadialGradient(0, 0, -1, 0, 0, 1);
+ } catch (e) {
+ println(`createRadialGradient with a negative radius: DOMException ${e.name}`);
+ }
+ try {
+ context.createLinearGradient(0, 0, NaN, 0);
+ } catch (e) {
+ println(`createLinearGradient with NaN: ${e.constructor.name}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/canvas/gradient-stops-at-one-offset-keep-their-order.html b/Tests/LibWeb/Text/input/canvas/gradient-stops-at-one-offset-keep-their-order.html
new file mode 100644
index 00000000000..25b5922b964
--- /dev/null
+++ b/Tests/LibWeb/Text/input/canvas/gradient-stops-at-one-offset-keep-their-order.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const canvas = document.createElement("canvas");
+ canvas.width = 100;
+ canvas.height = 1;
+ const context = canvas.getContext("2d");
+
+ // NB: Eight stops, which are hard bands of four colors. The stops at each inner offset must stay in the order
+ // they were added in, so that each band has one color.
+ const gradient = context.createLinearGradient(0, 0, 100, 0);
+ gradient.addColorStop(0, "red");
+ gradient.addColorStop(0.25, "red");
+ gradient.addColorStop(0.25, "lime");
+ gradient.addColorStop(0.5, "lime");
+ gradient.addColorStop(0.5, "blue");
+ gradient.addColorStop(0.75, "blue");
+ gradient.addColorStop(0.75, "yellow");
+ gradient.addColorStop(1, "yellow");
+
+ context.fillStyle = gradient;
+ context.fillRect(0, 0, 100, 1);
+
+ for (const x of [5, 20, 30, 45, 55, 70, 80, 95]) {
+ const [r, g, b, a] = context.getImageData(x, 0, 1, 1).data;
+ println(`x=${x}: rgba(${r}, ${g}, ${b}, ${a})`);
+ }
+ });
+</script>