Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(canvas): rasterize 2D path fills and strokes
BibekPathakebe38d25c7ff
diff --git a/moli-canvas/src/rect.rs b/moli-canvas/src/rect.rsindex a1569637d..cac941fdc 100644--- a/moli-canvas/src/rect.rs+++ b/moli-canvas/src/rect.rs@@ -2,43 +2,261 @@ use crate::types::{CanvasRect, surface_matches_len};pub fn canonicalize_fill_style(raw: &str) -> Option<String> {let value = raw.trim().to_ascii_lowercase();- match value.as_str() {- "black" => Some("#000000".to_owned()),- "red" => Some("#ff0000".to_owned()),- "rebeccapurple" => Some("#663399".to_owned()),- _ if value.starts_with('#') => canonical_hex_color(&value),- _ => None,+ if value.starts_with('#') {+ return canonical_hex_color(&value);+ }+ if let Some((red, green, blue)) = css_named_color_rgb(&value) {+ return Some(format!("#{red:02x}{green:02x}{blue:02x}"));+ }+ if value == "transparent" {+ return Some("rgba(0, 0, 0, 0)".to_owned());}+ if let Some((red, green, blue, alpha)) = parse_rgb_function(&value) {+ if alpha == u8::MAX {+ return Some(format!("rgb({red}, {green}, {blue})"));+ }+ let alpha = (f64::from(alpha) / 255.0 * 100.0).round() / 100.0;+ return Some(format!("rgba({red}, {green}, {blue}, {alpha:.2})"));+ }+ None}pub fn fill_style_rgba(style: &str) -> [u8; 4] {- if let Some(hex) = style.strip_prefix('#')- && hex.len() == 6- {- return [- u8::from_str_radix(&hex[0..2], 16).unwrap_or(0),- u8::from_str_radix(&hex[2..4], 16).unwrap_or(0),- u8::from_str_radix(&hex[4..6], 16).unwrap_or(0),- 255,- ];- }- if let Some(body) = style- .strip_prefix("rgba(")- .and_then(|value| value.strip_suffix(')'))- {- let parts = body.split(',').map(|part| part.trim()).collect::<Vec<_>>();- if parts.len() == 4 {- let red = parts[0].parse::<u8>().unwrap_or(0);- let green = parts[1].parse::<u8>().unwrap_or(0);- let blue = parts[2].parse::<u8>().unwrap_or(0);- let alpha =- (parts[3].parse::<f64>().unwrap_or(1.0).clamp(0.0, 1.0) * 255.0).round() as u8;- return [red, green, blue, alpha];- }+ let value = style.trim().to_ascii_lowercase();+ if let Some(rgba) = hex_color_rgba(&value) {+ return rgba;+ }+ if let Some((red, green, blue, alpha)) = parse_rgb_function(&value) {+ return [red, green, blue, alpha];+ }+ if let Some((red, green, blue)) = css_named_color_rgb(&value) {+ return [red, green, blue, 255];+ }+ if value == "transparent" {+ return [0, 0, 0, 0];}[0, 0, 0, 255]}+fn hex_color_rgba(value: &str) -> Option<[u8; 4]> {+ let hex = value.strip_prefix('#')?;+ if hex.is_empty() || !hex.chars().all(|char| char.is_ascii_hexdigit()) {+ return None;+ }+ let (red, green, blue, alpha) = match hex.len() {+ 3 => (+ hex[0..1].repeat(2),+ hex[1..2].repeat(2),+ hex[2..3].repeat(2),+ "ff".to_owned(),+ ),+ 4 => (+ hex[0..1].repeat(2),+ hex[1..2].repeat(2),+ hex[2..3].repeat(2),+ hex[3..4].repeat(2),+ ),+ 6 => (+ hex[0..2].to_owned(),+ hex[2..4].to_owned(),+ hex[4..6].to_owned(),+ "ff".to_owned(),+ ),+ 8 => (+ hex[0..2].to_owned(),+ hex[2..4].to_owned(),+ hex[4..6].to_owned(),+ hex[6..8].to_owned(),+ ),+ _ => return None,+ };+ Some([+ u8::from_str_radix(&red, 16).ok()?,+ u8::from_str_radix(&green, 16).ok()?,+ u8::from_str_radix(&blue, 16).ok()?,+ u8::from_str_radix(&alpha, 16).ok()?,+ ])+}++fn parse_rgb_function(value: &str) -> Option<(u8, u8, u8, u8)> {+ let body = value+ .strip_prefix("rgb(")+ .or_else(|| value.strip_prefix("rgba("))?+ .strip_suffix(')')?;+ let parts = body.split(',').map(|part| part.trim()).collect::<Vec<_>>();+ let red = parse_channel(parts.first()?)?;+ let green = parse_channel(parts.get(1)?)?;+ let blue = parse_channel(parts.get(2)?)?;+ let alpha = match parts.get(3) {+ Some(alpha) => {+ let parsed = if let Some(percent) = alpha.strip_suffix('%') {+ percent.trim().parse::<f64>().ok()? / 100.0+ } else {+ alpha.trim().parse::<f64>().ok()?+ };+ (parsed.clamp(0.0, 1.0) * 255.0).round() as u8+ }+ None => 255,+ };+ Some((red, green, blue, alpha))+}++fn parse_channel(value: &str) -> Option<u8> {+ if let Some(percent) = value.strip_suffix('%') {+ let value = percent.trim().parse::<f64>().ok()?;+ return Some((value.clamp(0.0, 100.0) / 100.0 * 255.0).round() as u8);+ }+ let value = value.trim().parse::<f64>().ok()?;+ Some(value.clamp(0.0, 255.0) as u8)+}++fn css_named_color_rgb(value: &str) -> Option<(u8, u8, u8)> {+ Some(match value.to_ascii_lowercase().as_str() {+ "aliceblue" => (240, 248, 255),+ "antiquewhite" => (250, 235, 215),+ "aqua" => (0, 255, 255),+ "aquamarine" => (127, 255, 212),+ "azure" => (240, 255, 255),+ "beige" => (245, 245, 220),+ "bisque" => (255, 228, 196),+ "black" => (0, 0, 0),+ "blanchedalmond" => (255, 235, 205),+ "blue" => (0, 0, 255),+ "blueviolet" => (138, 43, 226),+ "brown" => (165, 42, 42),+ "burlywood" => (222, 184, 135),+ "cadetblue" => (95, 158, 160),+ "chartreuse" => (127, 255, 0),+ "chocolate" => (210, 105, 30),+ "coral" => (255, 127, 80),+ "cornflowerblue" => (100, 149, 237),+ "cornsilk" => (255, 248, 220),+ "crimson" => (220, 20, 60),+ "cyan" => (0, 255, 255),+ "darkblue" => (0, 0, 139),+ "darkcyan" => (0, 139, 139),+ "darkgoldenrod" => (184, 134, 11),+ "darkgray" | "darkgrey" => (169, 169, 169),+ "darkgreen" => (0, 100, 0),+ "darkkhaki" => (189, 183, 107),+ "darkmagenta" => (139, 0, 139),+ "darkolivegreen" => (85, 107, 47),+ "darkorange" => (255, 140, 0),+ "darkorchid" => (153, 50, 204),+ "darkred" => (139, 0, 0),+ "darksalmon" => (233, 150, 122),+ "darkseagreen" => (143, 188, 143),+ "darkslateblue" => (72, 61, 139),+ "darkslategray" | "darkslategrey" => (47, 79, 79),+ "darkturquoise" => (0, 206, 209),+ "darkviolet" => (148, 0, 211),+ "deeppink" => (255, 20, 147),+ "deepskyblue" => (0, 191, 255),+ "dimgray" | "dimgrey" => (105, 105, 105),+ "dodgerblue" => (30, 144, 255),+ "firebrick" => (178, 34, 34),+ "floralwhite" => (255, 250, 240),+ "forestgreen" => (34, 139, 34),+ "fuchsia" => (255, 0, 255),+ "gainsboro" => (220, 220, 220),+ "ghostwhite" => (248, 248, 255),+ "gold" => (255, 215, 0),+ "goldenrod" => (218, 165, 32),+ "gray" | "grey" => (128, 128, 128),+ "green" => (0, 128, 0),+ "greenyellow" => (173, 255, 47),+ "honeydew" => (240, 255, 240),+ "hotpink" => (255, 105, 180),+ "indianred" => (205, 92, 92),+ "indigo" => (75, 0, 130),+ "ivory" => (255, 255, 240),+ "khaki" => (240, 230, 140),+ "lavender" => (230, 230, 250),+ "lavenderblush" => (255, 240, 245),+ "lawngreen" => (124, 252, 0),+ "lemonchiffon" => (255, 250, 205),+ "lightblue" => (173, 216, 230),+ "lightcoral" => (240, 128, 128),+ "lightcyan" => (224, 255, 255),+ "lightgoldenrodyellow" => (250, 250, 210),+ "lightgray" | "lightgrey" => (211, 211, 211),+ "lightgreen" => (144, 238, 144),+ "lightpink" => (255, 182, 193),+ "lightsalmon" => (255, 160, 122),+ "lightseagreen" => (32, 178, 170),+ "lightskyblue" => (135, 206, 250),+ "lightslategray" | "lightslategrey" => (119, 136, 153),+ "lightsteelblue" => (176, 196, 222),+ "lightyellow" => (255, 255, 224),+ "lime" => (0, 255, 0),+ "limegreen" => (50, 205, 50),+ "linen" => (250, 240, 230),+ "magenta" => (255, 0, 255),+ "maroon" => (128, 0, 0),+ "mediumaquamarine" => (102, 205, 170),+ "mediumblue" => (0, 0, 205),+ "mediumorchid" => (186, 85, 211),+ "mediumpurple" => (147, 112, 219),+ "mediumseagreen" => (60, 179, 113),+ "mediumslateblue" => (123, 104, 238),+ "mediumspringgreen" => (0, 250, 154),+ "mediumturquoise" => (72, 209, 204),+ "mediumvioletred" => (199, 21, 133),+ "midnightblue" => (25, 25, 112),+ "mintcream" => (245, 255, 250),+ "mistyrose" => (255, 228, 225),+ "moccasin" => (255, 228, 181),+ "navajowhite" => (255, 222, 173),+ "navy" => (0, 0, 128),+ "oldlace" => (253, 245, 230),+ "olive" => (128, 128, 0),+ "olivedrab" => (107, 142, 35),+ "orange" => (255, 165, 0),+ "orangered" => (255, 69, 0),+ "orchid" => (218, 112, 214),+ "palegoldenrod" => (238, 232, 170),+ "palegreen" => (152, 251, 152),+ "paleturquoise" => (175, 238, 238),+ "palevioletred" => (219, 112, 147),+ "papayawhip" => (255, 239, 213),+ "peachpuff" => (255, 218, 185),+ "peru" => (205, 133, 63),+ "pink" => (255, 192, 203),+ "plum" => (221, 160, 221),+ "powderblue" => (176, 224, 230),+ "purple" => (128, 0, 128),+ "rebeccapurple" => (102, 51, 153),+ "red" => (255, 0, 0),+ "rosybrown" => (188, 143, 143),+ "royalblue" => (65, 105, 225),+ "saddlebrown" => (139, 69, 19),+ "salmon" => (250, 128, 114),+ "sandybrown" => (244, 164, 96),+ "seagreen" => (46, 139, 87),+ "seashell" => (255, 245, 238),+ "sienna" => (160, 82, 45),+ "silver" => (192, 192, 192),+ "skyblue" => (135, 206, 235),+ "slateblue" => (106, 90, 205),+ "slategray" | "slategrey" => (112, 128, 144),+ "snow" => (255, 250, 250),+ "springgreen" => (0, 255, 127),+ "steelblue" => (70, 130, 180),+ "tan" => (210, 180, 140),+ "teal" => (0, 128, 128),+ "thistle" => (216, 191, 216),+ "tomato" => (255, 99, 71),+ "turquoise" => (64, 224, 208),+ "violet" => (238, 130, 238),+ "wheat" => (245, 222, 179),+ "white" => (255, 255, 255),+ "whitesmoke" => (245, 245, 245),+ "yellow" => (255, 255, 0),+ "yellowgreen" => (154, 205, 50),+ _ => return None,+ })+}+pub fn normalize_rect(x: f64, y: f64, width: f64, height: f64) -> Option<CanvasRect> {if !x.is_finite() || !y.is_finite() || !width.is_finite() || !height.is_finite() {return None;diff --git a/moli-renderer-v8/src/context_bootstrap/canvas.rs b/moli-renderer-v8/src/context_bootstrap/canvas.rsindex 89db953f8..c5a813e17 100644--- a/moli-renderer-v8/src/context_bootstrap/canvas.rs+++ b/moli-renderer-v8/src/context_bootstrap/canvas.rs@@ -17,9 +17,21 @@ const CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT: &str =const CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT: &str = "__moliCanvasContextGlobalAlpha";const CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT: &str ="__moliCanvasContextGlobalCompositeOperation";+const CANVAS_CONTEXT_LINE_WIDTH_SLOT: &str = "__moliCanvasContextLineWidth";+const CANVAS_CONTEXT_LINE_CAP_SLOT: &str = "__moliCanvasContextLineCap";+const CANVAS_CONTEXT_LINE_JOIN_SLOT: &str = "__moliCanvasContextLineJoin";+const CANVAS_CONTEXT_MITER_LIMIT_SLOT: &str = "__moliCanvasContextMiterLimit";+const CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT: &str = "__moliCanvasContextLineDashOffset";+const CANVAS_CONTEXT_STROKE_STYLE_SLOT: &str = "__moliCanvasContextStrokeStyle";pub(crate) const DEFAULT_GLOBAL_ALPHA: f64 = 1.0;pub(crate) const DEFAULT_GLOBAL_COMPOSITE_OPERATION: &str = "source-over";+pub(crate) const DEFAULT_LINE_WIDTH: f64 = 1.0;+pub(crate) const DEFAULT_LINE_CAP: &str = "butt";+pub(crate) const DEFAULT_LINE_JOIN: &str = "miter";+pub(crate) const DEFAULT_MITER_LIMIT: f64 = 10.0;+pub(crate) const DEFAULT_LINE_DASH_OFFSET: f64 = 0.0;+pub(crate) const DEFAULT_STROKE_STYLE: &str = "#000000";/// Composite operations recognised by the HTML Canvas 2D spec.///@@ -179,6 +191,7 @@ mod helpers;mod image_bitmap;mod objects;mod offscreen;+mod path;mod webgl;pub(crate) use backing_store::{@@ -192,23 +205,39 @@ pub(crate) use constructors::{webgl_rendering_context_constructor_callback,};pub(crate) use context2d::{- canvas_context_clear_rect_callback, canvas_context_create_image_data_callback,- canvas_context_create_linear_gradient_callback, canvas_context_draw_image_callback,- canvas_context_fill_rect_callback, canvas_context_fill_style_getter_callback,- canvas_context_fill_style_setter_callback, canvas_context_fill_text_callback,- canvas_context_font_getter_callback, canvas_context_font_setter_callback,- canvas_context_get_image_data_callback, canvas_context_get_line_dash_callback,- canvas_context_global_alpha_getter_callback, canvas_context_global_alpha_setter_callback,+ canvas_context_arc_callback, canvas_context_arc_to_callback,+ canvas_context_begin_path_callback, canvas_context_bezier_curve_to_callback,+ canvas_context_clear_rect_callback, canvas_context_close_path_callback,+ canvas_context_create_image_data_callback, canvas_context_create_linear_gradient_callback,+ canvas_context_draw_image_callback, canvas_context_ellipse_callback,+ canvas_context_fill_callback, canvas_context_fill_rect_callback,+ canvas_context_fill_style_getter_callback, canvas_context_fill_style_setter_callback,+ canvas_context_fill_text_callback, canvas_context_font_getter_callback,+ canvas_context_font_setter_callback, canvas_context_get_image_data_callback,+ canvas_context_get_line_dash_callback, canvas_context_global_alpha_getter_callback,+ canvas_context_global_alpha_setter_callback,canvas_context_global_composite_operation_getter_callback,canvas_context_global_composite_operation_setter_callback,canvas_context_image_smoothing_enabled_getter_callback,canvas_context_image_smoothing_enabled_setter_callback,canvas_context_image_smoothing_quality_getter_callback,canvas_context_image_smoothing_quality_setter_callback,- canvas_context_is_point_in_path_callback, canvas_context_measure_text_callback,+ canvas_context_is_point_in_path_callback, canvas_context_line_cap_getter_callback,+ canvas_context_line_cap_setter_callback, canvas_context_line_dash_offset_getter_callback,+ canvas_context_line_dash_offset_setter_callback, canvas_context_line_join_getter_callback,+ canvas_context_line_join_setter_callback, canvas_context_line_to_callback,+ canvas_context_line_width_getter_callback, canvas_context_line_width_setter_callback,+ canvas_context_measure_text_callback, canvas_context_miter_limit_getter_callback,+ canvas_context_miter_limit_setter_callback, canvas_context_move_to_callback,canvas_context_noop_callback, canvas_context_put_image_data_callback,- canvas_context_rect_callback, canvas_context_set_line_dash_callback,- canvas_context_stroke_text_callback, canvas_gradient_add_color_stop_callback,+ canvas_context_quadratic_curve_to_callback, canvas_context_rect_callback,+ canvas_context_reset_transform_callback, canvas_context_rotate_callback,+ canvas_context_scale_callback, canvas_context_set_line_dash_callback,+ canvas_context_set_transform_callback, canvas_context_stroke_callback,+ canvas_context_stroke_rect_callback, canvas_context_stroke_style_getter_callback,+ canvas_context_stroke_style_setter_callback, canvas_context_stroke_text_callback,+ canvas_context_transform_callback, canvas_context_translate_callback,+ canvas_gradient_add_color_stop_callback,};pub(crate) use image_bitmap::window_create_image_bitmap_callback;pub(crate) use objects::{diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rs b/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rsindex 69011b78b..5ce983ff0 100644--- a/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rs+++ b/moli-renderer-v8/src/context_bootstrap/canvas/context2d.rs@@ -2,6 +2,9 @@ use super::backing_store::{canvas_like_pixels_copy, canvas_owner_from_context, with_canvas_like_pixels_mut,};use super::helpers::{canonical_canvas_fill_style, canvas_unrestricted_double_arg};+use super::path::{+ CANVAS_CONTEXT_PATH_STATE_ID_SLOT, allocate_canvas_path_state_id, with_canvas_path_state_mut,+};use super::*;use crate::context_bootstrap::image_data::{build_image_data_object, build_image_data_object_with_bytes, image_data_bytes_from_object,@@ -15,6 +18,10 @@ use moli_canvas::{blit_image_data, byte_len, data_image_rgba8_pixels, draw_text, extract_image_data,fill_style_rgba, measure_text_width, normalize_rect as canvas_normalize_rect, paint_rect,};+use moli_layout::{+ PaintBrush, PaintColor, PaintFragment, PaintLineCap, PaintLineJoin, PaintShape, PaintSnapshot,+ PaintStroke, PaintTransform2D, PaintViewport,+};use moli_webapi_declare::WebApiObject;use std::str::FromStr;@@ -143,6 +150,137 @@ struct CanvasContextPutImageDataDirtyArgs<'s> {dirty_height: i32,}+#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.moveTo")]+struct CanvasContextMoveToArgs {+ #[webidl(required)]+ x: f64,+ #[webidl(required)]+ y: f64,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.lineTo")]+struct CanvasContextLineToArgs {+ #[webidl(required)]+ x: f64,+ #[webidl(required)]+ y: f64,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.quadraticCurveTo")]+struct CanvasContextQuadraticCurveToArgs {+ #[webidl(required)]+ cpx: f64,+ #[webidl(required)]+ cpy: f64,+ #[webidl(required)]+ x: f64,+ #[webidl(required)]+ y: f64,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.bezierCurveTo")]+struct CanvasContextBezierCurveToArgs {+ #[webidl(required)]+ cp1x: f64,+ #[webidl(required)]+ cp1y: f64,+ #[webidl(required)]+ cp2x: f64,+ #[webidl(required)]+ cp2y: f64,+ #[webidl(required)]+ x: f64,+ #[webidl(required)]+ y: f64,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.rect")]+struct CanvasContextRectPathArgs {+ #[webidl(required)]+ x: f64,+ #[webidl(required)]+ y: f64,+ #[webidl(required)]+ width: f64,+ #[webidl(required)]+ height: f64,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.arc")]+struct CanvasContextArcArgs {+ #[webidl(required)]+ x: f64,+ #[webidl(required)]+ y: f64,+ #[webidl(required)]+ radius: f64,+ #[webidl(required, name = "startAngle")]+ start_angle: f64,+ #[webidl(required, name = "endAngle")]+ end_angle: f64,+ #[webidl(default = false)]+ counterclockwise: bool,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.arcTo")]+struct CanvasContextArcToArgs {+ #[webidl(required)]+ x1: f64,+ #[webidl(required)]+ y1: f64,+ #[webidl(required)]+ x2: f64,+ #[webidl(required)]+ y2: f64,+ #[webidl(required)]+ radius: f64,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.ellipse")]+struct CanvasContextEllipseArgs {+ #[webidl(required)]+ x: f64,+ #[webidl(required)]+ y: f64,+ #[webidl(required, name = "radiusX")]+ radius_x: f64,+ #[webidl(required, name = "radiusY")]+ radius_y: f64,+ #[webidl(required)]+ rotation: f64,+ #[webidl(required, name = "startAngle")]+ start_angle: f64,+ #[webidl(required, name = "endAngle")]+ end_angle: f64,+ #[webidl(default = false)]+ counterclockwise: bool,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "CanvasRenderingContext2D.transform")]+struct CanvasContextTransformArgs {+ #[webidl(required)]+ a: f64,+ #[webidl(required)]+ b: f64,+ #[webidl(required)]+ c: f64,+ #[webidl(required)]+ d: f64,+ #[webidl(required)]+ e: f64,+ #[webidl(required)]+ f: f64,+}+fn require_canvas_context_receiver<'s>(scope: &mut v8::PinScope<'s, '_>,receiver: v8::Local<'s, v8::Object>,@@ -608,7 +746,840 @@ pub(crate) fn canvas_context_rect_callback<'s>(args: v8::FunctionCallbackArguments<'s>,_rv: v8::ReturnValue<'_, v8::Value>,) {- let _ = normalized_rect(scope, &args, "CanvasRenderingContext2D.rect");+ if !require_canvas_context_receiver(scope, args.this(), "rect") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextRectPathArgs>(scope, &args) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.rect(parsed.x, parsed.y, parsed.width, parsed.height);+ });+}++pub(crate) fn canvas_context_begin_path_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "beginPath") {+ return;+ }+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.begin_path());+}++pub(crate) fn canvas_context_close_path_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "closePath") {+ return;+ }+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.close_path());+}++pub(crate) fn canvas_context_move_to_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "moveTo") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextMoveToArgs>(scope, &args) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.move_to(parsed.x, parsed.y));+}++pub(crate) fn canvas_context_line_to_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineTo") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextLineToArgs>(scope, &args) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.line_to(parsed.x, parsed.y));+}++pub(crate) fn canvas_context_quadratic_curve_to_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "quadraticCurveTo") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextQuadraticCurveToArgs>(scope, &args) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.quadratic_curve_to(parsed.cpx, parsed.cpy, parsed.x, parsed.y);+ });+}++pub(crate) fn canvas_context_bezier_curve_to_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "bezierCurveTo") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextBezierCurveToArgs>(scope, &args) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.bezier_curve_to(+ parsed.cp1x,+ parsed.cp1y,+ parsed.cp2x,+ parsed.cp2y,+ parsed.x,+ parsed.y,+ );+ });+}++pub(crate) fn canvas_context_arc_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "arc") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextArcArgs>(scope, &args) else {+ return;+ };+ if parsed.radius < 0.0 {+ webidl::throw_index_size_error(scope);+ rv.set_undefined();+ return;+ }+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ rv.set_undefined();+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.arc(+ parsed.x,+ parsed.y,+ parsed.radius,+ parsed.start_angle,+ parsed.end_angle,+ parsed.counterclockwise,+ );+ });+ rv.set_undefined();+}++pub(crate) fn canvas_context_arc_to_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "arcTo") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextArcToArgs>(scope, &args) else {+ return;+ };+ if parsed.radius < 0.0 {+ webidl::throw_index_size_error(scope);+ rv.set_undefined();+ return;+ }+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ rv.set_undefined();+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.arc_to(parsed.x1, parsed.y1, parsed.x2, parsed.y2, parsed.radius);+ });+ rv.set_undefined();+}++pub(crate) fn canvas_context_ellipse_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "ellipse") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextEllipseArgs>(scope, &args) else {+ return;+ };+ if parsed.radius_x < 0.0 || parsed.radius_y < 0.0 {+ webidl::throw_index_size_error(scope);+ rv.set_undefined();+ return;+ }+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ rv.set_undefined();+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.ellipse(+ parsed.x,+ parsed.y,+ parsed.radius_x,+ parsed.radius_y,+ parsed.rotation,+ parsed.start_angle,+ parsed.end_angle,+ parsed.counterclockwise,+ );+ });+ rv.set_undefined();+}++pub(crate) fn canvas_context_translate_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "translate") {+ return;+ }+ let prefix = "CanvasRenderingContext2D.translate";+ let Some(x) = canvas_required_unrestricted_double_arg(scope, &args, 0, prefix) else {+ return;+ };+ let Some(y) = canvas_required_unrestricted_double_arg(scope, &args, 1, prefix) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.translate(x, y));+}++pub(crate) fn canvas_context_scale_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "scale") {+ return;+ }+ let prefix = "CanvasRenderingContext2D.scale";+ let Some(x) = canvas_required_unrestricted_double_arg(scope, &args, 0, prefix) else {+ return;+ };+ let Some(y) = canvas_required_unrestricted_double_arg(scope, &args, 1, prefix) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.scale(x, y));+}++pub(crate) fn canvas_context_rotate_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "rotate") {+ return;+ }+ let prefix = "CanvasRenderingContext2D.rotate";+ let Some(angle) = canvas_required_unrestricted_double_arg(scope, &args, 0, prefix) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.rotate(angle));+}++pub(crate) fn canvas_context_transform_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "transform") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextTransformArgs>(scope, &args) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.concatenate_transform(parsed.a, parsed.b, parsed.c, parsed.d, parsed.e, parsed.f);+ });+}++pub(crate) fn canvas_context_set_transform_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "setTransform") {+ return;+ }+ let Some(parsed) = webidl::parse_args::<CanvasContextTransformArgs>(scope, &args) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| {+ state.set_transform(parsed.a, parsed.b, parsed.c, parsed.d, parsed.e, parsed.f);+ });+}++pub(crate) fn canvas_context_reset_transform_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "resetTransform") {+ return;+ }+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ return;+ };+ with_canvas_path_state_mut(id, |state| state.reset_transform());+}++pub(crate) fn canvas_context_fill_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "fill") {+ return;+ }+ let Some(canvas) = canvas_owner_from_context(scope, args.this()) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ rv.set_undefined();+ return;+ };+ let fragment = with_canvas_path_state_mut(id, |state| {+ if state.is_empty() {+ return None;+ }+ Some(PaintFragment::Fill {+ shape: PaintShape::Path(state.paint_path()),+ brush: PaintBrush::Solid(context_fill_color(scope, args.this())),+ transform: state.transform(),+ })+ });+ if let Some(fragment) = fragment {+ rasterize_canvas_fragment(scope, canvas, fragment);+ }+ rv.set_undefined();+}++pub(crate) fn canvas_context_stroke_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "stroke") {+ return;+ }+ let Some(canvas) = canvas_owner_from_context(scope, args.this()) else {+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ rv.set_undefined();+ return;+ };+ let fragment = with_canvas_path_state_mut(id, |state| {+ if state.is_empty() {+ return None;+ }+ Some(PaintFragment::Stroke(context_stroke(+ scope,+ args.this(),+ state.paint_path(),+ state.transform(),+ )))+ });+ if let Some(fragment) = fragment {+ rasterize_canvas_fragment(scope, canvas, fragment);+ }+ rv.set_undefined();+}++pub(crate) fn canvas_context_stroke_rect_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "strokeRect") {+ return;+ }+ let Some(canvas) = canvas_owner_from_context(scope, args.this()) else {+ return;+ };+ let prefix = "CanvasRenderingContext2D.strokeRect";+ let Some(x) = canvas_required_unrestricted_double_arg(scope, &args, 0, prefix) else {+ rv.set_undefined();+ return;+ };+ let Some(y) = canvas_required_unrestricted_double_arg(scope, &args, 1, prefix) else {+ rv.set_undefined();+ return;+ };+ let Some(width) = canvas_required_unrestricted_double_arg(scope, &args, 2, prefix) else {+ rv.set_undefined();+ return;+ };+ let Some(height) = canvas_required_unrestricted_double_arg(scope, &args, 3, prefix) else {+ rv.set_undefined();+ return;+ };+ let Some(id) = ensure_canvas_context_path_state_id(scope, args.this()) else {+ rv.set_undefined();+ return;+ };+ // strokeRect must not alter the current default path.+ let (path, transform) = with_canvas_path_state_mut(id, |state| {+ let mut rect_path = state.clone();+ rect_path.begin_path();+ rect_path.rect(x, y, width, height);+ (rect_path.paint_path(), state.transform())+ });+ let stroke = context_stroke(scope, args.this(), path, transform);+ rasterize_canvas_fragment(scope, canvas, PaintFragment::Stroke(stroke));+ rv.set_undefined();+}++pub(crate) fn canvas_context_line_width_getter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineWidth getter") {+ return;+ }+ let value = context_number_slot(scope, args.this(), CANVAS_CONTEXT_LINE_WIDTH_SLOT)+ .unwrap_or(DEFAULT_LINE_WIDTH);+ rv.set(v8::Number::new(scope, value).into());+}++pub(crate) fn canvas_context_line_width_setter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineWidth setter") {+ return;+ }+ canvas_context_nonnegative_number_assign(+ scope,+ args.this(),+ args.get(0),+ CANVAS_CONTEXT_LINE_WIDTH_SLOT,+ );+ rv.set_undefined();+}++pub(crate) fn canvas_context_miter_limit_getter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "miterLimit getter") {+ return;+ }+ let value = context_number_slot(scope, args.this(), CANVAS_CONTEXT_MITER_LIMIT_SLOT)+ .unwrap_or(DEFAULT_MITER_LIMIT);+ rv.set(v8::Number::new(scope, value).into());+}++pub(crate) fn canvas_context_miter_limit_setter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "miterLimit setter") {+ return;+ }+ canvas_context_nonnegative_number_assign(+ scope,+ args.this(),+ args.get(0),+ CANVAS_CONTEXT_MITER_LIMIT_SLOT,+ );+ rv.set_undefined();+}++pub(crate) fn canvas_context_line_dash_offset_getter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineDashOffset getter") {+ return;+ }+ let value = context_number_slot(scope, args.this(), CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT)+ .unwrap_or(DEFAULT_LINE_DASH_OFFSET);+ rv.set(v8::Number::new(scope, value).into());+}++pub(crate) fn canvas_context_line_dash_offset_setter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineDashOffset setter") {+ return;+ }+ // A non-finite value is ignored per the canvas setter semantics.+ let value = webidl::convert::<webidl::UnrestrictedDouble>(+ scope,+ args.get(0),+ webidl::Context::member("CanvasRenderingContext2D", "lineDashOffset"),+ );+ if let Ok(value) = value {+ let value = f64::from(value);+ if value.is_finite() {+ set_context_number_slot(+ scope,+ args.this(),+ CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT,+ value,+ );+ }+ }+ rv.set_undefined();+}++pub(crate) fn canvas_context_line_cap_getter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineCap getter") {+ return;+ }+ let value = context_string_slot(scope, args.this(), CANVAS_CONTEXT_LINE_CAP_SLOT)+ .unwrap_or_else(|| DEFAULT_LINE_CAP.to_owned());+ rv.set(+ v8_string(scope, &value)+ .unwrap_or_else(|| v8::String::empty(scope))+ .into(),+ );+}++pub(crate) fn canvas_context_line_cap_setter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineCap setter") {+ return;+ }+ canvas_context_enum_string_assign(+ scope,+ args.this(),+ args.get(0),+ CANVAS_CONTEXT_LINE_CAP_SLOT,+ &["butt", "round", "square"],+ );+ rv.set_undefined();+}++pub(crate) fn canvas_context_line_join_getter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineJoin getter") {+ return;+ }+ let value = context_string_slot(scope, args.this(), CANVAS_CONTEXT_LINE_JOIN_SLOT)+ .unwrap_or_else(|| DEFAULT_LINE_JOIN.to_owned());+ rv.set(+ v8_string(scope, &value)+ .unwrap_or_else(|| v8::String::empty(scope))+ .into(),+ );+}++pub(crate) fn canvas_context_line_join_setter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "lineJoin setter") {+ return;+ }+ canvas_context_enum_string_assign(+ scope,+ args.this(),+ args.get(0),+ CANVAS_CONTEXT_LINE_JOIN_SLOT,+ &["miter", "round", "bevel"],+ );+ rv.set_undefined();+}++pub(crate) fn canvas_context_stroke_style_getter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "strokeStyle getter") {+ return;+ }+ let value = context_string_slot(scope, args.this(), CANVAS_CONTEXT_STROKE_STYLE_SLOT)+ .unwrap_or_else(|| DEFAULT_STROKE_STYLE.to_owned());+ rv.set(+ v8_string(scope, &value)+ .unwrap_or_else(|| v8::String::empty(scope))+ .into(),+ );+}++pub(crate) fn canvas_context_stroke_style_setter_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if !require_canvas_context_receiver(scope, args.this(), "strokeStyle setter") {+ return;+ }+ let Some(raw) = canvas_context_dom_string_value(+ scope,+ args.get(0),+ "CanvasRenderingContext2D",+ "strokeStyle",+ ) else {+ rv.set_undefined();+ return;+ };+ let Some(canonical) = canonical_canvas_fill_style(&raw) else {+ rv.set_undefined();+ return;+ };+ set_context_string_slot(+ scope,+ args.this(),+ CANVAS_CONTEXT_STROKE_STYLE_SLOT,+ &canonical,+ );+ rv.set_undefined();+}++fn canvas_context_nonnegative_number_assign<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ holder: v8::Local<'s, v8::Object>,+ value: v8::Local<'s, v8::Value>,+ slot: &'static str,+) {+ let value = webidl::convert::<webidl::UnrestrictedDouble>(+ scope,+ value,+ webidl::Context::member("CanvasRenderingContext2D", slot),+ );+ if let Ok(value) = value {+ let value = f64::from(value);+ if value.is_finite() && value >= 0.0 {+ set_context_number_slot(scope, holder, slot, value);+ }+ }+}++fn canvas_context_enum_string_assign<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ holder: v8::Local<'s, v8::Object>,+ value: v8::Local<'s, v8::Value>,+ slot: &'static str,+ accepted: &[&'static str],+) {+ let Some(string) =+ canvas_context_dom_string_value(scope, value, "CanvasRenderingContext2D", slot)+ else {+ return;+ };+ if accepted.contains(&string.as_str()) {+ set_context_string_slot(scope, holder, slot, &string);+ }+}++fn ensure_canvas_context_path_state_id<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ context: v8::Local<'s, v8::Object>,+) -> Option<u64> {+ if let Some(id) = context_number_slot(scope, context, CANVAS_CONTEXT_PATH_STATE_ID_SLOT) {+ return Some(id as u64);+ }+ let id = allocate_canvas_path_state_id();+ set_context_number_slot(scope, context, CANVAS_CONTEXT_PATH_STATE_ID_SLOT, id as f64);+ Some(id)+}++fn context_fill_color<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ context: v8::Local<'s, v8::Object>,+) -> PaintColor {+ let fill_style = context_string_slot(scope, context, CANVAS_CONTEXT_FILL_STYLE_SLOT)+ .unwrap_or_else(|| DEFAULT_FILL_STYLE.to_owned());+ color_with_global_alpha(+ fill_style_rgba(&fill_style),+ context_global_alpha(scope, context),+ )+}++fn context_global_alpha<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ context: v8::Local<'s, v8::Object>,+) -> f64 {+ context_number_slot(scope, context, CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT)+ .unwrap_or(DEFAULT_GLOBAL_ALPHA)+}++fn color_with_global_alpha(rgba: [u8; 4], global_alpha: f64) -> PaintColor {+ let alpha = (f64::from(rgba[3]) / 255.0 * global_alpha).clamp(0.0, 1.0) as f32;+ PaintColor::new(+ f64::from(rgba[0]) as f32 / 255.0,+ f64::from(rgba[1]) as f32 / 255.0,+ f64::from(rgba[2]) as f32 / 255.0,+ alpha,+ )+}++fn context_stroke<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ context: v8::Local<'s, v8::Object>,+ path: moli_layout::PaintPath,+ transform: PaintTransform2D,+) -> PaintStroke {+ let stroke_style = context_string_slot(scope, context, CANVAS_CONTEXT_STROKE_STYLE_SLOT)+ .unwrap_or_else(|| DEFAULT_STROKE_STYLE.to_owned());+ let join = match context_string_slot(scope, context, CANVAS_CONTEXT_LINE_JOIN_SLOT).as_deref() {+ Some("round") => PaintLineJoin::Round,+ Some("bevel") => PaintLineJoin::Bevel,+ _ => PaintLineJoin::Miter,+ };+ let cap = match context_string_slot(scope, context, CANVAS_CONTEXT_LINE_CAP_SLOT).as_deref() {+ Some("round") => PaintLineCap::Round,+ Some("square") => PaintLineCap::Square,+ _ => PaintLineCap::Butt,+ };+ PaintStroke {+ path,+ color: color_with_global_alpha(+ fill_style_rgba(&stroke_style),+ context_global_alpha(scope, context),+ ),+ width: context_number_slot(scope, context, CANVAS_CONTEXT_LINE_WIDTH_SLOT)+ .unwrap_or(DEFAULT_LINE_WIDTH) as f32,+ join,+ start_cap: cap,+ end_cap: cap,+ miter_limit: context_number_slot(scope, context, CANVAS_CONTEXT_MITER_LIMIT_SLOT)+ .unwrap_or(DEFAULT_MITER_LIMIT) as f32,+ dash_pattern: context_line_dash(scope, context),+ dash_offset: context_number_slot(scope, context, CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT)+ .unwrap_or(DEFAULT_LINE_DASH_OFFSET) as f32,+ transform,+ }+}++fn context_line_dash<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ context: v8::Local<'s, v8::Object>,+) -> Vec<f32> {+ let Some(array) = get_private_value(scope, context, CANVAS_CONTEXT_LINE_DASH_SLOT)+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())+ else {+ return Vec::new();+ };+ (0..array.length())+ .filter_map(|index| array.get_index(scope, index))+ .filter_map(|value| value.number_value(scope))+ .map(|value| value as f32)+ .collect()+}++fn rasterize_canvas_fragment<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ canvas: v8::Local<'s, v8::Object>,+ fragment: PaintFragment,+) {+ let _ = with_canvas_like_pixels_mut(scope, canvas, |pixels, width, height| {+ if width == 0 || height == 0 {+ return;+ }+ let mut snapshot = PaintSnapshot::new(+ PaintViewport::new(width, height, 1.0),+ PaintColor::new(0.0, 0.0, 0.0, 0.0),+ );+ snapshot.push_fragment(fragment);+ if let Ok(raster) = moli_paint::raster_snapshot(&snapshot)+ && raster.width == width+ && raster.height == height+ {+ composite_rgba8_over(pixels, &raster.rgba);+ }+ });+}++/// Composites `source` (premultiplied RGBA8) over `destination` (straight+/// RGBA8) using source-over. This is the format vello_cpu renders into, while+/// the canvas backing store is straight alpha.+fn composite_rgba8_over(destination: &mut [u8], source: &[u8]) {+ for (dst, src) in destination.chunks_exact_mut(4).zip(source.chunks_exact(4)) {+ let src_alpha = u32::from(src[3]);+ if src_alpha == 0 {+ continue;+ }+ let dst_alpha = u32::from(dst[3]);+ if src_alpha == 255 {+ dst.copy_from_slice(src);+ continue;+ }+ let out_alpha = src_alpha + dst_alpha * (255 - src_alpha) / 255;+ if out_alpha == 0 {+ dst.copy_from_slice(&[0, 0, 0, 0]);+ continue;+ }+ for channel in 0..3 {+ let src_premultiplied = u32::from(src[channel]);+ let dst_premultiplied = u32::from(dst[channel]) * dst_alpha / 255;+ let out_premultiplied = src_premultiplied + dst_premultiplied * (255 - src_alpha) / 255;+ dst[channel] = ((out_premultiplied * 255 + out_alpha / 2) / out_alpha) as u8;+ }+ dst[3] = out_alpha as u8;+ }}pub(crate) fn canvas_context_is_point_in_path_callback(diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs b/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rsindex 0374068b2..c7c4d7524 100644--- a/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs+++ b/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs@@ -33,6 +33,27 @@ struct CanvasLikeContextObjectDeclaration {constructor_default = super::DEFAULT_GLOBAL_COMPOSITE_OPERATION)]global_composite_operation: &'static str,+ #[webapi(slot = CANVAS_CONTEXT_LINE_WIDTH_SLOT, constructor_default = super::DEFAULT_LINE_WIDTH)]+ line_width: f64,+ #[webapi(slot = CANVAS_CONTEXT_LINE_CAP_SLOT, constructor_default = super::DEFAULT_LINE_CAP)]+ line_cap: &'static str,+ #[webapi(slot = CANVAS_CONTEXT_LINE_JOIN_SLOT, constructor_default = super::DEFAULT_LINE_JOIN)]+ line_join: &'static str,+ #[webapi(+ slot = CANVAS_CONTEXT_MITER_LIMIT_SLOT,+ constructor_default = super::DEFAULT_MITER_LIMIT+ )]+ miter_limit: f64,+ #[webapi(+ slot = CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT,+ constructor_default = super::DEFAULT_LINE_DASH_OFFSET+ )]+ line_dash_offset: f64,+ #[webapi(+ slot = CANVAS_CONTEXT_STROKE_STYLE_SLOT,+ constructor_default = super::DEFAULT_STROKE_STYLE+ )]+ stroke_style: &'static str,}pub(super) fn canvas_unrestricted_double_arg<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/path.rs b/moli-renderer-v8/src/context_bootstrap/canvas/path.rsnew file mode 100644index 000000000..eb9748af0--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/canvas/path.rs@@ -0,0 +1,528 @@+//! Canvas 2D current-path geometry.+//!+//! The CanvasRenderingContext2D path methods are thin V8 callbacks that+//! translate into this module's geometry. The accumulated path is kept in a+//! per-context side table keyed by a private-slot id (V8 private slots can+//! only hold `Value`, so a numeric id + global map is used instead of storing+//! a `Vec` directly on the object).+//!+//! Path elements map 1:1 onto [`moli_layout::PaintPathElement`] so the+//! existing `moli_paint::raster_snapshot` pipeline (vello CPU) can fill and+//! stroke them.++use std::collections::HashMap;+use std::sync::OnceLock;+use std::sync::atomic::{AtomicU64, Ordering};++use moli_layout::{+ LayoutPoint, LayoutRect, LayoutTransform2D, PaintPath, PaintPathElement, PaintRect,+};+use parking_lot::Mutex;++pub(crate) const CANVAS_CONTEXT_PATH_STATE_ID_SLOT: &str = "__moliCanvasContextPathStateId";++/// A Bezier path in the same flat form as a kurbo path: one `MoveTo` starts a+/// subpath, `Close` ends it, and a new `MoveTo` begins the next one.+#[derive(Clone, Debug)]+pub(crate) struct Canvas2dPathState {+ elements: Vec<PaintPathElement>,+ current: (f64, f64),+ current_subpath_start: (f64, f64),+ has_subpath: bool,+ just_closed: bool,+ transform: LayoutTransform2D,+}++impl Default for Canvas2dPathState {+ fn default() -> Self {+ Self {+ elements: Vec::new(),+ current: (0.0, 0.0),+ current_subpath_start: (0.0, 0.0),+ has_subpath: false,+ just_closed: false,+ transform: LayoutTransform2D::IDENTITY,+ }+ }+}++static NEXT_CANVAS_PATH_STATE_ID: AtomicU64 = AtomicU64::new(1);+static CANVAS_PATH_STATES: OnceLock<Mutex<HashMap<u64, Canvas2dPathState>>> = OnceLock::new();++fn canvas_path_states() -> &'static Mutex<HashMap<u64, Canvas2dPathState>> {+ CANVAS_PATH_STATES.get_or_init(|| Mutex::new(HashMap::new()))+}++pub(crate) fn allocate_canvas_path_state_id() -> u64 {+ NEXT_CANVAS_PATH_STATE_ID.fetch_add(1, Ordering::Relaxed)+}++/// Runs `update` against the current-path state for `id`, inserting a fresh+/// state when the context has never recorded one.+pub(crate) fn with_canvas_path_state_mut<T>(+ id: u64,+ update: impl FnOnce(&mut Canvas2dPathState) -> T,+) -> T {+ let mut states = canvas_path_states().lock();+ let state = states.entry(id).or_default();+ update(state)+}++const TWO_PI: f64 = std::f64::consts::TAU;++impl Canvas2dPathState {+ pub(super) fn begin_path(&mut self) {+ self.elements.clear();+ self.current = (0.0, 0.0);+ self.current_subpath_start = (0.0, 0.0);+ self.has_subpath = false;+ self.just_closed = false;+ }++ pub(super) fn move_to(&mut self, x: f64, y: f64) {+ self.elements.push(PaintPathElement::MoveTo(point(x, y)));+ self.current = (x, y);+ self.current_subpath_start = (x, y);+ self.has_subpath = true;+ self.just_closed = false;+ }++ /// Returns `false` when the path has no subpath, matching the spec: line+ /// and curve commands must do nothing when the path has no subpaths.+ fn ensure_open_subpath(&mut self) -> bool {+ if !self.has_subpath {+ return false;+ }+ if self.just_closed {+ self.elements.push(PaintPathElement::MoveTo(point(+ self.current.0,+ self.current.1,+ )));+ self.current_subpath_start = self.current;+ self.just_closed = false;+ }+ true+ }++ pub(super) fn line_to(&mut self, x: f64, y: f64) {+ if !self.ensure_open_subpath() {+ return;+ }+ self.elements.push(PaintPathElement::LineTo(point(x, y)));+ self.current = (x, y);+ }++ pub(super) fn quadratic_curve_to(&mut self, cpx: f64, cpy: f64, x: f64, y: f64) {+ if !self.ensure_open_subpath() {+ return;+ }+ self.elements+ .push(PaintPathElement::QuadTo(point(cpx, cpy), point(x, y)));+ self.current = (x, y);+ }++ pub(super) fn bezier_curve_to(+ &mut self,+ c1x: f64,+ c1y: f64,+ c2x: f64,+ c2y: f64,+ x: f64,+ y: f64,+ ) {+ if !self.ensure_open_subpath() {+ return;+ }+ self.elements.push(PaintPathElement::CubicTo(+ point(c1x, c1y),+ point(c2x, c2y),+ point(x, y),+ ));+ self.current = (x, y);+ }++ pub(super) fn close_path(&mut self) {+ if !self.has_subpath || self.just_closed {+ return;+ }+ self.elements.push(PaintPathElement::Close);+ self.current = self.current_subpath_start;+ self.just_closed = true;+ }++ pub(super) fn rect(&mut self, x: f64, y: f64, width: f64, height: f64) {+ self.move_to(x, y);+ self.line_to(x + width, y);+ self.line_to(x + width, y + height);+ self.line_to(x, y + height);+ self.close_path();+ }++ /// Appends the path for `ctx.arc(...)`. Returns `false` when the arguments+ /// are non-finite or the radius is negative (caller reports the error).+ pub(super) fn arc(+ &mut self,+ x: f64,+ y: f64,+ radius: f64,+ start: f64,+ end: f64,+ ccw: bool,+ ) -> bool {+ if !x.is_finite()+ || !y.is_finite()+ || !radius.is_finite()+ || !start.is_finite()+ || !end.is_finite()+ {+ return false;+ }+ if radius < 0.0 {+ return false;+ }+ if radius == 0.0 {+ return true;+ }+ let (start, end) = normalized_arc_angles(start, end, ccw);+ let start_point = (x + radius * start.cos(), y + radius * start.sin());+ if !self.has_subpath {+ self.move_to(start_point.0, start_point.1);+ } else if self.current != start_point {+ self.line_to(start_point.0, start_point.1);+ }+ self.push_arc_cubics((x, y), radius, start, end, ccw);+ self.current = (x + radius * end.cos(), y + radius * end.sin());+ true+ }++ /// Appends the path for `ctx.ellipse(...)`.+ pub(super) fn ellipse(+ &mut self,+ x: f64,+ y: f64,+ radius_x: f64,+ radius_y: f64,+ rotation: f64,+ start: f64,+ end: f64,+ ccw: bool,+ ) -> bool {+ if !x.is_finite()+ || !y.is_finite()+ || !radius_x.is_finite()+ || !radius_y.is_finite()+ || !rotation.is_finite()+ || !start.is_finite()+ || !end.is_finite()+ {+ return false;+ }+ if radius_x < 0.0 || radius_y < 0.0 {+ return false;+ }+ if radius_x == 0.0 || radius_y == 0.0 {+ return true;+ }+ let (start, end) = normalized_arc_angles(start, end, ccw);+ // Map unit-circle angles through the ellipse's scale + rotation.+ let ellipse_transform = LayoutTransform2D::IDENTITY+ .concatenate(LayoutTransform2D::rotation(rotation))+ .concatenate(LayoutTransform2D::scale(radius_x, radius_y))+ .concatenate(LayoutTransform2D::translation(x as f32, y as f32));+ let start_point = transform_point(ellipse_transform, start.cos(), start.sin());+ if !self.has_subpath {+ self.move_to(start_point.0, start_point.1);+ } else if self.current != start_point {+ self.line_to(start_point.0, start_point.1);+ }+ self.push_ellipse_cubics(ellipse_transform, start, end, ccw);+ let end_point = transform_point(ellipse_transform, end.cos(), end.sin());+ self.current = end_point;+ true+ }++ /// Appends the path for `ctx.arcTo(...)`.+ pub(super) fn arc_to(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, radius: f64) -> bool {+ if !x1.is_finite()+ || !y1.is_finite()+ || !x2.is_finite()+ || !y2.is_finite()+ || !radius.is_finite()+ {+ return false;+ }+ if radius < 0.0 {+ return false;+ }+ if !self.has_subpath {+ return true;+ }+ let (x0, y0) = self.current;+ let (p1, p2) = ((x1, y1), (x2, y2));+ if (x0, y0) == p1 || p1 == p2 || radius == 0.0 {+ self.line_to(x1, y1);+ return true;+ }+ let (x01, y01) = (p1.0 - x0, p1.1 - y0);+ let (x12, y12) = (p2.0 - p1.0, p2.1 - p1.1);+ let d01 = x01.hypot(y01);+ let d12 = x12.hypot(y12);+ if d01 <= f64::EPSILON || d12 <= f64::EPSILON {+ self.line_to(x1, y1);+ return true;+ }+ let cross = x01 * y12 - y01 * x12;+ if cross.abs() <= f64::EPSILON {+ self.line_to(x1, y1);+ return true;+ }+ let (ux01, uy01) = (x01 / d01, y01 / d01);+ let (ux12, uy12) = (x12 / d12, y12 / d12);+ let cos_theta = (x01 * x12 + y01 * y12) / (d01 * d12);+ let cos_theta = cos_theta.clamp(-1.0, 1.0);+ let theta = cos_theta.acos();+ let half = theta / 2.0;+ let tan_half = half.tan();+ if !tan_half.is_finite() || tan_half.abs() <= f64::EPSILON {+ self.line_to(x1, y1);+ return true;+ }+ let max_radius = d01.min(d12) * tan_half;+ let radius = radius.min(max_radius);+ let tangent = radius / tan_half;+ let (ta_x, ta_y) = (p1.0 + ux01 * tangent, p1.1 + uy01 * tangent);+ let (tb_x, tb_y) = (p1.0 + ux12 * tangent, p1.1 + uy12 * tangent);+ let (bx, by) = normalize((ux01 + ux12, uy01 + uy12));+ let sin_half = half.sin();+ if !sin_half.is_finite() || sin_half.abs() <= f64::EPSILON {+ self.line_to(x1, y1);+ return true;+ }+ let center = (+ p1.0 + bx * (radius / sin_half),+ p1.1 + by * (radius / sin_half),+ );+ let start_angle = (ta_y - center.1).atan2(ta_x - center.0);+ let end_angle = (tb_y - center.1).atan2(tb_x - center.0);+ let ccw = cross < 0.0;+ self.push_arc_cubics(center, radius, start_angle, end_angle, ccw);+ self.current = (tb_x, tb_y);+ true+ }++ /// Adds a straight connector to the current point when `connect` and the+ /// current point differs from `target`, then appends cubic approximations+ /// of the arc from `start` to `end` around `center` with radius `radius`.+ fn push_arc_cubics(+ &mut self,+ center: (f64, f64),+ radius: f64,+ start: f64,+ end: f64,+ ccw: bool,+ ) {+ let sweep = signed_arc_sweep(start, end, ccw);+ if sweep.abs() <= f64::EPSILON {+ return;+ }+ let segments = (sweep.abs() / (std::f64::consts::FRAC_PI_2)).ceil() as usize;+ let segments = segments.max(1);+ let delta = sweep / segments as f64;+ let mut angle = start;+ for _ in 0..segments {+ let next = angle + delta;+ let (cos_a, sin_a) = angle.sin_cos();+ let (cos_b, sin_b) = next.sin_cos();+ let alpha = (4.0 / 3.0) * (1.0 - (delta / 2.0).cos()) / (delta / 2.0).sin();+ let (p0x, p0y) = (center.0 + radius * cos_a, center.1 + radius * sin_a);+ let (c1x, c1y) = (p0x - alpha * radius * sin_a, p0y + alpha * radius * cos_a);+ let (p3x, p3y) = (center.0 + radius * cos_b, center.1 + radius * sin_b);+ let (c2x, c2y) = (p3x + alpha * radius * sin_b, p3y - alpha * radius * cos_b);+ self.elements.push(PaintPathElement::CubicTo(+ point(c1x, c1y),+ point(c2x, c2y),+ point(p3x, p3y),+ ));+ self.current = (p3x, p3y);+ angle = next;+ }+ }++ fn push_ellipse_cubics(+ &mut self,+ transform: LayoutTransform2D,+ start: f64,+ end: f64,+ ccw: bool,+ ) {+ let sweep = signed_arc_sweep(start, end, ccw);+ if sweep.abs() <= f64::EPSILON {+ return;+ }+ let segments = (sweep.abs() / (std::f64::consts::FRAC_PI_2)).ceil() as usize;+ let segments = segments.max(1);+ let delta = sweep / segments as f64;+ let mut angle = start;+ for _ in 0..segments {+ let next = angle + delta;+ let (cos_a, sin_a) = angle.sin_cos();+ let (cos_b, sin_b) = next.sin_cos();+ let alpha = (4.0 / 3.0) * (1.0 - (delta / 2.0).cos()) / (delta / 2.0).sin();+ let (p0x, p0y) = transform_point(transform, cos_a, sin_a);+ let (p3x, p3y) = transform_point(transform, cos_b, sin_b);+ // Tangents on the unit circle, then mapped through the transform.+ let tangent_a = radius_tangent(transform, -sin_a, cos_a);+ let tangent_b = radius_tangent(transform, -sin_b, cos_b);+ let (c1x, c1y) = (p0x + alpha * tangent_a.0, p0y + alpha * tangent_a.1);+ let (c2x, c2y) = (p3x - alpha * tangent_b.0, p3y - alpha * tangent_b.1);+ self.elements.push(PaintPathElement::CubicTo(+ point(c1x, c1y),+ point(c2x, c2y),+ point(p3x, p3y),+ ));+ self.current = (p3x, p3y);+ angle = next;+ }+ }++ pub(super) fn set_transform(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {+ self.transform = LayoutTransform2D::new([a, b, c, d, e, f]);+ }++ pub(super) fn reset_transform(&mut self) {+ self.transform = LayoutTransform2D::IDENTITY;+ }++ pub(super) fn translate(&mut self, x: f64, y: f64) {+ self.transform = self+ .transform+ .concatenate(LayoutTransform2D::translation(x as f32, y as f32));+ }++ pub(super) fn scale(&mut self, x: f64, y: f64) {+ self.transform = self.transform.concatenate(LayoutTransform2D::scale(x, y));+ }++ pub(super) fn rotate(&mut self, radians: f64) {+ self.transform = self+ .transform+ .concatenate(LayoutTransform2D::rotation(radians));+ }++ pub(super) fn concatenate_transform(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {+ self.transform = self+ .transform+ .concatenate(LayoutTransform2D::new([a, b, c, d, e, f]));+ }++ pub(super) fn transform(&self) -> LayoutTransform2D {+ self.transform+ }++ /// Builds an owned `PaintPath` with conservative local bounds.+ pub(super) fn paint_path(&self) -> PaintPath {+ PaintPath {+ elements: self.elements.clone(),+ bounds: self.bounds(),+ }+ }++ pub(super) fn is_empty(&self) -> bool {+ self.elements.is_empty()+ }++ fn bounds(&self) -> PaintRect {+ let mut min_x = f64::INFINITY;+ let mut min_y = f64::INFINITY;+ let mut max_x = f64::NEG_INFINITY;+ let mut max_y = f64::NEG_INFINITY;+ for element in &self.elements {+ match *element {+ PaintPathElement::MoveTo(point) | PaintPathElement::LineTo(point) => {+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, point);+ }+ PaintPathElement::QuadTo(first, second) => {+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, first);+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, second);+ }+ PaintPathElement::CubicTo(first, second, third) => {+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, first);+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, second);+ expand(&mut min_x, &mut min_y, &mut max_x, &mut max_y, third);+ }+ PaintPathElement::Close => {}+ }+ }+ if !min_x.is_finite() {+ return LayoutRect::ZERO;+ }+ LayoutRect::new(+ min_x as f32,+ min_y as f32,+ (max_x - min_x) as f32,+ (max_y - min_y) as f32,+ )+ }+}++fn point(x: f64, y: f64) -> LayoutPoint {+ LayoutPoint::new(x as f32, y as f32)+}++fn expand(min_x: &mut f64, min_y: &mut f64, max_x: &mut f64, max_y: &mut f64, point: LayoutPoint) {+ let x = f64::from(point.x);+ let y = f64::from(point.y);+ *min_x = (*min_x).min(x);+ *min_y = (*min_y).min(y);+ *max_x = (*max_x).max(x);+ *max_y = (*max_y).max(y);+}++fn normalize(vector: (f64, f64)) -> (f64, f64) {+ let length = vector.0.hypot(vector.1);+ if length <= f64::EPSILON {+ (0.0, 0.0)+ } else {+ (vector.0 / length, vector.1 / length)+ }+}++fn normalized_arc_angles(start: f64, end: f64, ccw: bool) -> (f64, f64) {+ let mut end = end;+ if ccw {+ while end > start {+ end -= TWO_PI;+ }+ } else {+ while end < start {+ end += TWO_PI;+ }+ }+ (start, end)+}++/// Signed sweep angle (positive counterclockwise, negative clockwise) in+/// `(-TAU, TAU]`. An exact full-circle difference is preserved as ±TAU.+fn signed_arc_sweep(start: f64, end: f64, ccw: bool) -> f64 {+ let difference = end - start;+ if difference.abs() >= TWO_PI {+ return if ccw { TWO_PI } else { -TWO_PI };+ }+ if ccw {+ difference.rem_euclid(TWO_PI)+ } else {+ -((start - end).rem_euclid(TWO_PI))+ }+}++fn transform_point(transform: LayoutTransform2D, x: f64, y: f64) -> (f64, f64) {+ let mapped = transform.map_point(LayoutPoint::new(x as f32, y as f32));+ (f64::from(mapped.x), f64::from(mapped.y))+}++/// Maps a unit-circle tangent through the ellipse's linear part only+/// (scale + rotation, excluding translation).+fn radius_tangent(transform: LayoutTransform2D, x: f64, y: f64) -> (f64, f64) {+ let [a, b, c, d, _, _] = transform.coefficients;+ (a * x + c * y, b * x + d * y)+}diff --git a/moli-renderer-v8/src/context_bootstrap/media_file_template.rs b/moli-renderer-v8/src/context_bootstrap/media_file_template.rsindex bfa09d44f..7df3980d2 100644--- a/moli-renderer-v8/src/context_bootstrap/media_file_template.rs+++ b/moli-renderer-v8/src/context_bootstrap/media_file_template.rs@@ -1,24 +1,39 @@use super::canvas::{- canvas_context_clear_rect_callback, canvas_context_create_image_data_callback,- canvas_context_create_linear_gradient_callback, canvas_context_draw_image_callback,- canvas_context_fill_rect_callback, canvas_context_fill_style_getter_callback,- canvas_context_fill_style_setter_callback, canvas_context_fill_text_callback,- canvas_context_font_getter_callback, canvas_context_font_setter_callback,- canvas_context_get_image_data_callback, canvas_context_get_line_dash_callback,- canvas_context_global_alpha_getter_callback, canvas_context_global_alpha_setter_callback,+ canvas_context_arc_callback, canvas_context_arc_to_callback,+ canvas_context_begin_path_callback, canvas_context_bezier_curve_to_callback,+ canvas_context_clear_rect_callback, canvas_context_close_path_callback,+ canvas_context_create_image_data_callback, canvas_context_create_linear_gradient_callback,+ canvas_context_draw_image_callback, canvas_context_ellipse_callback,+ canvas_context_fill_callback, canvas_context_fill_rect_callback,+ canvas_context_fill_style_getter_callback, canvas_context_fill_style_setter_callback,+ canvas_context_fill_text_callback, canvas_context_font_getter_callback,+ canvas_context_font_setter_callback, canvas_context_get_image_data_callback,+ canvas_context_get_line_dash_callback, canvas_context_global_alpha_getter_callback,+ canvas_context_global_alpha_setter_callback,canvas_context_global_composite_operation_getter_callback,canvas_context_global_composite_operation_setter_callback,canvas_context_image_smoothing_enabled_getter_callback,canvas_context_image_smoothing_enabled_setter_callback,canvas_context_image_smoothing_quality_getter_callback,canvas_context_image_smoothing_quality_setter_callback,- canvas_context_is_point_in_path_callback, canvas_context_measure_text_callback,+ canvas_context_is_point_in_path_callback, canvas_context_line_cap_getter_callback,+ canvas_context_line_cap_setter_callback, canvas_context_line_dash_offset_getter_callback,+ canvas_context_line_dash_offset_setter_callback, canvas_context_line_join_getter_callback,+ canvas_context_line_join_setter_callback, canvas_context_line_to_callback,+ canvas_context_line_width_getter_callback, canvas_context_line_width_setter_callback,+ canvas_context_measure_text_callback, canvas_context_miter_limit_getter_callback,+ canvas_context_miter_limit_setter_callback, canvas_context_move_to_callback,canvas_context_noop_callback, canvas_context_put_image_data_callback,- canvas_context_rect_callback, canvas_context_set_line_dash_callback,- canvas_context_stroke_text_callback, canvas_gradient_add_color_stop_callback,- install_canvas_template_bindings, offscreen_canvas_convert_to_blob_callback,- offscreen_canvas_get_context_callback, webgl_boolean_callback,- webgl_check_framebuffer_status_callback, webgl_create_buffer_callback,+ canvas_context_quadratic_curve_to_callback, canvas_context_rect_callback,+ canvas_context_reset_transform_callback, canvas_context_rotate_callback,+ canvas_context_scale_callback, canvas_context_set_line_dash_callback,+ canvas_context_set_transform_callback, canvas_context_stroke_callback,+ canvas_context_stroke_rect_callback, canvas_context_stroke_style_getter_callback,+ canvas_context_stroke_style_setter_callback, canvas_context_stroke_text_callback,+ canvas_context_transform_callback, canvas_context_translate_callback,+ canvas_gradient_add_color_stop_callback, install_canvas_template_bindings,+ offscreen_canvas_convert_to_blob_callback, offscreen_canvas_get_context_callback,+ webgl_boolean_callback, webgl_check_framebuffer_status_callback, webgl_create_buffer_callback,webgl_create_framebuffer_callback, webgl_create_program_callback,webgl_create_renderbuffer_callback, webgl_create_shader_callback,webgl_get_attrib_location_callback, webgl_get_context_attributes_callback,@@ -174,6 +189,48 @@ struct CanvasRenderingContext2dTemplateDeclaration {)]global_composite_operation: (),+ #[webapi(+ accessor_property = "lineWidth",+ getter = canvas_context_line_width_getter_callback,+ setter = canvas_context_line_width_setter_callback+ )]+ line_width: (),++ #[webapi(+ accessor_property = "lineCap",+ getter = canvas_context_line_cap_getter_callback,+ setter = canvas_context_line_cap_setter_callback+ )]+ line_cap: (),++ #[webapi(+ accessor_property = "lineJoin",+ getter = canvas_context_line_join_getter_callback,+ setter = canvas_context_line_join_setter_callback+ )]+ line_join: (),++ #[webapi(+ accessor_property = "miterLimit",+ getter = canvas_context_miter_limit_getter_callback,+ setter = canvas_context_miter_limit_setter_callback+ )]+ miter_limit: (),++ #[webapi(+ accessor_property = "lineDashOffset",+ getter = canvas_context_line_dash_offset_getter_callback,+ setter = canvas_context_line_dash_offset_setter_callback+ )]+ line_dash_offset: (),++ #[webapi(+ accessor_property = "strokeStyle",+ getter = canvas_context_stroke_style_getter_callback,+ setter = canvas_context_stroke_style_setter_callback+ )]+ stroke_style: (),+#[webapi(method = "setLineDash",length = 1,@@ -198,7 +255,11 @@ struct CanvasRenderingContext2dTemplateDeclaration {)]clear_rect: (),- #[webapi(method = "strokeRect", length = 4, callback = canvas_context_noop_callback)]+ #[webapi(+ method = "strokeRect",+ length = 4,+ callback = canvas_context_stroke_rect_callback+ )]stroke_rect: (),#[webapi(method = "fillText", length = 3, callback = canvas_context_fill_text_callback)]@@ -217,63 +278,71 @@ struct CanvasRenderingContext2dTemplateDeclaration {#[webapi(method = "restore", length = 0, callback = canvas_context_noop_callback)]restore: (),- #[webapi(method = "scale", length = 2, callback = canvas_context_noop_callback)]+ #[webapi(method = "scale", length = 2, callback = canvas_context_scale_callback)]scale: (),- #[webapi(method = "translate", length = 2, callback = canvas_context_noop_callback)]+ #[webapi(method = "translate", length = 2, callback = canvas_context_translate_callback)]translate: (),- #[webapi(method = "rotate", length = 1, callback = canvas_context_noop_callback)]+ #[webapi(method = "rotate", length = 1, callback = canvas_context_rotate_callback)]rotate: (),- #[webapi(method = "transform", length = 6, callback = canvas_context_noop_callback)]+ #[webapi(method = "transform", length = 6, callback = canvas_context_transform_callback)]transform: (),- #[webapi(method = "setTransform", length = 6, callback = canvas_context_noop_callback)]+ #[webapi(+ method = "setTransform",+ length = 6,+ callback = canvas_context_set_transform_callback+ )]set_transform: (),#[webapi(method = "resetTransform",length = 0,- callback = canvas_context_noop_callback+ callback = canvas_context_reset_transform_callback)]reset_transform: (),- #[webapi(method = "beginPath", length = 0, callback = canvas_context_noop_callback)]+ #[webapi(method = "beginPath", length = 0, callback = canvas_context_begin_path_callback)]begin_path: (),- #[webapi(method = "closePath", length = 0, callback = canvas_context_noop_callback)]+ #[webapi(method = "closePath", length = 0, callback = canvas_context_close_path_callback)]close_path: (),- #[webapi(method = "moveTo", length = 2, callback = canvas_context_noop_callback)]+ #[webapi(method = "moveTo", length = 2, callback = canvas_context_move_to_callback)]move_to: (),- #[webapi(method = "lineTo", length = 2, callback = canvas_context_noop_callback)]+ #[webapi(method = "lineTo", length = 2, callback = canvas_context_line_to_callback)]line_to: (),#[webapi(method = "quadraticCurveTo",length = 4,- callback = canvas_context_noop_callback+ callback = canvas_context_quadratic_curve_to_callback)]quadratic_curve_to: (),- #[webapi(method = "bezierCurveTo", length = 6, callback = canvas_context_noop_callback)]+ #[webapi(+ method = "bezierCurveTo",+ length = 6,+ callback = canvas_context_bezier_curve_to_callback+ )]bezier_curve_to: (),- #[webapi(method = "arcTo", length = 5, callback = canvas_context_noop_callback)]+ #[webapi(method = "arcTo", length = 5, callback = canvas_context_arc_to_callback)]arc_to: (),- #[webapi(method = "arc", length = 5, callback = canvas_context_noop_callback)]+ #[webapi(method = "arc", length = 5, callback = canvas_context_arc_callback)]arc: (),- #[webapi(method = "ellipse", length = 7, callback = canvas_context_noop_callback)]+ #[webapi(method = "ellipse", length = 7, callback = canvas_context_ellipse_callback)]ellipse: (),- #[webapi(method = "fill", length = 1, callback = canvas_context_noop_callback)]+ #[webapi(method = "fill", length = 1, callback = canvas_context_fill_callback)]fill: (),- #[webapi(method = "stroke", length = 0, callback = canvas_context_noop_callback)]+ #[webapi(method = "stroke", length = 0, callback = canvas_context_stroke_callback)]stroke: (),#[webapi(method = "clip", length = 0, callback = canvas_context_noop_callback)]diff --git a/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rs b/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rsindex ab0a4fe6a..4db630770 100644--- a/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rs+++ b/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rs@@ -724,6 +724,166 @@ fn html_canvas_clear_rect_only_clears_target_region() {);}+#[test]+fn html_canvas_arc_fill_renders_pixels() {+ let mut vm = new_storage_test_vm("https://canvas-arc-fill.test/");++ let result = vm+ .eval(+ r#"+(() => {+ const canvas = document.createElement('canvas');+ canvas.width = 20;+ canvas.height = 20;+ const ctx = canvas.getContext('2d');+ ctx.fillStyle = 'red';+ ctx.beginPath();+ ctx.arc(10, 10, 5, 0, Math.PI * 2);+ ctx.fill();+ const data = Array.from(ctx.getImageData(0, 0, 20, 20).data);+ const center = data.slice((10 * 20 + 10) * 4, (10 * 20 + 10) * 4 + 4);+ const corner = data.slice(0, 4);+ return JSON.stringify({ center, corner });+})()+"#,+ )+ .expect("canvas arc fill should evaluate");++ assert_eq!(+ result, r#"{"center":[255,0,0,255],"corner":[0,0,0,0]}"#,+ "arc()+fill() must rasterize a filled disk"+ );+}++#[test]+fn html_canvas_line_stroke_renders_pixels() {+ let mut vm = new_storage_test_vm("https://canvas-line-stroke.test/");++ let result = vm+ .eval(+ r#"+(() => {+ const canvas = document.createElement('canvas');+ canvas.width = 20;+ canvas.height = 20;+ const ctx = canvas.getContext('2d');+ ctx.strokeStyle = 'green';+ ctx.lineWidth = 2;+ ctx.beginPath();+ ctx.moveTo(2, 10);+ ctx.lineTo(18, 10);+ ctx.stroke();+ const data = Array.from(ctx.getImageData(0, 0, 20, 20).data);+ const hit = data.slice((10 * 20 + 10) * 4, (10 * 20 + 10) * 4 + 4);+ const miss = data.slice(0, 4);+ return JSON.stringify({ hit, miss });+})()+"#,+ )+ .expect("canvas line stroke should evaluate");++ assert_eq!(+ result, r#"{"hit":[0,128,0,255],"miss":[0,0,0,0]}"#,+ "moveTo()+lineTo()+stroke() must rasterize the stroked line"+ );+}++#[test]+fn html_canvas_rect_path_fill_renders_pixels() {+ let mut vm = new_storage_test_vm("https://canvas-rect-path-fill.test/");++ let result = vm+ .eval(+ r#"+(() => {+ const canvas = document.createElement('canvas');+ canvas.width = 20;+ canvas.height = 20;+ const ctx = canvas.getContext('2d');+ ctx.fillStyle = 'blue';+ ctx.beginPath();+ ctx.rect(2, 2, 4, 3);+ ctx.fill();+ const data = Array.from(ctx.getImageData(0, 0, 20, 20).data);+ const inside = data.slice((3 * 20 + 3) * 4, (3 * 20 + 3) * 4 + 4);+ const outside = data.slice(0, 4);+ return JSON.stringify({ inside, outside });+})()+"#,+ )+ .expect("canvas rect path fill should evaluate");++ assert_eq!(+ result, r#"{"inside":[0,0,255,255],"outside":[0,0,0,0]}"#,+ "rect()+fill() must rasterize the rectangle"+ );+}++#[test]+fn html_canvas_path_fill_respects_translate() {+ let mut vm = new_storage_test_vm("https://canvas-path-translate.test/");++ let result = vm+ .eval(+ r#"+(() => {+ const canvas = document.createElement('canvas');+ canvas.width = 20;+ canvas.height = 20;+ const ctx = canvas.getContext('2d');+ ctx.fillStyle = 'red';+ ctx.translate(5, 5);+ ctx.beginPath();+ ctx.rect(0, 0, 3, 3);+ ctx.fill();+ const data = Array.from(ctx.getImageData(0, 0, 20, 20).data);+ const translated = data.slice((6 * 20 + 6) * 4, (6 * 20 + 6) * 4 + 4);+ const origin = data.slice(0, 4);+ return JSON.stringify({ translated, origin });+})()+"#,+ )+ .expect("canvas translated path fill should evaluate");++ assert_eq!(+ result, r#"{"translated":[255,0,0,255],"origin":[0,0,0,0]}"#,+ "translate() must move the path geometry"+ );+}++#[test]+fn html_canvas_stroke_respects_line_width() {+ let mut vm = new_storage_test_vm("https://canvas-stroke-line-width.test/");++ let result = vm+ .eval(+ r#"+(() => {+ const canvas = document.createElement('canvas');+ canvas.width = 20;+ canvas.height = 20;+ const ctx = canvas.getContext('2d');+ ctx.strokeStyle = 'lime';+ ctx.lineWidth = 6;+ ctx.beginPath();+ ctx.moveTo(2, 10);+ ctx.lineTo(18, 10);+ ctx.stroke();+ const data = Array.from(ctx.getImageData(0, 0, 20, 20).data);+ const center = data.slice((10 * 20 + 10) * 4, (10 * 20 + 10) * 4 + 4);+ const edge = data.slice((12 * 20 + 10) * 4, (12 * 20 + 10) * 4 + 4);+ return JSON.stringify({ center, edge });+})()+"#,+ )+ .expect("canvas stroke line width should evaluate");++ assert_eq!(+ result, r#"{"center":[0,255,0,255],"edge":[0,255,0,255]}"#,+ "a 6px stroke must cover y in [7, 12]"+ );+}+#[test]fn canvas_context_rect_path_method_is_available_for_fingerprinting_scripts() {let mut vm = new_storage_test_vm("https://canvas-rect-path-method.test/");@@ -784,7 +944,7 @@ fn canvas_context_rect_path_method_is_available_for_fingerprinting_scripts() {assert_eq!(result,- r#"{"htmlType":"function","offscreenType":"function","arcType":"function","pointType":"function","htmlCall":"ok","offscreenCall":"ok","pointInPath":false,"pointInStroke":false,"changed":false}"#+ r#"{"htmlType":"function","offscreenType":"function","arcType":"function","pointType":"function","htmlCall":"ok","offscreenCall":"ok","pointInPath":false,"pointInStroke":false,"changed":true}"#);}