mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
fix(canvas): implement native stroke hit testing
This commit is contained in:
@@ -133,8 +133,8 @@ pub(crate) use context2d::{
|
||||
canvas_context_image_smoothing_enabled_setter_callback,
|
||||
canvas_context_image_smoothing_quality_getter_callback,
|
||||
canvas_context_image_smoothing_quality_setter_callback,
|
||||
canvas_context_is_point_in_stroke_callback, canvas_context_line_cap_getter_callback,
|
||||
canvas_context_line_cap_setter_callback, canvas_context_line_dash_offset_getter_callback,
|
||||
canvas_context_line_cap_getter_callback, canvas_context_line_cap_setter_callback,
|
||||
canvas_context_line_dash_offset_getter_callback,
|
||||
canvas_context_line_dash_offset_setter_callback, canvas_context_line_join_getter_callback,
|
||||
canvas_context_line_join_setter_callback, canvas_context_line_to_callback,
|
||||
canvas_context_line_width_getter_callback, canvas_context_line_width_setter_callback,
|
||||
|
||||
@@ -1357,37 +1357,73 @@ fn context_stroke<'s>(
|
||||
path: moli_layout::PaintPath,
|
||||
transform: PaintTransform2D,
|
||||
) -> PaintStroke {
|
||||
let join = match context_string_slot(scope, context, CANVAS_CONTEXT_LINE_JOIN_SLOT).as_deref() {
|
||||
Some("round") => PaintLineJoin::Round,
|
||||
Some("bevel") => PaintLineJoin::Bevel,
|
||||
_ => PaintLineJoin::Miter,
|
||||
};
|
||||
let cap = match context_string_slot(scope, context, CANVAS_CONTEXT_LINE_CAP_SLOT).as_deref() {
|
||||
Some("round") => PaintLineCap::Round,
|
||||
Some("square") => PaintLineCap::Square,
|
||||
_ => PaintLineCap::Butt,
|
||||
let style = context_stroke_style(scope, context);
|
||||
let cap = match style.start_cap {
|
||||
kurbo::Cap::Round => PaintLineCap::Round,
|
||||
kurbo::Cap::Square => PaintLineCap::Square,
|
||||
kurbo::Cap::Butt => PaintLineCap::Butt,
|
||||
};
|
||||
PaintStroke {
|
||||
path,
|
||||
color: PaintColor::WHITE,
|
||||
width: style.width as f32,
|
||||
join: match style.join {
|
||||
kurbo::Join::Round => PaintLineJoin::Round,
|
||||
kurbo::Join::Bevel => PaintLineJoin::Bevel,
|
||||
kurbo::Join::Miter => PaintLineJoin::Miter,
|
||||
},
|
||||
start_cap: cap,
|
||||
end_cap: cap,
|
||||
miter_limit: style.miter_limit as f32,
|
||||
dash_pattern: style
|
||||
.dash_pattern
|
||||
.iter()
|
||||
.map(|value| *value as f32)
|
||||
.collect(),
|
||||
dash_offset: style.dash_offset as f32,
|
||||
transform,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn context_stroke_style<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
) -> kurbo::Stroke {
|
||||
let join = match context_string_slot(scope, context, CANVAS_CONTEXT_LINE_JOIN_SLOT).as_deref() {
|
||||
Some("round") => kurbo::Join::Round,
|
||||
Some("bevel") => kurbo::Join::Bevel,
|
||||
_ => kurbo::Join::Miter,
|
||||
};
|
||||
let cap = match context_string_slot(scope, context, CANVAS_CONTEXT_LINE_CAP_SLOT).as_deref() {
|
||||
Some("round") => kurbo::Cap::Round,
|
||||
Some("square") => kurbo::Cap::Square,
|
||||
_ => kurbo::Cap::Butt,
|
||||
};
|
||||
let dashes = context_line_dash(scope, context);
|
||||
kurbo::Stroke {
|
||||
width: context_number_slot(scope, context, CANVAS_CONTEXT_LINE_WIDTH_SLOT)
|
||||
.unwrap_or(DEFAULT_LINE_WIDTH) as f32,
|
||||
.unwrap_or(DEFAULT_LINE_WIDTH),
|
||||
join,
|
||||
start_cap: cap,
|
||||
end_cap: cap,
|
||||
miter_limit: context_number_slot(scope, context, CANVAS_CONTEXT_MITER_LIMIT_SLOT)
|
||||
.unwrap_or(DEFAULT_MITER_LIMIT) as f32,
|
||||
dash_pattern: context_line_dash(scope, context),
|
||||
.unwrap_or(DEFAULT_MITER_LIMIT),
|
||||
// HTML treats an all-zero dash list as a solid stroke. Keep the
|
||||
// original private list intact for getLineDash and save/restore.
|
||||
dash_pattern: if dashes.iter().all(|dash| *dash == 0.0) {
|
||||
Default::default()
|
||||
} else {
|
||||
dashes.into_iter().collect()
|
||||
},
|
||||
dash_offset: context_number_slot(scope, context, CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT)
|
||||
.unwrap_or(DEFAULT_LINE_DASH_OFFSET) as f32,
|
||||
transform,
|
||||
.unwrap_or(DEFAULT_LINE_DASH_OFFSET),
|
||||
}
|
||||
}
|
||||
|
||||
fn context_line_dash<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
context: v8::Local<'s, v8::Object>,
|
||||
) -> Vec<f32> {
|
||||
) -> Vec<f64> {
|
||||
let Some(array) = get_private_value(scope, context, CANVAS_CONTEXT_LINE_DASH_SLOT)
|
||||
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
|
||||
else {
|
||||
@@ -1396,7 +1432,6 @@ fn context_line_dash<'s>(
|
||||
(0..array.length())
|
||||
.filter_map(|index| array.get_index(scope, index))
|
||||
.filter_map(|value| value.number_value(scope))
|
||||
.map(|value| value as f32)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1426,14 +1461,6 @@ fn rasterize_canvas_fragment<'s>(
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_context_is_point_in_stroke_callback(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
_args: v8::FunctionCallbackArguments<'_>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
rv.set(v8::Boolean::new(scope, false).into());
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_context_fill_text_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
|
||||
@@ -31,6 +31,8 @@ impl Default for Canvas2dPathState {
|
||||
}
|
||||
}
|
||||
|
||||
use moli_svg::StrokeQueryLimitExceeded;
|
||||
|
||||
const TWO_PI: f64 = std::f64::consts::TAU;
|
||||
|
||||
impl Canvas2dPathState {
|
||||
@@ -393,10 +395,18 @@ impl Canvas2dPathState {
|
||||
transform: LayoutTransform2D,
|
||||
fill_rule: moli_svg::SvgFillRule,
|
||||
) -> bool {
|
||||
let affine = kurbo::Affine::new(transform.coefficients);
|
||||
let path = self.bezier_path(kurbo::Affine::new(transform.coefficients));
|
||||
moli_svg::is_point_in_path_with_rule(
|
||||
&path,
|
||||
moli_svg::SvgGeometryPoint::new(x, y),
|
||||
fill_rule,
|
||||
)
|
||||
}
|
||||
|
||||
fn bezier_path(&self, affine: kurbo::Affine) -> kurbo::BezPath {
|
||||
let map =
|
||||
|point: LayoutPoint| affine * kurbo::Point::new(f64::from(point.x), f64::from(point.y));
|
||||
let path = kurbo::BezPath::from_vec(
|
||||
kurbo::BezPath::from_vec(
|
||||
self.elements
|
||||
.iter()
|
||||
.map(|element| match *element {
|
||||
@@ -409,13 +419,17 @@ impl Canvas2dPathState {
|
||||
PaintPathElement::Close => kurbo::PathEl::ClosePath,
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
moli_svg::is_point_in_path_with_rule(
|
||||
&path,
|
||||
moli_svg::SvgGeometryPoint::new(x, y),
|
||||
fill_rule,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn contains_stroke_point(
|
||||
&self,
|
||||
point: kurbo::Point,
|
||||
geometry_transform: kurbo::Affine,
|
||||
style: &kurbo::Stroke,
|
||||
) -> Result<bool, StrokeQueryLimitExceeded> {
|
||||
moli_svg::is_point_in_stroke_path(self.bezier_path(geometry_transform), point, style)
|
||||
}
|
||||
}
|
||||
|
||||
fn path_bounds(elements: &[PaintPathElement]) -> PaintRect {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! Native Path2D construction and shared CanvasPath bindings.
|
||||
|
||||
use super::*;
|
||||
mod hit_testing;
|
||||
use super::{path::Canvas2dPathState, state::canvas_path_state};
|
||||
use crate::webidl;
|
||||
use hit_testing::{is_point_in_path_callback, is_point_in_stroke_callback};
|
||||
use moli_webapi::{
|
||||
canvas_context_values::transform::validate_transform_init, geometry::DomMatrix2DInit,
|
||||
};
|
||||
@@ -55,6 +58,8 @@ macro_rules! canvas_draw_path_declaration {
|
||||
stroke: (),
|
||||
#[webapi(method = "isPointInPath", length = 2, callback = is_point_in_path_callback)]
|
||||
is_point_in_path: (),
|
||||
#[webapi(method = "isPointInStroke", length = 2, callback = is_point_in_stroke_callback)]
|
||||
is_point_in_stroke: (),
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -123,78 +128,6 @@ impl CanvasFillRule {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.isPointInPath")]
|
||||
struct PointArgs {
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
x: f64,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
y: f64,
|
||||
#[webidl(default = CanvasFillRule::Nonzero, converter = "enum")]
|
||||
rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.isPointInPath")]
|
||||
struct PathPointArgs<'s> {
|
||||
#[webidl(required, interface = web_api_interfaces::Path2D)]
|
||||
path: v8::Local<'s, v8::Object>,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
x: f64,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
y: f64,
|
||||
#[webidl(default = CanvasFillRule::Nonzero, converter = "enum")]
|
||||
rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
fn is_point_in_path_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let explicit_path = args.length() >= 4
|
||||
|| (args.length() == 3
|
||||
&& path_object(
|
||||
scope,
|
||||
args.get(0),
|
||||
webidl::Context::argument("CanvasDrawPath.isPointInPath", 1),
|
||||
)
|
||||
.is_ok());
|
||||
let (path, x, y, rule) = if explicit_path {
|
||||
let Some(parsed) = webidl::parse_args::<PathPointArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let target = web_api_object_target(scope, parsed.path).expect("validated Path2D argument");
|
||||
(Some(target), parsed.x, parsed.y, parsed.rule)
|
||||
} else {
|
||||
let Some(parsed) = webidl::parse_args::<PointArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
(None, parsed.x, parsed.y, parsed.rule)
|
||||
};
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
rv.set_bool(false);
|
||||
return;
|
||||
}
|
||||
// Read native state after all author conversions: valueOf can reset the
|
||||
// context or append geometry. Only Path2D geometry uses the current CTM;
|
||||
// the default path already froze each command's transform when recorded.
|
||||
let context = web_api_object_target(scope, args.this()).expect("validated Canvas 2D receiver");
|
||||
let context_state = canvas_path_state(scope, context);
|
||||
let transform = if path.is_some() {
|
||||
context_state.borrow().transform()
|
||||
} else {
|
||||
moli_layout::LayoutTransform2D::IDENTITY
|
||||
};
|
||||
let path_state = path
|
||||
.map(|object| canvas_path_state(scope, object))
|
||||
.unwrap_or(context_state);
|
||||
let contains = path_state
|
||||
.borrow()
|
||||
.contains_point(x, y, transform, rule.svg_rule());
|
||||
rv.set_bool(contains);
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.fill")]
|
||||
struct FillRuleArgs {
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Native Canvas fill and stroke hit testing after WebIDL conversion.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.isPointInPath")]
|
||||
struct PointArgs {
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
x: f64,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
y: f64,
|
||||
#[webidl(default = CanvasFillRule::Nonzero, converter = "enum")]
|
||||
rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.isPointInPath")]
|
||||
struct PathPointArgs<'s> {
|
||||
#[webidl(required, interface = web_api_interfaces::Path2D)]
|
||||
path: v8::Local<'s, v8::Object>,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
x: f64,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
y: f64,
|
||||
#[webidl(default = CanvasFillRule::Nonzero, converter = "enum")]
|
||||
rule: CanvasFillRule,
|
||||
}
|
||||
|
||||
pub(super) fn is_point_in_path_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let explicit_path = args.length() >= 4
|
||||
|| (args.length() == 3
|
||||
&& path_object(
|
||||
scope,
|
||||
args.get(0),
|
||||
webidl::Context::argument("CanvasDrawPath.isPointInPath", 1),
|
||||
)
|
||||
.is_ok());
|
||||
let (path, x, y, rule) = if explicit_path {
|
||||
let Some(parsed) = webidl::parse_args::<PathPointArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let target = web_api_object_target(scope, parsed.path).expect("validated Path2D argument");
|
||||
(Some(target), parsed.x, parsed.y, parsed.rule)
|
||||
} else {
|
||||
let Some(parsed) = webidl::parse_args::<PointArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
(None, parsed.x, parsed.y, parsed.rule)
|
||||
};
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
rv.set_bool(false);
|
||||
return;
|
||||
}
|
||||
// Read native state after all author conversions: valueOf can reset the
|
||||
// context or append geometry. Only Path2D geometry uses the current CTM;
|
||||
// the default path already froze each command's transform when recorded.
|
||||
let context = web_api_object_target(scope, args.this()).expect("validated Canvas 2D receiver");
|
||||
let context_state = canvas_path_state(scope, context);
|
||||
let transform = if path.is_some() {
|
||||
context_state.borrow().transform()
|
||||
} else {
|
||||
moli_layout::LayoutTransform2D::IDENTITY
|
||||
};
|
||||
let path_state = path
|
||||
.map(|object| canvas_path_state(scope, object))
|
||||
.unwrap_or(context_state);
|
||||
let contains = path_state
|
||||
.borrow()
|
||||
.contains_point(x, y, transform, rule.svg_rule());
|
||||
rv.set_bool(contains);
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.isPointInStroke")]
|
||||
struct StrokePointArgs {
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
x: f64,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
y: f64,
|
||||
}
|
||||
|
||||
#[derive(webidl::WebIdlArgs)]
|
||||
#[webidl(prefix = "CanvasDrawPath.isPointInStroke")]
|
||||
struct StrokePathPointArgs<'s> {
|
||||
#[webidl(required, interface = web_api_interfaces::Path2D)]
|
||||
path: v8::Local<'s, v8::Object>,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
x: f64,
|
||||
#[webidl(required, converter = "unrestricted_double")]
|
||||
y: f64,
|
||||
}
|
||||
|
||||
pub(super) fn is_point_in_stroke_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let (path, x, y) = if args.length() >= 3 {
|
||||
let Some(parsed) = webidl::parse_args::<StrokePathPointArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
let target = web_api_object_target(scope, parsed.path).expect("validated Path2D argument");
|
||||
(Some(target), parsed.x, parsed.y)
|
||||
} else {
|
||||
let Some(parsed) = webidl::parse_args::<StrokePointArgs>(scope, &args) else {
|
||||
return;
|
||||
};
|
||||
(None, parsed.x, parsed.y)
|
||||
};
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
rv.set_bool(false);
|
||||
return;
|
||||
}
|
||||
let context = web_api_object_target(scope, args.this()).expect("validated Canvas 2D receiver");
|
||||
let context_state = canvas_path_state(scope, context);
|
||||
let Some(inverse) = context_state.borrow().inverse_transform() else {
|
||||
rv.set_bool(false);
|
||||
return;
|
||||
};
|
||||
let style = super::super::context2d::context_stroke_style(scope, context);
|
||||
let geometry_transform = if path.is_some() {
|
||||
kurbo::Affine::IDENTITY
|
||||
} else {
|
||||
inverse
|
||||
};
|
||||
let state = path
|
||||
.map(|object| canvas_path_state(scope, object))
|
||||
.unwrap_or(context_state);
|
||||
// Stroke widths, caps and dashes are in the current user space. Transform
|
||||
// both the query and the frozen default geometry back to that space;
|
||||
// explicit Path2D geometry is already there.
|
||||
match state.borrow().contains_stroke_point(
|
||||
inverse * kurbo::Point::new(x, y),
|
||||
geometry_transform,
|
||||
&style,
|
||||
) {
|
||||
Ok(contains) => rv.set_bool(contains),
|
||||
Err(_) => {
|
||||
let message = crate::util::v8str(
|
||||
scope,
|
||||
"Stroke hit testing exceeded the geometry allocation limit.",
|
||||
);
|
||||
let error = v8::Exception::range_error(scope, message);
|
||||
scope.throw_exception(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@ use super::canvas::{
|
||||
canvas_context_image_smoothing_enabled_setter_callback,
|
||||
canvas_context_image_smoothing_quality_getter_callback,
|
||||
canvas_context_image_smoothing_quality_setter_callback,
|
||||
canvas_context_is_point_in_stroke_callback, canvas_context_line_cap_getter_callback,
|
||||
canvas_context_line_cap_setter_callback, canvas_context_line_dash_offset_getter_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,
|
||||
@@ -219,13 +219,6 @@ struct CanvasRenderingContext2dTemplateDeclaration {
|
||||
#[webapi(method = "clip", length = 0, callback = canvas_context_noop_callback)]
|
||||
clip: (),
|
||||
|
||||
#[webapi(
|
||||
method = "isPointInStroke",
|
||||
length = 2,
|
||||
callback = canvas_context_is_point_in_stroke_callback
|
||||
)]
|
||||
is_point_in_stroke: (),
|
||||
|
||||
#[webapi(method = "measureText", length = 1, callback = canvas_context_measure_text_callback)]
|
||||
measure_text: (),
|
||||
|
||||
|
||||
@@ -1,5 +1,66 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn canvas_stroke_hit_testing_preserves_styles_transforms_and_webidl_order_across_realms() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-stroke-hit.test/");
|
||||
vm.eval("document.body.innerHTML='<iframe id=other></iframe>'")
|
||||
.unwrap();
|
||||
vm.eval(&format!(
|
||||
"const strokeHitProbe={};const strokeHitRealms=[globalThis,document.getElementById('other').contentWindow];\
|
||||
globalThis.strokeHitChecks=[];\
|
||||
for(let owner=0;owner<2;owner++)for(let callee=0;callee<2;callee++)for(const kind of ['element','offscreen'])\
|
||||
strokeHitChecks.push(...strokeHitProbe(strokeHitRealms[owner],strokeHitRealms[callee],kind,owner+'-'+callee+'-'+kind));",
|
||||
include_str!("canvas_stroke_hit_testing.js"),
|
||||
)).unwrap();
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(strokeHitChecks.filter(row=>!row.passed))")
|
||||
.unwrap(),
|
||||
"[]"
|
||||
);
|
||||
assert_eq!(vm.eval("strokeHitChecks.length").unwrap(), "744");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_stroke_hit_testing_accepts_registered_native_context_and_path_proxies() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-stroke-hit-proxy.test/");
|
||||
vm.eval("globalThis.strokeContext=new OffscreenCanvas(1,1).getContext('2d');globalThis.strokePath=new Path2D();strokePath.moveTo(10,20);strokePath.lineTo(30,20);").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);
|
||||
for (source, destination) in [
|
||||
("strokeContext", "strokeContextProxy"),
|
||||
("strokePath", "strokePathProxy"),
|
||||
] {
|
||||
let key = crate::util::v8str(scope, source);
|
||||
let target =
|
||||
v8::Local::<v8::Object>::try_from(global.get(scope, key.into()).unwrap()).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)?;
|
||||
let key = crate::util::v8str(scope, destination);
|
||||
assert_eq!(
|
||||
global.create_data_property(scope, key.into(), proxy.into()),
|
||||
Some(true)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(vm.eval(r#"(() => {
|
||||
const hit=OffscreenCanvasRenderingContext2D.prototype.isPointInStroke;
|
||||
if(!hit.call(strokeContextProxy,strokePathProxy,20,20))return false;
|
||||
let conversions=0,traps=0;
|
||||
const coordinate={valueOf(){conversions++;return 20;}};
|
||||
for(const [receiver,path] of [
|
||||
[new Proxy(strokeContextProxy,{get(){traps++;throw Error('trap');}}),strokePathProxy],
|
||||
[strokeContextProxy,new Proxy(strokePathProxy,{get(){traps++;throw Error('trap');}})]]) {
|
||||
let rejected=false;try{hit.call(receiver,path,coordinate,20);}catch(error){rejected=error instanceof TypeError;}
|
||||
if(!rejected)return false;
|
||||
}
|
||||
return conversions===0&&traps===0;
|
||||
})()"#).unwrap(),"true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_fill_hit_testing_preserves_geometry_and_webidl_order_across_realms() {
|
||||
let mut vm = new_storage_page_task_executor_test_vm("https://canvas-hit-testing.test/");
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
(owner, callee, kind, label) => {
|
||||
const canvas = kind === 'element' ? owner.document.createElement('canvas') : new owner.OffscreenCanvas(100, 100);
|
||||
const context = canvas.getContext('2d');
|
||||
const iface = kind === 'element' ? 'CanvasRenderingContext2D' : 'OffscreenCanvasRenderingContext2D';
|
||||
const method = callee[iface].prototype.isPointInStroke;
|
||||
const hit = (...args) => Reflect.apply(method, context, args);
|
||||
const rows = [];
|
||||
const check = (name, run) => {
|
||||
try { rows.push({name: label + ':' + name, passed: run() === true}); }
|
||||
catch (error) { rows.push({name: label + ':' + name, passed: false, error: String(error)}); }
|
||||
};
|
||||
const throws = run => {
|
||||
try { run(); } catch (error) { return error instanceof callee.TypeError; }
|
||||
return false;
|
||||
};
|
||||
const line = () => {
|
||||
context.reset(); context.lineWidth = 10;
|
||||
context.moveTo(10, 20); context.lineTo(30, 20);
|
||||
};
|
||||
check('method length', () => method.length === 2);
|
||||
check('empty path', () => !hit(0, 0));
|
||||
line();
|
||||
for (const [x, y] of [[20,20],[10,20],[30,20],[20,15],[20,25]])
|
||||
check('butt stroke interior or boundary ' + x + ',' + y, () => hit(x,y));
|
||||
for (const [x, y] of [[9.99,20],[30.01,20],[20,14.99],[20,25.01]])
|
||||
check('butt stroke exterior ' + x + ',' + y, () => !hit(x,y));
|
||||
context.lineCap = 'round';
|
||||
check('round cap interior', () => hit(6,20));
|
||||
check('round cap boundary', () => hit(5,20));
|
||||
check('round cap excludes corner', () => !hit(6,24));
|
||||
context.lineCap = 'square';
|
||||
check('square cap includes corner', () => hit(6,24));
|
||||
check('square cap boundary', () => hit(5,25));
|
||||
check('square cap exterior', () => !hit(4.99,20));
|
||||
line(); context.beginPath(); context.moveTo(10,30); context.lineTo(30,30); context.lineTo(30,10);
|
||||
check('miter join interior', () => hit(34,34));
|
||||
check('miter join boundary', () => hit(35,35));
|
||||
context.lineJoin = 'bevel';
|
||||
check('bevel join excludes outer corner', () => !hit(33,33));
|
||||
context.lineJoin = 'round';
|
||||
check('round join interior', () => hit(33,33));
|
||||
check('round join excludes outer corner', () => !hit(34,34));
|
||||
context.lineJoin = 'miter'; context.miterLimit = 1;
|
||||
check('miter limit clips join', () => !hit(33,33));
|
||||
context.miterLimit = 10;
|
||||
check('miter limit restores join', () => hit(33,33));
|
||||
line(); context.lineWidth = 2; context.scale(2,3);
|
||||
check('default path freezes centerline', () => hit(20,20) && !hit(40,20));
|
||||
check('default stroke uses current anisotropic width', () => hit(20,22.5) && !hit(20,23.01));
|
||||
const path = new owner.Path2D(); path.moveTo(10,20); path.lineTo(30,20);
|
||||
check('explicit path uses current transform', () => hit(path,40,60));
|
||||
check('explicit path uses current anisotropic width', () => hit(path,40,62.5) && !hit(path,40,63.01));
|
||||
check('explicit path does not use untransformed coordinates', () => !hit(path,20,20));
|
||||
context.setTransform(2,1,0.5,3,20,-10); context.lineWidth = 10;
|
||||
check('sheared stroke interior', () => hit(path,72,82));
|
||||
check('sheared stroke exterior', () => !hit(path,73,88));
|
||||
context.resetTransform();
|
||||
check('query does not transform Path2D storage', () => hit(path,20,20));
|
||||
line(); context.beginPath(); context.moveTo(0,10); context.lineTo(50,10); context.lineWidth = 2; context.setLineDash([10,10]);
|
||||
check('dash on segments', () => hit(5,10) && hit(25,10));
|
||||
check('dash gap', () => !hit(15,10));
|
||||
context.lineDashOffset = 5;
|
||||
check('positive dash offset', () => hit(2,10) && !hit(7,10) && hit(17,10));
|
||||
context.lineDashOffset = -5;
|
||||
check('negative dash offset', () => !hit(2,10) && hit(7,10) && !hit(17,10));
|
||||
context.lineDashOffset = 45;
|
||||
check('dash offset wraps', () => hit(2,10) && !hit(7,10));
|
||||
context.lineDashOffset = 0; context.setLineDash([3,2,1]);
|
||||
check('odd dash pattern repeats with parity', () => hit(1,10) && !hit(4,10) && hit(5.5,10) && !hit(7,10) && hit(10,10) && !hit(11.5,10));
|
||||
context.setLineDash([0,0]);
|
||||
check('all-zero dashes are solid', () => hit(12,10));
|
||||
check('all-zero private list is preserved', () => context.getLineDash().join() === '0,0');
|
||||
context.save(); context.setLineDash([2,2]); context.restore();
|
||||
check('save restore keeps all-zero semantics', () => hit(12,10) && context.getLineDash().join() === '0,0');
|
||||
context.setLineDash([0,10]);
|
||||
check('zero-length butt dashes have no area', () => !hit(10,10));
|
||||
context.lineCap = 'round';
|
||||
check('zero-length round dash produces a dot', () => hit(10,10) && !hit(5,10));
|
||||
context.lineCap = 'square';
|
||||
check('zero-length square dash includes cap corners', () => hit(10.9,10.9));
|
||||
check('zero-length square dash exterior', () => !hit(11.01,10));
|
||||
check('zero-length square dash gap', () => !hit(5,10));
|
||||
context.lineDashOffset = 2;
|
||||
check('zero-length dash positive offset', () => hit(8,10) && !hit(3,10));
|
||||
context.lineDashOffset = -2;
|
||||
check('zero-length dash negative offset', () => hit(2,10) && !hit(7,10));
|
||||
context.lineDashOffset = 0; context.beginPath(); context.moveTo(0,0); context.lineTo(20,20);
|
||||
context.setLineDash([0,10*Math.SQRT2]);
|
||||
check('zero-length square dash follows diagonal direction', () => hit(11.2,10));
|
||||
check('diagonal square dash excludes rotated corner', () => !hit(10.8,10.8));
|
||||
context.beginPath(); context.moveTo(0,0); context.quadraticCurveTo(10,20,20,0); context.setLineDash([0,10]);
|
||||
check('zero-length square dash follows curve tangent', () => hit(-0.4,1.2));
|
||||
check('curve-tangent square dash exterior', () => !hit(-0.5,1.5));
|
||||
context.beginPath(); context.moveTo(0,0); context.bezierCurveTo(0,0,0,10,10,10);
|
||||
check('zero first derivative uses next distinct control direction', () => hit(0.9,0.9));
|
||||
context.lineCap = 'round';
|
||||
check('zero-length curve dash round cap', () => hit(-0.9,0));
|
||||
line(); context.lineWidth = 2; context.beginPath(); context.moveTo(0,0); context.lineTo(20,0); context.lineTo(20,20);
|
||||
check('open stroke is not implicitly closed', () => !hit(10,10));
|
||||
check('query leaves subpath open', () => { context.lineTo(0,20); return hit(10,20); });
|
||||
context.beginPath(); context.rect(0,0,20,20); context.setLineDash([15,10]);
|
||||
check('closed dashed seam preserves join', () => hit(-0.5,-0.5));
|
||||
line(); context.globalAlpha = 0; context.strokeStyle = 'transparent';
|
||||
check('alpha and stroke color do not affect geometry', () => hit(20,20));
|
||||
check('queries are not clipped to bitmap bounds', () => {
|
||||
context.beginPath(); context.moveTo(-100,-100); context.lineTo(-80,-100); return hit(-90,-100);
|
||||
});
|
||||
line(); context.scale(0,0);
|
||||
check('singular transform has no stroke area', () => !hit(20,20) && !hit(path,0,0));
|
||||
context.resetTransform();
|
||||
check('singular query does not mutate geometry', () => hit(20,20));
|
||||
check('point conversion precedes geometry snapshot', () => {
|
||||
context.beginPath();
|
||||
return hit({valueOf() { context.moveTo(10,20); context.lineTo(30,20); return 20; }},20);
|
||||
});
|
||||
check('point conversion precedes style snapshot', () => {
|
||||
context.lineWidth = 2;
|
||||
return hit({valueOf() { context.lineWidth = 20; return 20; }},28);
|
||||
});
|
||||
check('point conversion precedes transform snapshot', () => {
|
||||
context.lineWidth = 2;
|
||||
return hit(path,{valueOf() { context.scale(2,3); return 40; }},62.5);
|
||||
});
|
||||
check('resize during conversion resets native path', () => !hit({valueOf() { canvas.width = canvas.width; return 20; }},20));
|
||||
check('explicit path mutation during conversion is visible', () => {
|
||||
const p = new owner.Path2D();
|
||||
return hit(p,{valueOf() { p.moveTo(10,20); p.lineTo(30,20); return 20; }},20);
|
||||
});
|
||||
check('all coordinate conversions precede nonfinite return', () => {
|
||||
const order=[];
|
||||
return !hit({valueOf(){order.push('x');return NaN;}},{valueOf(){order.push('y');return 0;}}) && order.join() === 'x,y';
|
||||
});
|
||||
check('original conversion exception propagates', () => {
|
||||
const marker={};try { hit(NaN,{valueOf(){throw marker;}}); } catch(error) { return error===marker; } return false;
|
||||
});
|
||||
for (const [x,y] of [[NaN,0],[0,NaN],[Infinity,0],[0,-Infinity]])
|
||||
check('nonfinite query ' + x + ',' + y, () => !hit(x,y));
|
||||
for (const args of [[],[1],[1,Symbol('y')],[1,1n],[1,1,1]])
|
||||
check('invalid arguments ' + args.map(String).join(','), () => throws(() => hit(...args)));
|
||||
check('required arity precedes conversion', () => {
|
||||
let calls=0;return throws(() => hit({valueOf(){calls++;return 1;}})) && calls===0;
|
||||
});
|
||||
check('extra explicit path argument is ignored', () => hit(path,20,20,{toString(){throw Error('unused');}}));
|
||||
const revoked = owner.Proxy.revocable(context,{}); revoked.revoke();
|
||||
for (const [index,receiver] of [null,undefined,{},Object.create(callee[iface].prototype),Object.create(context),new owner.Proxy(context,{}),revoked.proxy].entries()) {
|
||||
check('invalid receiver before coordinates ' + index, () => {
|
||||
let calls=0;return throws(() => Reflect.apply(method,receiver,[{valueOf(){calls++;return 1;}},1])) && calls===0;
|
||||
});
|
||||
}
|
||||
const revokedPath = owner.Proxy.revocable(path,{}); revokedPath.revoke();
|
||||
for (const [index,value] of [null,undefined,{},Object.create(owner.Path2D.prototype),Object.create(path),new owner.Proxy(path,{}),revokedPath.proxy].entries()) {
|
||||
check('invalid path before coordinates ' + index, () => {
|
||||
let calls=0;return throws(() => hit(value,{valueOf(){calls++;return 1;}},1)) && calls===0;
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ mod helpers;
|
||||
mod length;
|
||||
mod matrix;
|
||||
mod path;
|
||||
mod stroke;
|
||||
mod timing;
|
||||
mod transform;
|
||||
|
||||
@@ -18,6 +19,7 @@ pub use length::{
|
||||
};
|
||||
pub use matrix::{SvgMatrixComponents, serialize_number};
|
||||
pub use path::{SvgPathSegment, parse_path_segments};
|
||||
pub use stroke::{StrokeQueryLimitExceeded, is_point_in_stroke_path};
|
||||
pub use timing::{
|
||||
SvgAnimationEvent, SvgAnimationEventKind, SvgAnimationEvents, SvgAnimationInstanceTimes,
|
||||
SvgAnimationInterval, SvgAnimationRestart, SvgAnimationTiming, SvgPresentationClock,
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Stroke outline containment and zero-length dash caps in user coordinates.
|
||||
|
||||
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct StrokeQueryLimitExceeded;
|
||||
|
||||
const MAX_STROKE_QUERY_ELEMENTS: usize = 1_000_000;
|
||||
const DASH_ACCURACY: f64 = 1e-6;
|
||||
|
||||
pub fn is_point_in_stroke_path(
|
||||
mut path: kurbo::BezPath,
|
||||
point: kurbo::Point,
|
||||
style: &kurbo::Stroke,
|
||||
) -> Result<bool, StrokeQueryLimitExceeded> {
|
||||
if !point.is_finite()
|
||||
|| !style.is_finite()
|
||||
|| style.width <= 0.0
|
||||
|| style.dash_pattern.iter().any(|dash| *dash < 0.0)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let mut style = style.clone();
|
||||
if style.dash_pattern.iter().all(|dash| *dash == 0.0) {
|
||||
style.dash_pattern.clear();
|
||||
} else if style.dash_pattern.len() % 2 == 1 {
|
||||
let repeated = style.dash_pattern.clone();
|
||||
style.dash_pattern.extend(repeated);
|
||||
}
|
||||
let mut scale = 1.0;
|
||||
// Avoid an infinite dash period: a negative offset normalized modulo
|
||||
// infinity would otherwise prevent the dash iterator from advancing.
|
||||
// Uniform power-of-two scaling preserves all geometric relationships.
|
||||
while style.dash_pattern.iter().sum::<f64>().is_infinite() {
|
||||
style.width *= 0.5;
|
||||
style.dash_offset *= 0.5;
|
||||
for dash in &mut style.dash_pattern {
|
||||
*dash *= 0.5;
|
||||
}
|
||||
scale *= 0.5;
|
||||
}
|
||||
let point = kurbo::Point::new(point.x * scale, point.y * scale);
|
||||
path.apply_affine(kurbo::Affine::scale(scale));
|
||||
if !path.is_finite() {
|
||||
return Ok(false);
|
||||
}
|
||||
if zero_dash_cap_contains(&path, point, &style)? {
|
||||
return Ok(true);
|
||||
}
|
||||
let path = if style.dash_pattern.is_empty() {
|
||||
path
|
||||
} else {
|
||||
let mut dashed = kurbo::BezPath::new();
|
||||
for element in kurbo::dash(path.iter(), style.dash_offset, &style.dash_pattern)
|
||||
.take(MAX_STROKE_QUERY_ELEMENTS + 1)
|
||||
{
|
||||
if dashed.elements().len() == MAX_STROKE_QUERY_ELEMENTS {
|
||||
return Err(StrokeQueryLimitExceeded);
|
||||
}
|
||||
dashed.push(element);
|
||||
}
|
||||
style.dash_pattern.clear();
|
||||
dashed
|
||||
};
|
||||
let tolerance = (0.001 * scale).max(style.width * 1e-6);
|
||||
let outline = kurbo::stroke(
|
||||
path.iter(),
|
||||
&style,
|
||||
&kurbo::StrokeOpts::default(),
|
||||
tolerance,
|
||||
);
|
||||
Ok(crate::is_point_in_path_with_rule(
|
||||
&outline,
|
||||
crate::SvgGeometryPoint::new(point.x, point.y),
|
||||
crate::SvgFillRule::NonZero,
|
||||
))
|
||||
}
|
||||
|
||||
/// Zero-on dashes are introduced after zero-length source segments have been
|
||||
/// pruned. Their caps need the direction at that exact source arc length;
|
||||
/// reconstructing a direction from the expanded zero-length segment loses it.
|
||||
fn zero_dash_cap_contains(
|
||||
path: &kurbo::BezPath,
|
||||
point: kurbo::Point,
|
||||
style: &kurbo::Stroke,
|
||||
) -> Result<bool, StrokeQueryLimitExceeded> {
|
||||
if style.start_cap == kurbo::Cap::Butt
|
||||
|| !style
|
||||
.dash_pattern
|
||||
.iter()
|
||||
.step_by(2)
|
||||
.any(|dash| *dash == 0.0)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let mut first = 0;
|
||||
let mut visited = 0;
|
||||
for (index, element) in path.elements().iter().enumerate() {
|
||||
if index > first && matches!(element, kurbo::PathEl::MoveTo(_)) {
|
||||
if subpath_dash_cap_contains(
|
||||
&path.elements()[first..index],
|
||||
point,
|
||||
style,
|
||||
&mut visited,
|
||||
)? {
|
||||
return Ok(true);
|
||||
}
|
||||
first = index;
|
||||
}
|
||||
}
|
||||
subpath_dash_cap_contains(&path.elements()[first..], point, style, &mut visited)
|
||||
}
|
||||
|
||||
fn subpath_dash_cap_contains(
|
||||
elements: &[kurbo::PathEl],
|
||||
point: kurbo::Point,
|
||||
style: &kurbo::Stroke,
|
||||
visited: &mut usize,
|
||||
) -> Result<bool, StrokeQueryLimitExceeded> {
|
||||
let segments = kurbo::segments(elements.iter().copied())
|
||||
.map(|segment| (segment, segment.arclen(DASH_ACCURACY)))
|
||||
.filter(|(_, length)| *length > 0.0)
|
||||
.collect::<Vec<_>>();
|
||||
let length = segments.iter().map(|(_, length)| length).sum::<f64>();
|
||||
let period = style.dash_pattern.iter().sum::<f64>();
|
||||
if segments.is_empty() || period <= 0.0 {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut prefix = 0.0;
|
||||
for (index, dash) in style.dash_pattern.iter().enumerate() {
|
||||
if index.is_multiple_of(2) && *dash == 0.0 {
|
||||
let difference = prefix - style.dash_offset;
|
||||
let mut position = if difference.is_finite() {
|
||||
difference.rem_euclid(period)
|
||||
} else {
|
||||
(prefix - style.dash_offset.rem_euclid(period)).rem_euclid(period)
|
||||
};
|
||||
let mut segment_index = 0;
|
||||
let mut segment_start = 0.0;
|
||||
while position <= length {
|
||||
*visited += 1;
|
||||
if *visited > MAX_STROKE_QUERY_ELEMENTS {
|
||||
return Err(StrokeQueryLimitExceeded);
|
||||
}
|
||||
while segment_index + 1 < segments.len()
|
||||
&& position >= segment_start + segments[segment_index].1
|
||||
{
|
||||
segment_start += segments[segment_index].1;
|
||||
segment_index += 1;
|
||||
}
|
||||
let (segment, segment_length) = segments[segment_index];
|
||||
let t = segment.inv_arclen(
|
||||
(position - segment_start).min(segment_length),
|
||||
DASH_ACCURACY,
|
||||
);
|
||||
if dash_cap_contains(segment, t, point, style) {
|
||||
return Ok(true);
|
||||
}
|
||||
let next = position + period;
|
||||
if next <= position {
|
||||
return Err(StrokeQueryLimitExceeded);
|
||||
}
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
prefix += dash;
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn dash_cap_contains(
|
||||
segment: kurbo::PathSeg,
|
||||
t: f64,
|
||||
point: kurbo::Point,
|
||||
style: &kurbo::Stroke,
|
||||
) -> bool {
|
||||
let center = segment.eval(t);
|
||||
let half_width = style.width * 0.5;
|
||||
if style.start_cap == kurbo::Cap::Round {
|
||||
return point.distance(center) <= half_width;
|
||||
}
|
||||
let Some(direction) = dash_direction(segment, t) else {
|
||||
return false;
|
||||
};
|
||||
let delta = point - center;
|
||||
delta.dot(direction).abs() <= half_width && delta.cross(direction).abs() <= half_width
|
||||
}
|
||||
|
||||
fn dash_direction(segment: kurbo::PathSeg, t: f64) -> Option<kurbo::Vec2> {
|
||||
let tangent = match segment {
|
||||
kurbo::PathSeg::Line(line) => line.p1 - line.p0,
|
||||
kurbo::PathSeg::Quad(curve) => curve.deriv().eval(t).to_vec2(),
|
||||
kurbo::PathSeg::Cubic(curve) => curve.deriv().eval(t).to_vec2(),
|
||||
};
|
||||
let length = tangent.hypot();
|
||||
if length > 0.0 && length.is_finite() {
|
||||
return Some(tangent / length);
|
||||
}
|
||||
// Repeated controls can make the first derivative zero at an endpoint
|
||||
// or cusp. The first distinct control gives the one-sided direction.
|
||||
let at_end = t == 1.0;
|
||||
let remaining = if at_end {
|
||||
segment
|
||||
} else {
|
||||
segment.subsegment(t..1.0)
|
||||
};
|
||||
let vectors = match (remaining, at_end) {
|
||||
(kurbo::PathSeg::Line(line), _) => [line.p1 - line.p0; 3],
|
||||
(kurbo::PathSeg::Quad(curve), false) => {
|
||||
[curve.p1 - curve.p0, curve.p2 - curve.p0, kurbo::Vec2::ZERO]
|
||||
}
|
||||
(kurbo::PathSeg::Quad(curve), true) => {
|
||||
[curve.p2 - curve.p1, curve.p2 - curve.p0, kurbo::Vec2::ZERO]
|
||||
}
|
||||
(kurbo::PathSeg::Cubic(curve), false) => [
|
||||
curve.p1 - curve.p0,
|
||||
curve.p2 - curve.p0,
|
||||
curve.p3 - curve.p0,
|
||||
],
|
||||
(kurbo::PathSeg::Cubic(curve), true) => [
|
||||
curve.p3 - curve.p2,
|
||||
curve.p3 - curve.p1,
|
||||
curve.p3 - curve.p0,
|
||||
],
|
||||
};
|
||||
vectors.into_iter().find_map(|vector| {
|
||||
let length = vector.hypot();
|
||||
(length > 0.0 && length.is_finite()).then(|| vector / length)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stroke_query_preserves_finite_offsets_when_dash_period_overflows() {
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.line_to((100.0, 0.0));
|
||||
for (offset, expected) in [(0.0, true), (1e308, false), (-1e308, false)] {
|
||||
let style = kurbo::Stroke::new(2.0)
|
||||
.with_caps(kurbo::Cap::Butt)
|
||||
.with_dashes(offset, [1e308, 1e308]);
|
||||
assert_eq!(
|
||||
is_point_in_stroke_path(path.clone(), kurbo::Point::new(50.0, 0.0), &style,)
|
||||
.unwrap(),
|
||||
expected,
|
||||
"offset {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_query_reports_allocation_limit_for_extremely_dense_dashes() {
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.line_to((100.0, 0.0));
|
||||
let style = kurbo::Stroke::new(2.0).with_dashes(0.0, [1e-30, 1e-30]);
|
||||
assert!(
|
||||
is_point_in_stroke_path(path.clone(), kurbo::Point::new(50.0, 0.0), &style,).is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user