fix(anatomy): V1-2.2 refuse annotations outside their view's frame

A view without view_box was framed by the drawing's viewBox: moving it and
translating the drawing back left the horse identical and its 19 main-view
markers out of frame, accepted. One frame definition (view_box, else the
drawing viewBox read with the SVG grammar) now frames both composers and is
measured by the verdict (verification.validation.out_of_frame) and the
preview; curves and arcs on their shape. The document is never rewritten.
This commit is contained in:
bchanot committed 2026-10-30 20:54:46 +01:00
1 parent 958228a9de
commit 0c87c7f6c3
8 files changed
+1406 -25

No files matched your search

+17 -7
View File
@@ -15,10 +15,17 @@
//! composers refuse such a tree.
//! Both forms append the marker layer as the root's last child, so the root never hides it: a
//! root `visibility` other than `visible` is refused by the reader and by both composers.
//! Both frame the view on `frame::view_frame` (the view's box, else the drawing's `viewBox` read
//! as a browser reads it), the frame the verdict and the preview measure the annotations against
//! (V1-2.2 owner brief 2026-10-30, defect 3); the canvas falls back to `0 0 100 100`, the PDF
//! view to no `viewBox`. The drawing's `preserveAspectRatio` is dropped: the default
//! `xMidYMid meet` shows the whole frame whatever the box (a `slice` would crop it where the
//! raster's aspect is clamped or the canvas box is not the frame's).
use std::collections::HashSet;
use super::layer::{LayerError, find_view, render_layer, view_box_of};
use super::frame::view_frame;
use super::layer::{LayerError, find_view, render_layer};
pub use super::svg::refs::HALO_FILTER_ID;
use super::svg::refs::holds_reserved_id;
use super::svg::sanitize::check_root_visibility;
@@ -97,14 +104,15 @@ pub fn compose_canvas(
attrs: asset
.attrs
.iter()
.filter(|a| a.qname != "width" && a.qname != "height")
.filter(|a| !matches!(a.qname.as_str(), "width" | "height" | "preserveAspectRatio"))
.cloned()
.collect(),
children: asset.children.clone(),
};
let view_box = view_box_of(view)
.or_else(|| asset.attr("viewBox").map(str::to_owned))
.unwrap_or_else(|| CANVAS_FALLBACK_VIEW_BOX.to_owned());
let view_box = view_frame(view, asset).map_or_else(
|| CANVAS_FALLBACK_VIEW_BOX.to_owned(),
|frame| frame.view_box(),
);
root.set_attr("viewBox", view_box);
let scope = id_scope(view_id);
scope_ids(&mut root, &scope);
@@ -183,11 +191,13 @@ pub fn compose_highlight(
if check_root_visibility(&asset).is_err() {
return Err(ComposeError::RootVisibility);
}
if let Some(view_box) = view_box_of(view) {
asset.set_attr("viewBox", view_box);
match view_frame(view, &asset) {
Some(frame) => asset.set_attr("viewBox", frame.view_box()),
None => asset.remove_attr("viewBox"),
}
asset.remove_attr("width");
asset.remove_attr("height");
asset.remove_attr("preserveAspectRatio");
if halo {
add_halo_filter(&mut asset);
}
+180
View File
@@ -0,0 +1,180 @@
//! The visible frame of a view, and whether an annotation lies in it (V1-2.2 owner brief
//! 2026-10-30, defect 3). One definition for the two composers, the server verdict and the
//! preview: the view's `view_box`, else the `viewBox` of the drawing the view draws, read with
//! the SVG grammar (`path::number_list`, four finite numbers, positive width and height).
//!
//! Annotations are drawn in the user space of the composition root, whose `viewBox` is that
//! frame and which carries no `preserveAspectRatio` (`xMidYMid meet`): the whole frame is
//! visible in the canvas and in the PDF raster, whatever their aspect. Transforms inside the
//! drawing move the drawing only; the reader removes the root's own `transform`. So an
//! annotation is in frame when every point of its shape is inside the frame, edges included.
use super::layer::find_view;
use super::path::{Bounds, number_list, path_bounds};
use super::svg::Element;
use crate::domain::sheet::{AnatomicalSheetDocument, Annotation, Geometry, SheetView};
use crate::json::js_number;
/// The rectangle of user space a view shows.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Frame {
pub min_x: f64,
pub min_y: f64,
pub width: f64,
pub height: f64,
}
/// Rounding slack on the edges, relative to the frame's span: far below a device pixel.
const EDGE_TOLERANCE: f64 = 1e-9;
impl Frame {
fn from_numbers(min_x: f64, min_y: f64, width: f64, height: f64) -> Option<Self> {
let usable = [min_x, min_y, width, height].iter().all(|n| n.is_finite())
&& width > 0.0
&& height > 0.0;
usable.then_some(Self {
min_x,
min_y,
width,
height,
})
}
/// The `viewBox` value the composers write, JavaScript number printing.
pub fn view_box(&self) -> String {
format!(
"{} {} {} {}",
js_number(self.min_x),
js_number(self.min_y),
js_number(self.width),
js_number(self.height)
)
}
fn holds(&self, bounds: &Bounds) -> bool {
let slack =
EDGE_TOLERANCE * (self.width.max(self.height) + self.min_x.abs().max(self.min_y.abs()));
bounds.min_x >= self.min_x - slack
&& bounds.min_y >= self.min_y - slack
&& bounds.max_x <= self.min_x + self.width + slack
&& bounds.max_y <= self.min_y + self.height + slack
}
}
/// The frame of `view` drawn on `drawing` (its sanitised root): the view's `view_box`, else
/// the drawing's `viewBox`; `None` when neither is usable.
pub fn view_frame(view: &SheetView, drawing: &Element) -> Option<Frame> {
match view.view_box() {
Some(b) => Frame::from_numbers(b.min_x, b.min_y, b.width, b.height),
None => drawing_frame(drawing),
}
}
/// The drawing root's `viewBox`, as a browser reads it.
pub fn drawing_frame(root: &Element) -> Option<Frame> {
match number_list(root.attr("viewBox")?)?.as_slice() {
[min_x, min_y, width, height] => Frame::from_numbers(*min_x, *min_y, *width, *height),
_ => None,
}
}
/// Where an annotation's shape lies against its view's frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Placement {
InFrame,
OutOfFrame,
/// Path data a browser would not read whole.
Unreadable,
}
pub fn geometry_bounds(geometry: &Geometry) -> Option<Bounds> {
match geometry {
Geometry::Circle(c) => Some(Bounds {
min_x: c.cx - c.r,
min_y: c.cy - c.r,
max_x: c.cx + c.r,
max_y: c.cy + c.r,
}),
Geometry::Polygon(p) => {
let (first, rest) = p.points.split_first()?;
let mut bounds = Bounds::point(first.0, first.1);
for point in rest {
bounds.add(point.0, point.1);
}
Some(bounds)
}
Geometry::Path(path) => path_bounds(&path.d),
}
}
pub fn placement(geometry: &Geometry, frame: &Frame) -> Placement {
match geometry_bounds(geometry) {
None => Placement::Unreadable,
Some(bounds) if frame.holds(&bounds) => Placement::InFrame,
Some(_) => Placement::OutOfFrame,
}
}
/// What the frame check found on one view.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameFault {
/// The view has no usable frame (no `view_box`, no usable drawing `viewBox`).
NoFrame { view_index: usize },
/// An annotation of the view is not entirely inside it, or cannot be measured.
Annotation {
annotation_index: usize,
placement: Placement,
},
}
/// The frame faults of every view whose drawing `drawing_of` gives (by asset id); a view whose
/// drawing is missing or refused is not measured (its own failure names it).
pub fn frame_faults<'a>(
document: &AnatomicalSheetDocument,
drawing_of: impl Fn(&str) -> Option<&'a Element>,
) -> Vec<FrameFault> {
let mut faults = Vec::new();
for (view_index, view) in document.views.iter().enumerate() {
// A repeated view id draws the first view of that id, as the composers find it.
if !find_view(document, view.id()).is_some_and(|first| std::ptr::eq(first, view)) {
continue;
}
let drawing = super::compose::asset_id_of_view(document, view.id()).and_then(&drawing_of);
let Some(drawing) = drawing else {
continue;
};
let Some(frame) = view_frame(view, drawing) else {
faults.push(FrameFault::NoFrame { view_index });
continue;
};
faults.extend(annotation_faults(document, view.id(), &frame));
}
faults
}
fn annotation_faults(
document: &AnatomicalSheetDocument,
view_id: &str,
frame: &Frame,
) -> Vec<FrameFault> {
document
.annotations
.iter()
.enumerate()
.filter(|(_, a)| a.view_id() == view_id)
.filter_map(|(annotation_index, annotation)| {
let placement = placement(geometry_of(annotation)?, frame);
(placement != Placement::InFrame).then_some(FrameFault::Annotation {
annotation_index,
placement,
})
})
.collect()
}
fn geometry_of(annotation: &Annotation) -> Option<&Geometry> {
match annotation {
Annotation::Observable(a) => a.geometry.as_ref(),
Annotation::DetailTrigger(a) => a.geometry.as_ref(),
}
}
+2
View File
@@ -4,5 +4,7 @@
//! at commit 756b7ef.
pub mod compose;
pub mod frame;
pub mod layer;
pub mod path;
pub mod svg;
+679
View File
@@ -0,0 +1,679 @@
//! Numbers and path data read with the SVG grammar (SVG 1.1 §8.3.9, §7.7), for the frame of a
//! view (`anatomy::frame`, V1-2.2 owner brief 2026-10-30, defect 3): a `viewBox` and the
//! `d` of a path annotation. Strict: anything a browser would stop reading at (a missing
//! number, a bad flag, an unknown command, a trailing comma, a number out of range) answers
//! `None`, never a guess. Curves and arcs are measured on their shape, not on their control
//! points; a moveto counts, as a subpath may start there.
/// The smallest box holding a set of points.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Bounds {
pub min_x: f64,
pub min_y: f64,
pub max_x: f64,
pub max_y: f64,
}
impl Bounds {
pub fn point(x: f64, y: f64) -> Self {
Self {
min_x: x,
min_y: y,
max_x: x,
max_y: y,
}
}
pub fn add(&mut self, x: f64, y: f64) {
self.min_x = self.min_x.min(x);
self.min_y = self.min_y.min(y);
self.max_x = self.max_x.max(x);
self.max_y = self.max_y.max(y);
}
}
/// A list of numbers separated by comma-wsp, surrounding whitespace allowed (`viewBox`).
pub fn number_list(value: &str) -> Option<Vec<f64>> {
let mut cursor = Cursor::new(value);
cursor.skip_space();
let mut numbers = Vec::new();
while !cursor.done() {
if !numbers.is_empty() {
cursor.separator()?;
}
numbers.push(cursor.number()?);
cursor.skip_space();
}
Some(numbers)
}
/// The bounds of every point `d` draws; `None` when a browser would not read all of it.
pub fn path_bounds(d: &str) -> Option<Bounds> {
let mut cursor = Cursor::new(d);
let mut pen = Pen::default();
cursor.skip_space();
if !matches!(cursor.peek(), Some(b'M' | b'm')) {
return None;
}
while let Some(command) = cursor.command() {
cursor.skip_space();
if matches!(command, b'Z' | b'z') {
pen.close();
continue;
}
loop {
pen.segment(command, &mut cursor)?;
if !cursor.more_parameters()? {
break;
}
}
}
if !cursor.done() {
return None;
}
pen.bounds
}
/// A position in the text being read.
struct Cursor<'a> {
bytes: &'a [u8],
at: usize,
}
fn is_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'\x0C')
}
impl<'a> Cursor<'a> {
fn new(text: &'a str) -> Self {
Self {
bytes: text.as_bytes(),
at: 0,
}
}
fn done(&self) -> bool {
self.at >= self.bytes.len()
}
fn peek(&self) -> Option<u8> {
self.bytes.get(self.at).copied()
}
fn skip_space(&mut self) {
while self.peek().is_some_and(is_space) {
self.at += 1;
}
}
/// comma-wsp between two numbers: whitespace, at most one comma, whitespace.
fn separator(&mut self) -> Option<()> {
self.skip_space();
if self.peek() == Some(b',') {
self.at += 1;
self.skip_space();
}
self.starts_number().then_some(())
}
fn starts_number(&self) -> bool {
self.peek()
.is_some_and(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.'))
}
/// After a parameter group: another one follows (`Some(true)`), a command or the end
/// does (`Some(false)`); a comma before anything but a number is an error.
fn more_parameters(&mut self) -> Option<bool> {
self.skip_space();
if self.peek() == Some(b',') {
return self.separator().map(|()| true);
}
Some(self.starts_number())
}
fn command(&mut self) -> Option<u8> {
let byte = self
.peek()
.filter(|b| b"MmZzLlHhVvCcSsQqTtAa".contains(b))?;
self.at += 1;
Some(byte)
}
/// `sign? (digits ('.' digits?)? | '.' digits) (('e'|'E') sign? digits)?`, finite.
fn number(&mut self) -> Option<f64> {
let start = self.at;
if matches!(self.peek(), Some(b'+' | b'-')) {
self.at += 1;
}
let integer = self.digits();
let mut fraction = 0;
if self.peek() == Some(b'.') {
self.at += 1;
fraction = self.digits();
}
if integer == 0 && fraction == 0 {
return None;
}
if matches!(self.peek(), Some(b'e' | b'E')) {
let mark = self.at;
self.at += 1;
if matches!(self.peek(), Some(b'+' | b'-')) {
self.at += 1;
}
if self.digits() == 0 {
self.at = mark;
}
}
let text = std::str::from_utf8(&self.bytes[start..self.at]).ok()?;
text.parse::<f64>().ok().filter(|n| n.is_finite())
}
fn digits(&mut self) -> usize {
let start = self.at;
while self.peek().is_some_and(|b| b.is_ascii_digit()) {
self.at += 1;
}
self.at - start
}
/// An arc flag: one `0` or `1`, which needs no separator after it.
fn flag(&mut self) -> Option<bool> {
let flag = match self.peek()? {
b'0' => false,
b'1' => true,
_ => return None,
};
self.at += 1;
Some(flag)
}
/// `count` numbers separated by comma-wsp.
fn numbers<const N: usize>(&mut self) -> Option<[f64; N]> {
let mut out = [0.0; N];
for (index, slot) in out.iter_mut().enumerate() {
if index > 0 {
self.separator()?;
}
*slot = self.number()?;
}
Some(out)
}
fn arc_parameters(&mut self) -> Option<Arc> {
let [rx, ry, rotation] = self.numbers::<3>()?;
self.separator_before_flag()?;
let large = self.flag()?;
self.separator_before_flag()?;
let sweep = self.flag()?;
self.separator()?;
let [x, y] = self.numbers::<2>()?;
Some(Arc {
rx,
ry,
rotation,
large,
sweep,
to: (x, y),
})
}
fn separator_before_flag(&mut self) -> Option<()> {
self.skip_space();
if self.peek() == Some(b',') {
self.at += 1;
self.skip_space();
}
matches!(self.peek(), Some(b'0' | b'1')).then_some(())
}
}
struct Arc {
rx: f64,
ry: f64,
rotation: f64,
large: bool,
sweep: bool,
to: (f64, f64),
}
/// The current point, the subpath start, the previous control point (for `S` and `T`), and
/// the bounds so far.
#[derive(Default)]
struct Pen {
at: (f64, f64),
start: (f64, f64),
cubic_control: Option<(f64, f64)>,
quadratic_control: Option<(f64, f64)>,
bounds: Option<Bounds>,
}
impl Pen {
fn add(&mut self, (x, y): (f64, f64)) {
match &mut self.bounds {
Some(bounds) => bounds.add(x, y),
None => self.bounds = Some(Bounds::point(x, y)),
}
}
fn close(&mut self) {
self.at = self.start;
self.cubic_control = None;
self.quadratic_control = None;
}
/// One parameter group of `command`; a moveto's later pairs are linetos.
fn segment(&mut self, command: u8, cursor: &mut Cursor<'_>) -> Option<()> {
let relative = command.is_ascii_lowercase();
let origin = if relative { self.at } else { (0.0, 0.0) };
let point = |x: f64, y: f64| (origin.0 + x, origin.1 + y);
let (mut cubic, mut quadratic) = (None, None);
match command.to_ascii_uppercase() {
b'M' => {
let [x, y] = cursor.numbers::<2>()?;
self.at = point(x, y);
self.start = self.at;
self.add(self.at);
self.cubic_control = None;
self.quadratic_control = None;
return self.linetos(relative, cursor);
}
b'L' => {
let [x, y] = cursor.numbers::<2>()?;
self.line(point(x, y));
}
b'H' => {
let [x] = cursor.numbers::<1>()?;
self.line((origin.0 + x, self.at.1));
}
b'V' => {
let [y] = cursor.numbers::<1>()?;
self.line((self.at.0, origin.1 + y));
}
b'C' => {
let [x1, y1, x2, y2, x, y] = cursor.numbers::<6>()?;
cubic = Some(self.cubic(point(x1, y1), point(x2, y2), point(x, y)));
}
b'S' => {
let [x2, y2, x, y] = cursor.numbers::<4>()?;
let first = reflect(self.cubic_control, self.at);
cubic = Some(self.cubic(first, point(x2, y2), point(x, y)));
}
b'Q' => {
let [x1, y1, x, y] = cursor.numbers::<4>()?;
quadratic = Some(self.quadratic(point(x1, y1), point(x, y)));
}
b'T' => {
let [x, y] = cursor.numbers::<2>()?;
let control = reflect(self.quadratic_control, self.at);
quadratic = Some(self.quadratic(control, point(x, y)));
}
_ => {
let mut arc = cursor.arc_parameters()?;
arc.to = point(arc.to.0, arc.to.1);
self.arc(&arc);
}
}
self.cubic_control = cubic;
self.quadratic_control = quadratic;
Some(())
}
/// The pairs after a moveto's first one.
fn linetos(&mut self, relative: bool, cursor: &mut Cursor<'_>) -> Option<()> {
while cursor.more_parameters()? {
let [x, y] = cursor.numbers::<2>()?;
let to = if relative {
(self.at.0 + x, self.at.1 + y)
} else {
(x, y)
};
self.line(to);
}
Some(())
}
fn line(&mut self, to: (f64, f64)) {
self.add(to);
self.at = to;
}
/// Adds the curve's extremes; answers its second control point.
fn cubic(&mut self, c1: (f64, f64), c2: (f64, f64), to: (f64, f64)) -> (f64, f64) {
let from = self.at;
for t in cubic_extremes(from.0, c1.0, c2.0, to.0)
.into_iter()
.chain(cubic_extremes(from.1, c1.1, c2.1, to.1))
.flatten()
{
self.add((
cubic_at(from.0, c1.0, c2.0, to.0, t),
cubic_at(from.1, c1.1, c2.1, to.1, t),
));
}
self.line(to);
c2
}
/// Adds the curve's extremes; answers its control point.
fn quadratic(&mut self, control: (f64, f64), to: (f64, f64)) -> (f64, f64) {
let from = self.at;
for t in [
quadratic_extreme(from.0, control.0, to.0),
quadratic_extreme(from.1, control.1, to.1),
]
.into_iter()
.flatten()
{
self.add((
quadratic_at(from.0, control.0, to.0, t),
quadratic_at(from.1, control.1, to.1, t),
));
}
self.line(to);
control
}
/// SVG 1.1 F.6: an arc to the current point draws nothing, a zero radius draws a line;
/// otherwise the ellipse's extremes inside the sweep count.
fn arc(&mut self, arc: &Arc) {
if arc.to == self.at {
return;
}
if arc.rx == 0.0 || arc.ry == 0.0 {
self.line(arc.to);
return;
}
let ellipse = Ellipse::through(self.at, arc);
for angle in ellipse.extreme_angles() {
if ellipse.sweeps(angle) {
self.add(ellipse.at(angle));
}
}
self.line(arc.to);
}
}
/// The reflection of the previous control point about the current point, or the current point.
fn reflect(control: Option<(f64, f64)>, at: (f64, f64)) -> (f64, f64) {
control.map_or(at, |(x, y)| (2.0 * at.0 - x, 2.0 * at.1 - y))
}
fn cubic_at(p0: f64, p1: f64, p2: f64, p3: f64, t: f64) -> f64 {
let s = 1.0 - t;
s * s * s * p0 + 3.0 * s * s * t * p1 + 3.0 * s * t * t * p2 + t * t * t * p3
}
fn quadratic_at(p0: f64, p1: f64, p2: f64, t: f64) -> f64 {
let s = 1.0 - t;
s * s * p0 + 2.0 * s * t * p1 + t * t * p2
}
fn inside_unit(t: f64) -> Option<f64> {
(t > 0.0 && t < 1.0).then_some(t)
}
/// The parameters in (0, 1) where one coordinate of a cubic stops growing or shrinking.
fn cubic_extremes(p0: f64, p1: f64, p2: f64, p3: f64) -> [Option<f64>; 2] {
let a = -p0 + 3.0 * p1 - 3.0 * p2 + p3;
let b = 2.0 * (p0 - 2.0 * p1 + p2);
let c = p1 - p0;
if a.abs() < 1e-12 {
if b.abs() < 1e-12 {
return [None, None];
}
return [inside_unit(-c / b), None];
}
let discriminant = b * b - 4.0 * a * c;
if discriminant < 0.0 {
return [None, None];
}
let root = discriminant.sqrt();
[
inside_unit((-b + root) / (2.0 * a)),
inside_unit((-b - root) / (2.0 * a)),
]
}
fn quadratic_extreme(p0: f64, p1: f64, p2: f64) -> Option<f64> {
let denominator = p0 - 2.0 * p1 + p2;
if denominator.abs() < 1e-12 {
return None;
}
inside_unit((p0 - p1) / denominator)
}
/// An arc in its centre parameterisation (SVG 1.1 F.6.5, radii scaled up when too small).
struct Ellipse {
centre: (f64, f64),
rx: f64,
ry: f64,
cos: f64,
sin: f64,
start: f64,
sweep: f64,
}
impl Ellipse {
fn through(from: (f64, f64), arc: &Arc) -> Self {
let (sin, cos) = arc.rotation.to_radians().sin_cos();
let (mut rx, mut ry) = (arc.rx.abs(), arc.ry.abs());
let half = ((from.0 - arc.to.0) / 2.0, (from.1 - arc.to.1) / 2.0);
let x1 = cos * half.0 + sin * half.1;
let y1 = -sin * half.0 + cos * half.1;
let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
if lambda > 1.0 {
rx *= lambda.sqrt();
ry *= lambda.sqrt();
}
let numerator = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
let denominator = rx * rx * y1 * y1 + ry * ry * x1 * x1;
let sign = if arc.large == arc.sweep { -1.0 } else { 1.0 };
let factor = sign * (numerator / denominator).max(0.0).sqrt();
let (cx1, cy1) = (factor * rx * y1 / ry, -factor * ry * x1 / rx);
let centre = (
cos * cx1 - sin * cy1 + (from.0 + arc.to.0) / 2.0,
sin * cx1 + cos * cy1 + (from.1 + arc.to.1) / 2.0,
);
let start = ((y1 - cy1) / ry).atan2((x1 - cx1) / rx);
let end = ((-y1 - cy1) / ry).atan2((-x1 - cx1) / rx);
let mut sweep = (end - start).rem_euclid(std::f64::consts::TAU);
if !arc.sweep && sweep > 0.0 {
sweep -= std::f64::consts::TAU;
}
Self {
centre,
rx,
ry,
cos,
sin,
start,
sweep,
}
}
fn at(&self, angle: f64) -> (f64, f64) {
let (s, c) = angle.sin_cos();
(
self.centre.0 + self.rx * self.cos * c - self.ry * self.sin * s,
self.centre.1 + self.rx * self.sin * c + self.ry * self.cos * s,
)
}
/// The four angles where x or y of the whole ellipse is extreme.
fn extreme_angles(&self) -> [f64; 4] {
let x = (-self.ry * self.sin).atan2(self.rx * self.cos);
let y = (self.ry * self.cos).atan2(self.rx * self.sin);
let pi = std::f64::consts::PI;
[x, x + pi, y, y + pi]
}
fn sweeps(&self, angle: f64) -> bool {
let tau = std::f64::consts::TAU;
if self.sweep >= 0.0 {
(angle - self.start).rem_euclid(tau) <= self.sweep
} else {
(self.start - angle).rem_euclid(tau) <= -self.sweep
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
/// A deterministic generator for the sampled comparisons.
struct Lcg(u64);
impl Lcg {
fn next(&mut self, low: f64, high: f64) -> f64 {
self.0 = self
.0
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
low + (high - low) * ((self.0 >> 11) as f64 / (1_u64 << 53) as f64)
}
}
fn sampled(points: impl Iterator<Item = (f64, f64)>) -> Bounds {
let mut bounds: Option<Bounds> = None;
for (x, y) in points {
match &mut bounds {
Some(b) => b.add(x, y),
None => bounds = Some(Bounds::point(x, y)),
}
}
bounds.unwrap()
}
/// The computed box holds every sampled point and is no larger than the samples show.
fn assert_tight(computed: Bounds, samples: Bounds, label: &str) {
let tolerance = 1e-6 * (1.0 + (samples.max_x - samples.min_x).abs());
let pairs = [
(computed.min_x, samples.min_x),
(computed.min_y, samples.min_y),
(-computed.max_x, -samples.max_x),
(-computed.max_y, -samples.max_y),
];
for (outer, inner) in pairs {
assert!(
outer <= inner + 1e-9,
"{label}: {computed:?} misses {samples:?}"
);
assert!(
inner - outer < tolerance * 10.0,
"{label}: {computed:?} vs {samples:?}"
);
}
}
#[test]
fn cubic_bounds_follow_the_curve() {
let mut rng = Lcg(7);
for case in 0..500 {
let p: Vec<f64> = (0..8).map(|_| rng.next(-50.0, 50.0)).collect();
let d = format!(
"M{} {}C{} {} {} {} {} {}",
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]
);
let computed = path_bounds(&d).unwrap();
let samples = sampled((0..=20_000).map(|i| {
let t = f64::from(i) / 20_000.0;
(
cubic_at(p[0], p[2], p[4], p[6], t),
cubic_at(p[1], p[3], p[5], p[7], t),
)
}));
assert_tight(computed, samples, &format!("cubic {case}: {d}"));
}
}
#[test]
fn arc_bounds_follow_the_arc() {
let mut rng = Lcg(11);
for case in 0..500 {
let from = (rng.next(-20.0, 20.0), rng.next(-20.0, 20.0));
let arc = Arc {
rx: rng.next(0.5, 30.0),
ry: rng.next(0.5, 30.0),
rotation: rng.next(-360.0, 360.0),
large: rng.next(0.0, 1.0) < 0.5,
sweep: rng.next(0.0, 1.0) < 0.5,
to: (rng.next(-20.0, 20.0), rng.next(-20.0, 20.0)),
};
let d = format!(
"M{} {}A{} {} {} {} {} {} {}",
from.0,
from.1,
arc.rx,
arc.ry,
arc.rotation,
u8::from(arc.large),
u8::from(arc.sweep),
arc.to.0,
arc.to.1
);
let computed = path_bounds(&d).unwrap();
let ellipse = Ellipse::through(from, &arc);
let end = ellipse.at(ellipse.start + ellipse.sweep);
assert!(
(end.0 - arc.to.0).abs() < 1e-6 && (end.1 - arc.to.1).abs() < 1e-6,
"arc {case}: the parameterisation ends at the endpoint"
);
let samples = sampled(
(0..=20_000)
.map(|i| ellipse.at(ellipse.start + ellipse.sweep * f64::from(i) / 20_000.0)),
);
assert_tight(computed, samples, &format!("arc {case}: {d}"));
}
}
#[test]
fn the_grammar_is_read_as_a_browser_reads_it() {
let read = |d: &str| path_bounds(d).map(|b| (b.min_x, b.min_y, b.max_x, b.max_y));
assert_eq!(read("M1 2L3 4"), Some((1.0, 2.0, 3.0, 4.0)));
assert_eq!(read("m1 2 3 4"), Some((1.0, 2.0, 4.0, 6.0)));
assert_eq!(read("M1,2,3,4"), Some((1.0, 2.0, 3.0, 4.0)));
assert_eq!(read("M.5.5L1-1"), Some((0.5, -1.0, 1.0, 0.5)));
assert_eq!(read("M0 0h5v-2H1V9z"), Some((0.0, -2.0, 5.0, 9.0)));
assert_eq!(read("M0 0a1 1 0 1010 0"), Some((0.0, 0.0, 10.0, 5.0)));
assert_eq!(read("M0 0 1e1 1E-1"), Some((0.0, 0.0, 10.0, 0.1)));
assert_eq!(read(" M0 0 Z m1 1 l1 1 "), Some((0.0, 0.0, 2.0, 2.0)));
for broken in [
"",
"L1 1",
"M",
"M1",
"M1 1L",
"M1 1,",
"M1 1,L2 2",
"M1 1 L 2",
"M1 1X2 2",
"M1e 1",
"M1 1A1 1 0 2 0 3 3",
"M1 1e999 1",
"M1 1 L2 2;",
"M--1 1",
] {
assert_eq!(read(broken), None, "{broken:?}");
}
}
#[test]
fn number_lists_follow_the_svg_grammar() {
assert_eq!(
number_list(" 0,0 10 ,10 "),
Some(vec![0.0, 0.0, 10.0, 10.0])
);
assert_eq!(
number_list("-0 +1e1 .5 5."),
Some(vec![-0.0, 10.0, 0.5, 5.0])
);
for broken in [
"0,,1", "0 1,", ",0", "0x1", "1px", "1e999", "Infinity", "NaN",
] {
assert_eq!(number_list(broken), None, "{broken:?}");
}
assert_eq!(number_list(""), Some(vec![]));
}
}
+5 -2
View File
@@ -21,7 +21,7 @@ use super::fingerprint::document_fingerprint;
use super::index::SheetIndex;
use super::index_data::{names, node_keys, sorted, spine_ids};
use super::loaded::{Drawing, read_drawing};
use super::report::{SheetReport, referenced_asset_ids, sheet_report};
use super::report::{SheetReport, frame_issues, referenced_asset_ids, sheet_report};
use super::review::DigestError;
use super::schema::{AnatomicalSheetDocument, LocalizedText};
use super::verdict::{read_document, sha256_hex};
@@ -270,12 +270,15 @@ impl PreviewSheet {
}
pub fn state(&self) -> Result<PreviewState, DigestError> {
let report = sheet_report(
let mut report = sheet_report(
&self.document,
self.document_bytes,
&self.drawing_sizes(),
None,
)?;
report.issues.extend(frame_issues(&self.document, |id| {
self.drawing(id).and_then(|d| d.as_ref().ok())
}));
Ok(PreviewState {
status: self.status,
fingerprint: self.fingerprint.clone(),
+60
View File
@@ -12,11 +12,19 @@ use super::caps::{CapsReport, caps_report};
use super::review::{Completeness, DigestError, ReviewGroup, completeness, review_groups};
use super::schema::{AnatomicalSheetDocument, Annotation};
use super::validate::{SheetIssue, SheetIssueSeverity, validate_sheet_document};
use crate::anatomy::frame::{FrameFault, Placement, frame_faults};
use crate::anatomy::svg::Element;
/// The submission rule of §6.7 the integrity tier does not hold: a draft may keep an
/// annotation without geometry, a submitted revision may not.
pub const GEOMETRY_MISSING: &str = "annotation.geometry.missing";
/// An annotation not entirely inside the frame of its view, or whose path data a browser would
/// not read whole (V1-2.2 owner brief 2026-10-30, `anatomy::frame`).
pub const OUT_OF_FRAME: &str = "annotation.geometry.out_of_frame";
/// A view drawn on a drawing with neither a `view_box` nor a usable drawing `viewBox`.
pub const NO_FRAME: &str = "view.frame.unknown";
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct SheetReport {
@@ -79,3 +87,55 @@ pub fn referenced_asset_ids(document: &AnatomicalSheetDocument) -> Vec<&str> {
.filter(|id| seen.insert(*id))
.collect()
}
/// The frame issues of `document` on the drawings `drawing_of` gives by asset id (read, with no
/// removal): the same faults for the verdict and the preview. A view whose drawing is not given
/// is not measured.
pub fn frame_issues<'a>(
document: &AnatomicalSheetDocument,
drawing_of: impl Fn(&str) -> Option<&'a Element>,
) -> Vec<SheetIssue> {
frame_faults(document, drawing_of)
.into_iter()
.map(|fault| frame_issue(document, &fault))
.collect()
}
fn frame_issue(document: &AnatomicalSheetDocument, fault: &FrameFault) -> SheetIssue {
let (code, path, message) = match *fault {
FrameFault::NoFrame { view_index } => (
NO_FRAME,
format!("views[{view_index}]"),
format!(
"View \"{}\" has neither a view_box nor a usable drawing viewBox",
document.views[view_index].id()
),
),
FrameFault::Annotation {
annotation_index,
placement,
} => {
let annotation = &document.annotations[annotation_index];
let what = if placement == Placement::Unreadable {
"has path data that cannot be read whole"
} else {
"is not entirely inside the frame"
};
(
OUT_OF_FRAME,
format!("annotations[{annotation_index}].geometry"),
format!(
"Annotation \"{}\" {what} of view \"{}\"",
annotation.id(),
annotation.view_id()
),
)
}
};
SheetIssue {
code: code.to_owned(),
severity: SheetIssueSeverity::Error,
path,
message,
}
}
+54 -16
View File
@@ -20,13 +20,15 @@ use ts_rs::TS;
use super::caps::CapsReport;
use super::fingerprint::{FingerprintError, document_fingerprint};
use super::report::{SheetReport, referenced_asset_ids, sheet_report};
use super::report::{
NO_FRAME, OUT_OF_FRAME, SheetReport, frame_issues, referenced_asset_ids, sheet_report,
};
use super::review::{Completeness, ElementChange, ReviewGroup, change_list};
use super::schema::AnatomicalSheetDocument;
use super::size::document_text_bytes;
use super::validate::{SheetIssue, SheetIssueSeverity};
use crate::anatomy::svg::serialize::stored_form;
use crate::anatomy::svg::{processing_instructions, read_svg};
use crate::anatomy::svg::{Element, processing_instructions, read_svg};
use crate::domain::js::parse_json;
/// The format of the verdict object, bumped with any change of its meaning.
@@ -49,6 +51,9 @@ pub mod codes {
pub const SVG_REJECTED: &str = "verification.integrity.svg_rejected";
pub const SVG_REMOVAL: &str = "verification.integrity.svg_removal";
pub const SVG_NOT_CANONICAL: &str = "verification.integrity.svg_not_canonical";
/// An annotation outside the frame of its view, or a view without a frame (V1-2.2):
/// measured on the views whose drawing reads clean.
pub const OUT_OF_FRAME: &str = "verification.validation.out_of_frame";
pub const FINGERPRINT: &str = "verification.integrity.fingerprint";
}
@@ -173,11 +178,19 @@ fn verify(input: &VerdictInput<'_>, verdict: &mut Verdict) -> Result<(), &'stati
let drawings = check_drawings(&document.typed, &input.drawings);
let sizes: Vec<u64> = drawings.iter().map(|d| d.size).collect();
let base_typed = base.as_ref().map(|b| &b.typed);
let report = sheet_report(&document.typed, document.bytes, &sizes, base_typed)
let mut report = sheet_report(&document.typed, document.bytes, &sizes, base_typed)
.map_err(|_| codes::FINGERPRINT)?;
let roots: HashMap<&str, &Element> = drawings
.iter()
.filter_map(|d| Some((d.check.asset_id.as_str(), d.root.as_ref()?)))
.collect();
report
.issues
.extend(frame_issues(&document.typed, |id| roots.get(id).copied()));
for code in rule_failures(&report)
.into_iter()
.chain(drawing_failures(&drawings))
.chain(frame_failures(&report))
{
fail(verdict, code);
}
@@ -262,7 +275,9 @@ fn rule_failures(report: &SheetReport) -> Vec<&'static str> {
.filter(|i| i.severity == SheetIssueSeverity::Error)
};
let mut out = Vec::new();
if errors().any(|i| i.code != super::report::GEOMETRY_MISSING) {
let rule =
|code: &str| ![super::report::GEOMETRY_MISSING, OUT_OF_FRAME, NO_FRAME].contains(&code);
if errors().any(|i| rule(&i.code)) {
out.push(codes::RULES);
}
if errors().any(|i| i.code == super::report::GEOMETRY_MISSING) {
@@ -274,10 +289,22 @@ fn rule_failures(report: &SheetReport) -> Vec<&'static str> {
out
}
/// The frame code when a frame issue was found (after the drawing faults: a view is measured
/// only on a drawing that reads clean).
fn frame_failures(report: &SheetReport) -> Option<&'static str> {
report
.issues
.iter()
.any(|i| i.code == OUT_OF_FRAME || i.code == NO_FRAME)
.then_some(codes::OUT_OF_FRAME)
}
struct CheckedDrawing {
check: DrawingCheck,
/// The size the caps count: the object's, else the row's.
size: u64,
/// The drawing as read, when it is `Ok` (the frame of its views).
root: Option<Element>,
}
/// Every drawing the views reference, in view order, against its row and its bytes.
@@ -292,12 +319,14 @@ fn check_drawings(
None => CheckedDrawing {
check: drawing_check(asset_id, None, DrawingResult::Missing, None),
size: 0,
root: None,
},
Some(row) => {
let (result, detail) = check_bytes(row);
let (result, detail, root) = check_bytes(row);
CheckedDrawing {
check: drawing_check(asset_id, Some(row), result, detail),
size: row.bytes.map_or(row.byte_size, |b| b.len() as u64),
root,
}
}
})
@@ -319,34 +348,43 @@ fn drawing_check(
}
}
/// Size, then the hash of the bytes against the row (the object key), then the reader.
fn check_bytes(row: &VerdictDrawing<'_>) -> (DrawingResult, Option<String>) {
/// Size, then the hash of the bytes against the row (the object key), then the reader; the
/// root read when the drawing is `Ok`.
fn check_bytes(row: &VerdictDrawing<'_>) -> (DrawingResult, Option<String>, Option<Element>) {
let Some(bytes) = row.bytes else {
return (DrawingResult::Missing, None);
return (DrawingResult::Missing, None, None);
};
if bytes.len() as u64 != row.byte_size {
return (DrawingResult::SizeMismatch, None);
return (DrawingResult::SizeMismatch, None, None);
}
if sha256_hex(bytes) != row.sha256 {
return (DrawingResult::HashMismatch, None);
return (DrawingResult::HashMismatch, None, None);
}
let Ok(text) = std::str::from_utf8(bytes) else {
return (DrawingResult::SvgRejected, Some("malformed".to_owned()));
return (
DrawingResult::SvgRejected,
Some("malformed".to_owned()),
None,
);
};
match read_svg(text) {
Err(rejection) => (
DrawingResult::SvgRejected,
Some(rejection.reason().to_owned()),
None,
),
Ok(read) if !read.removed.is_empty() => (
DrawingResult::SvgRemoval,
Some(read.removed.join(", ")),
None,
),
Ok(read) if !read.removed.is_empty() => {
(DrawingResult::SvgRemoval, Some(read.removed.join(", ")))
}
Ok(_) if !processing_instructions(text).is_empty() => (
DrawingResult::SvgRejected,
Some("processing_instruction".to_owned()),
None,
),
Ok(read) if stored_form(&read.root) != text => (DrawingResult::SvgNotCanonical, None),
Ok(_) => (DrawingResult::Ok, None),
Ok(read) if stored_form(&read.root) != text => (DrawingResult::SvgNotCanonical, None, None),
Ok(read) => (DrawingResult::Ok, None, Some(read.root)),
}
}
+409
View File
@@ -0,0 +1,409 @@
//! V1-2.2 owner brief « arbitrages propriétaire sur les trois MEDIUM » (2026-10-30), defect 3:
//! an annotation outside the visible frame of its view is refused, by the server verdict and by
//! the preview, from one frame definition (`anatomy::frame`): the view's `view_box`, else the
//! `viewBox` of the drawing the view draws, read as a browser reads it. Both composers frame the
//! view on it and drop the drawing's `preserveAspectRatio` (so `xMidYMid meet`): the whole frame
//! is what the canvas and the PDF show. The document is never rewritten.
//!
//! The reported drawing: the equine horse with its root `viewBox` moved by 10 000 and its
//! content moved back by a `translate`, pixel-identical, read clean; its 19 main-view markers
//! were drawn outside the frame.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use common::sheet_readers::{DETAIL_ASSET, MAIN_ASSET, OPEN, document, drawing, svg};
use std::collections::HashSet;
use faunosteo_core::anatomy::compose::{compose_canvas, compose_highlight};
use faunosteo_core::anatomy::svg::clean::clean_svg;
use faunosteo_core::anatomy::svg::read_svg;
use faunosteo_core::domain::sheet::preview::{PreviewInput, PreviewSheet, PreviewStatus};
use faunosteo_core::domain::sheet::verdict::{
DrawingResult, Verdict, VerdictBinding, VerdictDrawing, VerdictInput, codes, compute_verdict,
sha256_hex,
};
use serde_json::{Value, json};
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
const OUT_OF_FRAME: &str = "annotation.geometry.out_of_frame";
const NO_FRAME: &str = "view.frame.unknown";
/// The verdict's closed code (`verdict::codes::OUT_OF_FRAME`), as the SQL stores it.
const FRAME_FAILURE: &str = "verification.validation.out_of_frame";
fn binding() -> VerdictBinding {
VerdictBinding {
sheet_id: "s".to_owned(),
version_id: "v".to_owned(),
revision: 1,
review_id: "r".to_owned(),
}
}
fn verdict(document: &str, drawings: &[(&'static str, &str)]) -> Verdict {
let rows = drawings
.iter()
.map(|(asset_id, text)| VerdictDrawing {
asset_id,
sha256: Box::leak(sha256_hex(text.as_bytes()).into_boxed_str()),
byte_size: text.len() as u64,
bytes: Some(Box::leak(text.as_bytes().to_vec().into_boxed_slice())),
})
.collect();
compute_verdict(&VerdictInput {
binding: binding(),
document,
base_document: None,
drawings: rows,
})
}
/// The frame issues of a draft preview: `(code, path)`.
fn preview_frame_issues(document: &str, drawings: &[(&str, &str)]) -> Vec<(String, String)> {
let input = PreviewInput {
status: PreviewStatus::Draft,
document: document.to_owned(),
fingerprint: None,
};
let given = drawings
.iter()
.map(|(id, text)| drawing(id, text))
.collect();
let state = PreviewSheet::load(input, given).unwrap().state().unwrap();
frame_issues(&state.report.issues)
}
fn frame_issues(issues: &[faunosteo_core::domain::sheet::SheetIssue]) -> Vec<(String, String)> {
issues
.iter()
.filter(|i| i.code == OUT_OF_FRAME || i.code == NO_FRAME)
.map(|i| (i.code.clone(), i.path.clone()))
.collect()
}
/// The verdict and the preview agree; answers the frame issues and whether the verdict failed
/// with the frame code.
fn judged(document: &str, drawings: &[(&'static str, &str)]) -> (Vec<(String, String)>, bool) {
let verdict = verdict(document, drawings);
let from_verdict = frame_issues(&verdict.issues);
assert_eq!(from_verdict, preview_frame_issues(document, drawings));
let failed = verdict.failures.iter().any(|f| f == FRAME_FAILURE);
assert_eq!(failed, !from_verdict.is_empty(), "{:?}", verdict.failures);
(from_verdict, failed)
}
/// The shared two-view sheet with the main view's one annotation replaced.
fn with_geometry(view: &str, geometry: Value) -> String {
let mut doc: Value = serde_json::from_str(&document()).unwrap();
doc["annotations"][0]["geometry"] = geometry;
doc["annotations"][0]["view_id"] = json!(view);
doc.to_string()
}
fn with_view_box(doc: &str, view: usize, view_box: Value) -> String {
let mut doc: Value = serde_json::from_str(doc).unwrap();
doc["views"][view]["view_box"] = view_box;
doc.to_string()
}
fn main_drawing() -> String {
svg("<path d=\"M0 0h10v10z\"/>")
}
fn accepted(doc: &str) -> bool {
let main = main_drawing();
let detail = svg("<path d=\"M0 0h1\"/>");
judged(doc, &[(MAIN_ASSET, &main), (DETAIL_ASSET, &detail)])
.0
.is_empty()
}
fn circle(cx: f64, cy: f64, r: f64) -> Value {
json!({ "type": "circle", "cx": cx, "cy": cy, "r": r })
}
fn path(d: &str) -> Value {
json!({ "type": "path", "d": d })
}
fn polygon(points: Value) -> Value {
json!({ "type": "polygon", "points": points })
}
/// The horse with its frame moved and its content moved back: what a browser draws is the
/// same horse, the annotations (in the root's coordinates) are not on it any more.
fn shifted_horse() -> String {
let horse = common::repo_file(&format!("{SEED}/assets/horse.svg"));
let frame = "viewBox=\"0 0 2073.4 1629.4\">";
assert_eq!(horse.matches(frame).count(), 1);
let text = horse
.replacen(
frame,
"viewBox=\"10000 10000 2073.4 1629.4\"><g transform=\"translate(10000 10000)\">",
1,
)
.replacen("</svg>", "</g></svg>", 1);
clean_svg(text.as_bytes()).stored.unwrap()
}
#[test]
fn the_equine_draft_has_every_annotation_in_frame() {
let text = common::repo_file(&format!("{SEED}/document.json"));
let horse = common::repo_file(&format!("{SEED}/assets/horse.svg"));
let (issues, failed) = judged(&text, &[(HORSE_ID, &horse)]);
assert!(issues.is_empty() && !failed, "{issues:?}");
}
/// The reported defect: refused, the 19 main-view annotations named, the head view (its own
/// `view_box`) untouched, the document text unchanged.
#[test]
fn the_shifted_horse_is_refused_with_its_nineteen_markers() {
let text = common::repo_file(&format!("{SEED}/document.json"));
let before = text.clone();
let shifted = shifted_horse();
let (issues, failed) = judged(&text, &[(HORSE_ID, &shifted)]);
assert!(failed);
assert_eq!(issues.len(), 19, "{issues:?}");
let doc: Value = serde_json::from_str(&text).unwrap();
for (code, path) in &issues {
assert_eq!(code, OUT_OF_FRAME);
let index: usize = path
.strip_prefix("annotations[")
.and_then(|p| p.strip_suffix("].geometry"))
.unwrap()
.parse()
.unwrap();
assert_eq!(
doc["annotations"][index]["view_id"],
json!("main"),
"{path}"
);
}
assert_eq!(text, before, "the document is never rewritten");
let verdict = verdict(&text, &[(HORSE_ID, &shifted)]);
assert_eq!(
verdict.drawings[0].result,
DrawingResult::Ok,
"the drawing reads clean"
);
assert_eq!(
verdict.failures,
[FRAME_FAILURE],
"its own code, never a rules failure"
);
assert_eq!(verdict.failure_code.as_deref(), Some(FRAME_FAILURE));
}
#[test]
fn an_annotation_on_the_frame_edges_is_in_frame() {
assert!(accepted(&with_geometry("main", circle(5.0, 5.0, 5.0))));
assert!(accepted(&with_geometry("main", circle(1.0, 9.0, 1.0))));
assert!(accepted(&with_geometry(
"main",
polygon(json!([[0, 0], [10, 0], [10, 10], [0, 10]]))
)));
assert!(accepted(&with_geometry("main", path("M0 0L10 10H0Z"))));
}
#[test]
fn an_annotation_past_an_edge_is_refused() {
for geometry in [
circle(5.0, 5.0, 5.001),
circle(0.999, 5.0, 1.0),
circle(5.0, 9.5, 0.6),
circle(-3.0, -3.0, 1.0),
circle(50.0, 50.0, 1.0),
polygon(json!([[0, 0], [10.001, 0], [5, 5]])),
polygon(json!([[-1, 5], [5, 5], [5, 6]])),
path("M1 1L5 5L5 10.5"),
path("M5 5h-6"),
] {
assert!(
!accepted(&with_geometry("main", geometry.clone())),
"{geometry}"
);
}
}
/// Curves are measured where they go, not by their control points.
#[test]
fn curves_and_arcs_are_measured_on_their_shape() {
for inside in [
"M1 5C1 -0.5 9 -0.5 9 5",
"M1 5Q5 -4 9 5",
"M2 5A3 3 0 0 1 8 5",
"M2 5A3 3 0 0 0 8 5",
"M1 5a4 4 0 1 1 8 0a4 4 0 1 1 -8 0",
"M1 5S5 0 9 5T5 9",
] {
assert!(accepted(&with_geometry("main", path(inside))), "{inside}");
}
for outside in [
"M1 1C1 -5 9 -5 9 1",
"M1 1Q5 -9 9 1",
"M1 5A6 6 0 1 1 9 5",
"M1 5A6 6 0 1 0 9 5",
"M5 1A4 6 90 0 1 5 9",
] {
assert!(
!accepted(&with_geometry("main", path(outside))),
"{outside}"
);
}
}
/// Coordinates a browser would not read as the whole path are refused, never guessed.
#[test]
fn unreadable_path_data_is_refused() {
for d in [
"M1 1L",
"M1 1 L 2",
"L1 1",
"M1 1 X 2 2",
"M1e 1",
"M1 1A1 1 0 2 0 3 3",
] {
assert!(!accepted(&with_geometry("main", path(d))), "{d}");
}
}
/// A secondary view is checked against its own frame: its `view_box`, else its drawing's.
#[test]
fn a_secondary_view_is_checked_against_its_own_frame() {
let cropped = |geometry| {
with_view_box(
&with_geometry("detail", geometry),
1,
json!({ "min_x": 2, "min_y": 2, "width": 4, "height": 4 }),
)
};
assert!(accepted(&cropped(circle(4.0, 4.0, 2.0))));
assert!(!accepted(&cropped(circle(7.0, 4.0, 0.5))));
// No view_box: the detail drawing's own viewBox (0 0 10 10).
assert!(accepted(&with_geometry("detail", circle(9.0, 9.0, 1.0))));
assert!(!accepted(&with_geometry("detail", circle(9.5, 9.0, 1.0))));
}
/// The main view's `view_box` wins over the drawing's.
#[test]
fn a_view_box_of_the_document_is_the_frame() {
let framed = |geometry| {
with_view_box(
&with_geometry("main", geometry),
0,
json!({ "min_x": 100, "min_y": 100, "width": 10, "height": 10 }),
)
};
assert!(accepted(&framed(circle(105.0, 105.0, 1.0))));
assert!(!accepted(&framed(circle(5.0, 5.0, 1.0))));
}
/// A frame the drawing gives in another spelling is the same frame; a drawing without a
/// usable `viewBox` under a view without `view_box` has no frame: refused, not guessed.
#[test]
fn the_drawing_view_box_is_read_as_a_browser_reads_it() {
let doc = with_geometry("main", circle(5.0, 5.0, 1.0));
let detail = svg("<path d=\"M0 0h1\"/>");
let main_with = |view_box: Option<&str>| {
let open = match view_box {
Some(v) => OPEN.replace("viewBox=\"0 0 10 10\"", &format!("viewBox=\"{v}\"")),
None => OPEN.replace(" viewBox=\"0 0 10 10\"", ""),
};
clean_svg(format!("{open}<path d=\"M0 0h10\"/></svg>").as_bytes())
.stored
.unwrap()
};
for usable in [
"0,0,10,10",
" 0 0 10 10 ",
"0 0 1e1 1e1",
"-0 -0 +10 10.0",
"0, 0 10 ,10",
] {
let main = main_with(Some(usable));
let (issues, _) = judged(&doc, &[(MAIN_ASSET, &main), (DETAIL_ASSET, &detail)]);
assert!(issues.is_empty(), "{usable}: {issues:?}");
}
for unusable in [
None,
Some("0 0 0 10"),
Some("0 0 10 -10"),
Some("0 0 10"),
Some("0 0 10 10 10"),
Some("0x0 0 10 10"),
Some("0 0 10 10px"),
Some("0 0 1e999 10"),
Some(""),
] {
let main = main_with(unusable);
let (issues, failed) = judged(&doc, &[(MAIN_ASSET, &main), (DETAIL_ASSET, &detail)]);
assert!(failed, "{unusable:?}");
assert_eq!(
issues,
[(NO_FRAME.to_owned(), "views[0]".to_owned())],
"{unusable:?}"
);
}
}
/// Transforms inside the drawing move the drawing, never the annotations: a drawing scaled or
/// moved inside an unchanged frame keeps its annotations in frame; a frame moved with its
/// annotations is in frame too.
#[test]
fn legitimate_transforms_are_accepted() {
let detail = svg("<path d=\"M0 0h1\"/>");
let doc = with_geometry("main", circle(5.0, 5.0, 1.0));
let scaled = clean_svg(
svg("<g transform=\"scale(0.5) translate(3 3)\"><path d=\"M0 0h10v10z\"/></g>").as_bytes(),
)
.stored
.unwrap();
assert!(
judged(&doc, &[(MAIN_ASSET, &scaled), (DETAIL_ASSET, &detail)])
.0
.is_empty()
);
let open = OPEN.replace("viewBox=\"0 0 10 10\"", "viewBox=\"100 100 10 10\"");
let moved = clean_svg(format!("{open}<path d=\"M100 100h10\"/></svg>").as_bytes())
.stored
.unwrap();
let moved_doc = with_geometry("main", circle(105.0, 105.0, 1.0));
assert!(
judged(&moved_doc, &[(MAIN_ASSET, &moved), (DETAIL_ASSET, &detail)])
.0
.is_empty()
);
let (issues, failed) = judged(&doc, &[(MAIN_ASSET, &moved), (DETAIL_ASSET, &detail)]);
assert!(failed && issues.len() == 1);
}
/// A drawing missing or refused fails on its own code; its views are not measured.
#[test]
fn a_view_whose_drawing_is_missing_is_not_measured() {
let doc = with_geometry("main", circle(50.0, 50.0, 1.0));
let detail = svg("<path d=\"M0 0h1\"/>");
let verdict = verdict(&doc, &[(DETAIL_ASSET, &detail)]);
assert!(verdict.failures.iter().any(|f| f == codes::DRAWING_MISSING));
assert!(frame_issues(&verdict.issues).is_empty());
}
/// The composers frame each view on the same frame and own its fitting: the drawing's
/// `preserveAspectRatio` (here `slice`, which crops) never reaches the composed root.
#[test]
fn both_composers_frame_the_view_on_the_measured_frame() {
let sheet = common::sheet_readers::sheet();
let ids: HashSet<&str> = ["hock"].into_iter().collect();
let text = OPEN.replace(
"viewBox=\"0 0 10 10\"",
"preserveAspectRatio=\"xMidYMid slice\" viewBox=\"0,0,10,10\"",
) + "<path d=\"M0 0h10\"/></svg>";
let root = read_svg(&text).unwrap().root;
let canvas = compose_canvas(&sheet, "main", &root).unwrap();
let pdf = compose_highlight(&sheet, "main", root, &ids, false).unwrap();
for composed in [&canvas, &pdf] {
assert_eq!(composed.attr("viewBox"), Some("0 0 10 10"));
assert_eq!(composed.attr("preserveAspectRatio"), None);
}
}