fix(canvas): preserve native shadow and text style state

This commit is contained in:
ldm0
2026-11-03 18:08:13 +08:00
parent 7e64b4487e
commit 2a77d65a26
10 changed files with 627 additions and 11 deletions
+67 -6
View File
@@ -9,7 +9,28 @@ use style::{
stylesheets::{CssRuleType, Origin, UrlExtraData},
values::specified::color::{Color, ColorScheme, ColorSchemeFlags, SystemColor},
};
use style_traits::ParsingMode;
use style_traits::{ParsingMode, ToCss};
/// Parse a Canvas color with HTML-compatible serialization. Preserve modern
/// color spaces, and resolve `currentcolor` at assignment time against the
/// canvas element's computed color (or black for an OffscreenCanvas).
pub fn parse_css_color_for_canvas(value: &str, current_color: Option<&str>) -> Option<String> {
let specified = parse_specified_color(value)?;
let current = current_color
.and_then(parse_specified_color)
.and_then(|color| absolute_color(color, &AbsoluteColor::BLACK))
.unwrap_or(AbsoluteColor::BLACK);
let absolute = absolute_color(specified, &current)?;
if absolute.is_legacy_syntax() {
let legacy = absolute.into_srgb_legacy();
if legacy.alpha == 1.0 {
let [red, green, blue, _] = legacy.to_nscolor().to_le_bytes();
return Some(format!("#{red:02x}{green:02x}{blue:02x}"));
}
return Some(legacy.to_css_string());
}
Some(absolute.to_css_string())
}
/// Parse a CSS color and serialize its opaque sRGB channels as lowercase
/// `#rrggbb`.
@@ -30,15 +51,19 @@ pub fn parse_css_color_to_opaque_srgb_hex(value: &str) -> Option<String> {
/// serialization.
pub fn parse_css_color_to_srgb_bytes(value: &str) -> Option<[u8; 4]> {
let color = parse_specified_color(value)?;
let absolute = match color {
Color::CurrentColor => AbsoluteColor::BLACK,
let absolute = absolute_color(color, &AbsoluteColor::BLACK)?;
Some(absolute_srgb_bytes(absolute))
}
fn absolute_color(color: Color, current: &AbsoluteColor) -> Option<AbsoluteColor> {
Some(match color {
Color::CurrentColor => *current,
Color::System(system) => system_color_absolute(system),
color => color
.to_computed_color(None)
.ok()?
.resolve_to_absolute(&AbsoluteColor::BLACK),
};
Some(absolute_srgb_bytes(absolute))
.resolve_to_absolute(current),
})
}
/// Resolve a CSS system-color keyword through the headless Servo light
@@ -173,6 +198,42 @@ mod tests {
);
}
#[test]
fn canvas_colors_preserve_alpha_and_color_space() {
for (value, expected) in [
("red", "#ff0000"),
("rgb(1, 2, 3)", "#010203"),
("hsl(120deg 100% 50%)", "#00ff00"),
("transparent", "rgba(0, 0, 0, 0)"),
("rgba(255, 0, 0, 0.5)", "rgba(255, 0, 0, 0.5)"),
("color(display-p3 1 0 0)", "color(display-p3 1 0 0)"),
] {
assert_eq!(
parse_css_color_for_canvas(value, None).as_deref(),
Some(expected)
);
}
assert_eq!(
parse_css_color_for_canvas("currentcolor", Some("rgb(1, 2, 3)")).as_deref(),
Some("#010203")
);
assert_eq!(
parse_css_color_for_canvas("currentcolor", None).as_deref(),
Some("#000000")
);
for invalid in [
"",
"red green",
"rgb(1,2,3,0.5,1)",
"rgba(1,2,3,NaN)",
"#ggg",
"inherit",
"var(--color)",
] {
assert_eq!(parse_css_color_for_canvas(invalid, None), None, "{invalid}");
}
}
#[test]
fn css_colors_convert_to_opaque_srgb_hex() {
for (value, expected) in [
+2 -2
View File
@@ -19,8 +19,8 @@ mod util;
mod value;
pub use color::{
css_system_color_srgb, parse_css_color_scheme_flags, parse_css_color_to_opaque_srgb_hex,
parse_css_color_to_srgb_bytes,
css_system_color_srgb, parse_css_color_for_canvas, parse_css_color_scheme_flags,
parse_css_color_to_opaque_srgb_hex, parse_css_color_to_srgb_bytes,
};
pub use declaration::{
CssDeclaration, DeclarationParseOptions, parse_declaration_list,
@@ -24,6 +24,12 @@ const CANVAS_CONTEXT_MITER_LIMIT_SLOT: &str = "__moliCanvasContextMiterLimit";
const CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT: &str = "__moliCanvasContextLineDashOffset";
const CANVAS_CONTEXT_STROKE_STYLE_SLOT: &str = "__moliCanvasContextStrokeStyle";
const CANVAS_CONTEXT_LINE_DASH_SLOT: &str = "__moliCanvasContextLineDash";
const CANVAS_CONTEXT_SHADOW_BLUR_SLOT: &str = "__moliCanvasContextShadowBlur";
const CANVAS_CONTEXT_SHADOW_COLOR_SLOT: &str = "__moliCanvasContextShadowColor";
const CANVAS_CONTEXT_SHADOW_OFFSET_X_SLOT: &str = "__moliCanvasContextShadowOffsetX";
const CANVAS_CONTEXT_SHADOW_OFFSET_Y_SLOT: &str = "__moliCanvasContextShadowOffsetY";
const CANVAS_CONTEXT_TEXT_ALIGN_SLOT: &str = "__moliCanvasContextTextAlign";
const CANVAS_CONTEXT_TEXT_BASELINE_SLOT: &str = "__moliCanvasContextTextBaseline";
pub(crate) const DEFAULT_GLOBAL_ALPHA: f64 = 1.0;
pub(crate) const DEFAULT_GLOBAL_COMPOSITE_OPERATION: &str = "source-over";
@@ -193,6 +199,8 @@ mod canvas_context_kind_tests {
}
mod backing_store;
mod style_state;
pub(crate) use style_state::install_canvas_style_state_bindings;
mod bitmap_renderer;
pub(crate) use bitmap_renderer::build_bitmap_renderer_context;
mod blob_serialization;
@@ -32,6 +32,12 @@ canvas_drawing_slots! {
line_dash_offset: f64 => CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT = super::DEFAULT_LINE_DASH_OFFSET;
stroke_style: &'static str => CANVAS_CONTEXT_STROKE_STYLE_SLOT = super::DEFAULT_STROKE_STYLE;
line_dash: Vec<f64> => CANVAS_CONTEXT_LINE_DASH_SLOT = Vec::new();
shadow_blur: f64 => CANVAS_CONTEXT_SHADOW_BLUR_SLOT = 0.0;
shadow_color: &'static str => CANVAS_CONTEXT_SHADOW_COLOR_SLOT = "rgba(0, 0, 0, 0)";
shadow_offset_x: f64 => CANVAS_CONTEXT_SHADOW_OFFSET_X_SLOT = 0.0;
shadow_offset_y: f64 => CANVAS_CONTEXT_SHADOW_OFFSET_Y_SLOT = 0.0;
text_align: &'static str => CANVAS_CONTEXT_TEXT_ALIGN_SLOT = "start";
text_baseline: &'static str => CANVAS_CONTEXT_TEXT_BASELINE_SLOT = "alphabetic";
}
pub(super) fn canvas_unrestricted_double_arg<'s>(
@@ -0,0 +1,224 @@
//! Native Canvas shadow and text attributes shared by Window and worker contexts.
use super::*;
use crate::{
native_bridge::{
element::{StyleMode, style_property_value},
node_runtime_and_handle_from_object_or_detached,
},
util::{get_private_value, set_private_value},
};
use moli_webapi_declare::web_api_object_target;
macro_rules! style_state_declaration {
($name:ident, $interface:path) => {
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = $interface, enumerable, receiver)]
struct $name {
#[webapi(accessor_property = "shadowBlur", getter = shadow_blur_getter, setter = shadow_blur_setter)]
shadow_blur: (),
#[webapi(accessor_property = "shadowColor", getter = shadow_color_getter, setter = shadow_color_setter)]
shadow_color: (),
#[webapi(accessor_property = "shadowOffsetX", getter = shadow_offset_x_getter, setter = shadow_offset_x_setter)]
shadow_offset_x: (),
#[webapi(accessor_property = "shadowOffsetY", getter = shadow_offset_y_getter, setter = shadow_offset_y_setter)]
shadow_offset_y: (),
#[webapi(accessor_property = "textAlign", getter = text_align_getter, setter = text_align_setter)]
text_align: (),
#[webapi(accessor_property = "textBaseline", getter = text_baseline_getter, setter = text_baseline_setter)]
text_baseline: (),
}
};
}
style_state_declaration!(
CanvasStyleStateDeclaration,
web_api_interfaces::CanvasRenderingContext2D
);
style_state_declaration!(
OffscreenStyleStateDeclaration,
web_api_interfaces::OffscreenCanvasRenderingContext2D
);
pub(crate) fn install_canvas_style_state_bindings<'s>(
scope: &mut v8::PinScope<'s, '_, ()>,
prototype: v8::Local<'s, v8::ObjectTemplate>,
interface: &str,
) {
match interface {
"CanvasRenderingContext2D" => {
CanvasStyleStateDeclaration::initialize_prototype_template(scope, prototype)
}
"OffscreenCanvasRenderingContext2D" => {
OffscreenStyleStateDeclaration::initialize_prototype_template(scope, prototype)
}
_ => unreachable!("only 2D contexts have shadow and text attributes"),
}
}
macro_rules! state_getter {
($name:ident, $slot:ident) => {
fn $name<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let context =
web_api_object_target(scope, args.this()).expect("validated Canvas receiver");
rv.set(
get_private_value(scope, context, $slot)
.expect("native drawing state is initialized"),
);
}
};
}
state_getter!(shadow_blur_getter, CANVAS_CONTEXT_SHADOW_BLUR_SLOT);
state_getter!(shadow_color_getter, CANVAS_CONTEXT_SHADOW_COLOR_SLOT);
state_getter!(shadow_offset_x_getter, CANVAS_CONTEXT_SHADOW_OFFSET_X_SLOT);
state_getter!(shadow_offset_y_getter, CANVAS_CONTEXT_SHADOW_OFFSET_Y_SLOT);
state_getter!(text_align_getter, CANVAS_CONTEXT_TEXT_ALIGN_SLOT);
state_getter!(text_baseline_getter, CANVAS_CONTEXT_TEXT_BASELINE_SLOT);
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "CanvasShadowStyles")]
struct ShadowNumberArgs {
#[webidl(default = f64::NAN, converter = "unrestricted_double")]
value: f64,
}
macro_rules! number_setter {
($name:ident, $slot:ident, $nonnegative:expr) => {
fn $name<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
let context =
web_api_object_target(scope, args.this()).expect("validated Canvas receiver");
let Some(ShadowNumberArgs { value }) = webidl::parse_args(scope, &args) else {
return;
};
if value.is_finite() && (!$nonnegative || value >= 0.0) {
let value = v8::Number::new(scope, value);
set_private_value(scope, context, $slot, value.into());
}
}
};
}
number_setter!(shadow_blur_setter, CANVAS_CONTEXT_SHADOW_BLUR_SLOT, true);
number_setter!(
shadow_offset_x_setter,
CANVAS_CONTEXT_SHADOW_OFFSET_X_SLOT,
false
);
number_setter!(
shadow_offset_y_setter,
CANVAS_CONTEXT_SHADOW_OFFSET_Y_SLOT,
false
);
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "CanvasRenderingContext2D")]
struct StringArgs {
#[webidl(default = "undefined".to_owned(), converter = "dom_string")]
value: String,
}
fn shadow_color_setter<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
let context = web_api_object_target(scope, args.this()).expect("validated Canvas receiver");
let Some(StringArgs { value }) = webidl::parse_args(scope, &args) else {
return;
};
// Resolve after DOMString conversion: author code may change the canvas's
// owner document or inherited color during conversion.
let current = super::backing_store::canvas_owner_from_context(scope, context)
.and_then(|canvas| node_runtime_and_handle_from_object_or_detached(scope, canvas).ok())
.and_then(|(runtime, handle)| {
let runtime = unsafe { &*runtime };
// Canvas color resolution depends on DOM connection, including
// windowless Documents and unslotted light DOM. CSSOM's stricter
// rendered-flat-tree checks would reject those valid contexts.
if !runtime.node_is_connected_for_web_api(handle) {
return None;
}
Some(style_property_value(
runtime,
handle,
StyleMode::Computed,
"color",
))
});
if let Some(color) = moli_css_parse::parse_css_color_for_canvas(&value, current.as_deref()) {
set_string(scope, context, CANVAS_CONTEXT_SHADOW_COLOR_SLOT, &color);
}
}
#[derive(strum::EnumString, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase")]
enum TextAlign {
Start,
End,
Left,
Right,
Center,
}
#[derive(strum::EnumString, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase")]
enum TextBaseline {
Top,
Hanging,
Middle,
Alphabetic,
Ideographic,
Bottom,
}
fn text_align_setter<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
enum_setter::<TextAlign>(scope, args, CANVAS_CONTEXT_TEXT_ALIGN_SLOT);
}
fn text_baseline_setter<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
enum_setter::<TextBaseline>(scope, args, CANVAS_CONTEXT_TEXT_BASELINE_SLOT);
}
fn enum_setter<'s, T: FromStr + Into<&'static str>>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
slot: &'static str,
) {
let context = web_api_object_target(scope, args.this()).expect("validated Canvas receiver");
let Some(StringArgs { value }) = webidl::parse_args(scope, &args) else {
return;
};
// WebIDL enum attribute setters ignore unknown tokens, after ToString.
// Conversion exceptions still propagate through the generated argument parser.
if let Ok(value) = value.parse::<T>() {
set_string(scope, context, slot, value.into());
}
}
fn set_string(
scope: &mut v8::PinScope<'_, '_>,
context: v8::Local<'_, v8::Object>,
slot: &'static str,
value: &str,
) {
if let Some(value) = v8_string(scope, value) {
set_private_value(scope, context, slot, value.into());
}
}
@@ -27,9 +27,10 @@ use super::canvas::{
canvas_context_translate_callback, canvas_gradient_add_color_stop_callback,
install_canvas_draw_image_bindings, install_canvas_drawing_state_bindings,
install_canvas_rect_bindings, install_canvas_path_bindings,
install_canvas_template_bindings, install_canvas_transform_bindings,
offscreen_canvas_convert_to_blob_callback, offscreen_canvas_get_context_callback,
webgl_boolean_callback, webgl_check_framebuffer_status_callback, webgl_create_buffer_callback,
install_canvas_style_state_bindings, install_canvas_template_bindings,
install_canvas_transform_bindings, offscreen_canvas_convert_to_blob_callback,
offscreen_canvas_get_context_callback, webgl_boolean_callback,
webgl_check_framebuffer_status_callback, webgl_create_buffer_callback,
webgl_create_framebuffer_callback, webgl_create_program_callback,
webgl_create_renderbuffer_callback, webgl_create_shader_callback,
webgl_get_attrib_location_callback, webgl_get_context_attributes_callback,
@@ -615,6 +616,7 @@ pub(super) fn install_media_file_template_bindings<'s>(
);
install_canvas_transform_bindings(scope, proto, spec_name);
install_canvas_drawing_state_bindings(scope, proto, spec_name);
install_canvas_style_state_bindings(scope, proto, spec_name);
install_canvas_rect_bindings(scope, proto, spec_name);
install_canvas_path_bindings(scope, proto, spec_name);
install_canvas_draw_image_bindings(scope, proto, spec_name);
@@ -0,0 +1,39 @@
(owner, callee, label) => {
const checks = [];
const check = (name, run) => {
try { checks.push({name: label + ':' + name, passed: run() === true}); }
catch(error) { checks.push({name: label + ':' + name, passed: false, error: String(error)}); }
};
const setter = Object.getOwnPropertyDescriptor(callee.CanvasRenderingContext2D.prototype, 'shadowColor').set;
const get = Object.getOwnPropertyDescriptor(callee.CanvasRenderingContext2D.prototype, 'shadowColor').get;
const color = context => { setter.call(context, 'currentcolor'); return get.call(context); };
const canvas = owner.document.createElement('canvas');
const context = canvas.getContext('2d');
let hooks = 0;
Object.defineProperty(canvas, 'isConnected', {get() {hooks++; throw Error('author isConnected');}});
Object.defineProperty(canvas, 'ownerDocument', {get() {hooks++; throw Error('author ownerDocument');}});
canvas.style.color = 'rgb(1, 2, 3)';
check('detached canvas is black', () => color(context) === '#000000');
check('connected canvas uses its color', () => {owner.document.body.appendChild(canvas); return color(context) === '#010203';});
check('removal discards computed context', () => {canvas.remove(); return color(context) === '#000000';});
check('reattachment computes again', () => {owner.document.body.appendChild(canvas); canvas.style.color='rgb(4,5,6)'; return color(context)==='#040506';});
check('conversion removes canvas before resolution', () => {
setter.call(context, {toString() {canvas.remove(); return 'currentcolor';}});
return get.call(context)==='#000000';
});
check('conversion attaches canvas before resolution', () => {
setter.call(context, {toString() {owner.document.body.appendChild(canvas); return 'currentcolor';}});
return get.call(context)==='#040506';
});
const inert = owner.document.implementation.createHTMLDocument('');
const inertCanvas=inert.createElement('canvas');inertCanvas.style.color='red';inert.body.appendChild(inertCanvas);
check('windowless Document keeps connected color context', () => color(inertCanvas.getContext('2d'))==='#ff0000');
const host=owner.document.createElement('div');owner.document.body.appendChild(host);
const shadow=host.attachShadow({mode:'open'});
check('unslotted light DOM keeps connected color context', () => {host.appendChild(canvas);return color(context)==='#040506';});
check('connected shadow canvas keeps computed context', () => {shadow.appendChild(canvas);return color(context)==='#040506';});
check('detached shadow root has no computed context', () => {host.remove();return color(context)==='#000000';});
check('native membership bypasses author properties', () => hooks===0);
canvas.remove(); host.remove();
return checks;
}
@@ -0,0 +1,152 @@
(owner, callee, kind, label) => {
const checks = [];
const check = (name, run) => {
try { checks.push({ name: label + ':' + name, passed: run() === true }); }
catch (error) { checks.push({ name: label + ':' + name, passed: false, error: String(error) }); }
};
const make = (width = 8, height = 8) => {
const canvas = kind === 'element' ? owner.document.createElement('canvas') : new owner.OffscreenCanvas(width, height);
canvas.width = width; canvas.height = height;
return [canvas, canvas.getContext('2d')];
};
const iface = kind === 'element' ? 'CanvasRenderingContext2D' : 'OffscreenCanvasRenderingContext2D';
const proto = callee[iface].prototype;
const descriptor = name => Object.getOwnPropertyDescriptor(proto, name);
const get = (context, name) => Reflect.apply(descriptor(name).get, context, []);
const set = (context, name, value) => Reflect.apply(descriptor(name).set, context, [value]);
const call = (context, name) => Reflect.apply(proto[name], context, []);
const attributes = [
['shadowBlur', 0, 2.5, 3.5],
['shadowOffsetX', 0, -2.5, 3.5],
['shadowOffsetY', 0, 2.5, -3.5],
['shadowColor', 'rgba(0, 0, 0, 0)', '#112233', '#445566'],
['textAlign', 'start', 'center', 'right'],
['textBaseline', 'alphabetic', 'top', 'bottom']
];
for (const [name, initial, first, second] of attributes) {
const [, context] = make();
check(name + ':prototype accessor', () => {
const d = descriptor(name);
return d.enumerable && d.configurable && d.get.name === 'get ' + name && d.get.length === 0 && d.set.name === 'set ' + name && d.set.length === 1 && !Object.hasOwn(context, name);
});
check(name + ':initial value', () => get(context, name) === initial);
check(name + ':assignment', () => set(context, name, first) === undefined && get(context, name) === first);
check(name + ':nested restore', () => {
set(context, name, first); call(context, 'save');
set(context, name, second); call(context, 'save'); set(context, name, initial);
call(context, 'restore'); const inner = get(context, name) === second;
call(context, 'restore'); call(context, 'restore');
return inner && get(context, name) === first;
});
for (const operation of ['width', 'height', 'reset']) {
check(name + ':' + operation + ' resets value and stack', () => {
const [canvas, ctx] = make(); set(ctx, name, first); call(ctx, 'save'); set(ctx, name, second);
if (operation === 'reset') call(ctx, 'reset'); else canvas[operation] = canvas[operation];
call(ctx, 'restore'); return get(ctx, name) === initial;
});
}
check(name + ':zero-sized context', () => {
const [, ctx] = make(0, 0); set(ctx, name, first); call(ctx, 'save'); set(ctx, name, second); call(ctx, 'restore');
return get(ctx, name) === first;
});
check(name + ':state independent of author properties', () => {
const [, ctx] = make(); set(ctx, name, first); call(ctx, 'save');
let hooks = 0;
Object.defineProperty(ctx, name, { get() { hooks++; throw Error('getter'); }, set() { hooks++; throw Error('setter'); } });
Object.setPrototypeOf(ctx, null); Object.freeze(ctx);
set(ctx, name, second); call(ctx, 'restore');
return get(ctx, name) === first && hooks === 0;
});
check(name + ':independent contexts', () => {
const [, a] = make(), [, b] = make(); set(a, name, first); set(b, name, second);
return get(a, name) === first && get(b, name) === second;
});
check(name + ':conversion exactly once', () => {
let count = 0;
set(context, name, { [Symbol.toPrimitive](hint) { count++; if (hint !== (typeof first === 'number' ? 'number' : 'string')) throw Error('conversion hint'); return first; } });
return count === 1 && get(context, name) === first;
});
check(name + ':conversion exception identity', () => {
const sentinel = {}; set(context, name, first);
try { set(context, name, { [Symbol.toPrimitive]() { throw sentinel; } }); }
catch (error) { return error === sentinel && get(context, name) === first; }
return false;
});
check(name + ':conversion may reset the context', () => {
call(context, 'save');
set(context, name, { [Symbol.toPrimitive]() { call(context, 'reset'); return second; } });
call(context, 'restore'); return get(context, name) === second;
});
check(name + ':Symbol conversion throws in callee realm', () => {
try { set(context, name, Symbol()); } catch (error) { return error instanceof callee.TypeError; }
return false;
});
const revoked = owner.Proxy.revocable(context, {}); revoked.revoke();
let traps = 0, conversions = 0;
const author = new owner.Proxy(context, { get() { traps++; throw Error('get trap'); }, getPrototypeOf() { traps++; throw Error('prototype trap'); } });
const receivers = [null, undefined, {}, Object.create(proto), Object.create(context), author, revoked.proxy];
if (owner.document) receivers.push(kind === 'element' ? new owner.OffscreenCanvas(1, 1).getContext('2d') : owner.document.createElement('canvas').getContext('2d'));
for (let index = 0; index < receivers.length; index++) {
check(name + ':invalid getter receiver ' + index, () => {
try { get(receivers[index], name); } catch (error) { return error instanceof callee.TypeError; }
return false;
});
check(name + ':invalid setter receiver ' + index, () => {
try { set(receivers[index], name, { [Symbol.toPrimitive]() { conversions++; return first; } }); }
catch (error) { return error instanceof callee.TypeError && conversions === 0 && traps === 0; }
return false;
});
}
check(name + ':receiver checks bypass author hooks', () => traps === 0 && conversions === 0);
}
for (const name of ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY']) {
for (const value of [NaN, Infinity, -Infinity, undefined, 'bad', ...(name === 'shadowBlur' ? [-1] : [])]) {
check(name + ':ignore ' + String(value), () => {
const [, context] = make(); set(context, name, 2); set(context, name, value); return get(context, name) === 2;
});
}
for (const value of [0, -0, 2.25, 1e20, ...(name === 'shadowBlur' ? [] : [-2.25])]) {
check(name + ':finite value ' + (Object.is(value, -0) ? '-0' : value), () => {
const [, context] = make(); set(context, name, value); return get(context, name) === value;
});
}
check(name + ':null becomes zero', () => { const [, ctx] = make(); set(ctx, name, 2); set(ctx, name, null); return get(ctx, name) === 0; });
check(name + ':numeric string', () => { const [, ctx] = make(); set(ctx, name, '2.25'); return get(ctx, name) === 2.25; });
check(name + ':BigInt rejects', () => { const [, ctx] = make(); try { set(ctx, name, 1n); } catch (error) { return error instanceof callee.TypeError; } return false; });
}
for (const [name, values] of [
['textAlign', ['start', 'end', 'left', 'right', 'center']],
['textBaseline', ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom']]
]) {
for (const value of values) check(name + ':enum ' + value, () => { const [, ctx] = make(); set(ctx, name, value); return get(ctx, name) === value; });
for (const value of ['', 'CENTER', ' center ', 'bogus', null, undefined, 1n]) {
check(name + ':ignore enum ' + String(value), () => {
const [, ctx] = make(); set(ctx, name, values[1]); set(ctx, name, value); return get(ctx, name) === values[1];
});
}
}
for (const [value, expected] of [
['red', '#ff0000'], ['#AbC', '#aabbcc'], ['rgb(1, 2, 3)', '#010203'],
['transparent', 'rgba(0, 0, 0, 0)'], ['rgba(255, 0, 0, 0.5)', 'rgba(255, 0, 0, 0.5)'],
['hsl(120 100% 50%)', '#00ff00'], ['color(display-p3 1 0 0)', 'color(display-p3 1 0 0)']
]) {
check('shadowColor:CSS ' + value, () => { const [, ctx] = make(); set(ctx, 'shadowColor', value); return get(ctx, 'shadowColor') === expected; });
}
for (const value of ['', '#ggg', 'red blue', 'rgb(1,2,3,0.5,1)', 'rgba(1,2,3,NaN)', 'inherit', 'var(--color)', null, undefined]) {
check('shadowColor:ignore invalid CSS ' + String(value), () => {
const [, ctx] = make(); set(ctx, 'shadowColor', '#112233'); set(ctx, 'shadowColor', value); return get(ctx, 'shadowColor') === '#112233';
});
}
if (kind === 'offscreen') {
check('shadowColor:offscreen currentcolor is black', () => { const [, ctx] = make(); set(ctx, 'shadowColor', 'currentcolor'); return get(ctx, 'shadowColor') === '#000000'; });
check('transfer preserves all style state', () => {
const [canvas, ctx] = make();
for (const [name, , first] of attributes) set(ctx, name, first);
call(ctx, 'save'); const bitmap = canvas.transferToImageBitmap();
for (const [name, , , second] of attributes) set(ctx, name, second);
call(ctx, 'restore'); bitmap.close();
return attributes.every(([name, , first]) => get(ctx, name) === first);
});
}
return checks;
}
@@ -0,0 +1,123 @@
use super::*;
#[test]
fn canvas_shadow_color_uses_native_document_connection() {
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-color-membership.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++)
checks.push(...probe(realms[owner],realms[callee],owner+'-'+callee));
globalThis.__canvasMembershipChecks=checks;
return checks.length;
}})()"#,
include_str!("canvas_currentcolor_membership.js")
);
assert_eq!(vm.eval(&source).unwrap(), "44");
assert_eq!(
vm.eval("JSON.stringify(__canvasMembershipChecks.filter(row => !row.passed))")
.unwrap(),
"[]"
);
}
#[test]
fn canvas_style_attributes_validate_convert_and_restore_across_realms() {
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-style-state.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, owner + '-' + callee + '-' + kind));
globalThis.__canvasStyleChecks = checks;
return checks.length;
}})()"#,
include_str!("canvas_style_state.js")
);
let count: usize = vm.eval(&source).unwrap().parse().unwrap();
assert_eq!(count, 2_136, "the complete realm matrix must execute");
assert_eq!(
vm.eval("JSON.stringify(__canvasStyleChecks.filter(row => !row.passed))")
.unwrap(),
"[]"
);
}
#[test]
fn canvas_shadow_color_resolves_after_conversion_without_author_accessors() {
let mut vm =
new_storage_page_task_executor_test_vm("https://canvas-shadow-current-color.test/");
assert_eq!(vm.eval(r#"(() => {
const canvas = document.createElement('canvas'); document.body.appendChild(canvas);
canvas.style.color = 'rgb(1, 2, 3)';
const context = canvas.getContext('2d');
let hooks = 0;
Object.defineProperty(context, 'canvas', { get() { hooks++; throw Error('author canvas'); } });
Object.defineProperty(canvas, 'ownerDocument', { get() { hooks++; throw Error('author document'); } });
context.shadowColor = 'currentcolor';
if (context.shadowColor !== '#010203') throw Error('currentcolor');
context.save();
context.shadowColor = { toString() { canvas.style.color = 'rgb(4, 5, 6)'; return 'currentcolor'; } };
if (context.shadowColor !== '#040506') throw Error('conversion ordering');
context.restore();
return hooks === 0 && context.shadowColor === '#010203';
})()"#).unwrap(), "true");
}
#[test]
fn canvas_style_attributes_share_registered_proxy_identity() {
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-style-native-proxy.test/");
vm.eval("globalThis.styleContexts = [document.createElement('canvas').getContext('2d'), new OffscreenCanvas(8,8).getContext('2d')]").unwrap();
let context_ptr = &vm.page_default_runtime.context as *const _;
vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
let global = scope.get_current_context().global(scope);
let key = crate::util::v8str(scope, "styleContexts");
let contexts =
v8::Local::<v8::Array>::try_from(global.get(scope, key.into()).unwrap()).unwrap();
let mut proxies = Vec::new();
for index in 0..contexts.length() {
let context =
v8::Local::<v8::Object>::try_from(contexts.get_index(scope, index).unwrap())
.unwrap();
let handler = crate::util::new_null_prototype_object(scope);
let proxy = v8::Proxy::new(scope, context, handler).unwrap();
moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap();
proxies.push(proxy.into());
}
let proxies = v8::Array::new_with_elements(scope, &proxies);
let key = crate::util::v8str(scope, "styleProxies");
assert_eq!(
global.create_data_property(scope, key.into(), proxies.into()),
Some(true)
);
Ok(())
})
.unwrap();
assert_eq!(vm.eval(r#"(() => {
for (let index=0; index<2; index++) {
const real=styleContexts[index], proxy=styleProxies[index];
const proto=(index===0?CanvasRenderingContext2D:OffscreenCanvasRenderingContext2D).prototype;
for (const [name,value] of [['shadowBlur',2],['shadowOffsetX',-2],['shadowOffsetY',3],['shadowColor','#abcdef'],['textAlign','end'],['textBaseline','bottom']]) {
const d=Object.getOwnPropertyDescriptor(proto,name);
d.set.call(proxy,value); if(d.get.call(real)!==value) throw Error(name+' target');
d.set.call(real); if(d.get.call(real)!==value) throw Error(name+' missing value');
proto.save.call(proxy); proto.reset.call(proxy); d.set.call(real,value);
if(d.get.call(proxy)!==value) throw Error(name+' proxy');
let calls=0, rejected=false;
try { d.set.call(new Proxy(proxy,{}), { [Symbol.toPrimitive]() {calls++; return value;} }); }
catch(error) {rejected=error instanceof TypeError;}
if(!rejected || calls!==0) throw Error(name+' author proxy');
}
}
return true;
})()"#).unwrap(), "true");
}
@@ -2277,6 +2277,7 @@ mod canvas_drawing_state;
mod canvas_fill_rect;
mod canvas_image_proxies;
mod canvas_paths;
mod canvas_style_state;
mod canvas_transform_snapshots;
mod canvas_factory_realms;