oxedyne/fe2o3/fe2o3_austenite/tests/eval_grid.rs
29.1 KiB, 1 run
created by r1870400018:63586, 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 | //! U6c: grid and table layout against the `typst` oracle. Each case is written once, as data, and rendered |
| 2 | //! both as Typst source (for the installed `typst` 0.15.1) and as the evaluator's own argument values, so |
| 3 | //! the two engines lay out the same grid. Every cell holds a fixed-size block carrying a `metadata` marker; |
| 4 | //! Typst's positions for the markers, and the fills and lines in its SVG, are the expected values. |
| 5 | //! |
| 6 | //! The block flow is not this unit's, so cells are measured and set by a stand-in that reads the size from |
| 7 | //! the cell body and adds the resolved inset, which is exactly what Typst's padded fixed-size block does. |
| 8 | //! Everything under test -- placement, track sizing, groups, fills, lines -- is the grid's own. |
| 9 | //! |
| 10 | //! The rendered sources are kept under `tests/fixtures/eval/grid/`; a case whose source drifts from its |
| 11 | //! fixture fails, and `GRID_FIXTURES_WRITE=1` rewrites them. |
| 12 | |
| 13 | use oxedyne_fe2o3_austenite::eval::args::Args; |
| 14 | use oxedyne_fe2o3_austenite::eval::content::{ |
| 15 | construct, |
| 16 | Content, |
| 17 | ElemKind, |
| 18 | }; |
| 19 | use oxedyne_fe2o3_austenite::eval::lib::grid::fid; |
| 20 | use oxedyne_fe2o3_austenite::eval::styles::StyleChain; |
| 21 | use oxedyne_fe2o3_austenite::eval::value::{ |
| 22 | Alignment, |
| 23 | Color, |
| 24 | ColorSpace, |
| 25 | Dict, |
| 26 | Fraction, |
| 27 | HAlign, |
| 28 | Length, |
| 29 | Paint, |
| 30 | Ratio, |
| 31 | Stroke, |
| 32 | VAlign, |
| 33 | Value, |
| 34 | }; |
| 35 | use oxedyne_fe2o3_austenite::eval::{ |
| 36 | Engine, |
| 37 | World, |
| 38 | }; |
| 39 | use oxedyne_fe2o3_austenite::flow::grid::{ |
| 40 | plan, |
| 41 | resolve, |
| 42 | CellLayout, |
| 43 | GridPlan, |
| 44 | Part, |
| 45 | }; |
| 46 | use oxedyne_fe2o3_austenite::flow::Region; |
| 47 | use oxedyne_fe2o3_austenite::ir::{ |
| 48 | Dims, |
| 49 | Node, |
| 50 | Sp, |
| 51 | }; |
| 52 | use oxedyne_fe2o3_austenite::syntax::Span; |
| 53 | |
| 54 | use oxedyne_fe2o3_core::prelude::*; |
| 55 | |
| 56 | use std::path::PathBuf; |
| 57 | use std::process::Command; |
| 58 | use std::sync::Arc; |
| 59 | |
| 60 | // Case vocabulary |
| 61 | |
| 62 | #[derive(Clone, Debug)] |
| 63 | enum V { |
| 64 | Auto, |
| 65 | Nil, |
| 66 | Pt(f64), |
| 67 | Fr(f64), |
| 68 | Pct(f64), |
| 69 | Int(i64), |
| 70 | Bool(bool), |
| 71 | Col(&'static str), |
| 72 | Stroke(f64, &'static str), |
| 73 | Arr(Vec<V>), |
| 74 | Dict(Vec<(&'static str, V)>), |
| 75 | Align(&'static str), |
| 76 | } |
| 77 | |
| 78 | type Named = Vec<(&'static str, V)>; |
| 79 | |
| 80 | #[derive(Clone, Debug)] |
| 81 | enum Ch { |
| 82 | C(u32, f64, f64), // a plain child: id, width, height |
| 83 | Cell(u32, f64, f64, Named), // an explicit cell |
| 84 | HLine(Named), |
| 85 | VLine(Named), |
| 86 | Head(Named, Vec<Ch>), |
| 87 | Foot(Named, Vec<Ch>), |
| 88 | } |
| 89 | |
| 90 | struct Case { |
| 91 | name: &'static str, |
| 92 | table: bool, |
| 93 | args: Named, |
| 94 | children: Vec<Ch>, |
| 95 | } |
| 96 | |
| 97 | fn hex(name: &str) -> &'static str { |
| 98 | match name { |
| 99 | "red" => "#ff4136", |
| 100 | "blue" => "#0074d9", |
| 101 | "green" => "#2ecc40", |
| 102 | "yellow" => "#ffdc00", |
| 103 | "aqua" => "#7fdbff", |
| 104 | "olive" => "#3d9970", |
| 105 | _ => "#000000", |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn colour(name: &str) -> Color { |
| 110 | if name == "black" { |
| 111 | return Color { space: ColorSpace::Luma, c: [0.0; 4], alpha: 1.0 }; |
| 112 | } |
| 113 | let h = hex(name); |
| 114 | let byte = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).unwrap_or(0) as f32 / 255.0; |
| 115 | Color { space: ColorSpace::Rgb, c: [byte(1), byte(3), byte(5), 0.0], alpha: 1.0 } |
| 116 | } |
| 117 | |
| 118 | fn colour_hex(c: &Color) -> String { |
| 119 | let b = |v: f32| (v * 255.0).round() as u8; |
| 120 | match c.space { |
| 121 | ColorSpace::Luma => format!("#{:02x}{:02x}{:02x}", b(c.c[0]), b(c.c[0]), b(c.c[0])), |
| 122 | _ => format!("#{:02x}{:02x}{:02x}", b(c.c[0]), b(c.c[1]), b(c.c[2])), |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | impl V { |
| 127 | fn typst(&self) -> String { |
| 128 | match self { |
| 129 | V::Auto => "auto".into(), |
| 130 | V::Nil => "none".into(), |
| 131 | V::Pt(p) => format!("{}pt", p), |
| 132 | V::Fr(f) => format!("{}fr", f), |
| 133 | V::Pct(p) => format!("{}%", p), |
| 134 | V::Int(i) => format!("{}", i), |
| 135 | V::Bool(b) => format!("{}", b), |
| 136 | V::Col(c) => c.to_string(), |
| 137 | V::Align(a) => a.to_string(), |
| 138 | V::Stroke(t, c) => format!("{}pt + {}", t, c), |
| 139 | V::Arr(a) => format!("({},)", a.iter().map(|v| v.typst()).collect::<Vec<_>>().join(", ")), |
| 140 | V::Dict(d) => format!("({})", d.iter().map(|(k, v)| format!("{}: {}", k, v.typst())) |
| 141 | .collect::<Vec<_>>().join(", ")), |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn value(&self) -> Value { |
| 146 | match self { |
| 147 | V::Auto => Value::Auto, |
| 148 | V::Nil => Value::None, |
| 149 | V::Pt(p) => Value::Length(Length::pt(*p)), |
| 150 | V::Fr(f) => Value::Fraction(Fraction(*f)), |
| 151 | V::Pct(p) => Value::Ratio(Ratio(p / 100.0)), |
| 152 | V::Int(i) => Value::Int(*i), |
| 153 | V::Bool(b) => Value::Bool(*b), |
| 154 | V::Col(c) => Value::Color(colour(c)), |
| 155 | V::Align(a) => Value::Alignment(match *a { |
| 156 | "end" => Alignment { x: Some(HAlign::End), y: None }, |
| 157 | "bottom" => Alignment { x: None, y: Some(VAlign::Bottom) }, |
| 158 | _ => Alignment::default(), |
| 159 | }), |
| 160 | V::Stroke(t, c) => Value::Stroke(Arc::new(Stroke { |
| 161 | paint: Some(Paint::Color(colour(c))), |
| 162 | thickness: Some(Length::pt(*t)), |
| 163 | ..Stroke::default() |
| 164 | })), |
| 165 | V::Arr(a) => Value::array(a.iter().map(|v| v.value()).collect()), |
| 166 | V::Dict(d) => { |
| 167 | let mut out = Dict::new(); |
| 168 | for (k, v) in d { |
| 169 | out.insert(k, v.value()); |
| 170 | } |
| 171 | Value::dict(out) |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn named_typst(n: &Named) -> String { |
| 178 | n.iter().map(|(k, v)| format!("{}: {}, ", k, v.typst())).collect() |
| 179 | } |
| 180 | |
| 181 | impl Ch { |
| 182 | fn typst(&self, pre: &str) -> String { |
| 183 | match self { |
| 184 | Ch::C(id, w, h) => format!("c({}, {}, {})", id, w, h), |
| 185 | Ch::Cell(id, w, h, n) => format!("{}.cell({}c({}, {}, {}))", pre, named_typst(n), id, w, h), |
| 186 | Ch::HLine(n) => format!("{}.hline({})", pre, named_typst(n)), |
| 187 | Ch::VLine(n) => format!("{}.vline({})", pre, named_typst(n)), |
| 188 | Ch::Head(n, cs) => format!("{}.header({}{})", pre, named_typst(n), |
| 189 | cs.iter().map(|c| c.typst(pre)).collect::<Vec<_>>().join(", ")), |
| 190 | Ch::Foot(n, cs) => format!("{}.footer({}{})", pre, named_typst(n), |
| 191 | cs.iter().map(|c| c.typst(pre)).collect::<Vec<_>>().join(", ")), |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | fn value(&self, engine: &mut Engine, table: bool) -> Outcome<Value> { |
| 196 | let k = |g: ElemKind, t: ElemKind| if table { t } else { g }; |
| 197 | let body = |id: &u32, w: &f64, h: &f64| Value::Content(Content::text(&format!("{}:{}:{}", id, w, h))); |
| 198 | let build = |engine: &mut Engine, kind: ElemKind, pos: Vec<Value>, n: &Named| -> Outcome<Value> { |
| 199 | let mut args = Args::new(Span::detached()); |
| 200 | for v in pos { |
| 201 | args.push(Span::detached(), v); |
| 202 | } |
| 203 | for (name, v) in n { |
| 204 | args.push_named(Span::detached(), *name, v.value()); |
| 205 | } |
| 206 | Ok(Value::Content(res!(construct(engine, kind, &mut args)))) |
| 207 | }; |
| 208 | match self { |
| 209 | Ch::C(id, w, h) => Ok(body(id, w, h)), |
| 210 | Ch::Cell(id, w, h, n) => build(engine, k(ElemKind::GridCell, ElemKind::TableCell), vec![body(id, w, h)], n), |
| 211 | Ch::HLine(n) => build(engine, k(ElemKind::GridHLine, ElemKind::TableHLine), vec![], n), |
| 212 | Ch::VLine(n) => build(engine, k(ElemKind::GridVLine, ElemKind::TableVLine), vec![], n), |
| 213 | Ch::Head(n, cs) | Ch::Foot(n, cs) => { |
| 214 | let mut pos = Vec::new(); |
| 215 | for c in cs { |
| 216 | pos.push(res!(c.value(engine, table))); |
| 217 | } |
| 218 | let kind = match self { |
| 219 | Ch::Head(..) => k(ElemKind::GridHeader, ElemKind::TableHeader), |
| 220 | _ => k(ElemKind::GridFooter, ElemKind::TableFooter), |
| 221 | }; |
| 222 | build(engine, kind, pos, n) |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | impl Case { |
| 229 | fn typst(&self) -> String { |
| 230 | let pre = if self.table { "table" } else { "grid" }; |
| 231 | format!( |
| 232 | "#set page(width: 200pt, height: 400pt, margin: 0pt, fill: none)\n\ |
| 233 | #let c(id, w, h) = block(width: w * 1pt, height: h * 1pt)[#metadata(id)<m>]\n\ |
| 234 | #{}({}{})\n", |
| 235 | pre, named_typst(&self.args), |
| 236 | self.children.iter().map(|c| c.typst(pre)).collect::<Vec<_>>().join(", ")) |
| 237 | } |
| 238 | |
| 239 | fn element(&self, engine: &mut Engine) -> Outcome<Content> { |
| 240 | let mut args = Args::new(Span::detached()); |
| 241 | for (name, v) in &self.args { |
| 242 | args.push_named(Span::detached(), *name, v.value()); |
| 243 | } |
| 244 | for c in &self.children { |
| 245 | let v = res!(c.value(engine, self.table)); |
| 246 | args.push(Span::detached(), v); |
| 247 | } |
| 248 | let kind = if self.table { ElemKind::Table } else { ElemKind::Grid }; |
| 249 | construct(engine, kind, &mut args) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // The stand-in cell layout |
| 254 | |
| 255 | /// Reads `id:w:h` from the cell body and pads it by the resolved inset, as Typst's padded block measures. |
| 256 | struct Blocks; |
| 257 | |
| 258 | fn inset_pt(cell: &Content, side: &str) -> f64 { |
| 259 | match cell.get(fid::CELL_INSET) { |
| 260 | Some(Value::Dict(d)) => match d.get(side) { |
| 261 | Some(Value::Length(l)) => l.abs, |
| 262 | Some(Value::Relative(r)) => r.abs.abs, |
| 263 | _ => 0.0, |
| 264 | }, |
| 265 | _ => 0.0, |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | fn body_of(cell: &Content) -> (u32, f64, f64) { |
| 270 | let text = match cell.get(fid::BODY) { |
| 271 | Some(Value::Content(c)) => c.plain_text(), |
| 272 | _ => String::new(), |
| 273 | }; |
| 274 | let parts: Vec<&str> = text.split(':').collect(); |
| 275 | let num = |i: usize| parts.get(i).and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0); |
| 276 | (num(0) as u32, num(1), num(2)) |
| 277 | } |
| 278 | |
| 279 | impl CellLayout for Blocks { |
| 280 | fn measure(&mut self, _: &mut Engine, cell: &Content, _: &StyleChain, _: Region) -> Outcome<Dims> { |
| 281 | let (_, w, h) = body_of(cell); |
| 282 | Ok(Dims::new( |
| 283 | Sp::from_pt(w + inset_pt(cell, "left") + inset_pt(cell, "right")), |
| 284 | Sp::from_pt(h + inset_pt(cell, "top") + inset_pt(cell, "bottom")), |
| 285 | Sp::ZERO)) |
| 286 | } |
| 287 | |
| 288 | fn layout(&mut self, _: &mut Engine, _: &Content, _: &StyleChain, _: Region) -> Outcome<Vec<Node>> { |
| 289 | Ok(Vec::new()) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | // The oracle |
| 294 | |
| 295 | fn fixtures() -> PathBuf { |
| 296 | PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/eval/grid") |
| 297 | } |
| 298 | |
| 299 | fn scratch() -> PathBuf { |
| 300 | PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("eval_grid") |
| 301 | } |
| 302 | |
| 303 | /// Writes or checks the case's fixture, then runs `typst` over it. A case Typst must reject is marked |
| 304 | /// so for the structure oracle's corpus. |
| 305 | fn oracle_source(case: &Case, rejects: bool) -> Outcome<PathBuf> { |
| 306 | let src = if rejects { format!("// oracle: rejects\n{}", case.typst()) } else { case.typst() }; |
| 307 | let dir = fixtures(); |
| 308 | let path = dir.join(format!("{}.typ", case.name)); |
| 309 | if std::env::var("GRID_FIXTURES_WRITE").is_ok() { |
| 310 | res!(std::fs::create_dir_all(&dir).map_err(|e| err!("{}", e; IO))); |
| 311 | res!(std::fs::write(&path, &src).map_err(|e| err!("{}", e; IO))); |
| 312 | } |
| 313 | let kept = res!(std::fs::read_to_string(&path).map_err(|e| err!( |
| 314 | "fixture {} unreadable ({}); run with GRID_FIXTURES_WRITE=1", path.display(), e; IO))); |
| 315 | if kept != src { |
| 316 | return Err(err!("fixture {} is stale; run with GRID_FIXTURES_WRITE=1", path.display(); Invalid)); |
| 317 | } |
| 318 | Ok(path) |
| 319 | } |
| 320 | |
| 321 | fn typst(args: &[&str]) -> Outcome<(bool, String, String)> { |
| 322 | let out = res!(Command::new("typst").args(args).output().map_err(|e| err!( |
| 323 | "the typst oracle could not run: {}", e; IO))); |
| 324 | Ok((out.status.success(), String::from_utf8_lossy(&out.stdout).into_owned(), |
| 325 | String::from_utf8_lossy(&out.stderr).into_owned())) |
| 326 | } |
| 327 | |
| 328 | /// `[[id, x, y, page], ...]` from `typst eval`, as numbers. |
| 329 | fn numbers(s: &str) -> Vec<Vec<f64>> { |
| 330 | s.trim().trim_start_matches('[').trim_end_matches(']').split("],[") |
| 331 | .filter(|r| !r.trim().is_empty()) |
| 332 | .map(|r| r.trim_matches(|c| c == '[' || c == ']').split(',') |
| 333 | .filter_map(|n| n.trim().parse::<f64>().ok()).collect()) |
| 334 | .collect() |
| 335 | } |
| 336 | |
| 337 | struct Drawn { |
| 338 | fills: Vec<(String, f64, f64, f64, f64)>, // colour, x, y, w, h |
| 339 | lines: Vec<(bool, String, f64, f64, f64, f64)>, // vertical, colour, width, at, from, to |
| 340 | } |
| 341 | |
| 342 | fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> { |
| 343 | let key = format!(" {}=\"", name); |
| 344 | let i = tag.find(&key)? + key.len(); |
| 345 | let j = tag[i..].find('"')? + i; |
| 346 | Some(&tag[i..j]) |
| 347 | } |
| 348 | |
| 349 | /// The fills and lines of Typst's SVG: every path is `translate(x y)` then `M 0 0` and axis moves. |
| 350 | fn svg_drawn(svg: &str) -> Drawn { |
| 351 | let mut d = Drawn { fills: Vec::new(), lines: Vec::new() }; |
| 352 | for tag in svg.split('<').filter(|t| t.starts_with("path ")) { |
| 353 | let (tx, ty) = match attr(tag, "transform") { |
| 354 | Some(t) => { |
| 355 | let n: Vec<f64> = t.trim_start_matches("translate(").trim_end_matches(')') |
| 356 | .split(' ').filter_map(|v| v.parse().ok()).collect(); |
| 357 | (n.first().copied().unwrap_or(0.0), n.get(1).copied().unwrap_or(0.0)) |
| 358 | } |
| 359 | None => (0.0, 0.0), |
| 360 | }; |
| 361 | let path = attr(tag, "d").unwrap_or(""); |
| 362 | let steps: Vec<(char, f64)> = { |
| 363 | let mut out = Vec::new(); |
| 364 | let body = path.trim_start_matches("M 0 0"); |
| 365 | let mut cur: Option<char> = None; |
| 366 | let mut num = String::new(); |
| 367 | for ch in body.chars() { |
| 368 | if ch == 'v' || ch == 'h' || ch == 'Z' { |
| 369 | if let (Some(c), Ok(n)) = (cur, num.trim().parse::<f64>()) { |
| 370 | out.push((c, n)); |
| 371 | } |
| 372 | num.clear(); |
| 373 | cur = if ch == 'Z' { None } else { Some(ch) }; |
| 374 | } else { |
| 375 | num.push(ch); |
| 376 | } |
| 377 | } |
| 378 | if let (Some(c), Ok(n)) = (cur, num.trim().parse::<f64>()) { |
| 379 | out.push((c, n)); |
| 380 | } |
| 381 | out |
| 382 | }; |
| 383 | match (attr(tag, "stroke"), attr(tag, "fill")) { |
| 384 | (Some(col), _) => { |
| 385 | let w: f64 = attr(tag, "stroke-width").and_then(|w| w.parse().ok()).unwrap_or(1.0); |
| 386 | if let Some((axis, len)) = steps.first() { |
| 387 | match axis { |
| 388 | 'v' => d.lines.push((true, col.to_string(), w, tx, ty, ty + len)), |
| 389 | _ => d.lines.push((false, col.to_string(), w, ty, tx, tx + len)), |
| 390 | } |
| 391 | } |
| 392 | } |
| 393 | (None, Some(col)) if steps.len() >= 2 => { |
| 394 | let h = steps[0].1; |
| 395 | let w = steps[1].1; |
| 396 | d.fills.push((col.to_string(), tx, ty, w, h)); |
| 397 | } |
| 398 | _ => (), |
| 399 | } |
| 400 | } |
| 401 | d |
| 402 | } |
| 403 | |
| 404 | /// Merges collinear, overlapping or touching segments of one pen into maximal ones, and sorts them, so |
| 405 | /// Typst's merged runs and the grid's per-group runs compare as the same ink. |
| 406 | fn normalise(mut v: Vec<(bool, String, f64, f64, f64, f64)>) -> Vec<(bool, String, f64, f64, f64, f64)> { |
| 407 | v.sort_by(|a, b| (a.0, &a.1, a.3 as i64 * 1000, a.4 as i64 * 1000).cmp(&(b.0, &b.1, b.3 as i64 * 1000, b.4 as i64 * 1000)) |
| 408 | .then(a.3.partial_cmp(&b.3).unwrap_or(std::cmp::Ordering::Equal)) |
| 409 | .then(a.4.partial_cmp(&b.4).unwrap_or(std::cmp::Ordering::Equal))); |
| 410 | let mut out: Vec<(bool, String, f64, f64, f64, f64)> = Vec::new(); |
| 411 | for s in v { |
| 412 | if let Some(l) = out.last_mut() { |
| 413 | if l.0 == s.0 && l.1 == s.1 && (l.2 - s.2).abs() < 0.01 && (l.3 - s.3).abs() < 0.01 && s.4 <= l.5 + 0.01 { |
| 414 | if s.5 > l.5 { |
| 415 | l.5 = s.5; |
| 416 | } |
| 417 | continue; |
| 418 | } |
| 419 | } |
| 420 | out.push(s); |
| 421 | } |
| 422 | out |
| 423 | } |
| 424 | |
| 425 | fn close(a: f64, b: f64) -> bool { (a - b).abs() < 0.02 } |
| 426 | |
| 427 | fn ours_drawn(plan: &GridPlan) -> Drawn { |
| 428 | let mut d = Drawn { fills: Vec::new(), lines: Vec::new() }; |
| 429 | for g in &plan.groups { |
| 430 | for f in &g.fills { |
| 431 | if let Paint::Color(c) = &f.paint { |
| 432 | d.fills.push((colour_hex(c), f.x.to_pt(), f.y.to_pt(), f.w.to_pt(), f.h.to_pt())); |
| 433 | } |
| 434 | } |
| 435 | for s in &g.lines { |
| 436 | if let Paint::Color(c) = &s.pen.paint { |
| 437 | d.lines.push((s.vertical, colour_hex(c), s.pen.thickness.to_pt(), s.at.to_pt(), s.from.to_pt(), s.to.to_pt())); |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | d |
| 442 | } |
| 443 | |
| 444 | fn engine() -> Engine { Engine::new(World::new(PathBuf::from("."))) } |
| 445 | |
| 446 | fn region() -> Region { Region::new(Sp::from_pt(200.0), Sp::from_pt(400.0)) } |
| 447 | |
| 448 | /// Lays the case out both ways and compares positions, fills and lines. Returns the plan for extra checks. |
| 449 | fn check(case: &Case) -> Outcome<GridPlan> { |
| 450 | let src = res!(oracle_source(case, false)); |
| 451 | let src_s = src.to_string_lossy().into_owned(); |
| 452 | let (ok, out, err) = res!(typst(&["eval", |
| 453 | "query(<m>).map(m => (m.value, m.location().position().x.pt(), m.location().position().y.pt(), m.location().page()))", |
| 454 | "--in", &src_s])); |
| 455 | if !ok { |
| 456 | return Err(err!("typst failed on {}: {}", case.name, err; Invalid)); |
| 457 | } |
| 458 | let expected = numbers(&out); |
| 459 | res!(std::fs::create_dir_all(scratch()).map_err(|e| err!("{}", e; IO))); |
| 460 | let svg_path = scratch().join(format!("{}.svg", case.name)); |
| 461 | let (ok, _, err) = res!(typst(&["compile", &src_s, &svg_path.to_string_lossy()])); |
| 462 | if !ok { |
| 463 | return Err(err!("typst compile failed on {}: {}", case.name, err; Invalid)); |
| 464 | } |
| 465 | let svg = res!(std::fs::read_to_string(&svg_path).map_err(|e| err!("{}", e; IO))); |
| 466 | |
| 467 | let mut engine = engine(); |
| 468 | let elem = res!(case.element(&mut engine)); |
| 469 | let styles = StyleChain::root(); |
| 470 | let grid = res!(resolve(&mut engine, &elem, &styles)); |
| 471 | let plan = res!(plan(&mut engine, &grid, &styles, region(), &mut Blocks)); |
| 472 | |
| 473 | // Positions: each marker sits at its cell's origin plus the inset. |
| 474 | let mut ours = Vec::new(); |
| 475 | for g in &plan.groups { |
| 476 | for pc in &g.cells { |
| 477 | let cell = &grid.cells[pc.index]; |
| 478 | if body_of(&cell.elem) == (0, 0.0, 0.0) { |
| 479 | continue; // an empty cell filling a free slot carries no marker |
| 480 | } |
| 481 | let (id, _, _) = body_of(&cell.elem); |
| 482 | ours.push((id, pc.x.to_pt() + inset_pt(&cell.elem, "left"), pc.y.to_pt() + inset_pt(&cell.elem, "top"))); |
| 483 | } |
| 484 | } |
| 485 | assert_eq!(ours.len(), expected.len(), "{}: cell count, ours {:?} typst {:?}", case.name, ours, expected); |
| 486 | for e in &expected { |
| 487 | let id = e[0] as u32; |
| 488 | assert!(close(e[3], 1.0), "{}: marker {} on page {}", case.name, id, e[3]); |
| 489 | match ours.iter().find(|o| o.0 == id) { |
| 490 | Some(o) => assert!(close(o.1, e[1]) && close(o.2, e[2]), |
| 491 | "{}: cell {} at ({}, {}), typst ({}, {})", case.name, id, o.1, o.2, e[1], e[2]), |
| 492 | None => panic!("{}: cell {} missing", case.name, id), |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | let theirs = svg_drawn(&svg); |
| 497 | let mine = ours_drawn(&plan); |
| 498 | let mut tf = theirs.fills.clone(); |
| 499 | let mut of = mine.fills.clone(); |
| 500 | let key = |f: &(String, f64, f64, f64, f64)| (f.0.clone(), (f.1 * 100.0) as i64, (f.2 * 100.0) as i64); |
| 501 | tf.sort_by_key(key); |
| 502 | of.sort_by_key(key); |
| 503 | assert_eq!(tf.len(), of.len(), "{}: fills, ours {:?} typst {:?}", case.name, of, tf); |
| 504 | for (a, b) in tf.iter().zip(&of) { |
| 505 | assert!(a.0 == b.0 && close(a.1, b.1) && close(a.2, b.2) && close(a.3, b.3) && close(a.4, b.4), |
| 506 | "{}: fill ours {:?} typst {:?}", case.name, b, a); |
| 507 | } |
| 508 | let tl = normalise(theirs.lines); |
| 509 | let ol = normalise(mine.lines); |
| 510 | assert_eq!(tl.len(), ol.len(), "{}: lines,\n ours {:?}\n typst {:?}", case.name, ol, tl); |
| 511 | for (a, b) in tl.iter().zip(&ol) { |
| 512 | assert!(a.0 == b.0 && a.1 == b.1 && close(a.2, b.2) && close(a.3, b.3) && close(a.4, b.4) && close(a.5, b.5), |
| 513 | "{}: line ours {:?} typst {:?}", case.name, b, a); |
| 514 | } |
| 515 | Ok(plan) |
| 516 | } |
| 517 | |
| 518 | /// A case Typst refuses: the evaluator must refuse it with Typst's message. |
| 519 | fn check_error(case: &Case) -> Outcome<()> { |
| 520 | let src = res!(oracle_source(case, true)); |
| 521 | let (ok, _, err) = res!(typst(&["compile", &src.to_string_lossy(), &scratch().join("err.pdf").to_string_lossy()])); |
| 522 | assert!(!ok, "{}: typst accepted it", case.name); |
| 523 | let theirs = err.lines().next().unwrap_or("").trim_start_matches("error: ").to_string(); |
| 524 | let mut engine = engine(); |
| 525 | let elem = res!(case.element(&mut engine)); |
| 526 | let got = resolve(&mut engine, &elem, &StyleChain::root()); |
| 527 | assert!(got.is_err(), "{}: evaluator accepted it", case.name); |
| 528 | let ours = engine.diags.last().map(|d| d.message.clone()).unwrap_or_default(); |
| 529 | assert_eq!(ours, theirs, "{}: message", case.name); |
| 530 | Ok(()) |
| 531 | } |
| 532 | |
| 533 | fn n(v: Vec<(&'static str, V)>) -> Named { v } |
| 534 | |
| 535 | // Cases |
| 536 | |
| 537 | #[test] |
| 538 | fn tracks_auto_fixed_fraction_with_gutters() -> Outcome<()> { |
| 539 | res!(check(&Case { name: "tracks", table: false, |
| 540 | args: n(vec![("columns", V::Arr(vec![V::Auto, V::Pt(30.0), V::Fr(1.0)])), |
| 541 | ("column-gutter", V::Pt(3.0)), ("row-gutter", V::Pt(2.0))]), |
| 542 | children: vec![Ch::C(0, 20.0, 10.0), Ch::C(1, 10.0, 15.0), Ch::C(2, 5.0, 5.0), |
| 543 | Ch::Cell(3, 70.0, 4.0, n(vec![("colspan", V::Int(2))])), Ch::C(4, 1.0, 1.0), Ch::C(5, 1.0, 1.0)], |
| 544 | })); |
| 545 | // Fractions share by weight after relative (percent) and auto columns. |
| 546 | res!(check(&Case { name: "fractions", table: false, |
| 547 | args: n(vec![("columns", V::Arr(vec![V::Fr(1.0), V::Pct(25.0), V::Fr(2.0), V::Auto])), ("gutter", V::Pt(4.0))]), |
| 548 | children: vec![Ch::C(0, 5.0, 5.0), Ch::C(1, 5.0, 5.0), Ch::C(2, 5.0, 5.0), Ch::C(3, 12.0, 7.0), |
| 549 | Ch::C(4, 5.0, 9.0)], |
| 550 | })); |
| 551 | // A colspan over two autos puts its excess on the later one; a line after it sits past its span. |
| 552 | res!(check(&Case { name: "colspan_autos", table: false, |
| 553 | args: n(vec![("columns", V::Arr(vec![V::Auto, V::Auto, V::Auto]))]), |
| 554 | children: vec![Ch::C(0, 10.0, 5.0), Ch::C(1, 20.0, 5.0), Ch::C(2, 5.0, 5.0), |
| 555 | Ch::Cell(3, 60.0, 5.0, n(vec![("colspan", V::Int(2))])), |
| 556 | Ch::VLine(n(vec![("stroke", V::Col("red"))])), Ch::C(4, 5.0, 5.0)], |
| 557 | })); |
| 558 | // Integer columns, and auto columns wider than the region shrink fairly. |
| 559 | res!(check(&Case { name: "shrink", table: false, |
| 560 | args: n(vec![("columns", V::Int(3))]), |
| 561 | children: vec![Ch::C(0, 150.0, 5.0), Ch::C(1, 20.0, 5.0), Ch::C(2, 120.0, 5.0)], |
| 562 | })); |
| 563 | Ok(()) |
| 564 | } |
| 565 | |
| 566 | #[test] |
| 567 | fn rows_relative_auto_fraction_and_rowspan_excess() -> Outcome<()> { |
| 568 | res!(check(&Case { name: "rows", table: false, |
| 569 | args: n(vec![("columns", V::Arr(vec![V::Pt(30.0), V::Pt(30.0)])), |
| 570 | ("rows", V::Arr(vec![V::Pt(12.0), V::Auto, V::Auto, V::Fr(1.0), V::Pt(8.0)]))]), |
| 571 | children: vec![Ch::C(0, 5.0, 20.0), Ch::C(1, 5.0, 5.0), |
| 572 | Ch::Cell(2, 5.0, 50.0, n(vec![("rowspan", V::Int(2))])), Ch::C(3, 5.0, 7.0), Ch::C(4, 5.0, 9.0), |
| 573 | Ch::C(5, 5.0, 5.0), Ch::C(6, 5.0, 5.0), Ch::C(7, 5.0, 5.0), Ch::C(8, 5.0, 5.0)], |
| 574 | })); |
| 575 | // The last given row size repeats. |
| 576 | res!(check(&Case { name: "rows_repeat", table: false, |
| 577 | args: n(vec![("columns", V::Int(2)), ("rows", V::Arr(vec![V::Pt(9.0), V::Pt(13.0)]))]), |
| 578 | children: (0..8).map(|i| Ch::C(i, 4.0, 4.0)).collect(), |
| 579 | })); |
| 580 | Ok(()) |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn placement_fixed_partial_and_spans() -> Outcome<()> { |
| 585 | res!(check(&Case { name: "placement", table: false, |
| 586 | args: n(vec![("columns", V::Arr(vec![V::Pt(10.0), V::Pt(10.0), V::Pt(10.0)])), ("rows", V::Pt(10.0))]), |
| 587 | children: vec![Ch::Cell(0, 5.0, 5.0, n(vec![("x", V::Int(0)), ("y", V::Int(2))])), |
| 588 | Ch::Cell(1, 5.0, 5.0, n(vec![("x", V::Int(1))])), |
| 589 | Ch::Cell(2, 5.0, 5.0, n(vec![("y", V::Int(1))])), |
| 590 | Ch::C(3, 5.0, 5.0), Ch::C(4, 5.0, 5.0), |
| 591 | Ch::Cell(5, 5.0, 5.0, n(vec![("x", V::Int(0))])), |
| 592 | Ch::Cell(6, 5.0, 5.0, n(vec![("colspan", V::Int(2)), ("rowspan", V::Int(2))])), |
| 593 | Ch::C(7, 5.0, 5.0), Ch::C(8, 5.0, 5.0), Ch::C(9, 5.0, 5.0)], |
| 594 | })); |
| 595 | Ok(()) |
| 596 | } |
| 597 | |
| 598 | #[test] |
| 599 | fn headers_and_footers_place_and_group() -> Outcome<()> { |
| 600 | let plan = res!(check(&Case { name: "sections", table: false, |
| 601 | args: n(vec![("columns", V::Arr(vec![V::Pt(10.0), V::Pt(10.0), V::Pt(10.0)])), ("rows", V::Pt(10.0)), |
| 602 | ("row-gutter", V::Pt(3.0))]), |
| 603 | children: vec![Ch::C(0, 5.0, 5.0), |
| 604 | Ch::Head(n(vec![]), vec![Ch::C(1, 5.0, 5.0), Ch::Cell(2, 5.0, 5.0, n(vec![("x", V::Int(2))]))]), |
| 605 | Ch::C(3, 5.0, 5.0), Ch::Cell(4, 5.0, 5.0, n(vec![("rowspan", V::Int(2))])), Ch::C(5, 5.0, 5.0), |
| 606 | Ch::Head(n(vec![("level", V::Int(2))]), vec![Ch::C(6, 5.0, 5.0)]), |
| 607 | Ch::C(7, 5.0, 5.0), |
| 608 | Ch::Foot(n(vec![]), vec![Ch::C(8, 5.0, 5.0)])], |
| 609 | })); |
| 610 | let parts: Vec<Part> = plan.groups.iter().map(|g| g.part).collect(); |
| 611 | assert_eq!(parts, vec![Part::Body, Part::Header { level: 1, repeat: true }, Part::Body, |
| 612 | Part::Header { level: 2, repeat: true }, Part::Body, Part::Footer { repeat: true }]); |
| 613 | // The rowspan welds its two rows (and the gutter between them) into one group. |
| 614 | assert_eq!((plan.groups[2].start, plan.groups[2].end), (4, 7)); |
| 615 | Ok(()) |
| 616 | } |
| 617 | |
| 618 | #[test] |
| 619 | fn table_strokes_fills_and_lines() -> Outcome<()> { |
| 620 | // Default table stroke and inset, fill cycling by column, a cell's own stroke and fill. |
| 621 | res!(check(&Case { name: "table_basic", table: true, |
| 622 | args: n(vec![("columns", V::Arr(vec![V::Auto, V::Pt(30.0), V::Auto])), |
| 623 | ("fill", V::Arr(vec![V::Col("yellow"), V::Nil, V::Col("aqua")]))]), |
| 624 | children: vec![Ch::C(0, 10.0, 5.0), Ch::C(1, 5.0, 5.0), Ch::C(2, 7.0, 5.0), |
| 625 | Ch::Cell(3, 5.0, 5.0, n(vec![("stroke", V::Stroke(2.0, "blue")), ("fill", V::Col("red"))])), |
| 626 | Ch::Cell(4, 5.0, 15.0, n(vec![("colspan", V::Int(2)), ("inset", V::Dict(vec![("left", V::Pt(1.0)), ("y", V::Pt(2.0))]))])), |
| 627 | Ch::Cell(5, 5.0, 5.0, n(vec![("rowspan", V::Int(2))])), Ch::C(6, 5.0, 5.0), Ch::C(7, 5.0, 5.0)], |
| 628 | })); |
| 629 | // Explicit lines, auto positioned and ranged, over a stroke dictionary; `none` removes a stretch. |
| 630 | res!(check(&Case { name: "table_lines", table: true, |
| 631 | args: n(vec![("columns", V::Arr(vec![V::Pt(20.0), V::Pt(20.0), V::Pt(20.0)])), ("inset", V::Pt(2.0)), |
| 632 | ("stroke", V::Dict(vec![("x", V::Stroke(0.5, "black")), ("bottom", V::Stroke(1.5, "olive"))]))]), |
| 633 | children: vec![Ch::C(0, 5.0, 5.0), Ch::HLine(n(vec![("stroke", V::Col("red"))])), Ch::C(1, 5.0, 5.0), |
| 634 | Ch::VLine(n(vec![("stroke", V::Stroke(1.0, "blue"))])), Ch::C(2, 5.0, 5.0), Ch::C(3, 5.0, 5.0), |
| 635 | Ch::C(9, 5.0, 5.0), Ch::C(10, 5.0, 5.0), |
| 636 | Ch::HLine(n(vec![("start", V::Int(1)), ("end", V::Int(2)), ("stroke", V::Stroke(2.0, "green"))])), |
| 637 | Ch::VLine(n(vec![("x", V::Int(1)), ("stroke", V::Nil)])), |
| 638 | Ch::Cell(4, 5.0, 5.0, n(vec![("colspan", V::Int(3))])), Ch::C(5, 5.0, 5.0)], |
| 639 | })); |
| 640 | // Two grid-level strokes meeting at an edge: the later cell's wins the tie. |
| 641 | res!(check(&Case { name: "table_tie", table: true, |
| 642 | args: n(vec![("columns", V::Arr(vec![V::Pt(15.0), V::Pt(15.0)])), ("inset", V::Pt(1.0)), |
| 643 | ("stroke", V::Dict(vec![("top", V::Stroke(2.0, "red")), ("bottom", V::Stroke(1.5, "olive")), |
| 644 | ("left", V::Col("blue")), ("right", V::Stroke(3.0, "green"))]))]), |
| 645 | children: (0..4).map(|i| Ch::C(i, 5.0, 5.0)).collect(), |
| 646 | })); |
| 647 | // Gutters frame every cell separately; a `position: end` line sits before the gutter. |
| 648 | res!(check(&Case { name: "table_gutter", table: true, |
| 649 | args: n(vec![("columns", V::Arr(vec![V::Pt(10.0), V::Pt(10.0)])), ("rows", V::Pt(10.0)), ("inset", V::Pt(0.0)), |
| 650 | ("gutter", V::Pt(4.0)), ("fill", V::Col("blue"))]), |
| 651 | children: vec![Ch::C(0, 5.0, 5.0), Ch::C(1, 5.0, 5.0), |
| 652 | Ch::Cell(2, 5.0, 5.0, n(vec![("colspan", V::Int(2))])), |
| 653 | Ch::HLine(n(vec![("stroke", V::Col("red"))])), |
| 654 | Ch::VLine(n(vec![("x", V::Int(1)), ("stroke", V::Col("green"))])), |
| 655 | Ch::VLine(n(vec![("x", V::Int(1)), ("position", V::Align("end")), ("stroke", V::Col("olive"))]))], |
| 656 | })); |
| 657 | Ok(()) |
| 658 | } |
| 659 | |
| 660 | #[test] |
| 661 | fn refusals_match_typst() -> Outcome<()> { |
| 662 | let cols = || n(vec![("columns", V::Arr(vec![V::Pt(10.0), V::Pt(10.0), V::Pt(10.0)]))]); |
| 663 | res!(check_error(&Case { name: "err_colspan", table: false, args: cols(), |
| 664 | children: vec![Ch::C(0, 5.0, 5.0), Ch::Cell(1, 5.0, 5.0, n(vec![("colspan", V::Int(3))]))] })); |
| 665 | res!(check_error(&Case { name: "err_second", table: false, args: cols(), |
| 666 | children: vec![Ch::C(0, 5.0, 5.0), Ch::Cell(1, 5.0, 5.0, n(vec![("x", V::Int(0)), ("y", V::Int(0))]))] })); |
| 667 | res!(check_error(&Case { name: "err_row_full", table: false, args: cols(), |
| 668 | children: vec![Ch::C(0, 5.0, 5.0), Ch::C(1, 5.0, 5.0), Ch::C(2, 5.0, 5.0), Ch::Cell(3, 5.0, 5.0, n(vec![("y", V::Int(0))]))] })); |
| 669 | res!(check_error(&Case { name: "err_footer", table: false, args: cols(), |
| 670 | children: vec![Ch::Foot(n(vec![]), vec![Ch::C(0, 5.0, 5.0)]), Ch::C(1, 5.0, 5.0)] })); |
| 671 | res!(check_error(&Case { name: "err_span", table: false, args: cols(), |
| 672 | children: vec![Ch::C(0, 5.0, 5.0), Ch::Cell(1, 5.0, 5.0, n(vec![("x", V::Int(2)), ("y", V::Int(1))])), |
| 673 | Ch::Cell(2, 5.0, 5.0, n(vec![("colspan", V::Int(2)), ("rowspan", V::Int(2))])), |
| 674 | Ch::Cell(3, 5.0, 5.0, n(vec![("colspan", V::Int(2)), ("rowspan", V::Int(2))]))] })); |
| 675 | res!(check_error(&Case { name: "err_column", table: false, args: cols(), |
| 676 | children: vec![Ch::Cell(0, 5.0, 5.0, n(vec![("x", V::Int(3))]))] })); |
| 677 | Ok(()) |
| 678 | } |
| 679 | |
| 680 | #[test] |
| 681 | fn construction_normalises_as_typst_stores() -> Outcome<()> { |
| 682 | // `typst eval 'grid(columns: 3, gutter: 2pt, [a]).fields()'` gives three autos, both gutters as |
| 683 | // `0% + 2pt`, and the child wrapped in a cell. |
| 684 | let mut engine = engine(); |
| 685 | let mut args = Args::new(Span::detached()); |
| 686 | args.push_named(Span::detached(), "columns", Value::Int(3)); |
| 687 | args.push_named(Span::detached(), "gutter", Value::Length(Length::pt(2.0))); |
| 688 | args.push(Span::detached(), Value::Content(Content::text("a"))); |
| 689 | let g = res!(construct(&mut engine, ElemKind::Grid, &mut args)); |
| 690 | match g.field("columns") { |
| 691 | Some(Value::Array(a)) => assert!(a.len() == 3 && a.iter().all(|v| v.is_auto())), |
| 692 | other => panic!("columns: {:?}", other), |
| 693 | } |
| 694 | for name in ["column-gutter", "row-gutter"] { |
| 695 | match g.field(name) { |
| 696 | Some(Value::Array(a)) => assert!(matches!(a.first(), |
| 697 | Some(Value::Relative(r)) if r.rel.0 == 0.0 && r.abs.abs == 2.0)), |
| 698 | other => panic!("{}: {:?}", name, other), |
| 699 | } |
| 700 | } |
| 701 | match g.field("children") { |
| 702 | Some(Value::Array(a)) => match a.first() { |
| 703 | Some(Value::Content(c)) => assert!(c.is(ElemKind::GridCell) && c.plain_text() == "a"), |
| 704 | other => panic!("child: {:?}", other), |
| 705 | }, |
| 706 | other => panic!("children: {:?}", other), |
| 707 | } |
| 708 | // A grid cell inside a table is refused with Typst's wording. |
| 709 | let mut args = Args::new(Span::detached()); |
| 710 | args.push(Span::detached(), Value::Content(Content::text("a"))); |
| 711 | let cell = res!(construct(&mut engine, ElemKind::GridCell, &mut args)); |
| 712 | let mut args = Args::new(Span::detached()); |
| 713 | args.push(Span::detached(), Value::Content(cell)); |
| 714 | assert!(construct(&mut engine, ElemKind::Table, &mut args).is_err()); |
| 715 | assert_eq!(engine.diags.last().map(|d| d.message.clone()).unwrap_or_default(), |
| 716 | "cannot use `grid.cell` as a table cell"); |
| 717 | Ok(()) |
| 718 | } |
| 719 | |
| 720 | #[test] |
| 721 | fn lowering_welds_headers_and_footers_and_breaks_between_groups() -> Outcome<()> { |
| 722 | use oxedyne_fe2o3_austenite::flow::grid::lower; |
| 723 | use oxedyne_fe2o3_austenite::ir::Penalty; |
| 724 | // Positions are the oracle's (the `sections` case); this checks the vertical material built from them. |
| 725 | let case = Case { name: "lowering", table: false, |
| 726 | args: n(vec![("columns", V::Arr(vec![V::Pt(10.0), V::Pt(10.0)])), ("rows", V::Pt(10.0)), |
| 727 | ("row-gutter", V::Pt(2.0))]), |
| 728 | children: vec![Ch::Head(n(vec![]), vec![Ch::C(1, 5.0, 5.0), Ch::C(2, 5.0, 5.0)]), |
| 729 | Ch::C(3, 5.0, 5.0), Ch::Cell(4, 5.0, 5.0, n(vec![("rowspan", V::Int(2))])), Ch::C(5, 5.0, 5.0), |
| 730 | Ch::Foot(n(vec![]), vec![Ch::C(6, 5.0, 5.0), Ch::C(7, 5.0, 5.0)])] }; |
| 731 | let mut engine = engine(); |
| 732 | let elem = res!(case.element(&mut engine)); |
| 733 | let styles = StyleChain::root(); |
| 734 | let grid = res!(resolve(&mut engine, &elem, &styles)); |
| 735 | let plan = res!(plan(&mut engine, &grid, &styles, region(), &mut Blocks)); |
| 736 | let nodes = res!(lower(&mut engine, &grid, &plan)); |
| 737 | let shape: Vec<String> = nodes.iter().map(|nd| match nd { |
| 738 | Node::VBox(b) => format!("box {}x{}", b.dims.width.to_pt(), b.dims.height.to_pt()), |
| 739 | Node::RepeatHead(Some(b)) => format!("repeat {}", b.dims.height.to_pt()), |
| 740 | Node::RepeatHead(None) => "disarm".to_string(), |
| 741 | Node::Penalty(p) if p.cost >= Penalty::INFINITY => "weld".to_string(), |
| 742 | Node::Glue(g) => format!("glue {}", g.natural.to_pt()), |
| 743 | other => format!("{:?}", other), |
| 744 | }).collect(); |
| 745 | assert_eq!(shape, vec![ |
| 746 | "box 20x10", "repeat 10", "weld", "glue 2", // header, armed, welded to the first row |
| 747 | "box 20x22", // two rows and their gutter, welded by the rowspan |
| 748 | "weld", "glue 2", "box 20x10", // the footer, welded to the last row |
| 749 | "disarm", |
| 750 | ]); |
| 751 | Ok(()) |
| 752 | } |