mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
fix(canvas): save and restore native 2D drawing state
This commit is contained in:
@@ -10,7 +10,7 @@ pub(crate) use moli_webapi::canvas_context_values::{
|
||||
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_DASH_OFFSET_SLOT, CANVAS_CONTEXT_LINE_DASH_SLOT, CANVAS_CONTEXT_LINE_JOIN_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,
|
||||
@@ -144,6 +144,7 @@ pub(crate) use blob_serialization::{
|
||||
};
|
||||
mod constructors;
|
||||
mod context2d;
|
||||
mod drawing_state;
|
||||
mod helpers;
|
||||
mod image_bitmap;
|
||||
mod objects;
|
||||
@@ -198,6 +199,7 @@ pub(crate) use context2d::{
|
||||
canvas_context_transform_callback, canvas_context_translate_callback,
|
||||
install_canvas_draw_image_bindings, install_canvas_rect_bindings, is_canvas_context_receiver,
|
||||
};
|
||||
pub(crate) use drawing_state::install_canvas_drawing_state_bindings;
|
||||
pub(crate) use image_bitmap::{
|
||||
BitmapRejection, BitmapTaskResult, settle_bitmap_task_result,
|
||||
window_create_image_bitmap_callback,
|
||||
|
||||
@@ -24,15 +24,13 @@ use moli_webapi::text_metrics::CanvasTextMetricsDeclaration;
|
||||
use std::str::FromStr;
|
||||
|
||||
const DEFAULT_IMAGE_SMOOTHING_QUALITY: &str = "low";
|
||||
const CANVAS_CONTEXT_LINE_DASH_SLOT: &str = "__moliCanvasContextLineDash";
|
||||
|
||||
pub(super) fn reset_canvas_context_state<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
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::drawing_state::clear_canvas_drawing_stack(scope, context);
|
||||
super::state::reset_canvas_path_state(scope, context);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! V8-traced snapshots of native drawing attributes, excluding paths and pixels.
|
||||
|
||||
use super::{
|
||||
backing_store::{canvas_owner_from_context, reset_canvas_like_backing_store},
|
||||
helpers::CANVAS_DRAWING_SLOTS,
|
||||
state::canvas_path_state,
|
||||
};
|
||||
use crate::{
|
||||
util::{get_private_object, get_private_value, new_null_prototype_object, set_private_value},
|
||||
web_api_interfaces,
|
||||
};
|
||||
use moli_layout::LayoutTransform2D;
|
||||
use moli_webapi_declare::{WebApiFunctionTemplate, web_api_object_target};
|
||||
|
||||
const SAVED_STATE_SLOT: &str = "__moliCanvasSavedDrawingState";
|
||||
const SAVED_TRANSFORM_SLOT: &str = "__moliCanvasSavedTransform";
|
||||
|
||||
macro_rules! canvas_drawing_state_declaration {
|
||||
($name:ident, $interface:path) => {
|
||||
#[derive(WebApiFunctionTemplate)]
|
||||
#[webapi(interface = $interface, enumerable)]
|
||||
struct $name {
|
||||
#[webapi(method, length = 0, callback = save_callback)]
|
||||
save: (),
|
||||
#[webapi(method, length = 0, callback = restore_callback)]
|
||||
restore: (),
|
||||
#[webapi(method, length = 0, callback = reset_callback)]
|
||||
reset: (),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
canvas_drawing_state_declaration!(
|
||||
CanvasDrawingStateDeclaration,
|
||||
web_api_interfaces::CanvasRenderingContext2D
|
||||
);
|
||||
canvas_drawing_state_declaration!(
|
||||
OffscreenCanvasDrawingStateDeclaration,
|
||||
web_api_interfaces::OffscreenCanvasRenderingContext2D
|
||||
);
|
||||
|
||||
pub(crate) fn install_canvas_drawing_state_bindings<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_, ()>,
|
||||
prototype: v8::Local<'s, v8::ObjectTemplate>,
|
||||
interface: &str,
|
||||
) {
|
||||
match interface {
|
||||
"CanvasRenderingContext2D" => {
|
||||
CanvasDrawingStateDeclaration::initialize_prototype_template(scope, prototype);
|
||||
}
|
||||
"OffscreenCanvasRenderingContext2D" => {
|
||||
OffscreenCanvasDrawingStateDeclaration::initialize_prototype_template(scope, prototype);
|
||||
}
|
||||
_ => unreachable!("only 2D contexts have drawing state bindings"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clear_canvas_drawing_stack<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
set_private_value(scope, context, SAVED_STATE_SLOT, v8::null(scope).into());
|
||||
}
|
||||
|
||||
fn copy_drawing_slots<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
source: v8::Local<'s, v8::Object>,
|
||||
destination: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
for slot in CANVAS_DRAWING_SLOTS {
|
||||
let value = get_private_value(scope, source, slot)
|
||||
.expect("native drawing attributes are initialized together");
|
||||
// The private dash array is immutable: setLineDash replaces it and
|
||||
// getLineDash returns a copy. Retaining it cannot alias author data.
|
||||
set_private_value(scope, destination, slot, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn save_callback<'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 2D context receiver");
|
||||
let saved = new_null_prototype_object(scope);
|
||||
copy_drawing_slots(scope, context, saved);
|
||||
let transform = canvas_path_state(scope, context).borrow().transform();
|
||||
let values = transform
|
||||
.coefficients
|
||||
.map(|value| v8::Number::new(scope, value).into());
|
||||
let transform = v8::Array::new_with_elements(scope, &values);
|
||||
set_private_value(scope, saved, SAVED_TRANSFORM_SLOT, transform.into());
|
||||
let previous = get_private_value(scope, context, SAVED_STATE_SLOT)
|
||||
.unwrap_or_else(|| v8::null(scope).into());
|
||||
set_private_value(scope, saved, SAVED_STATE_SLOT, previous);
|
||||
// Publish only after the snapshot is complete. V8 traces the linked stack;
|
||||
// no Rust Global handle can keep an otherwise unreachable context alive.
|
||||
set_private_value(scope, context, SAVED_STATE_SLOT, saved.into());
|
||||
}
|
||||
|
||||
fn restore_callback<'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 2D context receiver");
|
||||
let Some(saved) = get_private_object(scope, context, SAVED_STATE_SLOT) else {
|
||||
return;
|
||||
};
|
||||
let transform = get_private_value(scope, saved, SAVED_TRANSFORM_SLOT)
|
||||
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
|
||||
.expect("saved drawing state contains its transform");
|
||||
let coefficients = std::array::from_fn(|index| {
|
||||
transform
|
||||
.get_index(scope, index as u32)
|
||||
.and_then(|value| value.number_value(scope))
|
||||
.expect("saved transform contains six own numeric values")
|
||||
});
|
||||
copy_drawing_slots(scope, saved, context);
|
||||
canvas_path_state(scope, context)
|
||||
.borrow_mut()
|
||||
.restore_transform(LayoutTransform2D::new(coefficients));
|
||||
let previous = get_private_value(scope, saved, SAVED_STATE_SLOT)
|
||||
.expect("saved drawing state contains its predecessor");
|
||||
set_private_value(scope, context, SAVED_STATE_SLOT, previous);
|
||||
}
|
||||
|
||||
fn reset_callback<'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 2D context receiver");
|
||||
if let Some(canvas) = canvas_owner_from_context(scope, context) {
|
||||
reset_canvas_like_backing_store(scope, canvas);
|
||||
} else {
|
||||
// Existing native construction can precede attachment to a canvas.
|
||||
// Such a context still owns drawing state, but has no bitmap to clear.
|
||||
super::context2d::reset_canvas_context_state(scope, context);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub(super) use moli_webapi::canvas_context_values::CANVAS_DRAWING_SLOTS;
|
||||
use crate::webidl;
|
||||
|
||||
pub(super) fn canvas_unrestricted_double_arg<'s>(
|
||||
|
||||
@@ -298,6 +298,12 @@ impl Canvas2dPathState {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn restore_transform(&mut self, transform: LayoutTransform2D) {
|
||||
// Restoring native state is not a new setTransform call: multiplication
|
||||
// of finite input matrices can already have overflowed a coefficient.
|
||||
self.transform = transform;
|
||||
}
|
||||
|
||||
pub(super) fn reset_transform(&mut self) {
|
||||
self.transform = LayoutTransform2D::IDENTITY;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ use super::canvas::{
|
||||
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,
|
||||
install_canvas_draw_image_bindings, install_canvas_path_bindings, install_canvas_rect_bindings, install_canvas_template_bindings,
|
||||
install_canvas_draw_image_bindings, install_canvas_drawing_state_bindings, 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,
|
||||
};
|
||||
@@ -203,12 +203,6 @@ struct CanvasRenderingContext2dTemplateDeclaration {
|
||||
)]
|
||||
stroke_text: (),
|
||||
|
||||
#[webapi(method = "save", length = 0, callback = canvas_context_noop_callback)]
|
||||
save: (),
|
||||
|
||||
#[webapi(method = "restore", length = 0, callback = canvas_context_noop_callback)]
|
||||
restore: (),
|
||||
|
||||
#[webapi(method = "scale", length = 2, callback = canvas_context_scale_callback)]
|
||||
scale: (),
|
||||
|
||||
@@ -309,6 +303,7 @@ pub(super) fn install_media_file_template_bindings<'s>(
|
||||
scope, proto,
|
||||
);
|
||||
install_canvas_transform_bindings(scope, proto, spec_name);
|
||||
install_canvas_drawing_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,181 @@
|
||||
(owner, callee, kind, label) => {
|
||||
const checks = [];
|
||||
const check = (name, passed) => checks.push({ name: label + ':' + name, passed: !!passed });
|
||||
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 call = (ctx, name, ...args) => Reflect.apply(proto[name], ctx, args);
|
||||
const get = (ctx, name) => Reflect.apply(Object.getOwnPropertyDescriptor(proto, name).get, ctx, []);
|
||||
const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
const matrix = ctx => { const m = call(ctx, 'getTransform'); return [m.a, m.b, m.c, m.d, m.e, m.f]; };
|
||||
const pixel = (ctx, x, y) => Array.from(call(ctx, 'getImageData', x, y, 1, 1).data);
|
||||
const attributes = [
|
||||
['fillStyle', '#112233', '#445566', '#778899'],
|
||||
['strokeStyle', '#112233', '#445566', '#778899'],
|
||||
['font', '12px serif', '16px serif', '20px serif'],
|
||||
['imageSmoothingEnabled', false, true, false],
|
||||
['imageSmoothingQuality', 'high', 'medium', 'low'],
|
||||
['globalAlpha', 0.25, 0.5, 0.75],
|
||||
['globalCompositeOperation', 'copy', 'xor', 'source-over'],
|
||||
['lineWidth', 2, 3, 4],
|
||||
['lineCap', 'round', 'square', 'butt'],
|
||||
['lineJoin', 'round', 'bevel', 'miter'],
|
||||
['miterLimit', 2, 3, 4],
|
||||
['lineDashOffset', -2, 3, 4]
|
||||
];
|
||||
for (const [name, first, second, third] of attributes) {
|
||||
const [, ctx] = make();
|
||||
ctx[name] = first;
|
||||
check(name + ':initial assignment', get(ctx, name) === first);
|
||||
call(ctx, 'save');
|
||||
check(name + ':save unchanged', get(ctx, name) === first);
|
||||
ctx[name] = second; call(ctx, 'save'); ctx[name] = third;
|
||||
call(ctx, 'restore'); check(name + ':inner restore', get(ctx, name) === second);
|
||||
call(ctx, 'restore'); check(name + ':outer restore', get(ctx, name) === first);
|
||||
call(ctx, 'restore'); check(name + ':empty restore unchanged', get(ctx, name) === first);
|
||||
}
|
||||
for (const name of ['save', 'restore', 'reset']) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(proto, name);
|
||||
check(name + ':descriptor', descriptor.enumerable && descriptor.writable && descriptor.configurable);
|
||||
check(name + ':name and length', descriptor.value.name === name && descriptor.value.length === 0);
|
||||
const [, real] = make();
|
||||
const revoked = owner.Proxy.revocable(real, {}); revoked.revoke();
|
||||
let traps = 0;
|
||||
const author = new owner.Proxy(real, { get() { traps++; throw Error('author trap'); } });
|
||||
const receivers = [null, undefined, {}, Object.create(proto), Object.create(real), author, revoked.proxy];
|
||||
if (owner.document) receivers.push(kind === 'element' ? new owner.OffscreenCanvas(8, 8).getContext('2d') : owner.document.createElement('canvas').getContext('2d'));
|
||||
for (let i = 0; i < receivers.length; i++) {
|
||||
let correct = false;
|
||||
try { call(receivers[i], name); } catch (error) { correct = error instanceof callee.TypeError; }
|
||||
check(name + ':invalid receiver ' + i, correct);
|
||||
}
|
||||
check(name + ':no author proxy traps', traps === 0);
|
||||
check(name + ':returns undefined', call(real, name, { toString() { throw Error('unused argument'); } }) === undefined);
|
||||
}
|
||||
{
|
||||
const [, ctx] = make();
|
||||
const segments = [1, 2, 3]; call(ctx, 'setLineDash', segments); call(ctx, 'save');
|
||||
segments[0] = 90;
|
||||
const returned = call(ctx, 'getLineDash'); returned[0] = 80;
|
||||
call(ctx, 'setLineDash', [4, 5]); call(ctx, 'save'); call(ctx, 'setLineDash', [6, 7]);
|
||||
call(ctx, 'restore'); check('dash inner snapshot', equal(call(ctx, 'getLineDash'), [4, 5]));
|
||||
call(ctx, 'restore'); check('dash outer snapshot has no author alias', equal(call(ctx, 'getLineDash'), [1, 2, 3, 1, 2, 3]));
|
||||
const copy = call(ctx, 'getLineDash'); copy.length = 0;
|
||||
check('restored dash remains private', call(ctx, 'getLineDash').length === 6);
|
||||
}
|
||||
{
|
||||
const [, ctx] = make();
|
||||
call(ctx, 'setTransform', 1, 2, 3, 4, 5, 6); call(ctx, 'save');
|
||||
call(ctx, 'setTransform', 7, 8, 9, 10, 11, 12); call(ctx, 'save'); call(ctx, 'resetTransform');
|
||||
call(ctx, 'restore'); check('transform inner snapshot', equal(matrix(ctx), [7, 8, 9, 10, 11, 12]));
|
||||
call(ctx, 'restore'); check('transform outer snapshot', equal(matrix(ctx), [1, 2, 3, 4, 5, 6]));
|
||||
call(ctx, 'getTransform').e = 90;
|
||||
call(ctx, 'restore'); check('transform empty restore unchanged', equal(matrix(ctx), [1, 2, 3, 4, 5, 6]));
|
||||
}
|
||||
{
|
||||
const [, ctx] = make();
|
||||
call(ctx, 'setTransform', 1e300, 0, 0, 1, 0, 0); call(ctx, 'scale', 1e300, 1);
|
||||
const before = matrix(ctx); call(ctx, 'save'); call(ctx, 'resetTransform'); call(ctx, 'restore');
|
||||
const after = matrix(ctx);
|
||||
check('large transform snapshot preserves native coefficients', before.every((value, index) => Object.is(value, after[index])));
|
||||
}
|
||||
{
|
||||
const [, ctx] = make();
|
||||
for (let i = 1; i <= 512; i++) { ctx.lineWidth = i; call(ctx, 'setTransform', 1, 0, 0, 1, i, 0); call(ctx, 'save'); }
|
||||
ctx.lineWidth = 999; call(ctx, 'resetTransform');
|
||||
let valid = true;
|
||||
for (let i = 512; i >= 1; i--) { call(ctx, 'restore'); valid = valid && get(ctx, 'lineWidth') === i && matrix(ctx)[4] === i; }
|
||||
check('512 nested snapshots', valid);
|
||||
for (let i = 0; i < 16; i++) call(ctx, 'restore');
|
||||
check('repeated underflow', get(ctx, 'lineWidth') === 1 && matrix(ctx)[4] === 1);
|
||||
}
|
||||
for (const operation of ['width', 'height', 'reset']) {
|
||||
const [canvas, ctx] = make();
|
||||
const defaults = attributes.map(([name]) => get(ctx, name));
|
||||
for (const [name, first] of attributes) ctx[name] = first;
|
||||
call(ctx, 'setLineDash', [1, 2]); call(ctx, 'translate', 3, 4); call(ctx, 'save');
|
||||
call(ctx, 'resetTransform'); ctx.fillStyle = '#ff0000'; call(ctx, 'fillRect', 0, 0, 8, 8);
|
||||
call(ctx, 'beginPath'); call(ctx, 'rect', 0, 0, 8, 8);
|
||||
if (operation === 'reset') call(ctx, 'reset'); else canvas[operation] = canvas[operation];
|
||||
call(ctx, 'restore');
|
||||
for (let i = 0; i < attributes.length; i++) check(operation + ':default ' + attributes[i][0], get(ctx, attributes[i][0]) === defaults[i]);
|
||||
check(operation + ':stack and transform cleared', equal(matrix(ctx), [1, 0, 0, 1, 0, 0]));
|
||||
check(operation + ':dash cleared', call(ctx, 'getLineDash').length === 0);
|
||||
check(operation + ':bitmap cleared', equal(pixel(ctx, 1, 1), [0, 0, 0, 0]));
|
||||
call(ctx, 'fill'); check(operation + ':path cleared', equal(pixel(ctx, 1, 1), [0, 0, 0, 0]));
|
||||
check(operation + ':owner and dimensions unchanged', ctx.canvas === canvas && canvas.width === 8 && canvas.height === 8);
|
||||
}
|
||||
for (const [width, height] of [[0, 0], [0, 8], [8, 0]]) {
|
||||
const [, ctx] = make(width, height);
|
||||
ctx.lineWidth = 2; call(ctx, 'save'); ctx.lineWidth = 3; call(ctx, 'restore');
|
||||
check('zero-size ' + width + 'x' + height, get(ctx, 'lineWidth') === 2);
|
||||
}
|
||||
{
|
||||
const [, ctx] = make();
|
||||
call(ctx, 'save'); call(ctx, 'beginPath'); call(ctx, 'rect', 0, 0, 4, 4); call(ctx, 'restore');
|
||||
ctx.fillStyle = '#00ff00'; call(ctx, 'fill');
|
||||
check('restore preserves current path', equal(pixel(ctx, 1, 1), [0, 255, 0, 255]) && equal(pixel(ctx, 6, 6), [0, 0, 0, 0]));
|
||||
ctx.fillStyle = '#ff0000'; call(ctx, 'fillRect', 0, 0, 8, 8); call(ctx, 'save');
|
||||
ctx.fillStyle = '#00ff00'; call(ctx, 'fillRect', 0, 0, 8, 8); call(ctx, 'restore');
|
||||
check('restore preserves bitmap', equal(pixel(ctx, 1, 1), [0, 255, 0, 255]));
|
||||
call(ctx, 'clearRect', 0, 0, 8, 8);
|
||||
ctx.fillStyle = '#00ff00'; call(ctx, 'translate', 4, 0); call(ctx, 'save');
|
||||
ctx.fillStyle = '#ff0000'; call(ctx, 'resetTransform'); call(ctx, 'restore'); call(ctx, 'fillRect', 0, 0, 4, 4);
|
||||
check('paint uses restored style and transform', equal(pixel(ctx, 5, 1), [0, 255, 0, 255]) && equal(pixel(ctx, 1, 1), [0, 0, 0, 0]));
|
||||
}
|
||||
{
|
||||
const [, a] = make(), [, b] = make();
|
||||
a.lineWidth = 2; b.lineWidth = 3; call(a, 'save'); call(b, 'save');
|
||||
a.lineWidth = 4; b.lineWidth = 5; call(b, 'restore'); call(a, 'restore');
|
||||
check('per-context stacks', get(a, 'lineWidth') === 2 && get(b, 'lineWidth') === 3);
|
||||
}
|
||||
{
|
||||
const [, ctx] = make();
|
||||
ctx.lineWidth = 2; ctx.custom = 4; call(ctx, 'save'); ctx.lineWidth = 3; ctx.custom = 5;
|
||||
let hooks = 0;
|
||||
Object.defineProperty(ctx, 'lineWidth', { get() { hooks++; throw Error('author getter'); }, configurable: true });
|
||||
ctx.__moliCanvasSavedDrawingState = { lineWidth: 99 };
|
||||
call(ctx, 'save'); call(ctx, 'restore'); call(ctx, 'restore');
|
||||
check('private slots bypass author properties', hooks === 0 && get(ctx, 'lineWidth') === 2 && ctx.custom === 5);
|
||||
Object.setPrototypeOf(ctx, null); Object.freeze(ctx); call(ctx, 'save'); call(ctx, 'restore');
|
||||
check('frozen receiver retains native state', get(ctx, 'lineWidth') === 2);
|
||||
}
|
||||
{
|
||||
const [, ctx] = make();
|
||||
const arrayProto = callee.Array.prototype, objectProto = callee.Object.prototype;
|
||||
const keys = [[arrayProto, 'push'], [arrayProto, 'pop'], [arrayProto, '0'], [objectProto, '__moliCanvasSavedDrawingState']];
|
||||
const originals = keys.map(([object, key]) => Object.getOwnPropertyDescriptor(object, key));
|
||||
let hooks = 0, valid = false;
|
||||
const fail = () => { hooks++; throw Error('prototype hook'); };
|
||||
try {
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const [object, key] = keys[i]; Object.defineProperty(object, key, { get: fail, set: fail, configurable: true });
|
||||
}
|
||||
ctx.lineWidth = 2; call(ctx, 'setLineDash', [1, 2]); call(ctx, 'save'); ctx.lineWidth = 3;
|
||||
call(ctx, 'setLineDash', [3, 4]); call(ctx, 'restore');
|
||||
valid = get(ctx, 'lineWidth') === 2 && call(ctx, 'getLineDash')[0] === 1;
|
||||
} finally {
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const [object, key] = keys[i]; if (originals[i]) Object.defineProperty(object, key, originals[i]); else delete object[key];
|
||||
}
|
||||
}
|
||||
check('snapshots bypass prototype hooks', valid && hooks === 0);
|
||||
}
|
||||
if (kind === 'offscreen') {
|
||||
const [canvas, ctx] = make();
|
||||
ctx.lineWidth = 2; ctx.fillStyle = '#00ff00'; call(ctx, 'translate', 4, 0); call(ctx, 'save');
|
||||
ctx.lineWidth = 3; ctx.fillStyle = '#ff0000'; call(ctx, 'resetTransform'); call(ctx, 'fillRect', 0, 0, 8, 8);
|
||||
const bitmap = canvas.transferToImageBitmap();
|
||||
call(ctx, 'restore');
|
||||
check('transfer preserves drawing stack', get(ctx, 'lineWidth') === 2 && get(ctx, 'fillStyle') === '#00ff00' && matrix(ctx)[4] === 4);
|
||||
check('restore cannot resurrect transferred pixels', equal(pixel(ctx, 1, 1), [0, 0, 0, 0]));
|
||||
call(ctx, 'fillRect', 0, 0, 4, 4);
|
||||
check('restored state paints replacement bitmap', equal(pixel(ctx, 5, 1), [0, 255, 0, 255]));
|
||||
bitmap.close();
|
||||
}
|
||||
return checks;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn canvas_drawing_stack_can_reset_unattached_native_contexts() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-state-unattached.test/");
|
||||
assert_eq!(
|
||||
vm.eval(
|
||||
r#"(() => {
|
||||
for (const Constructor of [CanvasRenderingContext2D, OffscreenCanvasRenderingContext2D]) {
|
||||
const ctx = new Constructor();
|
||||
ctx.lineWidth = 2; ctx.translate(3,4); ctx.save();
|
||||
ctx.lineWidth = 3; ctx.resetTransform(); ctx.restore();
|
||||
if(ctx.lineWidth!==2 || ctx.getTransform().e!==3) throw Error('unattached restore');
|
||||
ctx.save(); ctx.reset(); ctx.restore();
|
||||
if(ctx.lineWidth!==1 || ctx.getTransform().e!==0) throw Error('unattached reset retained state');
|
||||
}
|
||||
return true;
|
||||
})()"#,
|
||||
)
|
||||
.unwrap(),
|
||||
"true"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_drawing_stack_restores_native_attributes_transform_and_dash_across_realms() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-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, 'window-' + owner + '-' + callee + '-' + kind));
|
||||
globalThis.__canvasStateChecks = checks;
|
||||
return checks.length;
|
||||
}})()"#,
|
||||
include_str!("canvas_drawing_state.js"),
|
||||
);
|
||||
let count: usize = vm.eval(&source).unwrap().parse().unwrap();
|
||||
assert_eq!(count, 1_340, "the complete realm matrix must execute");
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(__canvasStateChecks.filter(row => !row.passed))")
|
||||
.unwrap(),
|
||||
"[]"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_drawing_stack_accepts_registered_native_proxies_without_author_hooks() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-state-proxy.test/");
|
||||
vm.eval(
|
||||
r#"document.body.innerHTML = '<iframe id=child></iframe>';
|
||||
globalThis.canvasStateContexts = [document.createElement('canvas'), new OffscreenCanvas(8,8)]
|
||||
.map(canvas => canvas.getContext('2d'));"#,
|
||||
)
|
||||
.unwrap();
|
||||
let context_ptr = &vm.current_main_world().unwrap().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, "canvasStateContexts");
|
||||
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 value = contexts.get_index(scope, index).unwrap();
|
||||
let context = v8::Local::<v8::Object>::try_from(value).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, "canvasStateProxies");
|
||||
assert_eq!(
|
||||
global.create_data_property(scope, key.into(), proxies.into()),
|
||||
Some(true)
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
vm.eval(
|
||||
r#"(() => {
|
||||
const realms = [globalThis, document.getElementById('child').contentWindow];
|
||||
for (let i=0;i<2;i++) {
|
||||
const real=canvasStateContexts[i], proxy=canvasStateProxies[i];
|
||||
const name=i===0?'CanvasRenderingContext2D':'OffscreenCanvasRenderingContext2D';
|
||||
for (const realm of realms) {
|
||||
const p=realm[name].prototype;
|
||||
real.lineWidth=2; real.setTransform(1,0,0,1,3,4); real.setLineDash([1,2]);
|
||||
p.save.call(proxy);
|
||||
real.lineWidth=5; real.resetTransform(); real.setLineDash([4,5]);
|
||||
p.restore.call(proxy);
|
||||
if(real.lineWidth!==2 || real.getTransform().e!==3 || real.getLineDash()[0]!==1)
|
||||
throw Error('native proxy snapshot differs from native target');
|
||||
for(const member of ['save','restore','reset']) {
|
||||
let rejected=false;
|
||||
try {p[member].call(new Proxy(proxy,{}));} catch(error) {rejected=error instanceof realm.TypeError;}
|
||||
if(!rejected) throw Error('author proxy accepted');
|
||||
}
|
||||
p.save.call(proxy); p.reset.call(proxy); p.restore.call(proxy);
|
||||
if(real.lineWidth!==1 || real.getTransform().e!==0 || real.getLineDash().length!==0)
|
||||
throw Error('native proxy reset retained stack');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})()"#,
|
||||
)
|
||||
.unwrap(),
|
||||
"true"
|
||||
);
|
||||
}
|
||||
@@ -2290,6 +2290,7 @@ mod cache_interfaces;
|
||||
mod dom_token_list_native_receivers;
|
||||
|
||||
mod canvas_arguments;
|
||||
mod canvas_drawing_state;
|
||||
mod canvas_fill_rect;
|
||||
mod canvas_image_proxies;
|
||||
mod canvas_paths;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn worker_offscreen_canvas_drawing_stack_preserves_native_state_and_bitmap_boundaries() {
|
||||
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/canvas_drawing_state.js"),
|
||||
);
|
||||
let mut worker = spawn_worker(source, "test://canvas_drawing_state".into());
|
||||
let message = timeout(TIMEOUT, worker.recv())
|
||||
.await
|
||||
.expect("timed out")
|
||||
.expect("channel closed");
|
||||
let value: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();
|
||||
assert_eq!(value["total"].as_u64(), Some(166));
|
||||
assert_eq!(value["failures"], serde_json::json!([]));
|
||||
}
|
||||
@@ -1560,6 +1560,7 @@ fn service_worker_storage_apis_use_explicit_registration_storage_key() {
|
||||
mod abort_signal_events;
|
||||
mod abort_signal_statics;
|
||||
mod bitmap_renderer;
|
||||
mod canvas_drawing_state;
|
||||
mod canvas_fill_rect;
|
||||
mod canvas_transform_snapshots;
|
||||
mod cors_redirects;
|
||||
|
||||
@@ -25,6 +25,7 @@ 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 CANVAS_CONTEXT_LINE_DASH_SLOT: &str = "__moliCanvasContextLineDash";
|
||||
|
||||
pub const DEFAULT_GLOBAL_ALPHA: f64 = 1.0;
|
||||
pub const DEFAULT_GLOBAL_COMPOSITE_OPERATION: &str = "source-over";
|
||||
@@ -35,57 +36,35 @@ 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(
|
||||
slot = CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT,
|
||||
constructor_default = true
|
||||
)]
|
||||
image_smoothing_enabled: bool,
|
||||
#[webapi(
|
||||
slot = CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT,
|
||||
constructor_default = "low"
|
||||
)]
|
||||
image_smoothing_quality: &'static str,
|
||||
#[webapi(
|
||||
slot = CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT,
|
||||
constructor_default = DEFAULT_GLOBAL_ALPHA
|
||||
)]
|
||||
global_alpha: f64,
|
||||
#[webapi(
|
||||
slot = CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT,
|
||||
constructor_default = DEFAULT_GLOBAL_COMPOSITE_OPERATION
|
||||
)]
|
||||
global_composite_operation: &'static str,
|
||||
#[webapi(slot = CANVAS_CONTEXT_LINE_WIDTH_SLOT, constructor_default = DEFAULT_LINE_WIDTH)]
|
||||
line_width: f64,
|
||||
#[webapi(slot = CANVAS_CONTEXT_LINE_CAP_SLOT, constructor_default = DEFAULT_LINE_CAP)]
|
||||
line_cap: &'static str,
|
||||
#[webapi(slot = CANVAS_CONTEXT_LINE_JOIN_SLOT, constructor_default = DEFAULT_LINE_JOIN)]
|
||||
line_join: &'static str,
|
||||
#[webapi(
|
||||
slot = CANVAS_CONTEXT_MITER_LIMIT_SLOT,
|
||||
constructor_default = DEFAULT_MITER_LIMIT
|
||||
)]
|
||||
miter_limit: f64,
|
||||
#[webapi(
|
||||
slot = CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT,
|
||||
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,
|
||||
// Initialization, reset and save/restore use the same list of implemented
|
||||
// drawing attributes. New native attributes must join this declaration.
|
||||
macro_rules! canvas_drawing_slots {
|
||||
($($name:ident: $ty:ty => $slot:ident = $default:expr;)*) => {
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(fragment, prototype = "CanvasRenderingContext2D")]
|
||||
struct CanvasLikeContextObjectDeclaration {
|
||||
$(#[webapi(slot = $slot, constructor_default = $default)]
|
||||
$name: $ty,)*
|
||||
}
|
||||
|
||||
pub const CANVAS_DRAWING_SLOTS: &[&str] = &[$($slot),*];
|
||||
};
|
||||
}
|
||||
|
||||
canvas_drawing_slots! {
|
||||
fill_style: &'static str => CANVAS_CONTEXT_FILL_STYLE_SLOT = DEFAULT_FILL_STYLE;
|
||||
font: &'static str => CANVAS_CONTEXT_FONT_SLOT = DEFAULT_FONT;
|
||||
image_smoothing_enabled: bool => CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT = true;
|
||||
image_smoothing_quality: &'static str => CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT = "low";
|
||||
global_alpha: f64 => CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT = DEFAULT_GLOBAL_ALPHA;
|
||||
global_composite_operation: &'static str => CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT = DEFAULT_GLOBAL_COMPOSITE_OPERATION;
|
||||
line_width: f64 => CANVAS_CONTEXT_LINE_WIDTH_SLOT = DEFAULT_LINE_WIDTH;
|
||||
line_cap: &'static str => CANVAS_CONTEXT_LINE_CAP_SLOT = DEFAULT_LINE_CAP;
|
||||
line_join: &'static str => CANVAS_CONTEXT_LINE_JOIN_SLOT = DEFAULT_LINE_JOIN;
|
||||
miter_limit: f64 => CANVAS_CONTEXT_MITER_LIMIT_SLOT = DEFAULT_MITER_LIMIT;
|
||||
line_dash_offset: f64 => CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT = DEFAULT_LINE_DASH_OFFSET;
|
||||
stroke_style: &'static str => CANVAS_CONTEXT_STROKE_STYLE_SLOT = DEFAULT_STROKE_STYLE;
|
||||
line_dash: Vec<f64> => CANVAS_CONTEXT_LINE_DASH_SLOT = Vec::new();
|
||||
}
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
|
||||
Reference in New Issue
Block a user