mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
feat(canvas): implement native Path2D geometry and drawing
This commit is contained in:
+43
-18
@@ -14,11 +14,13 @@ pub use pixel::{
|
||||
copy_rgba8_rect, flip_y_rgba8_in_place, multiply_u8_color, premultiply_rgba8_in_place,
|
||||
scale_rgba8, scale_rgba8_bilinear, scale_rgba8_nearest,
|
||||
};
|
||||
pub use rect::{css_named_color_rgb, normalize_rect, paint_rect, serialize_srgb_color};
|
||||
pub use rect::{
|
||||
canonicalize_fill_style, css_named_color_rgb, fill_style_rgba, normalize_rect, paint_rect,
|
||||
};
|
||||
pub use text::{draw_text, measure_text_width};
|
||||
pub use types::{
|
||||
CanvasRect, DEFAULT_FONT, DrawImageBlit, ImageDataRect, MAX_RGBA8_BYTE_LENGTH, Rgba8Rect,
|
||||
ScaleFilter, byte_len,
|
||||
CanvasRect, DEFAULT_FILL_STYLE, DEFAULT_FONT, DrawImageBlit, ImageDataRect,
|
||||
MAX_RGBA8_BYTE_LENGTH, Rgba8Rect, ScaleFilter, byte_len,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -37,23 +39,46 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_srgb_serialization_preserves_opaque_channels_and_every_alpha_byte() {
|
||||
assert_eq!(serialize_srgb_color([0, 0, 0, 255]), "#000000");
|
||||
fn fill_style_canonicalization_matches_canvas_surface() {
|
||||
assert_eq!(canonicalize_fill_style("black").as_deref(), Some("#000000"));
|
||||
assert_eq!(canonicalize_fill_style("#abc").as_deref(), Some("#aabbcc"));
|
||||
assert_eq!(
|
||||
serialize_srgb_color([255, 0, 0, 128]),
|
||||
"rgba(255, 0, 0, 0.5)"
|
||||
canonicalize_fill_style("#ff000080").as_deref(),
|
||||
Some("rgba(255, 0, 0, 0.50)")
|
||||
);
|
||||
assert_eq!(serialize_srgb_color([0x12, 0xab, 0x34, 255]), "#12ab34");
|
||||
assert_eq!(
|
||||
canonicalize_fill_style("#112233ff").as_deref(),
|
||||
Some("#112233")
|
||||
);
|
||||
assert_eq!(canonicalize_fill_style("#ggg"), None);
|
||||
assert_eq!(canonicalize_fill_style("#zzzzzz"), None);
|
||||
assert_eq!(canonicalize_fill_style("#112233gg"), None);
|
||||
assert_eq!(canonicalize_fill_style("bad"), None);
|
||||
}
|
||||
|
||||
for alpha in 0..255_u8 {
|
||||
let css = serialize_srgb_color([0x12, 0xab, 0x34, alpha]);
|
||||
let fraction = css
|
||||
.strip_prefix("rgba(18, 171, 52, ")
|
||||
.and_then(|value| value.strip_suffix(')'))
|
||||
.unwrap()
|
||||
.parse::<f64>()
|
||||
.unwrap();
|
||||
assert_eq!((fraction * 255.0).round() as u8, alpha, "{css}");
|
||||
#[test]
|
||||
fn hex_alpha_canonicalization_round_trips_every_byte() {
|
||||
for alpha in 0..=255_u8 {
|
||||
let raw = format!("#12ab34{alpha:02x}");
|
||||
let canonical = canonicalize_fill_style(&raw).expect("valid eight-digit hex");
|
||||
assert_eq!(
|
||||
fill_style_rgba(&canonical),
|
||||
[0x12, 0xab, 0x34, alpha],
|
||||
"{raw}: {canonical}"
|
||||
);
|
||||
}
|
||||
for alpha in 0..16_u8 {
|
||||
let raw = format!("#0f0{alpha:x}");
|
||||
let canonical = canonicalize_fill_style(&raw).expect("valid four-digit hex");
|
||||
assert_eq!(fill_style_rgba(&canonical), [0, 255, 0, alpha * 17]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_hex_colors_cannot_panic_or_install_a_style() {
|
||||
for raw in ["#", "#12", "#12345", "#gggg", "#💚", "#éé", "#0000000x"] {
|
||||
assert_eq!(canonicalize_fill_style(raw), None, "{raw}");
|
||||
assert_eq!(fill_style_rgba(raw), [0, 0, 0, 255], "{raw}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,7 +370,7 @@ mod tests {
|
||||
4.0,
|
||||
24.0,
|
||||
"16px sans-serif",
|
||||
[255, 0, 0, 255],
|
||||
fill_style_rgba("#ff0000"),
|
||||
);
|
||||
assert!(pixels.iter().any(|&value| value != 0));
|
||||
}
|
||||
|
||||
+125
-11
@@ -1,19 +1,112 @@
|
||||
use crate::types::{CanvasRect, surface_matches_len};
|
||||
|
||||
/// Serialize an 8-bit sRGB color for the Canvas 2D style getter.
|
||||
pub fn serialize_srgb_color([red, green, blue, alpha]: [u8; 4]) -> String {
|
||||
if alpha == u8::MAX {
|
||||
return format!("#{red:02x}{green:02x}{blue:02x}");
|
||||
pub fn canonicalize_fill_style(raw: &str) -> Option<String> {
|
||||
let value = raw.trim().to_ascii_lowercase();
|
||||
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})"));
|
||||
}
|
||||
return Some(canonical_rgba(red, green, blue, alpha));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
let fraction = f64::from(alpha) / 255.0;
|
||||
let hundredths = (fraction * 100.0).round() / 100.0;
|
||||
let alpha = if (hundredths * 255.0).round() as u8 == alpha {
|
||||
hundredths
|
||||
} else {
|
||||
(fraction * 1000.0).round() / 1000.0
|
||||
pub fn fill_style_rgba(style: &str) -> [u8; 4] {
|
||||
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,
|
||||
};
|
||||
format!("rgba({red}, {green}, {blue}, {alpha})")
|
||||
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)
|
||||
}
|
||||
|
||||
/// Resolve a CSS named color without parsing color expressions.
|
||||
@@ -205,3 +298,24 @@ pub fn paint_rect(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_hex_color(value: &str) -> Option<String> {
|
||||
let [red, green, blue, alpha] = hex_color_rgba(value)?;
|
||||
if alpha == u8::MAX {
|
||||
Some(format!("#{red:02x}{green:02x}{blue:02x}"))
|
||||
} else {
|
||||
Some(canonical_rgba(red, green, blue, alpha))
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_rgba(red: u8, green: u8, blue: u8, alpha: u8) -> String {
|
||||
let fraction = f64::from(alpha) / 255.0;
|
||||
let rounded = (fraction * 100.0).round() / 100.0;
|
||||
if (rounded * 255.0).round() as u8 == alpha {
|
||||
format!("rgba({red}, {green}, {blue}, {rounded:.2})")
|
||||
} else {
|
||||
// Two decimal places cannot represent every 8-bit alpha. Retain enough
|
||||
// precision that serializing a style does not change its pixels.
|
||||
format!("rgba({red}, {green}, {blue}, {fraction:.3})")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub const DEFAULT_FILL_STYLE: &str = "#000000";
|
||||
pub const DEFAULT_FONT: &str = "10px sans-serif";
|
||||
pub const MAX_RGBA8_BYTE_LENGTH: usize = 2_147_483_647;
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::super::{
|
||||
broadcast_channel::broadcast_channel_constructor_callback,
|
||||
canvas::{
|
||||
canvas_rendering_context_2d_constructor_callback, offscreen_canvas_constructor_callback,
|
||||
offscreen_canvas_rendering_context_2d_constructor_callback, path_2d_constructor_callback,
|
||||
offscreen_canvas_rendering_context_2d_constructor_callback, path2d_constructor_callback,
|
||||
webgl_debug_renderer_info_constructor_callback, webgl_lose_context_constructor_callback,
|
||||
webgl_rendering_context_constructor_callback,
|
||||
},
|
||||
@@ -505,14 +505,6 @@ pub(in crate::context_bootstrap) fn build_constructor_template_for_profile<'s>(
|
||||
let _ = instance.set_internal_field_count(1);
|
||||
template
|
||||
}
|
||||
ConstructorKind::Path2D => {
|
||||
v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(
|
||||
web_api_interfaces::Path2D,
|
||||
path_2d_constructor_callback
|
||||
))
|
||||
.length(0)
|
||||
.build(scope)
|
||||
}
|
||||
ConstructorKind::OffscreenCanvas => {
|
||||
v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(
|
||||
web_api_interfaces::OffscreenCanvas,
|
||||
@@ -521,6 +513,14 @@ pub(in crate::context_bootstrap) fn build_constructor_template_for_profile<'s>(
|
||||
.length(2)
|
||||
.build(scope)
|
||||
}
|
||||
ConstructorKind::Path2D => {
|
||||
v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(
|
||||
web_api_interfaces::Path2D,
|
||||
path2d_constructor_callback
|
||||
))
|
||||
.length(0)
|
||||
.build(scope)
|
||||
}
|
||||
ConstructorKind::CanvasRenderingContext2D => {
|
||||
v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(
|
||||
web_api_interfaces::CanvasRenderingContext2D,
|
||||
|
||||
@@ -8,13 +8,14 @@ use crate::web_api_interfaces;
|
||||
use moli_webapi_declare::WebApiFunctionTemplate;
|
||||
|
||||
pub(crate) use moli_webapi::canvas_context_values::{
|
||||
CANVAS_CONTEXT_FONT_SLOT, CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT,
|
||||
CANVAS_CONTEXT_FILL_STYLE_SLOT, CANVAS_CONTEXT_FONT_SLOT, CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT,
|
||||
CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT, CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT,
|
||||
CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT, CANVAS_CONTEXT_LINE_CAP_SLOT,
|
||||
CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT, CANVAS_CONTEXT_LINE_JOIN_SLOT,
|
||||
CANVAS_CONTEXT_LINE_WIDTH_SLOT, CANVAS_CONTEXT_MITER_LIMIT_SLOT, DEFAULT_GLOBAL_ALPHA,
|
||||
DEFAULT_GLOBAL_COMPOSITE_OPERATION, DEFAULT_LINE_CAP, DEFAULT_LINE_DASH_OFFSET,
|
||||
DEFAULT_LINE_JOIN, DEFAULT_LINE_WIDTH, DEFAULT_MITER_LIMIT, OFFSCREEN_CANVAS_HEIGHT_SLOT,
|
||||
CANVAS_CONTEXT_LINE_WIDTH_SLOT, CANVAS_CONTEXT_MITER_LIMIT_SLOT,
|
||||
CANVAS_CONTEXT_STROKE_STYLE_SLOT, DEFAULT_GLOBAL_ALPHA, DEFAULT_GLOBAL_COMPOSITE_OPERATION,
|
||||
DEFAULT_LINE_CAP, DEFAULT_LINE_DASH_OFFSET, DEFAULT_LINE_JOIN, DEFAULT_LINE_WIDTH,
|
||||
DEFAULT_MITER_LIMIT, DEFAULT_STROKE_STYLE, OFFSCREEN_CANVAS_HEIGHT_SLOT,
|
||||
OFFSCREEN_CANVAS_WIDTH_SLOT,
|
||||
};
|
||||
|
||||
@@ -99,6 +100,7 @@ mod state;
|
||||
mod transform;
|
||||
use moli_webapi::webgl;
|
||||
|
||||
pub(crate) use path2d::{install_canvas_path_bindings, path2d_constructor_callback};
|
||||
pub(crate) use transform::install_canvas_transform_bindings;
|
||||
|
||||
pub(crate) use backing_store::{
|
||||
@@ -110,13 +112,16 @@ pub(crate) use constructors::{
|
||||
offscreen_canvas_rendering_context_2d_constructor_callback,
|
||||
};
|
||||
pub(crate) use context2d::{
|
||||
canvas_context_begin_path_callback, canvas_context_create_image_data_callback,
|
||||
canvas_context_arc_callback, canvas_context_arc_to_callback,
|
||||
canvas_context_begin_path_callback, canvas_context_bezier_curve_to_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_fill_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_ellipse_callback, canvas_context_fill_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,
|
||||
@@ -126,20 +131,19 @@ pub(crate) use context2d::{
|
||||
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_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_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_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_path_arc_callback,
|
||||
canvas_path_arc_to_callback, canvas_path_bezier_curve_to_callback,
|
||||
canvas_path_close_path_callback, canvas_path_ellipse_callback, canvas_path_line_to_callback,
|
||||
canvas_path_move_to_callback, canvas_path_quadratic_curve_to_callback,
|
||||
canvas_path_rect_callback, install_canvas_rect_bindings, is_canvas_context_receiver,
|
||||
canvas_context_transform_callback, canvas_context_translate_callback,
|
||||
install_canvas_rect_bindings, is_canvas_context_receiver,
|
||||
};
|
||||
pub(crate) use image_bitmap::{
|
||||
BitmapRejection, BitmapTaskResult, settle_bitmap_task_result,
|
||||
@@ -150,7 +154,6 @@ pub(crate) use offscreen::{
|
||||
offscreen_canvas_convert_to_blob_callback, offscreen_canvas_get_context_callback,
|
||||
offscreen_canvas_transfer_to_image_bitmap_callback,
|
||||
};
|
||||
pub(crate) use path2d::path_2d_constructor_callback;
|
||||
pub(crate) use webgl::{
|
||||
build_webgl_context_object, build_webgl2_context_object,
|
||||
webgl_debug_renderer_info_constructor_callback, webgl_lose_context_constructor_callback,
|
||||
@@ -174,9 +177,6 @@ pub(super) fn install_canvas_template_bindings<'s>(
|
||||
"OffscreenCanvas" => {
|
||||
offscreen::install_offscreen_canvas_template_bindings(scope, template);
|
||||
}
|
||||
"Path2D" => {
|
||||
path2d::install_path_2d_template_bindings(scope, template);
|
||||
}
|
||||
"ImageBitmap" => {
|
||||
image_bitmap::install_image_bitmap_template_bindings(scope, template);
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ pub(crate) fn attach_canvas_like_context_object<'s>(
|
||||
}
|
||||
let _ = CanvasContextOwnerDeclaration::new(canvas).initialize(scope, context);
|
||||
set_private_value(scope, context, CANVAS_OWNER_SLOT, canvas.into());
|
||||
if super::context2d::is_canvas_context_receiver(scope, context) {
|
||||
if get_private_value(scope, context, super::CANVAS_CONTEXT_FILL_STYLE_SLOT).is_some() {
|
||||
set_private_value(scope, canvas, CANVAS_2D_CONTEXT_SLOT, context.into());
|
||||
}
|
||||
set_private_value(
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
use cssparser::color::clamp_unit_f32;
|
||||
use style::color::{AbsoluteColor, ColorFlags, ColorSpace};
|
||||
use style::values::serialize_specified_dimension;
|
||||
use style_traits::{CssWriter, ToCss};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum CanvasColorStyle {
|
||||
Fill,
|
||||
Stroke,
|
||||
}
|
||||
|
||||
pub(super) fn serialize_canvas_color(mut color: AbsoluteColor) -> String {
|
||||
let missing_components = color.flags.intersects(
|
||||
ColorFlags::C0_IS_NONE
|
||||
| ColorFlags::C1_IS_NONE
|
||||
| ColorFlags::C2_IS_NONE
|
||||
| ColorFlags::ALPHA_IS_NONE,
|
||||
);
|
||||
if color.flags.contains(ColorFlags::IS_LEGACY_SRGB) && !missing_components {
|
||||
let [red, green, blue, alpha] = canvas_srgb_components(color).map(clamp_unit_f32);
|
||||
if color.alpha == f32::from(alpha) / 255.0 {
|
||||
return moli_canvas::serialize_srgb_color([red, green, blue, alpha]);
|
||||
}
|
||||
return format!("rgba({red}, {green}, {blue}, {})", color.alpha);
|
||||
}
|
||||
|
||||
let alpha = color.alpha();
|
||||
// Use Stylo for the color components and serialize modern alpha at its
|
||||
// required six-decimal precision.
|
||||
color.alpha = 1.0;
|
||||
color
|
||||
.flags
|
||||
.remove(ColorFlags::IS_LEGACY_SRGB | ColorFlags::ALPHA_IS_NONE);
|
||||
let mut css =
|
||||
if missing_components && matches!(color.color_space, ColorSpace::Hsl | ColorSpace::Hwb) {
|
||||
let name = match color.color_space {
|
||||
ColorSpace::Hsl => "hsl",
|
||||
_ => "hwb",
|
||||
};
|
||||
// Stylo clamps the percentages in absolute HSL and HWB. Use
|
||||
// relative syntax to preserve extended components when reparsing.
|
||||
// Every channel is explicit, and the origin's alpha is opaque.
|
||||
let origin = if [color.c1(), color.c2()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| !value.is_nan() && !(0.0..=100.0).contains(&value))
|
||||
{
|
||||
"from black "
|
||||
} else {
|
||||
""
|
||||
};
|
||||
format!(
|
||||
"{name}({origin}{} {} {})",
|
||||
serialize_hsl_hwb_component(color.c0(), ""),
|
||||
serialize_hsl_hwb_component(color.c1(), "%"),
|
||||
serialize_hsl_hwb_component(color.c2(), "%")
|
||||
)
|
||||
} else {
|
||||
color.to_css_string()
|
||||
};
|
||||
|
||||
if alpha != Some(1.0) {
|
||||
css.pop();
|
||||
css.push_str(" / ");
|
||||
if let Some(alpha) = alpha {
|
||||
let rounded = (f64::from(alpha) * 1_000_000.0).round() / 1_000_000.0;
|
||||
css.push_str(&rounded.to_string());
|
||||
} else {
|
||||
css.push_str("none");
|
||||
}
|
||||
css.push(')');
|
||||
}
|
||||
css
|
||||
}
|
||||
|
||||
fn serialize_hsl_hwb_component(component: Option<f32>, unit: &str) -> String {
|
||||
let Some(value) = component else {
|
||||
return "none".to_owned();
|
||||
};
|
||||
if !value.is_finite() {
|
||||
let mut css = String::new();
|
||||
serialize_specified_dimension(value, unit, true, &mut CssWriter::new(&mut css))
|
||||
.expect("writing CSS to a String succeeds");
|
||||
return css;
|
||||
}
|
||||
if unit == "%" {
|
||||
// Stylo stores HSL and HWB percentages on a 0–100 scale.
|
||||
let rounded = (f64::from(value) * 100_000.0).round() / 100_000.0;
|
||||
return format!("{rounded}%");
|
||||
}
|
||||
value.to_css_string()
|
||||
}
|
||||
|
||||
pub(super) fn canvas_srgb_components(color: AbsoluteColor) -> [f32; 4] {
|
||||
color
|
||||
.to_color_space(ColorSpace::Srgb)
|
||||
.raw_components()
|
||||
.map(|component| component.clamp(0.0, 1.0))
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
use cssparser::color::clamp_unit_f32;
|
||||
use moli_webapi::canvas_context_values::ImageSmoothingQuality;
|
||||
|
||||
use super::backing_store::{
|
||||
canvas_like_pixels_copy, canvas_owner_from_context, with_canvas_like_pixels_mut,
|
||||
};
|
||||
use super::color::{CanvasColorStyle, canvas_srgb_components, serialize_canvas_color};
|
||||
use super::helpers::canvas_unrestricted_double_arg;
|
||||
use super::path2d::path_2d_object;
|
||||
use super::state::{canvas_color, canvas_path_state, set_canvas_color};
|
||||
use super::helpers::{canonical_canvas_fill_style, canvas_unrestricted_double_arg};
|
||||
use super::state::canvas_path_state;
|
||||
use super::*;
|
||||
use crate::context_bootstrap::image_data::{
|
||||
build_image_data_object, build_image_data_object_with_bytes, image_data_bytes_from_object,
|
||||
@@ -19,13 +16,13 @@ use crate::web_api_interfaces;
|
||||
use crate::webidl;
|
||||
use crate::webidl::dom_string_property_value as canvas_context_dom_string_value;
|
||||
use moli_canvas::{
|
||||
DEFAULT_FONT, DrawImageBlit, ScaleFilter, blit_draw_image_filtered, blit_image_data, byte_len,
|
||||
data_image_rgba8_pixels, draw_text, extract_image_data, measure_text_width,
|
||||
normalize_rect as canvas_normalize_rect, paint_rect,
|
||||
DEFAULT_FILL_STYLE, DEFAULT_FONT, DrawImageBlit, ScaleFilter, blit_draw_image_filtered,
|
||||
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, PaintFillRule, PaintFragment, PaintLineCap, PaintLineJoin, PaintShape,
|
||||
PaintSnapshot, PaintStroke, PaintTransform2D, PaintViewport,
|
||||
PaintBrush, PaintColor, PaintFragment, PaintLineCap, PaintLineJoin, PaintShape, PaintSnapshot,
|
||||
PaintStroke, PaintTransform2D, PaintViewport,
|
||||
};
|
||||
use moli_webapi::text_metrics::CanvasTextMetricsDeclaration;
|
||||
|
||||
@@ -39,7 +36,7 @@ pub(super) fn reset_canvas_context_state<'s>(
|
||||
super::helpers::init_canvas_like_context_object(scope, context);
|
||||
let dash = v8::Array::new(scope, 0);
|
||||
set_private_value(scope, context, CANVAS_CONTEXT_LINE_DASH_SLOT, dash.into());
|
||||
super::state::reset_canvas_state(scope, context);
|
||||
super::state::reset_canvas_path_state(scope, context);
|
||||
}
|
||||
|
||||
macro_rules! canvas_rect_declaration {
|
||||
@@ -305,45 +302,6 @@ struct CanvasContextEllipseArgs {
|
||||
counterclockwise: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, webidl::WebIdlEnum)]
|
||||
#[webidl(name = "CanvasFillRule", rename_all = "lowercase")]
|
||||
enum CanvasFillRule {
|
||||
NonZero,
|
||||
EvenOdd,
|
||||
}
|
||||
|
||||
impl From<CanvasFillRule> for PaintFillRule {
|
||||
fn from(rule: CanvasFillRule) -> Self {
|
||||
match rule {
|
||||
CanvasFillRule::NonZero => Self::NonZero,
|
||||
CanvasFillRule::EvenOdd => Self::EvenOdd,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasRenderingContext2D.fill")]
|
||||
struct CanvasFillArgs {
|
||||
#[webidl(name = "fillRule", converter = "enum", default = CanvasFillRule::NonZero)]
|
||||
fill_rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasRenderingContext2D.fill")]
|
||||
struct CanvasFillPathArgs<'s> {
|
||||
#[webidl(required, interface = web_api_interfaces::Path2D)]
|
||||
path: v8::Local<'s, v8::Object>,
|
||||
#[webidl(name = "fillRule", converter = "enum", default = CanvasFillRule::NonZero)]
|
||||
fill_rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasRenderingContext2D.stroke")]
|
||||
struct CanvasStrokePathArgs<'s> {
|
||||
#[webidl(required, interface = web_api_interfaces::Path2D)]
|
||||
path: v8::Local<'s, v8::Object>,
|
||||
}
|
||||
|
||||
pub(crate) fn is_canvas_context_receiver<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
receiver: v8::Local<'s, v8::Object>,
|
||||
@@ -370,60 +328,47 @@ fn require_canvas_context_receiver<'s>(
|
||||
pub(crate) fn canvas_context_fill_style_getter_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
rv: v8::ReturnValue<'_, v8::Value>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
get_canvas_color_style(scope, args.this(), rv, CanvasColorStyle::Fill);
|
||||
if !require_canvas_context_receiver(scope, args.this(), "fillStyle getter") {
|
||||
return;
|
||||
}
|
||||
let value = context_string_slot(scope, args.this(), CANVAS_CONTEXT_FILL_STYLE_SLOT)
|
||||
.unwrap_or_else(|| "#000000".to_owned());
|
||||
if let Some(value) = v8_string(scope, &value) {
|
||||
rv.set(value.into());
|
||||
} else {
|
||||
rv.set(v8::String::empty(scope).into());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_context_fill_style_setter_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
assign_canvas_color_style(scope, args, rv, CanvasColorStyle::Fill);
|
||||
}
|
||||
|
||||
fn get_canvas_color_style<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
style: CanvasColorStyle,
|
||||
) {
|
||||
let member = match style {
|
||||
CanvasColorStyle::Fill => "fillStyle getter",
|
||||
CanvasColorStyle::Stroke => "strokeStyle getter",
|
||||
};
|
||||
if !require_canvas_context_receiver(scope, context, member) {
|
||||
if !require_canvas_context_receiver(scope, args.this(), "fillStyle setter") {
|
||||
return;
|
||||
}
|
||||
let color = canvas_color(scope, context, style);
|
||||
let css = serialize_canvas_color(color);
|
||||
rv.set(
|
||||
v8_string(scope, &css)
|
||||
.unwrap_or_else(|| v8::String::empty(scope))
|
||||
.into(),
|
||||
let Some(raw) = canvas_context_dom_string_value(
|
||||
scope,
|
||||
args.get(0),
|
||||
"CanvasRenderingContext2D",
|
||||
"fillStyle",
|
||||
) 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_FILL_STYLE_SLOT,
|
||||
&canonical,
|
||||
);
|
||||
}
|
||||
|
||||
fn assign_canvas_color_style<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
style: CanvasColorStyle,
|
||||
) {
|
||||
let (property, member) = match style {
|
||||
CanvasColorStyle::Fill => ("fillStyle", "fillStyle setter"),
|
||||
CanvasColorStyle::Stroke => ("strokeStyle", "strokeStyle setter"),
|
||||
};
|
||||
if !require_canvas_context_receiver(scope, args.this(), member) {
|
||||
return;
|
||||
}
|
||||
let color =
|
||||
canvas_context_dom_string_value(scope, args.get(0), "CanvasRenderingContext2D", property)
|
||||
.and_then(|value| moli_css_parse::parse_absolute_css_color(&value));
|
||||
if let Some(color) = color {
|
||||
set_canvas_color(scope, args.this(), style, color);
|
||||
}
|
||||
rv.set_undefined();
|
||||
}
|
||||
|
||||
@@ -805,7 +750,7 @@ pub(crate) fn canvas_context_fill_rect_callback<'s>(
|
||||
let fragment = PaintFragment::Fill {
|
||||
fill_rule: moli_layout::PaintFillRule::NonZero,
|
||||
shape: PaintShape::Path(rectangle.paint_path()),
|
||||
brush: PaintBrush::Solid(context_paint_color(scope, context, CanvasColorStyle::Fill)),
|
||||
brush: PaintBrush::Solid(context_fill_color(scope, context)),
|
||||
transform,
|
||||
};
|
||||
rasterize_canvas_fragment(scope, canvas, fragment);
|
||||
@@ -832,15 +777,17 @@ fn canvas_context_clear_rect_callback<'s>(
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_rect_callback<'s>(
|
||||
pub(crate) fn canvas_context_rect_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextRectPathArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| {
|
||||
state.rect(parsed.x, parsed.y, parsed.width, parsed.height);
|
||||
});
|
||||
@@ -858,62 +805,72 @@ pub(crate) fn canvas_context_begin_path_callback<'s>(
|
||||
with_path_state(&path_state, |state| state.begin_path());
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_close_path_callback<'s>(
|
||||
pub(crate) fn canvas_context_close_path_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| state.close_path());
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_move_to_callback<'s>(
|
||||
pub(crate) fn canvas_context_move_to_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextMoveToArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| state.move_to(parsed.x, parsed.y));
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_line_to_callback<'s>(
|
||||
pub(crate) fn canvas_context_line_to_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextLineToArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| state.line_to(parsed.x, parsed.y));
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_quadratic_curve_to_callback<'s>(
|
||||
pub(crate) fn canvas_context_quadratic_curve_to_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextQuadraticCurveToArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| {
|
||||
state.quadratic_curve_to(parsed.cpx, parsed.cpy, parsed.x, parsed.y);
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_bezier_curve_to_callback<'s>(
|
||||
pub(crate) fn canvas_context_bezier_curve_to_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextBezierCurveToArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| {
|
||||
state.bezier_curve_to(
|
||||
parsed.cp1x,
|
||||
@@ -926,11 +883,13 @@ pub(crate) fn canvas_path_bezier_curve_to_callback<'s>(
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_arc_callback<'s>(
|
||||
pub(crate) fn canvas_context_arc_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextArcArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
@@ -951,7 +910,7 @@ pub(crate) fn canvas_path_arc_callback<'s>(
|
||||
rv.set_undefined();
|
||||
return;
|
||||
}
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| {
|
||||
state.arc(
|
||||
parsed.x,
|
||||
@@ -965,11 +924,13 @@ pub(crate) fn canvas_path_arc_callback<'s>(
|
||||
rv.set_undefined();
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_arc_to_callback<'s>(
|
||||
pub(crate) fn canvas_context_arc_to_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextArcToArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
@@ -984,18 +945,20 @@ pub(crate) fn canvas_path_arc_to_callback<'s>(
|
||||
rv.set_undefined();
|
||||
return;
|
||||
}
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| {
|
||||
state.arc_to(parsed.x1, parsed.y1, parsed.x2, parsed.y2, parsed.radius);
|
||||
});
|
||||
rv.set_undefined();
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_path_ellipse_callback<'s>(
|
||||
pub(crate) fn canvas_context_ellipse_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let receiver = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextEllipseArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
@@ -1018,7 +981,7 @@ pub(crate) fn canvas_path_ellipse_callback<'s>(
|
||||
rv.set_undefined();
|
||||
return;
|
||||
}
|
||||
let path_state = canvas_path_state(scope, args.this());
|
||||
let path_state = canvas_path_state(scope, receiver);
|
||||
with_path_state(&path_state, |state| {
|
||||
state.ellipse(
|
||||
parsed.x,
|
||||
@@ -1139,100 +1102,77 @@ pub(crate) fn canvas_context_reset_transform_callback<'s>(
|
||||
pub(crate) fn canvas_context_fill_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
if !require_canvas_context_receiver(scope, args.this(), "fill") {
|
||||
let context = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasDrawPath binding validates the receiver");
|
||||
let Some((explicit_path, rule)) = super::path2d::fill_arguments(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let Some(canvas) = canvas_owner_from_context(scope, context) else {
|
||||
return;
|
||||
};
|
||||
let path_state = canvas_path_state(scope, explicit_path.unwrap_or(context));
|
||||
let transform = canvas_path_state(scope, context).borrow().transform();
|
||||
let fragment = with_path_state(&path_state, |state| {
|
||||
if state.is_empty() || state.inverse_transform().is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(PaintFragment::Fill {
|
||||
fill_rule: rule.paint_rule(),
|
||||
shape: PaintShape::Path(state.paint_path()),
|
||||
brush: PaintBrush::Solid(context_fill_color(scope, context)),
|
||||
transform: if explicit_path.is_some() {
|
||||
transform
|
||||
} else {
|
||||
PaintTransform2D::IDENTITY
|
||||
},
|
||||
})
|
||||
});
|
||||
if let Some(fragment) = fragment {
|
||||
rasterize_canvas_fragment(scope, canvas, fragment);
|
||||
}
|
||||
let (path, fill_rule) = if args.length() >= 2 || path_2d_object(scope, args.get(0)).is_some() {
|
||||
let Some(parsed) = webidl::parse_args::<CanvasFillPathArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
(Some(parsed.path), parsed.fill_rule)
|
||||
} else {
|
||||
let Some(parsed) = webidl::parse_args::<CanvasFillArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
(None, parsed.fill_rule)
|
||||
};
|
||||
let Some(canvas) = canvas_owner_from_context(scope, args.this()) else {
|
||||
return;
|
||||
};
|
||||
let current_path = canvas_path_state(scope, args.this());
|
||||
let transform = {
|
||||
let current = current_path.borrow();
|
||||
if current.inverse_transform().is_none() {
|
||||
return;
|
||||
}
|
||||
current.transform()
|
||||
};
|
||||
let (path, transform) = match path {
|
||||
Some(path) => (canvas_path_state(scope, path), transform),
|
||||
None => (current_path, PaintTransform2D::IDENTITY),
|
||||
};
|
||||
let path = {
|
||||
let path = path.borrow();
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Canvas dimension reads during rasterization can run script.
|
||||
path.paint_path()
|
||||
};
|
||||
let fragment = PaintFragment::Fill {
|
||||
fill_rule: fill_rule.into(),
|
||||
shape: PaintShape::Path(path),
|
||||
brush: PaintBrush::Solid(context_paint_color(
|
||||
scope,
|
||||
args.this(),
|
||||
CanvasColorStyle::Fill,
|
||||
)),
|
||||
transform,
|
||||
};
|
||||
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>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
if !require_canvas_context_receiver(scope, args.this(), "stroke") {
|
||||
let context = moli_webapi_declare::web_api_object_target(scope, args.this())
|
||||
.expect("generated CanvasDrawPath binding validates the receiver");
|
||||
let Some(parsed) = webidl::parse_args::<super::path2d::StrokeArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let explicit_path = parsed.path.map(|object| {
|
||||
moli_webapi_declare::web_api_object_target(scope, object)
|
||||
.expect("validated Path2D argument")
|
||||
});
|
||||
let Some(canvas) = canvas_owner_from_context(scope, context) else {
|
||||
return;
|
||||
};
|
||||
let path_state = canvas_path_state(scope, explicit_path.unwrap_or(context));
|
||||
let transform = canvas_path_state(scope, context).borrow().transform();
|
||||
let fragment = with_path_state(&path_state, |state| {
|
||||
if state.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(PaintFragment::Stroke(context_stroke(
|
||||
scope,
|
||||
context,
|
||||
if explicit_path.is_some() {
|
||||
state.paint_path()
|
||||
} else {
|
||||
state.stroke_path()?
|
||||
},
|
||||
transform,
|
||||
)))
|
||||
});
|
||||
if let Some(fragment) = fragment {
|
||||
rasterize_canvas_fragment(scope, canvas, fragment);
|
||||
}
|
||||
let path = if args.length() > 0 {
|
||||
let Some(parsed) = webidl::parse_args::<CanvasStrokePathArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
Some(parsed.path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(canvas) = canvas_owner_from_context(scope, args.this()) else {
|
||||
return;
|
||||
};
|
||||
let current_path = canvas_path_state(scope, args.this());
|
||||
let supplied_path = path.map(|path| canvas_path_state(scope, path));
|
||||
let (path, transform) = {
|
||||
let current = current_path.borrow();
|
||||
let path = if let Some(path) = supplied_path {
|
||||
let path = path.borrow();
|
||||
if path.is_empty() || current.inverse_transform().is_none() {
|
||||
return;
|
||||
}
|
||||
path.paint_path()
|
||||
} else {
|
||||
if current.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(path) = current.stroke_path() else {
|
||||
return;
|
||||
};
|
||||
path
|
||||
};
|
||||
(path, current.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_stroke_rect_callback<'s>(
|
||||
@@ -1453,17 +1393,48 @@ pub(crate) fn canvas_context_line_join_setter_callback<'s>(
|
||||
pub(crate) fn canvas_context_stroke_style_getter_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
rv: v8::ReturnValue<'_, v8::Value>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
get_canvas_color_style(scope, args.this(), rv, CanvasColorStyle::Stroke);
|
||||
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>,
|
||||
rv: v8::ReturnValue<'_, v8::Value>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
assign_canvas_color_style(scope, args, rv, CanvasColorStyle::Stroke);
|
||||
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_positive_number_assign<'s>(
|
||||
@@ -1509,15 +1480,34 @@ fn with_path_state<T>(
|
||||
update(&mut state.borrow_mut())
|
||||
}
|
||||
|
||||
fn context_paint_color<'s>(
|
||||
fn context_fill_color<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
style: CanvasColorStyle,
|
||||
) -> PaintColor {
|
||||
let [red, green, blue, alpha] = canvas_srgb_components(canvas_color(scope, context, style));
|
||||
let global_alpha = context_number_slot(scope, context, CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT)
|
||||
.unwrap_or(DEFAULT_GLOBAL_ALPHA);
|
||||
PaintColor::new(red, green, blue, (f64::from(alpha) * global_alpha) as f32)
|
||||
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>(
|
||||
@@ -1526,6 +1516,8 @@ fn context_stroke<'s>(
|
||||
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,
|
||||
@@ -1538,7 +1530,10 @@ fn context_stroke<'s>(
|
||||
};
|
||||
PaintStroke {
|
||||
path,
|
||||
color: context_paint_color(scope, context, CanvasColorStyle::Stroke),
|
||||
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,
|
||||
@@ -1572,68 +1567,26 @@ fn context_line_dash<'s>(
|
||||
fn rasterize_canvas_fragment<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
canvas: v8::Local<'s, v8::Object>,
|
||||
mut fragment: PaintFragment,
|
||||
fragment: PaintFragment,
|
||||
) {
|
||||
let _ = with_canvas_like_pixels_mut(scope, canvas, |pixels, width, height| {
|
||||
let (bounds, transform) = match &mut fragment {
|
||||
PaintFragment::Fill {
|
||||
shape, transform, ..
|
||||
} => (canvas_raster_bounds(shape.bounds()), transform),
|
||||
PaintFragment::Stroke(stroke) => {
|
||||
// Include square caps and the farthest permitted miter join.
|
||||
let outset = f64::from(stroke.width) * f64::from(stroke.miter_limit.max(1.0));
|
||||
(
|
||||
canvas_raster_bounds(stroke.path.bounds).inflate(outset, outset),
|
||||
&mut stroke.transform,
|
||||
)
|
||||
}
|
||||
_ => unreachable!("Canvas path drawing only rasterizes fills and strokes"),
|
||||
};
|
||||
let surface = kurbo::Rect::new(0.0, 0.0, f64::from(width), f64::from(height));
|
||||
let transformed_bounds =
|
||||
kurbo::Affine::new(transform.coefficients).transform_rect_bbox(bounds);
|
||||
let region =
|
||||
if bounds.is_finite() && transformed_bounds.is_finite() && transform.is_finite() {
|
||||
// Retain the antialiased fringe and preserve the canvas pixel grid.
|
||||
surface.intersect(transformed_bounds.inflate(1.0, 1.0).expand())
|
||||
} else {
|
||||
surface
|
||||
};
|
||||
let region_width = region.width() as u32;
|
||||
let region_height = region.height() as u32;
|
||||
if region_width == 0 || region_height == 0 {
|
||||
if width == 0 || height == 0 {
|
||||
return;
|
||||
}
|
||||
let offset = PaintTransform2D::new([1.0, 0.0, 0.0, 1.0, -region.x0, -region.y0]);
|
||||
*transform = offset.concatenate(*transform);
|
||||
let mut snapshot = PaintSnapshot::new(
|
||||
PaintViewport::new(region_width, region_height, 1.0),
|
||||
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 == region_width
|
||||
&& raster.height == region_height
|
||||
&& raster.width == width
|
||||
&& raster.height == height
|
||||
{
|
||||
let offset = region.x0 as usize * 4;
|
||||
let canvas_rows = pixels
|
||||
.chunks_exact_mut(width as usize * 4)
|
||||
.skip(region.y0 as usize);
|
||||
let raster_rows = raster.rgba.chunks_exact(region_width as usize * 4);
|
||||
for (destination, source) in canvas_rows.zip(raster_rows) {
|
||||
composite_rgba8_over(&mut destination[offset..offset + source.len()], source);
|
||||
}
|
||||
composite_rgba8_over(pixels, &raster.rgba);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn canvas_raster_bounds(rect: moli_layout::PaintRect) -> kurbo::Rect {
|
||||
kurbo::Rect::from_origin_size(
|
||||
(f64::from(rect.x), f64::from(rect.y)),
|
||||
(f64::from(rect.width), f64::from(rect.height)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Composites straight-alpha RGBA8 source and destination using source-over.
|
||||
fn composite_rgba8_over(destination: &mut [u8], source: &[u8]) {
|
||||
for (dst, src) in destination
|
||||
@@ -1685,15 +1638,7 @@ pub(crate) fn canvas_context_fill_text_callback<'s>(
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextFillTextArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
draw_canvas_context_text(
|
||||
scope,
|
||||
args.this(),
|
||||
canvas,
|
||||
&parsed.text,
|
||||
parsed.x,
|
||||
parsed.y,
|
||||
CanvasColorStyle::Fill,
|
||||
);
|
||||
draw_canvas_context_text(scope, args.this(), canvas, &parsed.text, parsed.x, parsed.y);
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_context_stroke_text_callback<'s>(
|
||||
@@ -1707,15 +1652,7 @@ pub(crate) fn canvas_context_stroke_text_callback<'s>(
|
||||
let Some(parsed) = webidl::parse_args::<CanvasContextStrokeTextArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
draw_canvas_context_text(
|
||||
scope,
|
||||
args.this(),
|
||||
canvas,
|
||||
&parsed.text,
|
||||
parsed.x,
|
||||
parsed.y,
|
||||
CanvasColorStyle::Stroke,
|
||||
);
|
||||
draw_canvas_context_text(scope, args.this(), canvas, &parsed.text, parsed.x, parsed.y);
|
||||
}
|
||||
|
||||
fn draw_canvas_context_text<'s>(
|
||||
@@ -1725,11 +1662,12 @@ fn draw_canvas_context_text<'s>(
|
||||
text: &str,
|
||||
x: f64,
|
||||
y: f64,
|
||||
style: CanvasColorStyle,
|
||||
) {
|
||||
let fill_style = context_string_slot(scope, context, CANVAS_CONTEXT_FILL_STYLE_SLOT)
|
||||
.unwrap_or_else(|| DEFAULT_FILL_STYLE.to_owned());
|
||||
let font = context_string_slot(scope, context, CANVAS_CONTEXT_FONT_SLOT)
|
||||
.unwrap_or_else(|| DEFAULT_FONT.to_owned());
|
||||
let color = canvas_srgb_components(canvas_color(scope, context, style)).map(clamp_unit_f32);
|
||||
let color = fill_style_rgba(&fill_style);
|
||||
let _ = with_canvas_like_pixels_mut(scope, canvas, |pixels, width, height| {
|
||||
draw_text(pixels, width, height, text, x, y, &font, color);
|
||||
});
|
||||
|
||||
@@ -16,4 +16,8 @@ pub(super) fn canvas_unrestricted_double_arg<'s>(
|
||||
.map(f64::from)
|
||||
}
|
||||
|
||||
pub(super) fn canonical_canvas_fill_style(raw: &str) -> Option<String> {
|
||||
moli_canvas::canonicalize_fill_style(raw)
|
||||
}
|
||||
|
||||
pub(super) use moli_webapi::canvas_context_values::init_canvas_like_context_object;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Path geometry shared by Canvas 2D contexts and detached Path2D objects.
|
||||
//! Canvas 2D current-path geometry, owned by the context's native state.
|
||||
|
||||
use moli_layout::{
|
||||
LayoutPoint, LayoutRect, LayoutTransform2D, PaintPath, PaintPathElement, PaintRect,
|
||||
@@ -34,33 +34,49 @@ impl Default for Canvas2dPathState {
|
||||
const TWO_PI: f64 = std::f64::consts::TAU;
|
||||
|
||||
impl Canvas2dPathState {
|
||||
pub(super) fn from_svg(data: &str) -> Self {
|
||||
let mut path = Self::default();
|
||||
for element in moli_svg::parse_path_data(data) {
|
||||
match element {
|
||||
kurbo::PathEl::MoveTo(p) => path.move_to(p.x, p.y),
|
||||
kurbo::PathEl::LineTo(p) => path.line_to(p.x, p.y),
|
||||
kurbo::PathEl::QuadTo(a, p) => path.quadratic_curve_to(a.x, a.y, p.x, p.y),
|
||||
pub(super) fn from_svg(raw: &str) -> Self {
|
||||
let mut state = Self::default();
|
||||
for element in moli_svg::parse_path_data(raw).elements() {
|
||||
match *element {
|
||||
kurbo::PathEl::MoveTo(p) => state.move_to(p.x, p.y),
|
||||
kurbo::PathEl::LineTo(p) => state.line_to(p.x, p.y),
|
||||
kurbo::PathEl::QuadTo(a, p) => state.quadratic_curve_to(a.x, a.y, p.x, p.y),
|
||||
kurbo::PathEl::CurveTo(a, b, p) => {
|
||||
path.bezier_curve_to(a.x, a.y, b.x, b.y, p.x, p.y);
|
||||
state.bezier_curve_to(a.x, a.y, b.x, b.y, p.x, p.y);
|
||||
}
|
||||
kurbo::PathEl::ClosePath => path.close_path(),
|
||||
kurbo::PathEl::ClosePath => state.close_path(),
|
||||
}
|
||||
}
|
||||
if path.has_subpath {
|
||||
path.move_to(path.current.0, path.current.1);
|
||||
if state.has_subpath {
|
||||
state.move_to(state.current.0, state.current.1);
|
||||
}
|
||||
path
|
||||
state
|
||||
}
|
||||
|
||||
pub(super) fn add_path(&mut self, path: &Self, transform: [f64; 6]) {
|
||||
if path.is_empty() || !transform.into_iter().all(f64::is_finite) {
|
||||
/// Append a snapshot in local coordinates, then start a new subpath at its
|
||||
/// final point. The caller snapshots before borrowing the destination so
|
||||
/// addPath(self, transform) never borrows the same RefCell twice.
|
||||
pub(super) fn add_path(&mut self, source: &Self, matrix: [f64; 6]) {
|
||||
if !source.has_subpath || !matrix.into_iter().all(f64::is_finite) {
|
||||
return;
|
||||
}
|
||||
let transform = kurbo::Affine::new(transform);
|
||||
self.elements.extend(path.transformed_elements(transform));
|
||||
let end = transform * kurbo::Point::from(path.current);
|
||||
self.move_to(end.x, end.y);
|
||||
let affine = kurbo::Affine::new(matrix);
|
||||
let map = |p: LayoutPoint| {
|
||||
let p = affine * kurbo::Point::new(f64::from(p.x), f64::from(p.y));
|
||||
point(p.x, p.y)
|
||||
};
|
||||
self.elements
|
||||
.extend(source.elements.iter().map(|element| match *element {
|
||||
PaintPathElement::MoveTo(p) => PaintPathElement::MoveTo(map(p)),
|
||||
PaintPathElement::LineTo(p) => PaintPathElement::LineTo(map(p)),
|
||||
PaintPathElement::QuadTo(a, p) => PaintPathElement::QuadTo(map(a), map(p)),
|
||||
PaintPathElement::CubicTo(a, b, p) => {
|
||||
PaintPathElement::CubicTo(map(a), map(b), map(p))
|
||||
}
|
||||
PaintPathElement::Close => PaintPathElement::Close,
|
||||
}));
|
||||
let last = affine * kurbo::Point::from(source.current);
|
||||
self.move_to(last.x, last.y);
|
||||
}
|
||||
|
||||
pub(super) fn begin_path(&mut self) {
|
||||
@@ -328,32 +344,30 @@ impl Canvas2dPathState {
|
||||
/// back to that space and let the painter transform the resulting stroke,
|
||||
/// so anisotropic line widths, joins and dashes change without moving it.
|
||||
pub(super) fn stroke_path(&self) -> Option<PaintPath> {
|
||||
let elements: Vec<_> = self
|
||||
.transformed_elements(self.inverse_transform()?)
|
||||
.collect();
|
||||
let inverse = self.inverse_transform()?;
|
||||
let map = |p: LayoutPoint| {
|
||||
let p = inverse * kurbo::Point::new(f64::from(p.x), f64::from(p.y));
|
||||
point(p.x, p.y)
|
||||
};
|
||||
let elements = self
|
||||
.elements
|
||||
.iter()
|
||||
.map(|element| match *element {
|
||||
PaintPathElement::MoveTo(p) => PaintPathElement::MoveTo(map(p)),
|
||||
PaintPathElement::LineTo(p) => PaintPathElement::LineTo(map(p)),
|
||||
PaintPathElement::QuadTo(a, p) => PaintPathElement::QuadTo(map(a), map(p)),
|
||||
PaintPathElement::CubicTo(a, b, p) => {
|
||||
PaintPathElement::CubicTo(map(a), map(b), map(p))
|
||||
}
|
||||
PaintPathElement::Close => PaintPathElement::Close,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Some(PaintPath {
|
||||
bounds: path_bounds(&elements),
|
||||
elements,
|
||||
})
|
||||
}
|
||||
|
||||
fn transformed_elements(
|
||||
&self,
|
||||
transform: kurbo::Affine,
|
||||
) -> impl Iterator<Item = PaintPathElement> + '_ {
|
||||
let map = move |p: LayoutPoint| {
|
||||
let p = transform * kurbo::Point::new(f64::from(p.x), f64::from(p.y));
|
||||
point(p.x, p.y)
|
||||
};
|
||||
self.elements.iter().map(move |element| match *element {
|
||||
PaintPathElement::MoveTo(p) => PaintPathElement::MoveTo(map(p)),
|
||||
PaintPathElement::LineTo(p) => PaintPathElement::LineTo(map(p)),
|
||||
PaintPathElement::QuadTo(a, p) => PaintPathElement::QuadTo(map(a), map(p)),
|
||||
PaintPathElement::CubicTo(a, b, p) => PaintPathElement::CubicTo(map(a), map(b), map(p)),
|
||||
PaintPathElement::Close => PaintPathElement::Close,
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds an owned `PaintPath` with conservative local bounds.
|
||||
pub(super) fn paint_path(&self) -> PaintPath {
|
||||
PaintPath {
|
||||
@@ -368,9 +382,6 @@ impl Canvas2dPathState {
|
||||
}
|
||||
|
||||
fn path_bounds(elements: &[PaintPathElement]) -> PaintRect {
|
||||
if elements.is_empty() {
|
||||
return LayoutRect::ZERO;
|
||||
}
|
||||
let mut min_x = f64::INFINITY;
|
||||
let mut min_y = f64::INFINITY;
|
||||
let mut max_x = f64::NEG_INFINITY;
|
||||
@@ -392,6 +403,9 @@ fn path_bounds(elements: &[PaintPathElement]) -> PaintRect {
|
||||
PaintPathElement::Close => {}
|
||||
}
|
||||
}
|
||||
if !min_x.is_finite() {
|
||||
return LayoutRect::ZERO;
|
||||
}
|
||||
LayoutRect::new(
|
||||
min_x as f32,
|
||||
min_y as f32,
|
||||
@@ -400,6 +414,10 @@ fn path_bounds(elements: &[PaintPathElement]) -> PaintRect {
|
||||
)
|
||||
}
|
||||
|
||||
fn point(x: f64, y: f64) -> LayoutPoint {
|
||||
LayoutPoint::new(x as f32, y as f32)
|
||||
}
|
||||
|
||||
fn enclosing_extent(start: f64, end: f64) -> f32 {
|
||||
let extent = (end - start) as f32;
|
||||
// Reconstruct the far edge the same way as the raster crop. A rounded
|
||||
@@ -411,10 +429,6 @@ fn enclosing_extent(start: f64, end: f64) -> 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);
|
||||
|
||||
@@ -1,89 +1,217 @@
|
||||
use super::context2d::{
|
||||
canvas_path_arc_callback, canvas_path_arc_to_callback, canvas_path_bezier_curve_to_callback,
|
||||
canvas_path_close_path_callback, canvas_path_ellipse_callback, canvas_path_line_to_callback,
|
||||
canvas_path_move_to_callback, canvas_path_quadratic_curve_to_callback,
|
||||
canvas_path_rect_callback,
|
||||
//! Native Path2D construction and shared CanvasPath bindings.
|
||||
|
||||
use super::*;
|
||||
use super::{path::Canvas2dPathState, state::canvas_path_state};
|
||||
use moli_webapi::{
|
||||
canvas_context_values::transform::validate_transform_init, geometry::DomMatrix2DInit,
|
||||
};
|
||||
use super::path::Canvas2dPathState;
|
||||
use super::state::canvas_path_state;
|
||||
use crate::{util::throw_type_error, web_api_interfaces, webidl};
|
||||
use moli_webapi::canvas_context_values::transform::transform_init_coefficients;
|
||||
use moli_webapi::geometry::DomMatrix2DInit;
|
||||
use moli_webapi_declare::WebApiFunctionTemplate;
|
||||
use moli_webapi_declare::web_api_object_target;
|
||||
|
||||
macro_rules! canvas_path_declaration {
|
||||
($name:ident, $interface:path) => {
|
||||
#[derive(WebApiFunctionTemplate)]
|
||||
#[webapi(interface = $interface, enumerable)]
|
||||
struct $name {
|
||||
#[webapi(method = "closePath", length = 0, callback = canvas_context_close_path_callback)]
|
||||
close_path: (),
|
||||
#[webapi(method = "moveTo", length = 2, callback = canvas_context_move_to_callback)]
|
||||
move_to: (),
|
||||
#[webapi(method = "lineTo", length = 2, callback = canvas_context_line_to_callback)]
|
||||
line_to: (),
|
||||
#[webapi(method = "quadraticCurveTo", length = 4, callback = canvas_context_quadratic_curve_to_callback)]
|
||||
quadratic_curve_to: (),
|
||||
#[webapi(method = "bezierCurveTo", length = 6, callback = canvas_context_bezier_curve_to_callback)]
|
||||
bezier_curve_to: (),
|
||||
#[webapi(method = "arcTo", length = 5, callback = canvas_context_arc_to_callback)]
|
||||
arc_to: (),
|
||||
#[webapi(method = "arc", length = 5, callback = canvas_context_arc_callback)]
|
||||
arc: (),
|
||||
#[webapi(method = "ellipse", length = 7, callback = canvas_context_ellipse_callback)]
|
||||
ellipse: (),
|
||||
#[webapi(method = "rect", length = 4, callback = canvas_context_rect_callback)]
|
||||
rect: (),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
canvas_path_declaration!(Path2dCanvasPathDeclaration, web_api_interfaces::Path2D);
|
||||
canvas_path_declaration!(
|
||||
CanvasPathDeclaration,
|
||||
web_api_interfaces::CanvasRenderingContext2D
|
||||
);
|
||||
canvas_path_declaration!(
|
||||
OffscreenCanvasPathDeclaration,
|
||||
web_api_interfaces::OffscreenCanvasRenderingContext2D
|
||||
);
|
||||
|
||||
macro_rules! canvas_draw_path_declaration {
|
||||
($name:ident, $interface:path) => {
|
||||
#[derive(WebApiFunctionTemplate)]
|
||||
#[webapi(interface = $interface, enumerable)]
|
||||
struct $name {
|
||||
#[webapi(method = "fill", length = 0, callback = canvas_context_fill_callback)]
|
||||
fill: (),
|
||||
#[webapi(method = "stroke", length = 0, callback = canvas_context_stroke_callback)]
|
||||
stroke: (),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
canvas_draw_path_declaration!(
|
||||
CanvasDrawPathDeclaration,
|
||||
web_api_interfaces::CanvasRenderingContext2D
|
||||
);
|
||||
canvas_draw_path_declaration!(
|
||||
OffscreenCanvasDrawPathDeclaration,
|
||||
web_api_interfaces::OffscreenCanvasRenderingContext2D
|
||||
);
|
||||
|
||||
#[derive(WebApiFunctionTemplate)]
|
||||
#[webapi(interface = web_api_interfaces::Path2D, enumerable)]
|
||||
struct Path2dMethods {
|
||||
struct Path2dPrototypeDeclaration {
|
||||
#[webapi(method = "addPath", length = 1, callback = add_path_callback)]
|
||||
add_path: (),
|
||||
#[webapi(method = "closePath", length = 0, callback = canvas_path_close_path_callback)]
|
||||
close_path: (),
|
||||
#[webapi(method = "moveTo", length = 2, callback = canvas_path_move_to_callback)]
|
||||
move_to: (),
|
||||
#[webapi(method = "lineTo", length = 2, callback = canvas_path_line_to_callback)]
|
||||
line_to: (),
|
||||
#[webapi(method = "quadraticCurveTo", length = 4, callback = canvas_path_quadratic_curve_to_callback)]
|
||||
quadratic_curve_to: (),
|
||||
#[webapi(method = "bezierCurveTo", length = 6, callback = canvas_path_bezier_curve_to_callback)]
|
||||
bezier_curve_to: (),
|
||||
#[webapi(method = "arcTo", length = 5, callback = canvas_path_arc_to_callback)]
|
||||
arc_to: (),
|
||||
#[webapi(method = "rect", length = 4, callback = canvas_path_rect_callback)]
|
||||
rect: (),
|
||||
#[webapi(method = "arc", length = 5, callback = canvas_path_arc_callback)]
|
||||
arc: (),
|
||||
#[webapi(method = "ellipse", length = 7, callback = canvas_path_ellipse_callback)]
|
||||
ellipse: (),
|
||||
}
|
||||
|
||||
pub(super) fn install_path_2d_template_bindings<'s>(
|
||||
pub(crate) fn install_canvas_path_bindings<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_, ()>,
|
||||
template: v8::Local<'s, v8::FunctionTemplate>,
|
||||
prototype: v8::Local<'s, v8::ObjectTemplate>,
|
||||
interface: &str,
|
||||
) {
|
||||
let prototype = template.prototype_template(scope);
|
||||
Path2dMethods::initialize_prototype_template(scope, prototype);
|
||||
match interface {
|
||||
"Path2D" => {
|
||||
Path2dCanvasPathDeclaration::initialize_prototype_template(scope, prototype);
|
||||
Path2dPrototypeDeclaration::initialize_prototype_template(scope, prototype);
|
||||
}
|
||||
"CanvasRenderingContext2D" => {
|
||||
CanvasPathDeclaration::initialize_prototype_template(scope, prototype);
|
||||
CanvasDrawPathDeclaration::initialize_prototype_template(scope, prototype);
|
||||
}
|
||||
"OffscreenCanvasRenderingContext2D" => {
|
||||
OffscreenCanvasPathDeclaration::initialize_prototype_template(scope, prototype);
|
||||
OffscreenCanvasDrawPathDeclaration::initialize_prototype_template(scope, prototype);
|
||||
}
|
||||
_ => unreachable!("only CanvasPath interfaces have path bindings"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn path_2d_object<'s>(
|
||||
#[derive(Clone, Copy, Default, webidl::WebIdlEnum)]
|
||||
#[webidl(name = "CanvasFillRule")]
|
||||
pub(super) enum CanvasFillRule {
|
||||
#[default]
|
||||
#[webidl(token = "nonzero")]
|
||||
Nonzero,
|
||||
#[webidl(token = "evenodd")]
|
||||
Evenodd,
|
||||
}
|
||||
|
||||
impl CanvasFillRule {
|
||||
pub(super) fn paint_rule(self) -> moli_layout::PaintFillRule {
|
||||
match self {
|
||||
Self::Nonzero => moli_layout::PaintFillRule::NonZero,
|
||||
Self::Evenodd => moli_layout::PaintFillRule::EvenOdd,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.fill")]
|
||||
struct FillRuleArgs {
|
||||
#[webidl(default = CanvasFillRule::Nonzero, converter = "enum")]
|
||||
rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.fill")]
|
||||
struct FillPathArgs<'s> {
|
||||
#[webidl(required, interface = web_api_interfaces::Path2D)]
|
||||
path: v8::Local<'s, v8::Object>,
|
||||
#[webidl(default = CanvasFillRule::Nonzero, converter = "enum")]
|
||||
rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
pub(super) fn fill_arguments<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: &v8::FunctionCallbackArguments<'s>,
|
||||
) -> Option<(Option<v8::Local<'s, v8::Object>>, CanvasFillRule)> {
|
||||
if args.length() > 1 {
|
||||
let parsed = webidl::parse_args::<FillPathArgs>(scope, args)?;
|
||||
let target = web_api_object_target(scope, parsed.path).expect("validated Path2D argument");
|
||||
return Some((Some(target), parsed.rule));
|
||||
}
|
||||
if let Ok(object) = path_object(
|
||||
scope,
|
||||
args.get(0),
|
||||
webidl::Context::argument("CanvasDrawPath.fill", 1),
|
||||
) {
|
||||
return Some((Some(object), CanvasFillRule::Nonzero));
|
||||
}
|
||||
let parsed = webidl::parse_args::<FillRuleArgs>(scope, args)?;
|
||||
Some((None, parsed.rule))
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.stroke")]
|
||||
pub(super) struct StrokeArgs<'s> {
|
||||
#[webidl(interface = web_api_interfaces::Path2D)]
|
||||
pub(super) path: Option<v8::Local<'s, v8::Object>>,
|
||||
}
|
||||
|
||||
/// Union selection uses the same native interface converter as derive fields;
|
||||
/// it never consults author-visible constructors or prototype chains.
|
||||
pub(super) fn path_object<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
value: v8::Local<'s, v8::Value>,
|
||||
) -> Option<v8::Local<'s, v8::Object>> {
|
||||
let object = v8::Local::<v8::Object>::try_from(value).ok()?;
|
||||
web_api_interfaces::Path2D::is_instance(scope, object).then_some(object)
|
||||
context: webidl::Context,
|
||||
) -> Result<v8::Local<'s, v8::Object>, webidl::WebIdlError> {
|
||||
webidl::convert_with_options::<webidl::InterfaceObject>(
|
||||
scope,
|
||||
value,
|
||||
context,
|
||||
&webidl::InterfaceOptions {
|
||||
name: web_api_interfaces::Path2D::NAME,
|
||||
brand_check: web_api_interfaces::Path2D::is_instance,
|
||||
},
|
||||
)
|
||||
.map(|object| {
|
||||
web_api_object_target(scope, object.0).expect("branded Path2D has native identity")
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn path_2d_constructor_callback<'s>(
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "Path2D")]
|
||||
struct ConstructorArgs<'s> {
|
||||
path: Option<v8::Local<'s, v8::Value>>,
|
||||
}
|
||||
|
||||
pub(crate) fn path2d_constructor_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
if !args.is_construct_call() {
|
||||
throw_type_error(
|
||||
scope,
|
||||
"Failed to construct 'Path2D': Please use the 'new' operator.",
|
||||
);
|
||||
throw_type_error(scope, "Path2D requires the new operator");
|
||||
return;
|
||||
}
|
||||
let input = args.get(0);
|
||||
if input.is_undefined() {
|
||||
let Some(parsed) = webidl::parse_args::<ConstructorArgs>(scope, &args) else {
|
||||
return;
|
||||
}
|
||||
let path = if let Some(source) = path_2d_object(scope, input) {
|
||||
canvas_path_state(scope, source).borrow().clone()
|
||||
} else {
|
||||
match webidl::convert::<webidl::DomString>(
|
||||
scope,
|
||||
input,
|
||||
webidl::Context::argument("Path2D", 1),
|
||||
) {
|
||||
Ok(data) => Canvas2dPathState::from_svg(&data.0),
|
||||
Err(error) => {
|
||||
webidl::throw_error(scope, &error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
*canvas_path_state(scope, args.this()).borrow_mut() = path;
|
||||
let context = webidl::Context::argument("Path2D", 1);
|
||||
let state = match parsed.path {
|
||||
None => Canvas2dPathState::default(),
|
||||
Some(value) => match path_object(scope, value, context) {
|
||||
Ok(object) => canvas_path_state(scope, object).borrow().clone(),
|
||||
Err(_) => match webidl::convert::<webidl::DomString>(scope, value, context) {
|
||||
Ok(text) => Canvas2dPathState::from_svg(&text.0),
|
||||
Err(error) => {
|
||||
webidl::throw_error(scope, &error);
|
||||
return;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
*canvas_path_state(scope, args.this()).borrow_mut() = state;
|
||||
rv.set(args.this().into());
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
@@ -91,7 +219,7 @@ pub(crate) fn path_2d_constructor_callback<'s>(
|
||||
struct AddPathArgs<'s> {
|
||||
#[webidl(required, interface = web_api_interfaces::Path2D)]
|
||||
path: v8::Local<'s, v8::Object>,
|
||||
#[webidl(dictionary, default = DomMatrix2DInit::default())]
|
||||
#[webidl(dictionary)]
|
||||
transform: DomMatrix2DInit,
|
||||
}
|
||||
|
||||
@@ -103,16 +231,20 @@ fn add_path_callback<'s>(
|
||||
let Some(parsed) = webidl::parse_args::<AddPathArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let source = canvas_path_state(scope, parsed.path);
|
||||
let source = web_api_object_target(scope, parsed.path).expect("validated Path2D argument");
|
||||
let source = canvas_path_state(scope, source);
|
||||
if source.borrow().is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(transform) = transform_init_coefficients(scope, &parsed.transform) else {
|
||||
let Some(matrix) = validate_transform_init(scope, parsed.transform) else {
|
||||
return;
|
||||
};
|
||||
// Copy before borrowing the destination, since addPath can append itself.
|
||||
let source = source.borrow().clone();
|
||||
canvas_path_state(scope, args.this())
|
||||
if !matrix.into_iter().all(f64::is_finite) {
|
||||
return;
|
||||
}
|
||||
let snapshot = source.borrow().clone();
|
||||
let target = web_api_object_target(scope, args.this()).expect("validated Path2D receiver");
|
||||
canvas_path_state(scope, target)
|
||||
.borrow_mut()
|
||||
.add_path(&source, transform);
|
||||
.add_path(&snapshot, matrix);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
//! Canvas contexts own their drawing state. Path2D objects own their paths.
|
||||
//! Native path state belongs to the V8 context object, never to the process.
|
||||
//!
|
||||
//! The isolate owns the table. Weak context handles remove entries on GC;
|
||||
//! dropping the isolate also drops every remaining entry without needing GC.
|
||||
|
||||
use std::{cell::RefCell, collections::HashMap, rc::Rc};
|
||||
use style::color::AbsoluteColor;
|
||||
|
||||
use super::color::CanvasColorStyle;
|
||||
use super::path::Canvas2dPathState;
|
||||
use crate::util::{get_private_value, set_private_value};
|
||||
|
||||
const CANVAS_STATE_SLOT: &str = "__moliCanvasState";
|
||||
const PATH_STATE_SLOT: &str = "__moliCanvasPathState";
|
||||
type StateStore = Rc<RefCell<CanvasStates>>;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -20,26 +18,14 @@ struct CanvasStates {
|
||||
}
|
||||
|
||||
struct CanvasStateEntry {
|
||||
_owner: v8::Weak<v8::Object>,
|
||||
path: Rc<RefCell<Canvas2dPathState>>,
|
||||
fill: AbsoluteColor,
|
||||
stroke: AbsoluteColor,
|
||||
_context: v8::Weak<v8::Object>,
|
||||
state: Rc<RefCell<Canvas2dPathState>>,
|
||||
}
|
||||
|
||||
impl CanvasStateEntry {
|
||||
fn color(&mut self, style: CanvasColorStyle) -> &mut AbsoluteColor {
|
||||
match style {
|
||||
CanvasColorStyle::Fill => &mut self.fill,
|
||||
CanvasColorStyle::Stroke => &mut self.stroke,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn with_canvas_state<'s, T>(
|
||||
pub(super) fn canvas_path_state<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
object: v8::Local<'s, v8::Object>,
|
||||
update: impl FnOnce(&mut CanvasStateEntry) -> T,
|
||||
) -> T {
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
) -> Rc<RefCell<Canvas2dPathState>> {
|
||||
let store = if let Some(store) = scope.get_slot::<StateStore>() {
|
||||
store.clone()
|
||||
} else {
|
||||
@@ -47,86 +33,55 @@ fn with_canvas_state<'s, T>(
|
||||
scope.set_slot(store.clone());
|
||||
store
|
||||
};
|
||||
let id = if let Some(id) = get_private_value(scope, object, CANVAS_STATE_SLOT)
|
||||
if let Some(id) = get_private_value(scope, context, PATH_STATE_SLOT)
|
||||
.and_then(|value| v8::Local::<v8::BigInt>::try_from(value).ok())
|
||||
.map(|value| value.u64_value().0)
|
||||
{
|
||||
id
|
||||
} else {
|
||||
let id = {
|
||||
let mut store = store.borrow_mut();
|
||||
store.next_id = store
|
||||
.next_id
|
||||
.checked_add(1)
|
||||
.expect("canvas state identity exhausted");
|
||||
store.next_id
|
||||
};
|
||||
let weak_store = Rc::downgrade(&store);
|
||||
let owner = v8::Weak::with_finalizer(
|
||||
scope,
|
||||
object,
|
||||
Box::new(move |_| {
|
||||
if let Some(store) = weak_store.upgrade() {
|
||||
store.borrow_mut().entries.remove(&id);
|
||||
}
|
||||
}),
|
||||
);
|
||||
store.borrow_mut().entries.insert(
|
||||
id,
|
||||
CanvasStateEntry {
|
||||
_owner: owner,
|
||||
path: Rc::new(RefCell::new(Canvas2dPathState::default())),
|
||||
fill: AbsoluteColor::BLACK,
|
||||
stroke: AbsoluteColor::BLACK,
|
||||
},
|
||||
);
|
||||
let identity = v8::BigInt::new_from_u64(scope, id);
|
||||
set_private_value(scope, object, CANVAS_STATE_SLOT, identity.into());
|
||||
id
|
||||
};
|
||||
let mut store = store.borrow_mut();
|
||||
update(
|
||||
store
|
||||
return store
|
||||
.borrow()
|
||||
.entries
|
||||
.get_mut(&id)
|
||||
.expect("a live object must retain its native drawing state"),
|
||||
)
|
||||
.get(&id)
|
||||
.expect("a live context must retain its native path state")
|
||||
.state
|
||||
.clone();
|
||||
}
|
||||
let id = {
|
||||
let mut store = store.borrow_mut();
|
||||
store.next_id = store
|
||||
.next_id
|
||||
.checked_add(1)
|
||||
.expect("canvas state identity exhausted");
|
||||
store.next_id
|
||||
};
|
||||
let weak_store = Rc::downgrade(&store);
|
||||
let owner = v8::Weak::with_finalizer(
|
||||
scope,
|
||||
context,
|
||||
Box::new(move |_| {
|
||||
if let Some(store) = weak_store.upgrade() {
|
||||
store.borrow_mut().entries.remove(&id);
|
||||
}
|
||||
}),
|
||||
);
|
||||
let state = Rc::new(RefCell::new(Canvas2dPathState::default()));
|
||||
store.borrow_mut().entries.insert(
|
||||
id,
|
||||
CanvasStateEntry {
|
||||
_context: owner,
|
||||
state: state.clone(),
|
||||
},
|
||||
);
|
||||
let id = v8::BigInt::new_from_u64(scope, id);
|
||||
set_private_value(scope, context, PATH_STATE_SLOT, id.into());
|
||||
state
|
||||
}
|
||||
|
||||
pub(super) fn canvas_path_state<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
object: v8::Local<'s, v8::Object>,
|
||||
) -> Rc<RefCell<Canvas2dPathState>> {
|
||||
with_canvas_state(scope, object, |state| state.path.clone())
|
||||
}
|
||||
|
||||
pub(super) fn canvas_color<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
style: CanvasColorStyle,
|
||||
) -> AbsoluteColor {
|
||||
with_canvas_state(scope, context, |state| *state.color(style))
|
||||
}
|
||||
|
||||
pub(super) fn set_canvas_color<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
style: CanvasColorStyle,
|
||||
color: AbsoluteColor,
|
||||
) {
|
||||
with_canvas_state(scope, context, |state| *state.color(style) = color);
|
||||
}
|
||||
|
||||
pub(super) fn reset_canvas_state<'s>(
|
||||
pub(super) fn reset_canvas_path_state<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
if get_private_value(scope, context, CANVAS_STATE_SLOT).is_some() {
|
||||
with_canvas_state(scope, context, |state| {
|
||||
*state.path.borrow_mut() = Canvas2dPathState::default();
|
||||
state.fill = AbsoluteColor::BLACK;
|
||||
state.stroke = AbsoluteColor::BLACK;
|
||||
});
|
||||
if get_private_value(scope, context, PATH_STATE_SLOT).is_some() {
|
||||
*canvas_path_state(scope, context).borrow_mut() = Canvas2dPathState::default();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::canvas::{
|
||||
canvas_context_begin_path_callback, canvas_context_create_image_data_callback,
|
||||
canvas_context_create_linear_gradient_callback, canvas_context_draw_image_callback,
|
||||
canvas_context_fill_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_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,
|
||||
@@ -21,14 +21,11 @@ use super::canvas::{
|
||||
canvas_context_noop_callback, canvas_context_put_image_data_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_set_transform_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_path_arc_callback,
|
||||
canvas_path_arc_to_callback, canvas_path_bezier_curve_to_callback,
|
||||
canvas_path_close_path_callback, canvas_path_ellipse_callback, canvas_path_line_to_callback,
|
||||
canvas_path_move_to_callback, canvas_path_quadratic_curve_to_callback,
|
||||
canvas_path_rect_callback, install_canvas_rect_bindings, install_canvas_template_bindings,
|
||||
canvas_context_transform_callback, canvas_context_translate_callback,
|
||||
install_canvas_path_bindings, install_canvas_rect_bindings, install_canvas_template_bindings,
|
||||
install_canvas_transform_bindings, offscreen_canvas_convert_to_blob_callback,
|
||||
offscreen_canvas_get_context_callback, offscreen_canvas_transfer_to_image_bitmap_callback,
|
||||
};
|
||||
@@ -245,50 +242,9 @@ struct CanvasRenderingContext2dTemplateDeclaration {
|
||||
#[webapi(method = "beginPath", length = 0, callback = canvas_context_begin_path_callback)]
|
||||
begin_path: (),
|
||||
|
||||
#[webapi(method = "closePath", length = 0, callback = canvas_path_close_path_callback)]
|
||||
close_path: (),
|
||||
|
||||
#[webapi(method = "moveTo", length = 2, callback = canvas_path_move_to_callback)]
|
||||
move_to: (),
|
||||
|
||||
#[webapi(method = "lineTo", length = 2, callback = canvas_path_line_to_callback)]
|
||||
line_to: (),
|
||||
|
||||
#[webapi(
|
||||
method = "quadraticCurveTo",
|
||||
length = 4,
|
||||
callback = canvas_path_quadratic_curve_to_callback
|
||||
)]
|
||||
quadratic_curve_to: (),
|
||||
|
||||
#[webapi(
|
||||
method = "bezierCurveTo",
|
||||
length = 6,
|
||||
callback = canvas_path_bezier_curve_to_callback
|
||||
)]
|
||||
bezier_curve_to: (),
|
||||
|
||||
#[webapi(method = "arcTo", length = 5, callback = canvas_path_arc_to_callback)]
|
||||
arc_to: (),
|
||||
|
||||
#[webapi(method = "arc", length = 5, callback = canvas_path_arc_callback)]
|
||||
arc: (),
|
||||
|
||||
#[webapi(method = "ellipse", length = 7, callback = canvas_path_ellipse_callback)]
|
||||
ellipse: (),
|
||||
|
||||
#[webapi(method = "fill", length = 0, callback = canvas_context_fill_callback)]
|
||||
fill: (),
|
||||
|
||||
#[webapi(method = "stroke", length = 0, callback = canvas_context_stroke_callback)]
|
||||
stroke: (),
|
||||
|
||||
#[webapi(method = "clip", length = 0, callback = canvas_context_noop_callback)]
|
||||
clip: (),
|
||||
|
||||
#[webapi(method = "rect", length = 4, callback = canvas_path_rect_callback)]
|
||||
rect: (),
|
||||
|
||||
#[webapi(
|
||||
method = "isPointInPath",
|
||||
length = 2,
|
||||
@@ -361,6 +317,10 @@ pub(super) fn install_media_file_template_bindings<'s>(
|
||||
);
|
||||
install_canvas_transform_bindings(scope, proto, spec_name);
|
||||
install_canvas_rect_bindings(scope, proto, spec_name);
|
||||
install_canvas_path_bindings(scope, proto, spec_name);
|
||||
}
|
||||
"Path2D" => {
|
||||
install_canvas_path_bindings(scope, template.prototype_template(scope), spec_name);
|
||||
}
|
||||
"FileReader" => {
|
||||
let proto = template.prototype_template(scope);
|
||||
|
||||
@@ -85,6 +85,7 @@ pub(in crate::context_bootstrap) enum ConstructorKind {
|
||||
VideoColorSpace,
|
||||
MediaMetadata,
|
||||
OffscreenCanvas,
|
||||
Path2D,
|
||||
CanvasRenderingContext2D,
|
||||
OffscreenCanvasRenderingContext2D,
|
||||
WebGLRenderingContext,
|
||||
|
||||
@@ -29,148 +29,6 @@ async fn run_one_canvas_image_load_event_task(
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_html_and_offscreen_draw_with_modern_fill_and_stroke_colors() {
|
||||
let mut vm = new_storage_test_vm("https://canvas-css-colors.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
for (const canvas of [document.createElement('canvas'), new OffscreenCanvas(8, 8)]) {
|
||||
canvas.width = canvas.height = 8;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.lineWidth = 2;
|
||||
const pixel = (x, y) => Array.from(ctx.getImageData(x, y, 1, 1).data);
|
||||
for (const [color, expected] of [
|
||||
['oklch(0.5 0 0)', [99, 99, 99, 255]],
|
||||
['hsl(120 100% 50%)', [0, 255, 0, 255]],
|
||||
['CanvasText', [0, 0, 0, 255]],
|
||||
['currentcolor', [0, 0, 0, 255]],
|
||||
['color(srgb 1 0 0 / 0.5)', [255, 0, 0, 128]],
|
||||
['color-mix(in srgb, red 50%, blue 50%)', [128, 0, 128, 255]],
|
||||
]) {
|
||||
ctx.fillStyle = 'black';
|
||||
ctx.strokeStyle = 'black';
|
||||
ctx.fillStyle = color;
|
||||
ctx.strokeStyle = color;
|
||||
const style = ctx.fillStyle;
|
||||
if (ctx.strokeStyle !== style) throw new Error('stroke color differs');
|
||||
for (const invalid of ['oklch(invalid)', 'light-dark(red, blue)',
|
||||
'rgb(1, 2, 3, 1, 0)', 'rgb(50%, 0, 0)']) {
|
||||
ctx.fillStyle = invalid;
|
||||
ctx.strokeStyle = invalid;
|
||||
if (ctx.fillStyle !== style || ctx.strokeStyle !== style) {
|
||||
throw new Error("invalid assignment changed the style: " + invalid);
|
||||
}
|
||||
}
|
||||
ctx.clearRect(0, 0, 8, 8);
|
||||
ctx.fillRect(0, 0, 1, 1);
|
||||
ctx.strokeRect(2, 2, 4, 4);
|
||||
for (const rgba of [pixel(0, 0), pixel(4, 2)]) {
|
||||
if (rgba.some((value, index) => Math.abs(value - expected[index]) > 1)) {
|
||||
throw new Error(color + ': ' + rgba + ' != ' + expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx.clearRect(0, 0, 8, 8);
|
||||
ctx.fillStyle = 'color(srgb 1 0 0 / 0.1)';
|
||||
ctx.globalAlpha = 0.6;
|
||||
ctx.fillRect(0, 0, 1, 1);
|
||||
if (pixel(0, 0)[3] !== 15) throw new Error('alpha was quantized before drawing');
|
||||
}
|
||||
return 'ok';
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.expect("HTML and OffscreenCanvas should draw with modern CSS colors");
|
||||
assert_eq!(result, "ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_style_getters_keep_modern_color_spaces_and_precision() {
|
||||
let mut vm = new_storage_test_vm("https://canvas-color-serialization.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r##"
|
||||
(() => {
|
||||
for (const canvas of [document.createElement('canvas'), new OffscreenCanvas(2, 2)]) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
for (const [input, expected] of [
|
||||
['rgb(1, 2, 3)', '#010203'],
|
||||
['rgb(1 2 3)', '#010203'],
|
||||
['#ff000080', 'rgba(255, 0, 0, 0.5)'],
|
||||
['rgba(255, 0, 0, 0.9999)', 'rgba(255, 0, 0, 0.9999)'],
|
||||
['lab(29% 39 20)', 'lab(29 39 20)'],
|
||||
['oklch(0.543218 0.12 33.25)', 'oklch(0.543218 0.12 33.25)'],
|
||||
['color(srgb 1 0 0 / 0.5)', 'color(srgb 1 0 0 / 0.5)'],
|
||||
['color-mix(in srgb, red 50%, blue 50%)', 'color(srgb 0.5 0 0.5)'],
|
||||
['color(display-p3 1 0.25 0 / 0.1234567)', 'color(display-p3 1 0.25 0 / 0.123457)'],
|
||||
['rgb(none 0 0)', 'color(srgb none 0 0)'],
|
||||
['hsl(none 20% 30% / none)', 'hsl(none 20% 30% / none)'],
|
||||
]) {
|
||||
ctx.fillStyle = input;
|
||||
ctx.strokeStyle = input;
|
||||
if (ctx.fillStyle !== expected || ctx.strokeStyle !== expected) {
|
||||
throw new Error(input + ': ' + [ctx.fillStyle, ctx.strokeStyle] + ' != ' + expected);
|
||||
}
|
||||
}
|
||||
canvas.width = canvas.width;
|
||||
if (ctx.fillStyle !== '#000000' || ctx.strokeStyle !== '#000000') {
|
||||
throw new Error('resizing did not reset both colors');
|
||||
}
|
||||
}
|
||||
return 'ok';
|
||||
})()
|
||||
"##,
|
||||
)
|
||||
.expect("Canvas getters should serialize typed colors");
|
||||
assert_eq!(result, "ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_styles_round_trip_hsl_and_hwb_with_non_finite_components() {
|
||||
let mut vm = new_storage_test_vm("https://canvas-color-round-trip.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
for (const canvas of [document.createElement('canvas'), new OffscreenCanvas(2, 2)]) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
for (const [input, expected] of [
|
||||
['hsl(from red none calc(infinity * 1%) 50%)',
|
||||
'hsl(from black none calc(infinity * 1%) 50%)'],
|
||||
['hwb(from red none calc(infinity * 1%) 20%)',
|
||||
'hwb(from black none calc(infinity * 1%) 20%)'],
|
||||
['hwb(from red 120 none calc(-infinity * 1%) / 0.5)',
|
||||
'hwb(from black 120 none calc(-infinity * 1%) / 0.5)'],
|
||||
['hsl(120 none calc(NaN * 1%))', 'hsl(120 none calc(NaN * 1%))'],
|
||||
['hwb(calc(infinity) 10% none)', 'hwb(calc(NaN) 10% none)'],
|
||||
['hsl(from red none 125% 30% / none)', 'hsl(from black none 125% 30% / none)'],
|
||||
]) {
|
||||
for (const property of ['fillStyle', 'strokeStyle']) {
|
||||
ctx[property] = 'white';
|
||||
ctx[property] = input;
|
||||
const serialized = ctx[property];
|
||||
if (serialized !== expected) {
|
||||
throw new Error(property + ' serialized ' + input + ' as ' + serialized);
|
||||
}
|
||||
ctx[property] = 'white';
|
||||
ctx[property] = serialized;
|
||||
if (ctx[property] !== serialized) {
|
||||
throw new Error(property + ' reparsed ' + serialized + ' as ' + ctx[property]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 'ok';
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.expect("Canvas HSL and HWB styles should round-trip through CSS strings");
|
||||
assert_eq!(result, "ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webgl_viewport_state_matches_chromium_on_html_and_offscreen_contexts() {
|
||||
let mut vm = new_storage_test_vm("https://webgl-viewport.test/");
|
||||
|
||||
@@ -2588,6 +2588,7 @@ mod svg_transform_lists;
|
||||
mod svg_value_lists;
|
||||
|
||||
mod indexed_db_prototype_handlers;
|
||||
mod path2d_native;
|
||||
|
||||
mod beacon_receiver_owner;
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
(function path2dContract(owner, callee, kind, tag) {
|
||||
const checks = [];
|
||||
const check = (name, run) => {
|
||||
try {checks.push({name: 'path2d/' + tag + '/' + name, passed: run() === true});}
|
||||
catch(error) {checks.push({name: 'path2d/' + tag + '/' + name, passed: false, error: String(error)});}
|
||||
};
|
||||
const P = owner.Path2D, proto = callee.Path2D.prototype;
|
||||
const canvas = kind === 'element' ? owner.document.createElement('canvas') : new owner.OffscreenCanvas(96,96);
|
||||
canvas.width = canvas.height = 96;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const cp = callee[kind === 'element' ? 'CanvasRenderingContext2D' : 'OffscreenCanvasRenderingContext2D'].prototype;
|
||||
const typeError = fn => {try {fn();} catch(e) {return e instanceof callee.TypeError;} return false;};
|
||||
const rect = () => {const p = new P(); p.rect(10,10,20,20); return p;};
|
||||
const clear = () => {ctx.resetTransform(); ctx.clearRect(0,0,96,96); ctx.beginPath(); ctx.fillStyle = '#00f'; ctx.strokeStyle = '#00f'; ctx.lineWidth = 4; ctx.setLineDash([]);};
|
||||
const pixel = (x,y) => ctx.getImageData(x,y,1,1).data[3];
|
||||
const fill = (p, rule='nonzero') => cp.fill.call(ctx,p,rule);
|
||||
const methods = [['closePath',0],['moveTo',2],['lineTo',2],['quadraticCurveTo',4],['bezierCurveTo',6],['arcTo',5],['arc',5],['ellipse',7],['rect',4],['addPath',1]];
|
||||
|
||||
check('constructor metadata', () => P.length === 0 && P.name === 'Path2D' && proto.constructor === callee.Path2D);
|
||||
check('native empty construction', () => {const p = new P(); return Object.getPrototypeOf(p) === P.prototype && Object.keys(p).length === 0;});
|
||||
check('constructor without new', () => typeError(() => callee.Path2D()));
|
||||
check('empty fill leaves default path alone', () => {clear(); ctx.rect(50,50,20,20); fill(new P()); return pixel(60,60) === 0;});
|
||||
check('rect fill', () => {clear(); fill(rect()); return pixel(20,20) === 255 && pixel(40,40) === 0;});
|
||||
check('copy independent source mutation', () => {const p=rect(), copy=new P(p); p.rect(50,50,20,20); clear(); fill(copy); return pixel(20,20) === 255 && pixel(60,60) === 0;});
|
||||
check('copy independent destination mutation', () => {const p=rect(), copy=new P(p); copy.rect(50,50,20,20); clear(); fill(p); return pixel(20,20) === 255 && pixel(60,60) === 0;});
|
||||
check('cross realm constructor copy', () => {const p=rect(),copy=new callee.Path2D(p); clear(); fill(copy); return pixel(20,20) === 255;});
|
||||
check('paint applies current transform', () => {const p=rect(); clear(); ctx.translate(40,0); fill(p); return pixel(60,20)===255 && pixel(20,20)===0;});
|
||||
check('painting does not mutate path', () => {const p=rect(); clear(); ctx.translate(40,0); fill(p); clear(); fill(p); return pixel(20,20)===255 && pixel(60,20)===0;});
|
||||
check('Path2D painting preserves current default path', () => {clear(); ctx.rect(50,50,20,20); fill(rect()); clear(); ctx.rect(50,50,20,20); fill(rect()); ctx.clearRect(0,0,96,96); cp.fill.call(ctx); return pixel(60,60)===255 && pixel(20,20)===0;});
|
||||
check('stroke explicit path', () => {clear(); cp.stroke.call(ctx,rect()); return pixel(10,20)===255 && pixel(20,20)===0;});
|
||||
check('stroke transform and line width', () => {clear(); ctx.scale(2,1); cp.stroke.call(ctx,rect()); return pixel(18,20)===255 && pixel(40,20)===0;});
|
||||
check('nested path nonzero', () => {const p=rect(); p.rect(15,15,10,10); clear(); fill(p); return pixel(20,20)===255;});
|
||||
check('nested path evenodd', () => {const p=rect(); p.rect(15,15,10,10); clear(); fill(p,'evenodd'); return pixel(12,12)===255 && pixel(20,20)===0;});
|
||||
check('default path evenodd', () => {clear(); ctx.rect(10,10,20,20); ctx.rect(15,15,10,10); cp.fill.call(ctx,'evenodd'); return pixel(12,12)===255 && pixel(20,20)===0;});
|
||||
check('fill enum object conversion', () => {clear(); ctx.rect(10,10,20,20); let n=0; cp.fill.call(ctx,{toString(){n++;return 'evenodd';}}); return n===1 && pixel(20,20)===255;});
|
||||
check('fill invalid enum', () => typeError(() => cp.fill.call(ctx,'invalid')));
|
||||
check('fill invalid second argument', () => typeError(() => cp.fill.call(ctx,rect(),'invalid')));
|
||||
check('stroke invalid interface', () => typeError(() => cp.stroke.call(ctx,{})));
|
||||
|
||||
for (const [name,arity] of methods) {
|
||||
check(name+' descriptor', () => {const d=Object.getOwnPropertyDescriptor(proto,name); return d && typeof d.value==='function' && d.enumerable && d.writable && d.configurable && d.value.name===name && d.value.length===arity;});
|
||||
for (const label of ['plain','forged','inherited','proxy','revoked']) check(name+' receiver '+label, () => {
|
||||
const p=rect(), revoked=owner.Proxy.revocable(p,{}); revoked.revoke();
|
||||
const fake={plain:{},forged:Object.create(proto),inherited:Object.create(p),proxy:new owner.Proxy(p,{}),revoked:revoked.proxy}[label];
|
||||
let conversions=0,traps=0;
|
||||
const poison=new Proxy({}, {get(){traps++;throw Error('conversion trap');}});
|
||||
const number={valueOf(){conversions++;return 1;}};
|
||||
const args=name==='addPath'?[p,poison]:Array(arity).fill(number);
|
||||
return typeError(() => proto[name].call(fake,...args)) && conversions===0 && traps===0;
|
||||
});
|
||||
}
|
||||
for (const [name,args] of [['moveTo',[10,10]],['lineTo',[10,10]],['quadraticCurveTo',[10,10,20,20]],['bezierCurveTo',[10,10,20,20,30,30]],['arcTo',[10,10,20,20,5]],['arc',[20,20,5,0,Math.PI]],['ellipse',[20,20,5,10,0,0,Math.PI]],['rect',[10,10,20,20]]]) {
|
||||
check(name+' arity', () => typeError(() => proto[name].call(new P(),...args.slice(0,-1))));
|
||||
check(name+' context receiver rejected', () => typeError(() => proto[name].call(ctx,...args)));
|
||||
check(name+' path receiver rejected by context method', () => typeError(() => cp[name].call(new P(),...args)));
|
||||
check(name+' cross realm genuine path', () => proto[name].call(new P(),...args) === undefined);
|
||||
}
|
||||
check('line commands', () => {const p=new P(); proto.moveTo.call(p,10,10); proto.lineTo.call(p,30,10); proto.lineTo.call(p,30,30); proto.lineTo.call(p,10,30); proto.closePath.call(p); clear(); fill(p); return pixel(20,20)===255;});
|
||||
check('quadratic curve', () => {const p=new P(); p.moveTo(10,30); p.quadraticCurveTo(20,0,30,30); p.closePath(); clear(); fill(p); return pixel(20,25)===255 && pixel(20,10)===0;});
|
||||
check('cubic curve', () => {const p=new P(); p.moveTo(10,30); p.bezierCurveTo(10,10,30,10,30,30); p.closePath(); clear(); fill(p); return pixel(20,25)===255 && pixel(20,10)===0;});
|
||||
check('circle', () => {const p=new P(); p.arc(20,20,10,0,Math.PI*2); clear(); fill(p); return pixel(20,20)===255 && pixel(40,20)===0;});
|
||||
check('ellipse', () => {const p=new P(); p.ellipse(30,30,20,10,0,0,Math.PI*2); clear(); fill(p); return pixel(30,30)===255 && pixel(30,45)===0;});
|
||||
for (const [name,args] of [['arc',[20,20,-1,0,1]],['arcTo',[10,10,20,20,-1]],['ellipse',[20,20,-1,2,0,0,1]]])
|
||||
check(name+' negative radius', () => {try {proto[name].call(new P(),...args);} catch(e) {return e instanceof callee.DOMException && e.name==='IndexSizeError';} return false;});
|
||||
check('nonfinite path command ignored', () => {const p=rect(); p.rect(Infinity,50,20,20); clear(); fill(p); return pixel(20,20)===255 && pixel(60,60)===0;});
|
||||
for (const [name,svg] of [['absolute','M10 10H30V30H10Z'],['relative','m10 10h20v20h-20z'],['implicit','M10 10 30 10 30 30 10 30z'],['invalid suffix','M10 10H30V30H10Z X'],['incomplete suffix','M10 10H30V30H10Z M50'],['arc','M10 20A10 10 0 0 1 30 20A10 10 0 0 1 10 20Z']])
|
||||
check('SVG '+name, () => {clear(); fill(new P(svg)); return pixel(20,20)===255 && pixel(50,50)===0;});
|
||||
check('SVG conversion once and inherited method', () => {let n=0; clear(); fill(new P(Object.create({toString(){n++;return 'M10 10H30V30H10Z';}}))); return n===1 && pixel(20,20)===255;});
|
||||
check('SVG original conversion exception', () => {const sentinel={}; try {new P({toString(){throw sentinel;}});} catch(e) {return e===sentinel;} return false;});
|
||||
check('SVG constructor Symbol rejected', () => typeError(() => new callee.Path2D(Symbol())));
|
||||
for (const value of [undefined,null,'', 'invalid']) check('empty SVG '+String(value), () => {clear(); fill(new P(value)); return pixel(20,20)===0;});
|
||||
check('SVG starts a new subpath at last point', () => {const p=new P('M10 10L30 10L30 30'); p.lineTo(10,30); clear(); cp.stroke.call(ctx,p); return pixel(20,30)===255 && pixel(20,20)===0;});
|
||||
|
||||
for (const [name,transform] of [['omitted',undefined],['null',null],['empty',{}],['identity',{a:1,b:0,c:0,d:1,e:0,f:0}]])
|
||||
check('addPath '+name, () => {const p=new P(); proto.addPath.call(p,rect(),transform); clear(); fill(p); return pixel(20,20)===255 && pixel(50,50)===0;});
|
||||
check('addPath translation', () => {const p=new P(); proto.addPath.call(p,rect(),{e:40}); clear(); fill(p); return pixel(60,20)===255 && pixel(20,20)===0;});
|
||||
check('addPath aliases', () => {const p=new P(); proto.addPath.call(p,rect(),{m41:40,m42:20}); clear(); fill(p); return pixel(60,40)===255 && pixel(20,20)===0;});
|
||||
check('addPath snapshot source', () => {const source=rect(),p=new P(); p.addPath(source); source.rect(50,50,20,20); clear(); fill(p); return pixel(20,20)===255 && pixel(60,60)===0;});
|
||||
check('addPath self snapshot', () => {const p=rect(); p.addPath(p,{e:40}); clear(); fill(p); return pixel(20,20)===255 && pixel(60,20)===255;});
|
||||
check('addPath transform composition', () => {const p=new P(),q=new P(); p.addPath(rect(),{e:20}); q.addPath(p,{a:2,d:2}); clear(); fill(q); return pixel(70,40)===255 && pixel(40,40)===0;});
|
||||
check('addPath new subpath endpoint', () => {const source=new P(); source.moveTo(10,10); source.lineTo(30,10); source.lineTo(30,30); const p=new P(); p.addPath(source); p.lineTo(10,30); clear(); cp.stroke.call(ctx,p); return pixel(20,30)===255 && pixel(20,20)===0;});
|
||||
for (const [short,long] of [['a','m11'],['b','m12'],['c','m21'],['d','m22'],['e','m41'],['f','m42']])
|
||||
check('addPath aliases atomic '+short, () => {const p=rect(); const thrown=typeError(() => proto.addPath.call(p,rect(),{[short]:1,[long]:2})); clear(); fill(p); return thrown && pixel(20,20)===255 && pixel(60,60)===0;});
|
||||
for (const value of [NaN,Infinity,-Infinity]) check('addPath nonfinite '+String(value), () => {const p=rect(); proto.addPath.call(p,rect(),{e:value,m41:value}); clear(); fill(p); return pixel(20,20)===255 && pixel(60,20)===0;});
|
||||
check('addPath 3D fields ignored', () => {let reads=0; const p=new P(); p.addPath(rect(),{get is2D(){reads++;throw Error('3D');},get m33(){reads++;throw Error('3D');}}); clear(); fill(p); return reads===0 && pixel(20,20)===255;});
|
||||
check('addPath ordered dictionary reads', () => {const order=[], init={}; for(const name of ['m42','m41','m22','m21','m12','m11','f','e','d','c','b','a']) Object.defineProperty(init,name,{get(){order.push(name);return undefined;}}); new P().addPath(rect(),init); return order.join() === 'a,b,c,d,e,f,m11,m12,m21,m22,m41,m42';});
|
||||
check('addPath getter exception identity', () => {const sentinel={}; try {new P().addPath(rect(),{get e(){throw sentinel;}});} catch(e) {return e===sentinel;} return false;});
|
||||
check('addPath invalid source before dictionary reads', () => {let reads=0; return typeError(() => proto.addPath.call(new P(),{}, {get a(){reads++;return 1;}})) && reads===0;});
|
||||
check('addPath missing source', () => typeError(() => proto.addPath.call(new P())));
|
||||
check('prototype null and frozen native state', () => {const p=rect(); p.__moliCanvasPathState=0; Object.setPrototypeOf(p,null); Object.freeze(p); proto.rect.call(p,50,50,20,20); clear(); fill(p); return pixel(20,20)===255 && pixel(60,60)===255;});
|
||||
return checks;
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn path2d_native_geometry_copy_add_path_and_drawing_across_realms() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://path2d-native.test/");
|
||||
vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
|
||||
.unwrap();
|
||||
let source = format!(
|
||||
r#"(() => {{
|
||||
const probe = {};
|
||||
const realms = [globalThis, document.getElementById('child').contentWindow];
|
||||
const checks = [];
|
||||
for(let owner=0;owner<2;owner++) for(let callee=0;callee<2;callee++)
|
||||
for(const kind of ['element','offscreen'])
|
||||
checks.push(...probe(realms[owner],realms[callee],kind,`window-${{owner}}-${{callee}}-${{kind}}`));
|
||||
globalThis.__path2dChecks = checks;
|
||||
return checks.length;
|
||||
}})()"#,
|
||||
include_str!("path2d_native.js"),
|
||||
);
|
||||
assert_eq!(vm.eval(&source).unwrap(), "1280");
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(__path2dChecks.filter(row => !row.passed))")
|
||||
.unwrap(),
|
||||
"[]"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path2d_registered_native_proxies_share_state_and_reject_author_wrappers() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://path2d-proxy.test/");
|
||||
vm.eval(
|
||||
r#"globalThis.path = new Path2D(); path.rect(10,10,20,20);
|
||||
globalThis.ctx = new OffscreenCanvas(96,96).getContext('2d');"#,
|
||||
)
|
||||
.unwrap();
|
||||
let context_ptr = &vm.page_default_context as *const _;
|
||||
vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
|
||||
let global = scope.get_current_context().global(scope);
|
||||
for (name, proxy_name) in [("path", "pathProxy"), ("ctx", "ctxProxy")] {
|
||||
let key = crate::util::v8str(scope, name);
|
||||
let value = global.get(scope, key.into()).unwrap();
|
||||
let target = v8::Local::<v8::Object>::try_from(value).unwrap();
|
||||
let handler = crate::util::new_null_prototype_object(scope);
|
||||
let proxy = v8::Proxy::new(scope, target, handler).unwrap();
|
||||
moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap();
|
||||
let key = crate::util::v8str(scope, proxy_name);
|
||||
assert_eq!(
|
||||
global.create_data_property(scope, key.into(), proxy.into()),
|
||||
Some(true)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
vm.eval(r#"(() => {
|
||||
const p = new Path2D(pathProxy);
|
||||
Path2D.prototype.addPath.call(pathProxy, pathProxy, {e:40});
|
||||
const fill = OffscreenCanvasRenderingContext2D.prototype.fill;
|
||||
fill.call(ctxProxy,pathProxy);
|
||||
if(ctx.getImageData(20,20,1,1).data[3] !== 255 || ctx.getImageData(60,20,1,1).data[3] !== 255)
|
||||
throw Error('native proxy identity/state');
|
||||
ctx.clearRect(0,0,96,96); fill.call(ctxProxy,p);
|
||||
if(ctx.getImageData(60,20,1,1).data[3] !== 0) throw Error('copy independence');
|
||||
let reads=0;
|
||||
const bad=new Proxy(pathProxy, {get(){reads++;throw Error('trap');}});
|
||||
for(const run of [() => Path2D.prototype.addPath.call(pathProxy,bad,{get a(){reads++;return 1;}}),
|
||||
() => Path2D.prototype.rect.call(bad, {valueOf(){reads++;return 1;}}, 1,2,3),
|
||||
() => fill.call(new Proxy(ctxProxy,{}),p)]) {
|
||||
let rejected=false; try {run();} catch(e) {rejected=e instanceof TypeError;}
|
||||
if(!rejected) throw Error('author proxy accepted');
|
||||
}
|
||||
if(reads!==0) throw Error('brand failure ran author code');
|
||||
return true;
|
||||
})()"#).unwrap(),
|
||||
"true"
|
||||
);
|
||||
}
|
||||
@@ -1595,6 +1595,7 @@ mod payment_events;
|
||||
mod performance_handler_order;
|
||||
mod trusted_type_policy_interface;
|
||||
|
||||
mod path2d_native;
|
||||
mod performance_user_timing;
|
||||
|
||||
mod abort_controller_receivers;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn worker_path2d_geometry_and_offscreen_drawing_use_native_brands() {
|
||||
ensure_v8();
|
||||
let source = format!(
|
||||
r#"const probe = {};
|
||||
const checks = probe(globalThis,globalThis,'offscreen','worker');
|
||||
postMessage({{total:checks.length,failures:checks.filter(row => !row.passed)}});
|
||||
close();"#,
|
||||
include_str!("../../../script_vm/tests/path2d_native.js"),
|
||||
);
|
||||
let mut worker = spawn_worker(source, "test://path2d_native".into());
|
||||
let message = timeout(TIMEOUT, worker.recv())
|
||||
.await
|
||||
.expect("timed out")
|
||||
.expect("channel closed");
|
||||
assert_eq!(expect_post_json(message), r#"{"total":160,"failures":[]}"#);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::helpers::svg_number_list;
|
||||
use crate::matrix::SvgMatrixComponents;
|
||||
use crate::path::parse_path_data;
|
||||
use crate::path::path_geometry;
|
||||
use kurbo::{
|
||||
Arc, BezPath, Circle, Ellipse, Line, ParamCurve, ParamCurveArclen, ParamCurveExtrema,
|
||||
ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape,
|
||||
@@ -302,7 +302,7 @@ fn geometry_path(element: &SvgGeometryElement) -> Option<BezPath> {
|
||||
path.line_to((*x2, *y2));
|
||||
Some(path)
|
||||
}
|
||||
SvgGeometryElement::Path { d } => Some(parse_path_data(d)),
|
||||
SvgGeometryElement::Path { d } => path_geometry(d),
|
||||
SvgGeometryElement::Polygon { points } => poly_points_geometry_path(points, true),
|
||||
SvgGeometryElement::Polyline { points } => poly_points_geometry_path(points, false),
|
||||
SvgGeometryElement::Rect {
|
||||
|
||||
+6
-1
@@ -15,12 +15,17 @@ pub use length::{
|
||||
parse_point_list,
|
||||
};
|
||||
pub use matrix::{SvgMatrixComponents, serialize_number};
|
||||
pub use path::parse_path_data;
|
||||
pub use transform::{
|
||||
SvgTransform, SvgTransformKind, consolidate_transform_matrices, parse_transform_attribute,
|
||||
serialize_transform_list,
|
||||
};
|
||||
|
||||
/// Parse SVG path data, retaining complete commands before an invalid suffix.
|
||||
/// The same geometry and error recovery serve SVG elements and Canvas Path2D.
|
||||
pub fn parse_path_data(raw: &str) -> kurbo::BezPath {
|
||||
path::path_geometry(raw).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use kurbo::BezPath;
|
||||
use svgtypes::{SimplePathSegment, SimplifyingPathParser};
|
||||
|
||||
/// Parse SVG path data, preserving the complete segments before any parse error.
|
||||
pub fn parse_path_data(raw: &str) -> BezPath {
|
||||
pub(crate) fn path_geometry(raw: &str) -> Option<BezPath> {
|
||||
let mut path = BezPath::new();
|
||||
for segment in SimplifyingPathParser::from(path_data_before_invalid_number(raw)) {
|
||||
let Ok(segment) = segment else {
|
||||
@@ -25,7 +24,7 @@ pub fn parse_path_data(raw: &str) -> BezPath {
|
||||
SimplePathSegment::ClosePath => path.close_path(),
|
||||
}
|
||||
}
|
||||
path
|
||||
Some(path)
|
||||
}
|
||||
|
||||
fn path_data_before_invalid_number(raw: &str) -> &str {
|
||||
|
||||
@@ -4,7 +4,7 @@ pub mod transform;
|
||||
|
||||
use crate::image_data::new_uint8_clamped_array_from_bytes;
|
||||
use crate::interfaces as web_api_interfaces;
|
||||
use moli_canvas::DEFAULT_FONT;
|
||||
use moli_canvas::{DEFAULT_FILL_STYLE, DEFAULT_FONT};
|
||||
use moli_v8_util::{set_private_value, throw_type_error};
|
||||
use moli_webapi_declare::WebApiObject;
|
||||
use moli_webidl as webidl;
|
||||
@@ -13,6 +13,7 @@ use std::str::FromStr;
|
||||
pub const CANVAS_BACKING_STORE_SLOT: &str = "__moliCanvasBackingStore";
|
||||
pub const OFFSCREEN_CANVAS_WIDTH_SLOT: &str = "__moliOffscreenCanvasWidth";
|
||||
pub const OFFSCREEN_CANVAS_HEIGHT_SLOT: &str = "__moliOffscreenCanvasHeight";
|
||||
pub const CANVAS_CONTEXT_FILL_STYLE_SLOT: &str = "__moliCanvasContextFillStyle";
|
||||
pub const CANVAS_CONTEXT_FONT_SLOT: &str = "__moliCanvasContextFont";
|
||||
pub const CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT: &str =
|
||||
"__moliCanvasContextImageSmoothingEnabled";
|
||||
@@ -26,6 +27,7 @@ pub const CANVAS_CONTEXT_LINE_CAP_SLOT: &str = "__moliCanvasContextLineCap";
|
||||
pub const CANVAS_CONTEXT_LINE_JOIN_SLOT: &str = "__moliCanvasContextLineJoin";
|
||||
pub const CANVAS_CONTEXT_MITER_LIMIT_SLOT: &str = "__moliCanvasContextMiterLimit";
|
||||
pub const CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT: &str = "__moliCanvasContextLineDashOffset";
|
||||
pub const CANVAS_CONTEXT_STROKE_STYLE_SLOT: &str = "__moliCanvasContextStrokeStyle";
|
||||
|
||||
pub const DEFAULT_GLOBAL_ALPHA: f64 = 1.0;
|
||||
pub const DEFAULT_GLOBAL_COMPOSITE_OPERATION: &str = "source-over";
|
||||
@@ -34,10 +36,16 @@ pub const DEFAULT_LINE_CAP: &str = "butt";
|
||||
pub const DEFAULT_LINE_JOIN: &str = "miter";
|
||||
pub const DEFAULT_MITER_LIMIT: f64 = 10.0;
|
||||
pub const DEFAULT_LINE_DASH_OFFSET: f64 = 0.0;
|
||||
pub const DEFAULT_STROKE_STYLE: &str = "#000000";
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(fragment, prototype = "CanvasRenderingContext2D")]
|
||||
struct CanvasLikeContextObjectDeclaration {
|
||||
#[webapi(
|
||||
slot = CANVAS_CONTEXT_FILL_STYLE_SLOT,
|
||||
constructor_default = DEFAULT_FILL_STYLE
|
||||
)]
|
||||
fill_style: &'static str,
|
||||
#[webapi(slot = CANVAS_CONTEXT_FONT_SLOT, constructor_default = DEFAULT_FONT)]
|
||||
font: &'static str,
|
||||
#[webapi(
|
||||
@@ -76,6 +84,11 @@ struct CanvasLikeContextObjectDeclaration {
|
||||
constructor_default = DEFAULT_LINE_DASH_OFFSET
|
||||
)]
|
||||
line_dash_offset: f64,
|
||||
#[webapi(
|
||||
slot = CANVAS_CONTEXT_STROKE_STYLE_SLOT,
|
||||
constructor_default = DEFAULT_STROKE_STYLE
|
||||
)]
|
||||
stroke_style: &'static str,
|
||||
}
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
|
||||
@@ -48,12 +48,12 @@ pub fn set_transform_arguments<'s>(
|
||||
return None;
|
||||
}
|
||||
};
|
||||
transform_init_coefficients(scope, &init)
|
||||
validate_transform_init(scope, init)
|
||||
}
|
||||
|
||||
pub fn transform_init_coefficients(
|
||||
pub fn validate_transform_init(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
init: &DomMatrix2DInit,
|
||||
init: DomMatrix2DInit,
|
||||
) -> Option<[f64; 6]> {
|
||||
let mut values = [0.0; 6];
|
||||
for (value, (alias, component, default)) in values.iter_mut().zip(init.affine_aliases()) {
|
||||
|
||||
@@ -191,10 +191,10 @@ fn canvas_construction_converts_dimensions_once_and_allocates_initial_pixels_wit
|
||||
] {
|
||||
let context = v8::Local::<v8::Object>::try_from(eval(scope, source)).unwrap();
|
||||
assert_eq!(
|
||||
get_private_value(scope, context, canvas::CANVAS_CONTEXT_FONT_SLOT)
|
||||
get_private_value(scope, context, canvas::CANVAS_CONTEXT_FILL_STYLE_SLOT)
|
||||
.unwrap()
|
||||
.to_rust_string_lossy(scope),
|
||||
moli_canvas::DEFAULT_FONT
|
||||
moli_canvas::DEFAULT_FILL_STYLE
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user