Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/tests/eval_visual.rs

31.6 KiB, 3 runs

created by r1870400018:63642, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! U6d: visual elements (shapes, curves, images, transforms, hide, repeat) laid out by `flow::visual`,
2//! checked against the `typst` 0.15 oracle. Each fixture under `tests/fixtures/eval/visual/` is compiled by
3//! `typst` to SVG at test time; the SVG's drawn paths, stroke widths, colours and images are compared, op by
4//! op, with the frame Austenite lays out for the same element, and the page size with the frame's size.
5//! The element is built here through `content::construct`, as the evaluator will build it from the call.
6//! A missing `typst` fails the suite unless `EVAL_ORACLE_SKIP=1` is set.
7
8use oxedyne_fe2o3_austenite::diag::DiagnosticKind;
9use oxedyne_fe2o3_austenite::eval::args::Args;
10use oxedyne_fe2o3_austenite::eval::content::{
11 construct,
12 Content,
13 ElemKind,
14};
15use oxedyne_fe2o3_austenite::eval::eval::{
16 eval_string,
17 EvalMode,
18};
19use oxedyne_fe2o3_austenite::eval::lib::visual;
20use oxedyne_fe2o3_austenite::eval::scope::Scope;
21use oxedyne_fe2o3_austenite::eval::styles::StyleChain;
22use oxedyne_fe2o3_austenite::eval::value::{
23 Alignment,
24 Angle,
25 Color,
26 ColorSpace,
27 Dict,
28 Fraction,
29 HAlign,
30 Length,
31 Paint,
32 Ratio,
33 VAlign,
34 Value,
35};
36use oxedyne_fe2o3_austenite::eval::{
37 Engine,
38 World,
39};
40use oxedyne_fe2o3_austenite::flow::visual::{
41 frame_to_node,
42 layout_frame_with,
43 Frame,
44 Item,
45 Pod,
46};
47use oxedyne_fe2o3_austenite::flow::Region;
48use oxedyne_fe2o3_austenite::ir::{
49 Sp,
50 Transform,
51};
52use oxedyne_fe2o3_austenite::syntax::Span;
53
54use oxedyne_fe2o3_core::prelude::*;
55use oxedyne_fe2o3_graphics::path::{
56 Bounds,
57 Path,
58};
59use oxedyne_fe2o3_graphics::svg_doc::{
60 self,
61 SvgOp,
62};
63use oxedyne_fe2o3_graphics::transform::Transform as GTransform;
64
65use std::path::PathBuf;
66use std::process::Command;
67use std::sync::Arc;
68
69const TOL: f32 = 0.02; // points
70
71// Values
72
73fn pt(x: f64) -> Value { Value::Length(Length::pt(x)) }
74fn pct(x: f64) -> Value { Value::Ratio(Ratio(x / 100.0)) }
75fn deg(x: f64) -> Value { Value::Angle(Angle(x.to_radians())) }
76fn pair(a: Value, b: Value) -> Value { Value::array(vec![a, b]) }
77fn pts(a: f64, b: f64) -> Value { pair(pt(a), pt(b)) }
78fn s(x: &str) -> Value { Value::str(x) }
79fn rgb(r: u8, g: u8, b: u8) -> Value {
80 Value::Color(Color { space: ColorSpace::Rgb, c: [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 0.0], alpha: 1.0 })
81}
82fn dict(kv: Vec<(&str, Value)>) -> Value {
83 let mut d = Dict::new();
84 for (k, v) in kv {
85 d.insert(k, v);
86 }
87 Value::dict(d)
88}
89fn stroke_of(thickness: f64, colour: Value) -> Value { dict(vec![("thickness", pt(thickness)), ("paint", colour)]) }
90fn align(x: Option<HAlign>, y: Option<VAlign>) -> Value { Value::Alignment(Alignment { x, y }) }
91
92fn engine() -> Engine { Engine::new(World::new(PathBuf::from("/"))) }
93
94fn el(e: &mut Engine, kind: ElemKind, pos: Vec<Value>, named: Vec<(&str, Value)>) -> Outcome<Content> {
95 let mut args = Args::new(Span::detached());
96 for v in pos {
97 args.push(Span::detached(), v);
98 }
99 for (k, v) in named {
100 args.push_named(Span::detached(), k, v);
101 }
102 construct(e, kind, &mut args)
103}
104
105fn c(v: Content) -> Value { Value::Content(v) }
106
107// The PNG the image fixtures name, kept beside them so the fixtures stand alone: 20 by 10 pixels,
108// each distinct, so a crop that is off shows.
109fn png_bytes() -> Vec<u8> {
110 let p = fixture_dir().join("px.png");
111 match std::fs::read(&p) {
112 Ok(b) => b,
113 Err(e) => panic!("{}: {}", p.display(), e),
114 }
115}
116
117const SVG_SRC: &str = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"20\" viewBox=\"0 0 40 20\"><rect x=\"0\" y=\"0\" width=\"40\" height=\"20\" fill=\"#0000ff\"/></svg>";
118
119/// The element each fixture draws, built as the evaluator builds it.
120fn build(e: &mut Engine, name: &str) -> Outcome<Content> {
121 use ElemKind as K;
122 let blue = rgb(0, 0, 255);
123 let red = rgb(255, 0, 0);
124 let green = rgb(0, 128, 0);
125 Ok(match name {
126 "rect_default" => res!(el(e, K::Rect, vec![], vec![])),
127 "rect_fill" => res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)), ("fill", blue)])),
128 "rect_fill_stroke" => res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)),
129 ("fill", blue), ("stroke", stroke_of(2.0, red))])),
130 "rect_radius" => res!(el(e, K::Rect, vec![], vec![("width", pt(30.0)), ("height", pt(20.0)), ("radius", pt(5.0))])),
131 "rect_sides" => res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)), ("radius", pt(2.0)),
132 ("stroke", dict(vec![("left", stroke_of(2.0, red)), ("rest", pt(1.0))])), ("fill", blue)])),
133 "rect_corners" => res!(el(e, K::Rect, vec![], vec![("width", pt(40.0)), ("height", pt(24.0)),
134 ("radius", dict(vec![("top-left", pt(8.0)), ("bottom-right", pt(3.0))])),
135 ("stroke", dict(vec![("top", pt(3.0)), ("bottom", stroke_of(1.0, green))]))])),
136 "rect_outset" => res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)),
137 ("outset", dict(vec![("x", pt(3.0)), ("y", pt(1.0))])), ("fill", blue)])),
138 "rect_dashed" => res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)),
139 ("stroke", dict(vec![("thickness", pt(2.0)), ("dash", s("dashed"))]))])),
140 "rect_cap_round" => res!(el(e, K::Rect, vec![], vec![("width", pt(40.0)), ("height", pt(24.0)),
141 ("radius", dict(vec![("top-left", pt(10.0)), ("top-right", pt(10.0))])),
142 ("stroke", dict(vec![("top", dict(vec![("thickness", pt(3.0)), ("cap", s("round"))]))]))])),
143 "rect_cap_square" => res!(el(e, K::Rect, vec![], vec![("width", pt(40.0)), ("height", pt(24.0)), ("radius", pt(10.0)),
144 ("stroke", dict(vec![("top", dict(vec![("thickness", pt(3.0)), ("cap", s("square"))])), ("right", pt(1.0))]))])),
145 "rect_dash_sides" => res!(el(e, K::Rect, vec![], vec![("width", pt(40.0)), ("height", pt(24.0)), ("radius", pt(6.0)),
146 ("stroke", dict(vec![("left", dict(vec![("thickness", pt(2.0)), ("dash", s("dashed"))])), ("rest", pt(1.0))]))])),
147 "rect_rel_radius" => res!(el(e, K::Rect, vec![], vec![("width", pt(30.0)), ("height", pt(20.0)), ("radius", pct(50.0)), ("fill", blue)])),
148 "square_default" => res!(el(e, K::Square, vec![], vec![])),
149 "square_size" => res!(el(e, K::Square, vec![], vec![("size", pt(12.0))])),
150 "square_min" => res!(el(e, K::Square, vec![], vec![("width", pt(10.0)), ("height", pt(20.0))])),
151 "circle_default" => res!(el(e, K::Circle, vec![], vec![])),
152 "circle_radius" => res!(el(e, K::Circle, vec![], vec![("radius", pt(7.0)), ("fill", red), ("stroke", stroke_of(1.0, blue))])),
153 "ellipse_sized" => res!(el(e, K::Ellipse, vec![], vec![("width", pt(40.0)), ("height", pt(10.0))])),
154 "line_default" => res!(el(e, K::Line, vec![], vec![])),
155 "line_end" => res!(el(e, K::Line, vec![], vec![("end", pts(20.0, 10.0))])),
156 "line_angle" => res!(el(e, K::Line, vec![], vec![("start", pts(5.0, 5.0)), ("length", pt(20.0)),
157 ("angle", deg(30.0)), ("stroke", pt(3.0))])),
158 "line_up" => res!(el(e, K::Line, vec![], vec![("end", pts(10.0, -5.0))])),
159 "line_round" => res!(el(e, K::Line, vec![], vec![("length", pt(20.0)),
160 ("stroke", dict(vec![("thickness", pt(4.0)), ("cap", s("round"))]))])),
161 "line_relative" => res!(el(e, K::Line, vec![], vec![("length", pct(50.0)), ("angle", deg(90.0))])),
162 "polygon_tri" => res!(el(e, K::Polygon, vec![pts(0.0, 0.0), pts(20.0, 5.0), pts(5.0, 15.0)],
163 vec![("fill", blue), ("stroke", stroke_of(2.0, red))])),
164 "polygon_regular" | "polygon_em" => {
165 let mut args = Args::new(Span::detached());
166 if name == "polygon_regular" {
167 args.push_named(Span::detached(), "size", pt(20.0));
168 args.push_named(Span::detached(), "vertices", Value::Int(5));
169 args.push_named(Span::detached(), "fill", green);
170 } else {
171 args.push_named(Span::detached(), "vertices", Value::Int(6));
172 }
173 match res!(visual::call(visual::VisualFn::PolygonRegular, e, args)) {
174 Value::Content(c) => c,
175 _ => return Err(err!("polygon.regular did not give content"; Bug)),
176 }
177 },
178 "curve_mixed" => {
179 let m = res!(el(e, K::CurveMove, vec![pts(0.0, 10.0)], vec![]));
180 let l = res!(el(e, K::CurveLine, vec![pts(10.0, 0.0)], vec![]));
181 let q = res!(el(e, K::CurveQuad, vec![Value::Auto, pts(20.0, 10.0)], vec![]));
182 let cu = res!(el(e, K::CurveCubic, vec![Value::None, pts(25.0, 30.0), pts(10.0, 20.0)], vec![]));
183 let cl = res!(el(e, K::CurveClose, vec![], vec![]));
184 res!(el(e, K::Curve, vec![c(m), c(l), c(q), c(cu), c(cl)], vec![("fill", blue)]))
185 },
186 "curve_relative" => {
187 let m = res!(el(e, K::CurveMove, vec![pts(5.0, 5.0)], vec![]));
188 let l = res!(el(e, K::CurveLine, vec![pts(10.0, 0.0)], vec![("relative", Value::Bool(true))]));
189 let q = res!(el(e, K::CurveQuad, vec![pts(5.0, 10.0), pts(0.0, 10.0)], vec![("relative", Value::Bool(true))]));
190 let cl = res!(el(e, K::CurveClose, vec![], vec![("mode", s("straight"))]));
191 res!(el(e, K::Curve, vec![c(m), c(l), c(q), c(cl)], vec![]))
192 },
193 "curve_open" => {
194 let m = res!(el(e, K::CurveMove, vec![pts(0.0, 0.0)], vec![]));
195 let c1 = res!(el(e, K::CurveCubic, vec![pts(10.0, 20.0), pts(20.0, -10.0), pts(30.0, 10.0)], vec![]));
196 let c2 = res!(el(e, K::CurveCubic, vec![Value::Auto, pts(40.0, 0.0), pts(50.0, 5.0)], vec![]));
197 res!(el(e, K::Curve, vec![c(m), c(c1), c(c2)], vec![("stroke", pt(2.0))]))
198 },
199 "rect_body" => {
200 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(10.0)), ("height", pt(10.0)), ("fill", blue)]));
201 res!(el(e, K::Rect, vec![c(inner)], vec![("inset", pt(4.0))]))
202 },
203 "rect_body_sized" => {
204 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(10.0)), ("height", pt(10.0)), ("fill", blue)]));
205 res!(el(e, K::Rect, vec![c(inner)], vec![("width", pt(40.0)),
206 ("inset", dict(vec![("x", pt(2.0)), ("top", pt(6.0))]))]))
207 },
208 "circle_body" => {
209 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(10.0)), ("height", pt(5.0)), ("fill", blue)]));
210 res!(el(e, K::Circle, vec![c(inner)], vec![]))
211 },
212 "square_body" => {
213 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(10.0)), ("height", pt(4.0)), ("fill", blue)]));
214 res!(el(e, K::Square, vec![c(inner)], vec![]))
215 },
216 "ellipse_body" => {
217 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(6.0))]));
218 res!(el(e, K::Ellipse, vec![c(inner)], vec![("inset", pt(0.0))]))
219 },
220 "rotate_plain" | "rotate_reflow" => {
221 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)), ("fill", blue)]));
222 let reflow = name == "rotate_reflow";
223 res!(el(e, K::Rotate, vec![deg(30.0), c(inner)], vec![("reflow", Value::Bool(reflow))]))
224 },
225 "rotate_origin" => {
226 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0))]));
227 res!(el(e, K::Rotate, vec![deg(-45.0), c(inner)], vec![
228 ("origin", align(Some(HAlign::Left), Some(VAlign::Top))), ("reflow", Value::Bool(true))]))
229 },
230 "scale_half" => {
231 let inner = res!(el(e, K::Rect, vec![], vec![]));
232 res!(el(e, K::Scale, vec![pct(50.0), c(inner)], vec![]))
233 },
234 "scale_reflow" => {
235 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)), ("fill", blue)]));
236 res!(el(e, K::Scale, vec![c(inner)], vec![("x", pct(200.0)), ("y", pct(50.0)), ("reflow", Value::Bool(true))]))
237 },
238 "scale_length" => {
239 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0))]));
240 res!(el(e, K::Scale, vec![c(inner)], vec![("x", pt(40.0)), ("y", Value::Auto), ("reflow", Value::Bool(true))]))
241 },
242 "skew_plain" => {
243 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0))]));
244 res!(el(e, K::Skew, vec![c(inner)], vec![("ax", deg(20.0))]))
245 },
246 "skew_reflow" => {
247 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)), ("fill", blue)]));
248 res!(el(e, K::Skew, vec![c(inner)], vec![("ay", deg(10.0)), ("reflow", Value::Bool(true))]))
249 },
250 "move_plain" => {
251 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0))]));
252 res!(el(e, K::Move, vec![c(inner)], vec![("dx", pt(5.0)), ("dy", pt(3.0))]))
253 },
254 "rotate_nested" => {
255 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0))]));
256 let sc = res!(el(e, K::Scale, vec![c(inner)], vec![("x", pct(50.0)), ("y", pct(100.0)), ("reflow", Value::Bool(true))]));
257 res!(el(e, K::Rotate, vec![deg(90.0), c(sc)], vec![("reflow", Value::Bool(true))]))
258 },
259 "hide_rect" => {
260 let inner = res!(el(e, K::Rect, vec![], vec![]));
261 res!(el(e, K::Hide, vec![c(inner)], vec![]))
262 },
263 "repeat_gap" | "repeat_nojustify" => {
264 let inner = res!(el(e, K::Rect, vec![], vec![("width", pt(10.0)), ("height", pt(5.0))]));
265 let mut named = vec![("gap", pt(2.0))];
266 if name == "repeat_nojustify" {
267 named.push(("justify", Value::Bool(false)));
268 }
269 res!(el(e, K::Repeat, vec![c(inner)], named))
270 },
271 "rect_relative" => res!(el(e, K::Rect, vec![], vec![("width", pct(50.0)), ("height", pt(10.0)), ("fill", blue)])),
272 "image_natural" => res!(el(e, K::Image, vec![Value::Bytes(Arc::new(png_bytes()))], vec![])),
273 "image_width" => res!(el(e, K::Image, vec![Value::Bytes(Arc::new(png_bytes()))], vec![("width", pt(30.0))])),
274 "image_cover" => res!(el(e, K::Image, vec![Value::Bytes(Arc::new(png_bytes()))], vec![("width", pt(30.0)), ("height", pt(30.0))])),
275 "image_contain" => res!(el(e, K::Image, vec![Value::Bytes(Arc::new(png_bytes()))], vec![("width", pt(30.0)), ("height", pt(30.0)), ("fit", s("contain"))])),
276 "image_stretch" => res!(el(e, K::Image, vec![Value::Bytes(Arc::new(png_bytes()))], vec![("width", pt(30.0)), ("height", pt(30.0)), ("fit", s("stretch"))])),
277 "image_svg" => res!(el(e, K::Image, vec![Value::Bytes(Arc::new(SVG_SRC.as_bytes().to_vec()))], vec![])),
278 other => return Err(err!("no builder for fixture {}", other; Bug, Missing)),
279 })
280}
281
282// The page width a fixture sets, when not `auto`.
283fn page_width(src: &str) -> Option<f64> {
284 let i = src.find("width: ")?;
285 let rest = &src[i + 7..];
286 let end = rest.find("pt")?;
287 rest[..end].trim().parse::<f64>().ok()
288}
289
290// Lays a body out as the test's flow: a visual element through `layout_frame_with`, recursively; the empty
291// body as an empty frame. Anything else needs U6a/U6b's flow and is not a fixture here.
292fn body_fn(e: &mut Engine, body: &Content, styles: &StyleChain, pod: Pod) -> Outcome<Frame> {
293 if body.is_empty() {
294 return Ok(Frame::new(if pod.expand_x { pod.w } else { 0.0 }, if pod.expand_y { pod.h } else { 0.0 }));
295 }
296 let mut f = res!(layout_frame_with(e, body, styles, pod.region(), &mut body_fn));
297 if pod.expand_x && pod.w.is_finite() {
298 f.width = pod.w;
299 }
300 if pod.expand_y && pod.h.is_finite() {
301 f.height = pod.h;
302 }
303 Ok(f)
304}
305
306// Comparison
307
308#[derive(Clone, Debug)]
309enum Op {
310 Fill { b: Bounds, colour: Option<String> },
311 Stroke { b: Bounds, width: f32, colour: Option<String> },
312 Image { b: Bounds },
313}
314
315fn hex(v: &Paint) -> Option<String> {
316 match v {
317 Paint::Color(c) => {
318 let to = |x: f32| (x * 255.0).round() as u8;
319 match c.space {
320 ColorSpace::Rgb => Some(fmt!("#{:02x}{:02x}{:02x}", to(c.c[0]), to(c.c[1]), to(c.c[2]))),
321 ColorSpace::Luma => Some(fmt!("#{:02x}{:02x}{:02x}", to(c.c[0]), to(c.c[0]), to(c.c[0]))),
322 _ => None,
323 }
324 },
325 _ => None,
326 }
327}
328
329fn gt(t: &Transform) -> GTransform {
330 GTransform { a: t.a as f32, b: t.b as f32, c: t.c as f32, d: t.d as f32, e: t.e as f32, f: t.f as f32 }
331}
332
333// The bounds of what a path draws. Typst's SVG opens every path with `M 0 0` and then a relative move,
334// so a move followed by another move draws nothing and is left out.
335fn bounds(p: &Path) -> Outcome<Bounds> {
336 use oxedyne_fe2o3_graphics::path::Seg;
337 let segs = p.segs();
338 let mut b: Option<Bounds> = None;
339 let mut add = |x: f32, y: f32| {
340 let pb = Bounds::new(x, y, x, y);
341 b = Some(match b {
342 Some(cur) => Bounds::new(cur.x0.min(x), cur.y0.min(y), cur.x1.max(x), cur.y1.max(y)),
343 None => pb,
344 });
345 };
346 for (i, s) in segs.iter().enumerate() {
347 match s {
348 Seg::MoveTo(pt) => {
349 if !matches!(segs.get(i + 1), Some(Seg::MoveTo(_)) | None) {
350 add(pt.x, pt.y);
351 }
352 },
353 Seg::LineTo(pt) => add(pt.x, pt.y),
354 Seg::QuadTo(_, pt) => add(pt.x, pt.y),
355 Seg::CubicTo(_, _, pt) => add(pt.x, pt.y),
356 Seg::Close => (),
357 }
358 }
359 // Curves bulge past their end points; the flattened bounds catch that, begun from the drawn points.
360 if let Some(fb) = p.bounds(&GTransform::IDENTITY) {
361 if let Some(cur) = b {
362 let dangling = segs.first().map(|s| matches!(s, Seg::MoveTo(_))).unwrap_or(false)
363 && matches!(segs.get(1), Some(Seg::MoveTo(_)));
364 if !dangling {
365 b = Some(Bounds::new(cur.x0.min(fb.x0), cur.y0.min(fb.y0), cur.x1.max(fb.x1), cur.y1.max(fb.y1)));
366 } else {
367 let mut rest = oxedyne_fe2o3_graphics::path::PathBuilder::new();
368 for s in &segs[1..] {
369 match *s {
370 Seg::MoveTo(q) => rest.move_to(q),
371 Seg::LineTo(q) => rest.line_to(q),
372 Seg::QuadTo(c, q) => rest.quad_to(c, q),
373 Seg::CubicTo(a, c, q) => rest.cubic_to(a, c, q),
374 Seg::Close => rest.close(),
375 }
376 }
377 if let Ok(rp) = rest.finish() {
378 if let Some(rb) = rp.bounds(&GTransform::IDENTITY) {
379 b = Some(Bounds::new(cur.x0.min(rb.x0), cur.y0.min(rb.y0), cur.x1.max(rb.x1), cur.y1.max(rb.y1)));
380 }
381 }
382 }
383 }
384 }
385 b.ok_or_else(|| err!("empty path"; Bug))
386}
387
388// Every op the frame draws, in page coordinates and paint order.
389fn frame_ops(f: &Frame, t: GTransform, out: &mut Vec<Op>) -> Outcome<()> {
390 for (p, item) in &f.items {
391 let it = GTransform::translate(p.x as f32, p.y as f32).then(&t);
392 match item {
393 Item::Shape(sh) => {
394 if std::env::var("VISUAL_DEBUG").is_ok() {
395 eprintln!("shape {:?}", sh.curve);
396 }
397 let path = res!(res!(sh.curve.to_path(Default::default())).transform(&it));
398 if let Some(fill) = &sh.fill {
399 out.push(Op::Fill { b: res!(bounds(&path)), colour: hex(fill) });
400 }
401 if let Some(st) = &sh.stroke {
402 out.push(Op::Stroke { b: res!(bounds(&path)), width: st.thickness as f32 * it.scale_factor(), colour: hex(&st.paint) });
403 }
404 },
405 Item::Raster { w, h, .. } => {
406 let a = it.apply(oxedyne_fe2o3_graphics::path::Pt::new(0.0, 0.0));
407 let b = it.apply(oxedyne_fe2o3_graphics::path::Pt::new(*w as f32, *h as f32));
408 out.push(Op::Image { b: Bounds::new(a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y)) });
409 },
410 Item::Ops(ops) => for op in ops {
411 match op {
412 oxedyne_fe2o3_austenite::ir::DrawOp::Fill { path, colour } => out.push(Op::Fill {
413 b: res!(bounds(&res!(path.transform(&it)))), colour: Some(colour.to_rgba().to_hex()[..7].to_lowercase()) }),
414 _ => return Err(err!("unexpected op kind in an image"; Bug)),
415 }
416 },
417 Item::Nodes { .. } => return Err(err!("a fixture produced laid-out nodes"; Bug)),
418 Item::Group { frame, transform, .. } => res!(frame_ops(frame, gt(transform).then(&it), out)),
419 }
420 }
421 Ok(())
422}
423
424// The oracle's ops, an image clipped to the page as Typst clips a covering image.
425fn svg_ops(pic: &svg_doc::SvgPicture) -> Outcome<Vec<Op>> {
426 let mut out = Vec::new();
427 for op in &pic.ops {
428 match op {
429 SvgOp::Fill { path, colour } => out.push(Op::Fill { b: res!(bounds(path)), colour: Some(colour.to_hex()[..7].to_lowercase()) }),
430 SvgOp::Stroke { path, colour, stroke } => out.push(Op::Stroke { b: res!(bounds(path)), width: stroke.width, colour: Some(colour.to_hex()[..7].to_lowercase()) }),
431 SvgOp::Image { x, y, w, h, .. } => {
432 let b = Bounds::new(*x, *y, x + w, y + h).intersect(Bounds::new(0.0, 0.0, pic.width, pic.height));
433 out.push(Op::Image { b });
434 },
435 SvgOp::Text { .. } => return Err(err!("the oracle drew text"; Bug)),
436 }
437 }
438 Ok(out)
439}
440
441fn close(a: &Bounds, b: &Bounds) -> bool {
442 (a.x0 - b.x0).abs() <= TOL && (a.y0 - b.y0).abs() <= TOL && (a.x1 - b.x1).abs() <= TOL && (a.y1 - b.y1).abs() <= TOL
443}
444
445fn compare(name: &str, mine: &[Op], oracle: &[Op]) -> Vec<String> {
446 let mut errs = Vec::new();
447 if mine.len() != oracle.len() {
448 errs.push(fmt!("{}: {} ops, oracle {}\n mine {:?}\n oracle {:?}", name, mine.len(), oracle.len(), mine, oracle));
449 return errs;
450 }
451 for (i, (m, o)) in mine.iter().zip(oracle).enumerate() {
452 let ok = match (m, o) {
453 (Op::Fill { b: a, colour: ca }, Op::Fill { b, colour: cb }) =>
454 close(a, b) && (ca.is_none() || cb.is_none() || ca == cb),
455 (Op::Stroke { b: a, width: wa, colour: ca }, Op::Stroke { b, width: wb, colour: cb }) =>
456 close(a, b) && (wa - wb).abs() < 1e-3 && (ca.is_none() || cb.is_none() || ca == cb),
457 (Op::Image { b: a }, Op::Image { b }) => close(a, b),
458 _ => false,
459 };
460 if !ok {
461 errs.push(fmt!("{} op {}: mine {:?}, oracle {:?}", name, i, m, o));
462 }
463 }
464 errs
465}
466
467fn fixture_dir() -> PathBuf {
468 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/eval/visual")
469}
470
471fn work_dir() -> Outcome<PathBuf> {
472 let d = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("eval_visual");
473 res!(std::fs::create_dir_all(&d).map_err(|e| err!(e, "work dir"; IO)));
474 Ok(d)
475}
476
477fn typst_available() -> bool {
478 Command::new("typst").arg("--version").output().map(|o| o.status.success()).unwrap_or(false)
479}
480
481// Compiles a fixture with `typst` and reads its SVG.
482fn oracle(name: &str, src: &str) -> Outcome<svg_doc::SvgPicture> {
483 let dir = res!(work_dir());
484 let typ = dir.join(fmt!("{}.typ", name));
485 let svg = dir.join(fmt!("{}.svg", name));
486 res!(std::fs::write(&typ, src).map_err(|e| err!(e, "write fixture"; IO)));
487 res!(std::fs::copy(fixture_dir().join("px.png"), dir.join("px.png")).map_err(|e| err!(e, "copy png"; IO)));
488 let out = res!(Command::new("typst").arg("compile").arg(&typ).arg(&svg).output()
489 .map_err(|e| err!(e, "run typst"; IO)));
490 if !out.status.success() {
491 return Err(err!("typst failed on {}: {}", name, String::from_utf8_lossy(&out.stderr); Input, Invalid));
492 }
493 let text = res!(std::fs::read_to_string(&svg).map_err(|e| err!(e, "read svg"; IO)));
494 svg_doc::read_document(&text)
495}
496
497#[test]
498fn visual_fixtures_match_the_typst_oracle() -> Outcome<()> {
499 if !typst_available() {
500 if std::env::var("EVAL_ORACLE_SKIP").as_deref() == Ok("1") {
501 return Ok(());
502 }
503 return Err(err!("typst is not on PATH; set EVAL_ORACLE_SKIP=1 to skip the oracle deliberately"; Missing));
504 }
505 let mut names: Vec<String> = Vec::new();
506 for entry in res!(std::fs::read_dir(fixture_dir()).map_err(|e| err!(e, "fixture dir"; IO))) {
507 let p = res!(entry.map_err(|e| err!(e, "fixture entry"; IO))).path();
508 if p.extension().and_then(|x| x.to_str()) == Some("typ") {
509 if let Some(stem) = p.file_stem().and_then(|x| x.to_str()) {
510 names.push(stem.to_string());
511 }
512 }
513 }
514 names.sort();
515 assert!(names.len() >= 50, "expected the whole visual fixture set, found {}", names.len());
516 let mut errs = Vec::new();
517 for name in &names {
518 let src = res!(std::fs::read_to_string(fixture_dir().join(fmt!("{}.typ", name))).map_err(|e| err!(e, "read"; IO)));
519 let pic = res!(oracle(name, &src));
520 let mut e = engine();
521 let elem = res!(build(&mut e, name));
522 let w = match page_width(src.lines().next().unwrap_or("")) {
523 Some(w) => Sp::from_pt(w),
524 None => Sp(i32::MAX),
525 };
526 let region = Region { width: w, height: Sp(i32::MAX), base: (w, Sp(i32::MAX)), expand_x: false, expand_y: false };
527 let frame = match layout_frame_with(&mut e, &elem, &StyleChain::root(), region, &mut body_fn) {
528 Ok(f) => f,
529 Err(err) => {
530 errs.push(fmt!("{}: layout failed: {} {:?}", name, err, e.diags));
531 continue;
532 },
533 };
534 // The page is the frame, except where the fixture fixes the page width; Typst's page is never
535 // less than 1pt in either direction.
536 if (frame.height.max(1.0) as f32 - pic.height).abs() > TOL
537 || (w.0 == i32::MAX && (frame.width as f32 - pic.width).abs() > TOL)
538 {
539 errs.push(fmt!("{}: size {}x{}, oracle {}x{}", name, frame.width, frame.height, pic.width, pic.height));
540 }
541 let mut mine = Vec::new();
542 if let Err(err) = frame_ops(&frame, GTransform::IDENTITY, &mut mine) {
543 errs.push(fmt!("{}: drawing failed: {}", name, err));
544 continue;
545 }
546 // Typst embeds an SVG image as an SVG data URI the reader does not open; its size is the check.
547 let svg_text = res!(std::fs::read_to_string(res!(work_dir()).join(fmt!("{}.svg", name))).map_err(|e| err!(e, "read"; IO)));
548 if svg_text.contains("data:image/svg+xml") {
549 continue;
550 }
551 errs.extend(compare(name, &mine, &res!(svg_ops(&pic))));
552 }
553 assert!(errs.is_empty(), "{} mismatches against typst:\n{}", errs.len(), errs.join("\n"));
554 Ok(())
555}
556
557// Values: the casts that normalise sides, corners, sizes and scale factors, against `typst eval`.
558#[test]
559fn visual_field_casts_match_the_typst_oracle() -> Outcome<()> {
560 if !typst_available() {
561 if std::env::var("EVAL_ORACLE_SKIP").as_deref() == Ok("1") {
562 return Ok(());
563 }
564 return Err(err!("typst is not on PATH; set EVAL_ORACLE_SKIP=1 to skip the oracle deliberately"; Missing));
565 }
566 // Each probe: the Typst expression, and the same element built here.
567 let probe = |expr: &str| -> Outcome<String> {
568 let out = res!(Command::new("typst").arg("eval").arg(expr).output().map_err(|e| err!(e, "run typst"; IO)));
569 if !out.status.success() {
570 return Err(err!("typst eval failed: {}", String::from_utf8_lossy(&out.stderr); Invalid));
571 }
572 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
573 };
574 let mut e = engine();
575 let keys = |v: Option<&Value>| -> String {
576 match v {
577 Some(Value::Dict(d)) => fmt!("[{}]", d.keys().map(|k| fmt!("\"{}\"", k)).collect::<Vec<_>>().join(",")),
578 Some(other) => fmt!("\"{}\"", other.ty().name()),
579 None => "null".to_string(),
580 }
581 };
582 let compact = |s: String| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
583 let mut errs = Vec::new();
584 let cases: Vec<(&str, Content, &str)> = vec![
585 ("rect(stroke: (left: 2pt, x: red)).stroke.keys()",
586 res!(el(&mut e, ElemKind::Rect, vec![], vec![("stroke", dict(vec![("left", pt(2.0)), ("x", rgb(255, 0, 0))]))])), "stroke"),
587 ("rect(radius: (top-left: 2pt, rest: 1pt)).radius.keys()",
588 res!(el(&mut e, ElemKind::Rect, vec![], vec![("radius", dict(vec![("top-left", pt(2.0)), ("rest", pt(1.0))]))])), "radius"),
589 ("rect(radius: (left: 2pt, top: 1pt)).radius.keys()",
590 res!(el(&mut e, ElemKind::Rect, vec![], vec![("radius", dict(vec![("left", pt(2.0)), ("top", pt(1.0))]))])), "radius"),
591 ("rect(inset: (x: 2pt)).inset.keys()",
592 res!(el(&mut e, ElemKind::Rect, vec![], vec![("inset", dict(vec![("x", pt(2.0))]))])), "inset"),
593 ("str(type(rect(inset: (rest: 2pt)).inset))",
594 res!(el(&mut e, ElemKind::Rect, vec![], vec![("inset", dict(vec![("rest", pt(2.0))]))])), "inset"),
595 ("str(type(rect(width: 1pt).width))",
596 res!(el(&mut e, ElemKind::Rect, vec![], vec![("width", pt(1.0))])), "width"),
597 ("str(type(rect(height: 1fr).height))",
598 res!(el(&mut e, ElemKind::Rect, vec![], vec![("height", Value::Fraction(Fraction(1.0)))])), "height"),
599 ("str(type(circle(radius: 2pt).height))",
600 res!(el(&mut e, ElemKind::Circle, vec![], vec![("radius", pt(2.0))])), "height"),
601 ("str(type(scale(50%)[a].y))",
602 res!(el(&mut e, ElemKind::Scale, vec![pct(50.0), Value::Content(Content::text("a"))], vec![])), "y"),
603 ("str(type(line(stroke: 2pt).stroke))",
604 res!(el(&mut e, ElemKind::Line, vec![], vec![("stroke", pt(2.0))])), "stroke"),
605 ];
606 for (expr, content, field) in cases {
607 let want = compact(res!(probe(expr)));
608 // Typst names the relative type "relative length"; U0's `Type::name` says "relative".
609 let got = match expr.starts_with("str(type(") {
610 true => fmt!("\"{}\"", content.field(field).map(|v| match v.ty() {
611 oxedyne_fe2o3_austenite::eval::value::Type::Relative => "relativelength",
612 t => t.name(),
613 }).unwrap_or("none")),
614 false => keys(content.field(field)),
615 };
616 if want != got {
617 errs.push(fmt!("{}: typst {}, austenite {}", expr, want, got));
618 }
619 }
620 // The sides of `(left: 2pt, x: red)`: left keeps its own 2pt, right takes x's red.
621 let r = res!(el(&mut e, ElemKind::Rect, vec![], vec![("stroke", dict(vec![("left", pt(2.0)), ("x", rgb(255, 0, 0))]))]));
622 if let Some(v) = r.field("stroke") {
623 let sides = visual::sides_of(v);
624 let left_ok = matches!(&sides[0], Some(Value::Stroke(s)) if s.thickness == Some(Length::pt(2.0)) && s.paint.is_none());
625 let right_ok = matches!(&sides[2], Some(Value::Stroke(s)) if s.thickness.is_none() && s.paint.is_some());
626 if !left_ok || !right_ok {
627 errs.push(fmt!("stroke sides of (left: 2pt, x: red) are wrong: {:?}", sides));
628 }
629 }
630 assert!(errs.is_empty(), "{}", errs.join("\n"));
631 Ok(())
632}
633
634// `path` is the file-path type in Typst 0.15; the old drawing element is refused, as Typst refuses it.
635#[test]
636fn path_element_is_refused_as_in_typst() -> Outcome<()> {
637 let mut e = engine();
638 let r = el(&mut e, ElemKind::Path, vec![pts(0.0, 0.0), pts(1.0, 1.0)], vec![]);
639 assert!(r.is_err(), "the removed path element was constructed");
640 Ok(())
641}
642
643// Lowering to IR: a hidden shape is an ink-less graphic leaf of the shape's size (45pt by 30pt, as the
644// oracle fixture `hide_rect` measures), its baseline at the bottom; laid-out content is overlaid in a
645// vertical box of the frame's size.
646#[test]
647fn frames_lower_to_one_box_of_the_frame_size() -> Outcome<()> {
648 use oxedyne_fe2o3_austenite::flow::visual::{
649 layout_visual,
650 P2,
651 };
652 use oxedyne_fe2o3_austenite::ir::{
653 Dims,
654 LeafKind,
655 Node,
656 };
657 let mut e = engine();
658 let r = res!(el(&mut e, ElemKind::Rect, vec![], vec![]));
659 let h = res!(el(&mut e, ElemKind::Hide, vec![c(r)], vec![]));
660 let region = Region { width: Sp(i32::MAX), height: Sp(i32::MAX), base: (Sp(i32::MAX), Sp(i32::MAX)), expand_x: false, expand_y: false };
661 // `hide` shows as its body under the `hidden` style, and flow draws nothing under it.
662 let shown = match res!(visual::show(&mut e, &h, &StyleChain::root())) {
663 Some(s) => s,
664 None => return Err(err!("hide has no show"; Bug)),
665 };
666 let (inner, styles) = match &shown {
667 Content::Styled(st) => (st.child.clone(), StyleChain::root().chain(&st.styles)),
668 _ => return Err(err!("hide did not style its body"; Bug)),
669 };
670 assert!(res!(visual::is_hidden(&styles)));
671 let node = res!(layout_visual(&mut e, &inner, &styles, region));
672 match node {
673 Node::Leaf(l) => {
674 assert_eq!(l.dims, Dims::new(Sp::from_pt(45.0), Sp::from_pt(30.0), Sp::ZERO));
675 match l.kind {
676 LeafKind::Graphic(g) => assert!(g.ops.is_empty(), "a hidden rect drew ink"),
677 _ => panic!("not a graphic"),
678 }
679 },
680 other => panic!("expected a leaf, got {:?}", other),
681 }
682 // Laid-out content keeps its nodes, placed at their offset inside a box of the frame's size.
683 let mut f = Frame::new(20.0, 10.0);
684 f.push(P2::new(3.0, 2.0), Item::Nodes { nodes: vec![], dims: Dims::new(Sp::from_pt(5.0), Sp::from_pt(4.0), Sp::ZERO) });
685 match res!(frame_to_node(&mut e, &f, Span::detached())) {
686 Node::VBox(b) => assert_eq!(b.dims, Dims::new(Sp::from_pt(20.0), Sp::from_pt(10.0), Sp::ZERO)),
687 other => panic!("expected a vertical box, got {:?}", other),
688 }
689 Ok(())
690}
691
692// The drawing layer carries flat colours only, so a gradient fill is drawn in one colour and a tiling not
693// at all. Each says so with a warning of kind `unsupported`, the kind a strict compile refuses: the
694// document was not set as written.
695#[test]
696fn a_paint_the_drawing_layer_cannot_draw_warns_as_unsupported() -> Outcome<()> {
697 let mut e = engine();
698 let region = Region { width: Sp(i32::MAX), height: Sp(i32::MAX), base: (Sp(i32::MAX), Sp(i32::MAX)), expand_x: false, expand_y: false };
699 let mut raised = 0;
700 for paint in ["gradient.linear(red, blue)", "tiling(size: (4pt, 4pt))[x]"] {
701 let fill = res!(eval_string(&mut e, paint, EvalMode::Code, Scope::new(), Span::detached()));
702 let rect = res!(el(&mut e, ElemKind::Rect, vec![], vec![("width", pt(20.0)), ("height", pt(10.0)), ("fill", fill)]));
703 let before = e.diags.len();
704 let frame = res!(layout_frame_with(&mut e, &rect, &StyleChain::root(), region, &mut body_fn));
705 // The paint is turned into ink only when the frame lowers to a node, so the warning is raised there.
706 res!(frame_to_node(&mut e, &frame, Span::detached()));
707 let warned: Vec<_> = e.diags[before..].iter().filter(|d| !d.is_error()).collect();
708 assert!(!warned.is_empty(), "{} fill drew without a warning", paint);
709 for d in &warned {
710 assert_eq!(d.kind, DiagnosticKind::Unsupported, "{}: {}", paint, d.message);
711 assert!(d.kind.refuses_strict(), "{}: a strict compile must refuse it", paint);
712 }
713 raised += warned.len();
714 }
715 assert!(raised >= 2, "only {} warning(s) for the two paints", raised);
716 Ok(())
717}