Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/flow/grid.rs

57.5 KiB, 69 runs

created by r1870400018:63522, 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 owns this file: grid and table into rows, with colspan/rowspan, gutters, per-cell fill/stroke/align
2// (values, arrays cycling by column, or closures of x and y), lines, and repeating headers.
3//
4// Three stages, each Typst's. `resolve` places every cell (auto-placement skips occupied slots and never
5// wraps a colspan), folds each cell's inset, align, fill and stroke over the grid's, and writes them back
6// into the cell so a `show table.cell` rule reads them. `plan` sizes the tracks (relative, then auto from
7// the cells' natural sizes with a span's excess on its last auto track, then fractions of what is left,
8// shrinking overlarge auto columns fairly when nothing is left) and resolves every line segment by
9// Typst's priorities: an explicit line over a cell's own stroke over the grid's, the later cell winning a
10// tie. `lower` turns the plan into vertical material: one unbreakable box per group of rows a rowspan
11// welds, zero or gutter glue between them as the legal page breaks, and the header armed as a
12// `Node::RepeatHead`.
13//
14// A boundary line between two row groups is drawn by both: each group's box carries its own top and bottom
15// rules, so a page break between them frames both pages, as Typst does. Coincident strokes draw twice.
16
17use crate::diag::DiagnosticKind;
18use crate::eval::args::Args;
19use crate::eval::content::{
20 Content,
21 ElemKind,
22};
23use crate::eval::lib::grid::{
24 self as schema,
25 fid,
26};
27use crate::eval::locate::Locator;
28use crate::eval::styles::StyleChain;
29use crate::eval::value::{
30 Alignment,
31 Dash,
32 DashItem,
33 Dict,
34 LineCap,
35 LineJoin,
36 Length,
37 Paint,
38 Ratio,
39 Relative,
40 Stroke,
41 Value,
42};
43use crate::eval::Engine;
44use crate::flow::block::{
45 layout_fragment_in,
46 Frame,
47 Item as BlockItem,
48 Regions,
49};
50use crate::flow::Region;
51use crate::ir::{
52 BoxNode,
53 Dims,
54 DrawOp,
55 Glue,
56 Graphic,
57 Leaf,
58 Node,
59 Penalty,
60 Sp,
61};
62use crate::syntax::Span;
63
64use oxedyne_fe2o3_core::prelude::*;
65use oxedyne_fe2o3_graphics::{
66 colour::{
67 Ink,
68 Rgba,
69 },
70 path::{
71 Bounds,
72 Path,
73 PathBuilder,
74 Pt,
75 },
76};
77
78use std::sync::Arc;
79
80/// A grid or table as vertical material: rows that may break across pages.
81pub fn layout_grid(
82 engine: &mut Engine,
83 elem: &Content,
84 styles: &StyleChain,
85 region: Region,
86)
87 -> Outcome<Vec<Node>>
88{
89 let grid = res!(resolve(engine, elem, styles));
90 let plan = res!(plan(engine, &grid, styles, region, &mut FlowCells));
91 lower(engine, &grid, &plan)
92}
93
94/// A grid or table as vertical material, with the rows that may break across regions marked, and what
95/// breaking one takes.
96pub struct Rows {
97 pub nodes: Vec<Node>,
98 pub breaks: Vec<Option<usize>>, // for each node, its group when that is a breakable row
99 grid: CellGrid,
100 plan: GridPlan,
101}
102
103/// How a row that does not fit the room left is dealt with.
104pub enum RowSplit {
105 Whole, // it does not break: it goes to the next region whole
106 Skip, // its first part would be empty: it starts in the next region
107 Parts(Vec<BoxNode>), // a part for each region it spans
108}
109
110/// As [`layout_grid`], keeping what is needed to break a row.
111pub fn layout_rows(engine: &mut Engine, elem: &Content, styles: &StyleChain, region: Region) -> Outcome<Rows> {
112 let grid = res!(resolve(engine, elem, styles));
113 let plan = res!(plan(engine, &grid, styles, region, &mut FlowCells));
114 let (nodes, breaks) = res!(lower_rows(engine, &grid, &plan));
115 // A group of rows that stays together (a rowspan's, a header's or a footer's) taller than the region is
116 // set whole and runs past it, where Typst breaks it.
117 let full = region.base.1;
118 if plan.groups.iter().any(|g| g.height > full && g.end > g.start + 1)
119 {
120 engine.warn(DiagnosticKind::Unsupported, grid.span,
121 "rows held together by a rowspan, a header or a footer that are taller than a page are not broken across pages");
122 }
123 Ok(Rows { nodes, breaks, grid, plan })
124}
125
126impl Rows {
127 /// Sets the cells of group `gi`, one automatically sized row, into `regions`, whose first has the room
128 /// left, Typst's breakable row: each cell is measured into the regions, every part but the last is
129 /// grown to fill its region less `head` (a repeated header), and the cells are set again into those
130 /// heights. When `skip` is set a row whose first part would be empty for a cell that has more to show
131 /// is left to start in the next region.
132 pub fn split(&self, engine: &mut Engine, styles: &StyleChain, gi: usize, regions: &Regions, head: f64, skip: bool)
133 -> Outcome<RowSplit>
134 {
135 let g = &self.plan.groups[gi];
136 // A frame with nothing in it but tags, or no height, holds no content.
137 let bare = |fr: &Frame| fr.h <= 0.01 || fr.items.iter().all(|(_, _, i)| matches!(i, BlockItem::Tag(_)));
138 let mut sizes: Vec<f64> = Vec::new();
139 for pc in &g.cells {
140 let cell = &self.grid.cells[pc.index];
141 let mut r = regions.clone();
142 r.w = pc.w.to_pt();
143 r.expand_x = true;
144 r.expand_y = false;
145 let frames = res!(layout_fragment_in(engine, cell.elem.place(), &cell.elem, styles, r));
146 if skip && frames.first().map(|f| bare(f)).unwrap_or(false) && frames.iter().skip(1).any(|f| !bare(f)) {
147 return Ok(RowSplit::Skip);
148 }
149 for (i, fr) in frames.iter().enumerate() {
150 match sizes.get_mut(i) {
151 Some(h) => *h = h.max(fr.h),
152 None => sizes.push(fr.h),
153 }
154 }
155 }
156 let n = sizes.len();
157 if n <= 1 {
158 return Ok(RowSplit::Whole);
159 }
160 let mut walk = regions.clone();
161 for i in 0..n - 1 {
162 if i > 0 {
163 walk.next();
164 }
165 let room = walk.h - if i > 0 { head } else { 0.0 };
166 sizes[i] = sizes[i].max(room);
167 }
168 let mut parts: Vec<Vec<CellPart>> = (0..n).map(|_| Vec::new()).collect();
169 for pc in &g.cells {
170 let cell = &self.grid.cells[pc.index];
171 let r = Regions {
172 w: pc.w.to_pt(), h: sizes[0], full: regions.full, backlog: sizes[1..].to_vec(), last: None,
173 expand_x: true, expand_y: true,
174 };
175 let frames = res!(layout_fragment_in(engine, cell.elem.place(), &cell.elem, styles, r));
176 for (k, part) in parts.iter_mut().enumerate() {
177 let h = Sp::from_pt(sizes[k]);
178 let nodes = match frames.get(k) {
179 Some(fr) => vec![Node::VBox(BoxNode::new(vec![fr.clone().into_node()], Dims::new(pc.w, h, Sp::ZERO)))],
180 None => Vec::new(),
181 };
182 part.push(CellPart { x: pc.x, w: pc.w, h, nodes });
183 }
184 }
185 let mut boxes = Vec::new();
186 for (k, cells) in parts.into_iter().enumerate() {
187 let h = Sp::from_pt(sizes[k]);
188 let ys = vec![Sp::ZERO; cells.len()];
189 boxes.push(res!(part_box(engine, &self.grid, &self.plan, g, cells, ys, h, k == 0, k + 1 == n)));
190 }
191 if !self.grid.hlines.is_empty() || !self.grid.vlines.is_empty() {
192 engine.warn(DiagnosticKind::Unsupported, self.grid.span,
193 "a row broken across pages is ruled at each break by the lines of its own edges; Typst's explicit lines at a break differ");
194 }
195 Ok(RowSplit::Parts(boxes))
196 }
197}
198
199// Cell layout seam
200
201/// How a cell's content is measured and set. The grid owns the geometry; the content is the block flow's.
202pub trait CellLayout {
203 /// The natural size of a cell's content in `region`, which does not expand.
204 fn measure(&mut self, engine: &mut Engine, cell: &Content, styles: &StyleChain, region: Region) -> Outcome<Dims>;
205
206 /// The cell's content set into exactly its spanned area, as a vertical list.
207 fn layout(&mut self, engine: &mut Engine, cell: &Content, styles: &StyleChain, region: Region) -> Outcome<Vec<Node>>;
208}
209
210/// Cells laid out by the block flow, through realisation, so show rules on the cell apply.
211pub struct FlowCells;
212
213impl CellLayout for FlowCells {
214 fn measure(&mut self, engine: &mut Engine, cell: &Content, styles: &StyleChain, region: Region) -> Outcome<Dims> {
215 engine.within(cell.place(), |engine| crate::flow::measure(engine, cell, styles, region))
216 }
217
218 fn layout(&mut self, engine: &mut Engine, cell: &Content, styles: &StyleChain, region: Region) -> Outcome<Vec<Node>> {
219 engine.within(cell.place(), |engine| crate::flow::layout_block(engine, cell, styles, region))
220 }
221}
222
223// Vocabulary
224
225#[derive(Clone, Copy, Debug, PartialEq)]
226pub enum Sizing {
227 Auto,
228 Rel(Relative),
229 Fr(f64),
230}
231
232impl Sizing {
233 fn from_value(v: &Value) -> Option<Sizing> {
234 match v {
235 Value::Auto => Some(Sizing::Auto),
236 Value::Length(l) => Some(Sizing::Rel(Relative { rel: Ratio(0.0), abs: *l })),
237 Value::Ratio(r) => Some(Sizing::Rel(Relative { rel: *r, abs: Length::zero() })),
238 Value::Relative(r) => Some(Sizing::Rel(*r)),
239 Value::Fraction(f) => Some(Sizing::Fr(f.0)),
240 _ => None,
241 }
242 }
243
244 fn is_auto(&self) -> bool { matches!(self, Sizing::Auto) }
245}
246
247#[derive(Clone, Copy, Debug, Default, PartialEq)]
248pub struct Sides<T> {
249 pub left: T,
250 pub top: T,
251 pub right: T,
252 pub bottom: T,
253}
254
255impl<T: Clone> Sides<T> {
256 pub fn splat(v: T) -> Self { Sides { left: v.clone(), top: v.clone(), right: v.clone(), bottom: v } }
257}
258
259/// A resolved pen: every part of a stroke settled, the thickness in scaled points.
260#[derive(Clone, Debug)]
261pub struct Pen {
262 pub paint: Paint,
263 pub thickness: Sp,
264 pub cap: LineCap,
265 pub join: LineJoin,
266 pub dash: Option<Dash>,
267 pub miter: f64,
268}
269
270impl Pen {
271 fn same(&self, o: &Pen) -> bool {
272 self.thickness == o.thickness && self.cap == o.cap && self.join == o.join && self.dash == o.dash
273 && self.miter == o.miter && same_paint(&self.paint, &o.paint)
274 }
275}
276
277fn same_paint(a: &Paint, b: &Paint) -> bool {
278 match (a, b) {
279 (Paint::Color(x), Paint::Color(y)) => x == y,
280 (Paint::Gradient(x), Paint::Gradient(y)) => x == y,
281 (Paint::Tiling(x), Paint::Tiling(y)) => Arc::ptr_eq(x, y),
282 _ => false,
283 }
284}
285
286/// Which part of the grid a run of rows belongs to.
287#[derive(Clone, Copy, Debug, PartialEq, Eq)]
288pub enum Part {
289 Body,
290 Header { level: i64, repeat: bool },
291 Footer { repeat: bool },
292}
293
294/// A header or footer: the content rows `start..end` it occupies.
295#[derive(Clone, Copy, Debug, PartialEq, Eq)]
296pub struct Section {
297 pub start: usize,
298 pub end: usize,
299 pub part: Part,
300}
301
302/// A placed cell, in content coordinates, with its properties folded over the grid's.
303#[derive(Clone, Debug)]
304pub struct Cell {
305 pub x: usize,
306 pub y: usize,
307 pub colspan: usize,
308 pub rowspan: usize,
309 pub elem: Content, // the cell element, resolved fields written in
310 pub fill: Option<Paint>,
311 pub stroke: Sides<Option<Stroke>>,
312 pub prioritised: Sides<bool>, // the cell's own stroke set this side
313 pub inset: Sides<Relative>,
314 pub align: Alignment,
315}
316
317/// An explicit `hline` or `vline`, in track coordinates.
318#[derive(Clone, Debug)]
319pub struct Line {
320 pub at: usize, // the track boundary it is drawn on
321 pub start: usize, // first track it covers
322 pub end: usize, // one past the last
323 pub stroke: Option<Stroke>, // `None`: `stroke: none`, which removes cell strokes there
324}
325
326/// A grid with every cell placed. Tracks interleave gutters when any gutter is given, as in Typst: content
327/// column `x` is track `2x` then.
328#[derive(Clone, Debug)]
329pub struct CellGrid {
330 pub cols: Vec<Sizing>,
331 pub rows: Vec<Sizing>,
332 pub gutter: bool,
333 pub n_cols: usize,
334 pub n_rows: usize,
335 pub cells: Vec<Cell>,
336 pub hlines: Vec<Line>,
337 pub vlines: Vec<Line>,
338 pub sections: Vec<Section>, // headers and the footer, in row order
339 pub font_pt: f64,
340 pub span: Span,
341 parents: Vec<Option<usize>>, // the cell covering each (column track, row track)
342}
343
344impl CellGrid {
345 /// The track of content column or row `i`.
346 pub fn track(&self, i: usize) -> usize { if self.gutter { 2 * i } else { i } }
347
348 /// The tracks a span of `n` content columns or rows starting at `i` covers, gutters between included.
349 pub fn track_span(&self, i: usize, n: usize) -> (usize, usize) {
350 let a = self.track(i);
351 (a, self.track(i + n - 1) + 1)
352 }
353
354 /// The cell covering a track position, when one does.
355 pub fn parent(&self, xt: usize, yt: usize) -> Option<&Cell> {
356 let w = self.cols.len();
357 if xt >= w || yt >= self.rows.len() {
358 return None;
359 }
360 self.parents.get(yt * w + xt).copied().flatten().and_then(|i| self.cells.get(i))
361 }
362
363 fn cell_tracks(&self, c: &Cell) -> ((usize, usize), (usize, usize)) {
364 (self.track_span(c.x, c.colspan), self.track_span(c.y, c.rowspan))
365 }
366}
367
368// Resolution
369
370fn int_of(v: &Value) -> Option<i64> {
371 match v {
372 Value::Int(i) => Some(*i),
373 _ => None,
374 }
375}
376
377/// The font size in force, for `em` lengths.
378pub fn font_size_pt(styles: &StyleChain) -> f64 { styles.font_size() }
379
380/// A per-cell property as Typst's `Celled`: a value, an array cycling by column, or a function of x and y.
381fn celled(engine: &mut Engine, v: &Value, x: usize, y: usize, span: Span) -> Outcome<Value> {
382 match v {
383 Value::Func(f) => {
384 let mut args = Args::new(span);
385 args.push(span, Value::Int(x as i64));
386 args.push(span, Value::Int(y as i64));
387 engine.call_func(f, args)
388 }
389 Value::Array(a) => match a.len() {
390 0 => Ok(Value::None),
391 n => Ok(a.get(x % n).cloned().unwrap_or(Value::None)),
392 },
393 other => Ok(other.clone()),
394 }
395}
396
397fn paint_of(engine: &mut Engine, span: Span, v: &Value) -> Outcome<Option<Paint>> {
398 match v {
399 Value::None | Value::Auto => Ok(None),
400 Value::Color(c) => Ok(Some(Paint::Color(*c))),
401 Value::Gradient(g) => Ok(Some(Paint::Gradient(g.clone()))),
402 Value::Tiling(t) => Ok(Some(Paint::Tiling(t.clone()))),
403 other => Err(engine.error(DiagnosticKind::Type, span, fmt!("expected color, gradient, tiling, or none, found {}", other.ty().name()))),
404 }
405}
406
407/// A stroke-like value (length, paint or stroke) as a partial stroke.
408fn stroke_of(engine: &mut Engine, span: Span, v: &Value) -> Outcome<Stroke> {
409 match v {
410 Value::Length(l) => Ok(Stroke { thickness: Some(*l), ..Stroke::default() }),
411 Value::Color(_) | Value::Gradient(_) | Value::Tiling(_)
412 => Ok(Stroke { paint: res!(paint_of(engine, span, v)), ..Stroke::default() }),
413 Value::Stroke(s) => Ok((**s).clone()),
414 Value::Dict(d) => stroke_dict(engine, span, d),
415 other => Err(engine.error(DiagnosticKind::Type, span, fmt!(
416 "expected length, color, gradient, tiling, dictionary, or stroke, found {}", other.ty().name()))),
417 }
418}
419
420/// `(paint: .., thickness: .., cap: .., join: .., dash: .., miter-limit: ..)`, the dictionary form of a stroke.
421fn stroke_dict(engine: &mut Engine, span: Span, d: &Dict) -> Outcome<Stroke> {
422 let mut s = Stroke::default();
423 for (k, v) in d.iter() {
424 match k {
425 "paint" => s.paint = res!(paint_of(engine, span, v)),
426 "thickness" => match v {
427 Value::Length(l) => s.thickness = Some(*l),
428 Value::Auto => (),
429 other => return Err(engine.error(DiagnosticKind::Type, span, fmt!("expected length, found {}", other.ty().name()))),
430 },
431 "cap" => s.cap = match v {
432 Value::Str(t) if t.as_str() == "butt" => Some(LineCap::Butt),
433 Value::Str(t) if t.as_str() == "round" => Some(LineCap::Round),
434 Value::Str(t) if t.as_str() == "square" => Some(LineCap::Square),
435 _ => None,
436 },
437 "join" => s.join = match v {
438 Value::Str(t) if t.as_str() == "miter" => Some(LineJoin::Miter),
439 Value::Str(t) if t.as_str() == "round" => Some(LineJoin::Round),
440 Value::Str(t) if t.as_str() == "bevel" => Some(LineJoin::Bevel),
441 _ => None,
442 },
443 "dash" => s.dash = Some(res!(dash_of(engine, span, v))),
444 "miter-limit" => s.miter_limit = match v {
445 Value::Float(f) => Some(*f),
446 Value::Int(i) => Some(*i as f64),
447 _ => None,
448 },
449 other => return Err(engine.error(DiagnosticKind::Type, span, fmt!("unexpected key \"{}\", valid keys are \"paint\", \"thickness\", \"cap\", \"join\", \"dash\", and \"miter-limit\"", other))),
450 }
451 }
452 Ok(s)
453}
454
455fn dash_of(engine: &mut Engine, span: Span, v: &Value) -> Outcome<Option<Dash>> {
456 let pattern = |a: &[f64]| a.iter().map(|x| DashItem::Len(Length::pt(*x))).collect::<Vec<_>>();
457 let named = |s: &str| -> Option<Vec<DashItem>> {
458 Some(match s {
459 "solid" => return None,
460 "dotted" => vec![DashItem::Dot, DashItem::Len(Length::pt(2.0))],
461 "densely-dotted" => vec![DashItem::Dot, DashItem::Len(Length::pt(1.0))],
462 "loosely-dotted" => vec![DashItem::Dot, DashItem::Len(Length::pt(4.0))],
463 "dashed" => pattern(&[3.0, 3.0]),
464 "densely-dashed" => pattern(&[3.0, 2.0]),
465 "loosely-dashed" => pattern(&[3.0, 6.0]),
466 "dash-dotted" => vec![DashItem::Len(Length::pt(3.0)), DashItem::Len(Length::pt(2.0)),
467 DashItem::Dot, DashItem::Len(Length::pt(2.0))],
468 "densely-dash-dotted" => vec![DashItem::Len(Length::pt(3.0)), DashItem::Len(Length::pt(1.0)),
469 DashItem::Dot, DashItem::Len(Length::pt(1.0))],
470 "loosely-dash-dotted" => vec![DashItem::Len(Length::pt(3.0)), DashItem::Len(Length::pt(4.0)),
471 DashItem::Dot, DashItem::Len(Length::pt(4.0))],
472 _ => return None,
473 })
474 };
475 match v {
476 Value::None => Ok(None),
477 Value::Str(s) => Ok(named(s).map(|array| Dash { array, phase: Length::zero() })),
478 Value::Array(a) => {
479 let mut array = Vec::new();
480 for item in a.iter() {
481 match item {
482 Value::Length(l) => array.push(DashItem::Len(*l)),
483 Value::Str(s) if s.as_str() == "dot" => array.push(DashItem::Dot),
484 other => return Err(engine.error(DiagnosticKind::Type, span, fmt!("expected length or \"dot\", found {}", other.ty().name()))),
485 }
486 }
487 Ok(Some(Dash { array, phase: Length::zero() }))
488 }
489 other => Err(engine.error(DiagnosticKind::Type, span, fmt!("expected string, array, dictionary, or none, found {}", other.ty().name()))),
490 }
491}
492
493/// `a` over `b`, part by part: Typst's stroke fold.
494fn fold_stroke(a: &Stroke, b: &Stroke) -> Stroke {
495 Stroke {
496 paint: a.paint.clone().or_else(|| b.paint.clone()),
497 thickness: a.thickness.or(b.thickness),
498 cap: a.cap.or(b.cap),
499 join: a.join.or(b.join),
500 dash: a.dash.clone().or_else(|| b.dash.clone()),
501 miter_limit: a.miter_limit.or(b.miter_limit),
502 }
503}
504
505/// A stroke side as written: unspecified (`None`), explicitly none (`Some(None)`), or a stroke.
506type SideStroke = Option<Option<Stroke>>;
507
508/// A stroke value by side: `none`, a stroke-like value for all four, or a dictionary of sides with `x`,
509/// `y` and `rest`.
510fn sides_stroke(engine: &mut Engine, span: Span, v: &Value) -> Outcome<Sides<SideStroke>> {
511 let one = |engine: &mut Engine, v: &Value| -> Outcome<SideStroke> {
512 match v {
513 Value::None => Ok(Some(None)),
514 v => Ok(Some(Some(res!(stroke_of(engine, span, v))))),
515 }
516 };
517 match v {
518 Value::Auto => Ok(Sides::splat(None)),
519 Value::Dict(d) if is_sides_dict(d) => {
520 let mut s: Sides<SideStroke> = Sides::splat(None);
521 let get = |engine: &mut Engine, k: &str| -> Outcome<SideStroke> {
522 match d.get(k) {
523 Some(v) => one(engine, v),
524 None => Ok(None),
525 }
526 };
527 let rest = res!(get(engine, "rest"));
528 let x = res!(get(engine, "x"));
529 let y = res!(get(engine, "y"));
530 s.left = res!(get(engine, "left")).or_else(|| x.clone()).or_else(|| rest.clone());
531 s.right = res!(get(engine, "right")).or_else(|| x.clone()).or_else(|| rest.clone());
532 s.top = res!(get(engine, "top")).or_else(|| y.clone()).or_else(|| rest.clone());
533 s.bottom = res!(get(engine, "bottom")).or_else(|| y.clone()).or_else(|| rest.clone());
534 Ok(s)
535 }
536 v => Ok(Sides::splat(res!(one(engine, v)))),
537 }
538}
539
540/// `a` over `b` side by side, a stroke over a stroke part by part.
541fn fold_sides(a: &Sides<SideStroke>, b: &Sides<SideStroke>) -> Sides<SideStroke> {
542 let one = |a: &SideStroke, b: &SideStroke| match (a, b) {
543 (Some(Some(x)), Some(Some(y))) => Some(Some(fold_stroke(x, y))),
544 (Some(x), _) => Some(x.clone()),
545 (None, y) => y.clone(),
546 };
547 Sides {
548 left: one(&a.left, &b.left),
549 top: one(&a.top, &b.top),
550 right: one(&a.right, &b.right),
551 bottom: one(&a.bottom, &b.bottom),
552 }
553}
554
555fn is_sides_dict(d: &Dict) -> bool {
556 d.keys().all(|k| matches!(k, "left" | "top" | "right" | "bottom" | "x" | "y" | "rest"))
557}
558
559fn sides_inset(engine: &mut Engine, span: Span, v: &Value) -> Outcome<Sides<Option<Relative>>> {
560 let rel = |engine: &mut Engine, v: &Value| -> Outcome<Option<Relative>> {
561 match v {
562 Value::Length(l) => Ok(Some(Relative { rel: Ratio(0.0), abs: *l })),
563 Value::Ratio(r) => Ok(Some(Relative { rel: *r, abs: Length::zero() })),
564 Value::Relative(r) => Ok(Some(*r)),
565 Value::None => Ok(Some(Relative::default())),
566 other => Err(engine.error(DiagnosticKind::Type, span, fmt!("expected relative length, found {}", other.ty().name()))),
567 }
568 };
569 match v {
570 Value::Auto => Ok(Sides::splat(None)),
571 Value::Dict(d) => {
572 let get = |engine: &mut Engine, k: &str| -> Outcome<Option<Relative>> {
573 match d.get(k) {
574 Some(v) => rel(engine, v),
575 None => Ok(None),
576 }
577 };
578 let rest = res!(get(engine, "rest"));
579 let x = res!(get(engine, "x"));
580 let y = res!(get(engine, "y"));
581 Ok(Sides {
582 left: res!(get(engine, "left")).or(x).or(rest),
583 right: res!(get(engine, "right")).or(x).or(rest),
584 top: res!(get(engine, "top")).or(y).or(rest),
585 bottom: res!(get(engine, "bottom")).or(y).or(rest),
586 })
587 }
588 v => Ok(Sides::splat(res!(rel(engine, v)))),
589 }
590}
591
592fn align_of(engine: &mut Engine, span: Span, v: &Value) -> Outcome<Alignment> {
593 match v {
594 Value::Auto | Value::None => Ok(Alignment::default()),
595 Value::Alignment(a) => Ok(*a),
596 other => Err(engine.error(DiagnosticKind::Type, span, fmt!("expected alignment or auto, found {}", other.ty().name()))),
597 }
598}
599
600fn rel_value(r: Relative) -> Value {
601 if r.rel.0 == 0.0 {
602 Value::Length(r.abs)
603 } else {
604 Value::Relative(r)
605 }
606}
607
608fn side_stroke_value(s: &Option<Stroke>) -> Value {
609 match s {
610 Some(s) => Value::Stroke(Arc::new(s.clone())),
611 None => Value::None,
612 }
613}
614
615/// Grows the occupancy map to `rows` rows.
616fn ensure_rows(occ: &mut Vec<Option<usize>>, cols: usize, rows: usize) {
617 if occ.len() < cols * rows {
618 occ.resize(cols * rows, None);
619 }
620}
621
622fn is_free(occ: &[Option<usize>], i: usize) -> bool {
623 occ.get(i).map(|s| s.is_none()).unwrap_or(true)
624}
625
626/// A child cell's position and spans before its properties are resolved.
627struct Placing {
628 elem: Content,
629 x: usize,
630 y: usize,
631 colspan: usize,
632 rowspan: usize,
633}
634
635/// Places one cell by Typst's rules: both coordinates fixed; x fixed, the first free row in that column;
636/// y fixed, the first free column in that row; neither, the first free slot from the automatic index,
637/// never wrapping a colspan to the next row.
638#[allow(clippy::too_many_arguments)]
639fn place_cell(
640 engine: &mut Engine,
641 styles: &StyleChain,
642 c: usize,
643 occ: &mut Vec<Option<usize>>,
644 auto: &mut usize,
645 first: usize,
646 placed: &mut Vec<Placing>,
647 elem: Content,
648)
649 -> Outcome<()>
650{
651 let span = elem.span();
652 let fx = int_of(&res!(schema::resolve(styles, &elem, fid::X)));
653 let fy = int_of(&res!(schema::resolve(styles, &elem, fid::Y)));
654 let colspan = int_of(&res!(schema::resolve(styles, &elem, fid::COLSPAN))).unwrap_or(1).max(1) as usize;
655 let rowspan = int_of(&res!(schema::resolve(styles, &elem, fid::ROWSPAN))).unwrap_or(1).max(1) as usize;
656 for v in [fx, fy].into_iter().flatten() {
657 if v < 0 {
658 return Err(engine.error(DiagnosticKind::Type, span, "number must be at least zero"));
659 }
660 }
661 let index = match (fx, fy) {
662 (Some(x), Some(y)) => {
663 let (x, y) = (x as usize, y as usize);
664 if x >= c {
665 return Err(engine.error(DiagnosticKind::Type, span, fmt!("cell could not be placed at invalid column {}", x)));
666 }
667 let i = y * c + x;
668 if !is_free(occ, i) {
669 return Err(engine.error_hint(DiagnosticKind::Type, span,
670 fmt!("attempted to place a second cell at column {}, row {}", x, y),
671 "try specifying your cells in a different order"));
672 }
673 i
674 }
675 (Some(x), None) => {
676 let x = x as usize;
677 if x >= c {
678 return Err(engine.error(DiagnosticKind::Type, span, fmt!("cell could not be placed at invalid column {}", x)));
679 }
680 // Within a header or footer the search starts at its first row.
681 let mut y = first;
682 while !is_free(occ, y * c + x) {
683 y += 1;
684 }
685 y * c + x
686 }
687 (None, Some(y)) => {
688 let y = y as usize;
689 match (0..c).find(|x| is_free(occ, y * c + x)) {
690 Some(x) => y * c + x,
691 None => return Err(engine.error_hint(DiagnosticKind::Type, span,
692 fmt!("cell could not be placed in row {} because it was full", y),
693 "try specifying your cells in a different order")),
694 }
695 }
696 (None, None) => {
697 let mut i = *auto;
698 while !is_free(occ, i) {
699 i += 1;
700 }
701 i
702 }
703 };
704 let (x, y) = (index % c, index / c);
705 if colspan > c - x {
706 return Err(engine.error_hint(DiagnosticKind::Type, span,
707 "cell's colspan would cause it to exceed the available column(s)",
708 "try placing the cell in another position or reducing its colspan"));
709 }
710 ensure_rows(occ, c, y + rowspan);
711 for dy in 0..rowspan {
712 for dx in 0..colspan {
713 let j = (y + dy) * c + x + dx;
714 if let Some(Some(_)) = occ.get(j) {
715 return Err(engine.error_hint(DiagnosticKind::Type, span,
716 fmt!("cell would span a previously placed cell at column {}, row {}", x + dx, y + dy),
717 "try specifying your cells in a different order or reducing the cell's rowspan or colspan"));
718 }
719 }
720 }
721 let n = placed.len();
722 for dy in 0..rowspan {
723 for dx in 0..colspan {
724 if let Some(s) = occ.get_mut((y + dy) * c + x + dx) {
725 *s = Some(n);
726 }
727 }
728 }
729 if fx.is_none() && fy.is_none() {
730 // A full-width cell leaves no room beside it, so its rowspan pushes the automatic index down too.
731 *auto = if colspan == c { index + colspan * rowspan } else { index + colspan };
732 }
733 placed.push(Placing { elem, x, y, colspan, rowspan });
734 Ok(())
735}
736
737/// An `hline` or `vline` as found, before the row count is known.
738struct PendingLine {
739 vertical: bool,
740 at: usize,
741 start: usize,
742 end: Option<usize>,
743 stroke: Option<Stroke>,
744 after: bool, // `position: bottom` or `end`: before the gutter rather than after it
745 span: Span,
746}
747
748fn pending_line(
749 engine: &mut Engine,
750 styles: &StyleChain,
751 elem: &Content,
752 vertical: bool,
753 c: usize,
754 auto: usize,
755)
756 -> Outcome<PendingLine>
757{
758 let span = elem.span();
759 let at = match res!(schema::resolve(styles, elem, fid::LINE_AT)) {
760 Value::Int(i) if i >= 0 => i as usize,
761 Value::Int(_) => return Err(engine.error(DiagnosticKind::Type, span, "number must be at least zero")),
762 // After the latest automatically positioned cell: below its row, or right of it.
763 _ if vertical => if auto == 0 { 0 } else { (auto - 1) % c + 1 },
764 _ => auto.div_ceil(c),
765 };
766 let start = match res!(schema::resolve(styles, elem, fid::LINE_START)) {
767 Value::Int(i) if i >= 0 => i as usize,
768 _ => 0,
769 };
770 let end = match res!(schema::resolve(styles, elem, fid::LINE_END)) {
771 Value::Int(i) if i >= 0 => Some(i as usize),
772 _ => None,
773 };
774 // A line's stroke is not folded with its default: parts it leaves unset come from the cell strokes it
775 // overrides (`hline(stroke: red)` over a 1.5pt cell edge draws red at 1.5pt, as in Typst).
776 let stroke = match res!(schema::resolve(styles, elem, fid::LINE_STROKE)) {
777 Value::None => None,
778 v => Some(res!(stroke_of(engine, span, &v))),
779 };
780 let after = match res!(schema::resolve(styles, elem, fid::LINE_POS)) {
781 Value::Alignment(a) => match (vertical, a.x, a.y) {
782 (true, Some(crate::eval::value::HAlign::End), _) => true,
783 (true, Some(crate::eval::value::HAlign::Right), _) => true,
784 (false, _, Some(crate::eval::value::VAlign::Bottom)) => true,
785 _ => false,
786 },
787 _ => false,
788 };
789 Ok(PendingLine { vertical, at, start, end, stroke, after, span })
790}
791
792/// Places every child and resolves every cell's properties.
793pub fn resolve(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<CellGrid> {
794 let span = elem.span();
795 let kind = match elem.kind() {
796 Some(k @ (ElemKind::Grid | ElemKind::Table)) => k,
797 _ => return Err(err!("layout_grid expects a grid or table element, found {:?}", elem.kind(); Input, Invalid)),
798 };
799 let (_, head_k, foot_k, hline_k, vline_k) = schema::family_of(kind);
800 let font_pt = font_size_pt(styles);
801
802 let sizings = |engine: &mut Engine, id| -> Outcome<Vec<Sizing>> {
803 match res!(schema::resolve(styles, elem, id)) {
804 Value::Array(a) => {
805 let mut out = Vec::new();
806 for v in a.iter() {
807 match Sizing::from_value(v) {
808 Some(s) => out.push(s),
809 None => return Err(engine.error(DiagnosticKind::Type, span, fmt!(
810 "expected auto, relative length, or fraction, found {}", v.ty().name()))),
811 }
812 }
813 Ok(out)
814 }
815 Value::Int(n) if n >= 0 => Ok(vec![Sizing::Auto; n as usize]),
816 v => match Sizing::from_value(&v) {
817 Some(s) => Ok(vec![s]),
818 None => Ok(Vec::new()),
819 },
820 }
821 };
822 let col_t = res!(sizings(engine, fid::COLUMNS));
823 let row_t = res!(sizings(engine, fid::ROWS));
824 let col_g = res!(sizings(engine, fid::COL_GUTTER));
825 let row_g = res!(sizings(engine, fid::ROW_GUTTER));
826 let c = col_t.len().max(1);
827
828 let children = match res!(schema::resolve(styles, elem, fid::CHILDREN)) {
829 Value::Array(a) => a,
830 _ => Arc::new(Vec::new()),
831 };
832
833 let mut occ: Vec<Option<usize>> = Vec::new();
834 let mut placed: Vec<Placing> = Vec::new();
835 let mut pending: Vec<PendingLine> = Vec::new();
836 let mut sections: Vec<Section> = Vec::new();
837 let mut auto = 0usize;
838
839 for child in children.iter() {
840 let child = match child {
841 Value::Content(ch) => ch.clone(),
842 _ => continue,
843 };
844 let k = match child.kind() {
845 Some(k) => k,
846 None => continue, // construction wraps every non-element child in a cell
847 };
848 if k == hline_k || k == vline_k {
849 pending.push(res!(pending_line(engine, styles, &child, k == vline_k, c, auto)));
850 } else if k == head_k || k == foot_k {
851 let is_head = k == head_k;
852 // A header or footer starts on the first wholly free row at or after the automatic position.
853 let mut row = auto.div_ceil(c);
854 while (0..c).any(|x| !is_free(&occ, row * c + x)) {
855 row += 1;
856 }
857 let first = placed.len();
858 let mut local = row * c;
859 let at = if is_head { fid::HEAD_CHILDREN } else { fid::FOOT_CHILDREN };
860 let parts = match res!(schema::resolve(styles, &child, at)) {
861 Value::Array(a) => a,
862 _ => Arc::new(Vec::new()),
863 };
864 for p in parts.iter() {
865 if let Value::Content(pc) = p {
866 match pc.kind() {
867 Some(pk) if pk == hline_k || pk == vline_k => pending.push(
868 res!(pending_line(engine, styles, pc, pk == vline_k, c, local))),
869 _ => res!(place_cell(engine, styles, c, &mut occ, &mut local, row, &mut placed, pc.clone())),
870 }
871 }
872 }
873 let end = placed[first..].iter().map(|p| p.y + p.rowspan).max().unwrap_or(row).max(row);
874 let start = placed[first..].iter().map(|p| p.y).min().unwrap_or(row).min(row);
875 let repeat = matches!(res!(schema::resolve(styles, &child, fid::REPEAT)), Value::Bool(true));
876 let part = if is_head {
877 let level = int_of(&res!(schema::resolve(styles, &child, fid::LEVEL))).unwrap_or(1);
878 Part::Header { level, repeat }
879 } else {
880 Part::Footer { repeat }
881 };
882 sections.push(Section { start, end, part });
883 auto = end * c;
884 } else {
885 res!(place_cell(engine, styles, c, &mut occ, &mut auto, 0, &mut placed, child));
886 }
887 }
888
889 let mut n_rows = row_t.len();
890 for p in &placed {
891 n_rows = n_rows.max(p.y + p.rowspan);
892 }
893 for s in &sections {
894 n_rows = n_rows.max(s.end);
895 }
896 for s in &sections {
897 if let Part::Footer { .. } = s.part {
898 if s.end != n_rows {
899 return Err(engine.error(DiagnosticKind::Type, span, "footer must end at the last row"));
900 }
901 }
902 }
903
904 // Every slot no cell covers holds an empty cell, as in Typst: it takes the grid's inset, fill and
905 // stroke like any other.
906 let (cell_k, ..) = schema::family_of(kind);
907 ensure_rows(&mut occ, c, n_rows);
908 for i in 0..c * n_rows {
909 if is_free(&occ, i) {
910 let empty = Content::new(cell_k, vec![(fid::BODY, Value::Content(Content::empty()))], span);
911 placed.push(Placing { elem: empty, x: i % c, y: i / c, colspan: 1, rowspan: 1 });
912 }
913 }
914
915 // Tracks: a missing size repeats the last given, else auto for content and zero for gutter.
916 let gutter = !col_g.is_empty() || !row_g.is_empty();
917 let zero = Sizing::Rel(Relative::default());
918 let pick = |v: &[Sizing], i: usize, d: Sizing| v.get(i).or(v.last()).copied().unwrap_or(d);
919 let mut cols = Vec::new();
920 for x in 0..c {
921 cols.push(pick(&col_t, x, Sizing::Auto));
922 if gutter && x + 1 < c {
923 cols.push(pick(&col_g, x, zero));
924 }
925 }
926 let mut rows = Vec::new();
927 for y in 0..n_rows {
928 rows.push(pick(&row_t, y, Sizing::Auto));
929 if gutter && y + 1 < n_rows {
930 rows.push(pick(&row_g, y, zero));
931 }
932 }
933
934 // Properties: the cell's own value, else the grid's resolved at the cell's position.
935 let g_fill = res!(schema::resolve(styles, elem, fid::FILL));
936 let g_align = res!(schema::resolve(styles, elem, fid::ALIGN));
937 let g_inset = res!(schema::resolve(styles, elem, fid::INSET));
938 let inset_default = match kind {
939 ElemKind::Table => Some(Relative { rel: Ratio(0.0), abs: Length::pt(5.0) }),
940 _ => None,
941 };
942 let g_stroke = res!(schema::resolve(styles, elem, fid::STROKE));
943 // A table's side left unspecified is a stroke with no part set: drawn as `1pt + black`, but in a fold
944 // at a shared edge it yields every part to the neighbour's specified stroke. So `stroke: (bottom:
945 // olive)` draws olive between rows and black only where no neighbour speaks, as Typst does.
946 let stroke_default: Sides<SideStroke> = match kind {
947 ElemKind::Table => Sides::splat(Some(Some(Stroke::default()))),
948 _ => Sides::splat(None),
949 };
950 let mut cells = Vec::with_capacity(placed.len());
951 // Each cell is realised at a place of its own under the grid's, so that the measurements and the layout of
952 // a cell, and a layout of the grid again, locate what is in it alike.
953 let mut places = elem.place().map(Locator::new);
954 for p in placed {
955 let cspan = p.elem.span();
956 let mut el = p.elem;
957 if let (Some(l), Some(k)) = (places.as_mut(), el.kind()) {
958 el.set_place(l.next(k, el.shell()));
959 }
960 let fill = match res!(schema::resolve(styles, &el, fid::CELL_FILL)) {
961 Value::Auto => {
962 let v = res!(celled(engine, &g_fill, p.x, p.y, cspan));
963 res!(paint_of(engine, cspan, &v))
964 }
965 v => res!(paint_of(engine, cspan, &v)),
966 };
967 let own_a = res!(align_of(engine, cspan, &res!(schema::resolve(styles, &el, fid::CELL_ALIGN))));
968 let grid_a = {
969 let v = res!(celled(engine, &g_align, p.x, p.y, cspan));
970 res!(align_of(engine, cspan, &v))
971 };
972 let align = Alignment { x: own_a.x.or(grid_a.x), y: own_a.y.or(grid_a.y) };
973 let own_i = res!(sides_inset(engine, cspan, &res!(schema::resolve(styles, &el, fid::CELL_INSET))));
974 let grid_i = {
975 let v = res!(celled(engine, &g_inset, p.x, p.y, cspan));
976 res!(sides_inset(engine, cspan, &v))
977 };
978 // A side of a table's inset that nothing specifies keeps the default 5 pt: `inset: (y: 8pt)` folds over it.
979 let side = |own: Option<Relative>, grid: Option<Relative>| own.or(grid).or(inset_default).unwrap_or_default();
980 let inset = Sides {
981 left: side(own_i.left, grid_i.left),
982 top: side(own_i.top, grid_i.top),
983 right: side(own_i.right, grid_i.right),
984 bottom: side(own_i.bottom, grid_i.bottom),
985 };
986 let own_s = res!(sides_stroke(engine, cspan, &res!(schema::resolve(styles, &el, fid::CELL_STROKE))));
987 let grid_s = {
988 let v = res!(celled(engine, &g_stroke, p.x, p.y, cspan));
989 let s = res!(sides_stroke(engine, cspan, &v));
990 match &g_stroke {
991 Value::Func(_) | Value::Array(_) => s,
992 _ => fold_sides(&s, &stroke_default),
993 }
994 };
995 let folded = fold_sides(&own_s, &grid_s);
996 let stroke = Sides {
997 left: folded.left.flatten(),
998 top: folded.top.flatten(),
999 right: folded.right.flatten(),
1000 bottom: folded.bottom.flatten(),
1001 };
1002 let prio = |s: &SideStroke| matches!(s, Some(Some(_)));
1003 let prioritised = Sides {
1004 left: prio(&own_s.left),
1005 top: prio(&own_s.top),
1006 right: prio(&own_s.right),
1007 bottom: prio(&own_s.bottom),
1008 };
1009
1010 // Written back, so `show table.cell: it => ..` reads the resolved values as in Typst.
1011 el.set(fid::X, Value::Int(p.x as i64));
1012 el.set(fid::Y, Value::Int(p.y as i64));
1013 el.set(fid::COLSPAN, Value::Int(p.colspan as i64));
1014 el.set(fid::ROWSPAN, Value::Int(p.rowspan as i64));
1015 el.set(fid::CELL_FILL, match &fill {
1016 Some(Paint::Color(c)) => Value::Color(*c),
1017 Some(Paint::Gradient(g)) => Value::Gradient(g.clone()),
1018 Some(Paint::Tiling(t)) => Value::Tiling(t.clone()),
1019 None => Value::None,
1020 });
1021 el.set(fid::CELL_ALIGN, if align == Alignment::default() { Value::Auto } else { Value::Alignment(align) });
1022 let mut d = Dict::new();
1023 d.insert("top", rel_value(inset.top));
1024 d.insert("right", rel_value(inset.right));
1025 d.insert("bottom", rel_value(inset.bottom));
1026 d.insert("left", rel_value(inset.left));
1027 el.set(fid::CELL_INSET, Value::dict(d));
1028 let mut d = Dict::new();
1029 d.insert("top", side_stroke_value(&stroke.top));
1030 d.insert("right", side_stroke_value(&stroke.right));
1031 d.insert("bottom", side_stroke_value(&stroke.bottom));
1032 d.insert("left", side_stroke_value(&stroke.left));
1033 el.set(fid::CELL_STROKE, Value::dict(d));
1034
1035 cells.push(Cell {
1036 x: p.x, y: p.y, colspan: p.colspan, rowspan: p.rowspan, elem: el,
1037 fill, stroke, prioritised, inset, align,
1038 });
1039 }
1040
1041 let mut grid = CellGrid {
1042 cols, rows, gutter, n_cols: c, n_rows, cells,
1043 hlines: Vec::new(), vlines: Vec::new(), sections, font_pt, span, parents: Vec::new(),
1044 };
1045
1046 // Parents over tracks.
1047 let (w, h) = (grid.cols.len(), grid.rows.len());
1048 let mut parents = vec![None; w * h];
1049 for (i, cell) in grid.cells.iter().enumerate() {
1050 let ((x0, x1), (y0, y1)) = grid.cell_tracks(cell);
1051 for yt in y0..y1 {
1052 for xt in x0..x1 {
1053 if let Some(s) = parents.get_mut(yt * w + xt) {
1054 *s = Some(i);
1055 }
1056 }
1057 }
1058 }
1059 grid.parents = parents;
1060
1061 // Lines into track coordinates.
1062 for l in pending {
1063 let (limit, other) = if l.vertical { (c, n_rows) } else { (n_rows, c) };
1064 if l.at > limit {
1065 let what = if l.vertical { "vertical line at invalid column" } else { "horizontal line at invalid row" };
1066 return Err(engine.error(DiagnosticKind::Type, l.span, fmt!("cannot place {} {}", what, l.at)));
1067 }
1068 let end = l.end.unwrap_or(other).min(other);
1069 if l.start >= end {
1070 continue;
1071 }
1072 let at = if l.at == limit {
1073 if l.vertical { grid.cols.len() } else { grid.rows.len() }
1074 } else if l.after {
1075 // `bottom` or `end`: after row or column `at`, before the gutter that follows it.
1076 grid.track(l.at) + 1
1077 } else {
1078 grid.track(l.at)
1079 };
1080 let (s, e) = grid.track_span(l.start, end - l.start);
1081 let line = Line { at, start: s, end: e, stroke: l.stroke };
1082 if l.vertical {
1083 grid.vlines.push(line);
1084 } else {
1085 grid.hlines.push(line);
1086 }
1087 }
1088 Ok(grid)
1089}
1090
1091// Planning
1092
1093/// A cell set at its place, in the grid's own frame (top left origin, y down).
1094#[derive(Clone, Debug)]
1095pub struct PlacedCell {
1096 pub index: usize, // into `CellGrid::cells`
1097 pub x: Sp,
1098 pub y: Sp,
1099 pub w: Sp,
1100 pub h: Sp,
1101 pub nodes: Vec<Node>,
1102}
1103
1104#[derive(Clone, Debug)]
1105pub struct FillRect {
1106 pub x: Sp,
1107 pub y: Sp,
1108 pub w: Sp,
1109 pub h: Sp,
1110 pub paint: Paint,
1111}
1112
1113/// One drawn line segment, its ends already extended by half its thickness as Typst draws them.
1114#[derive(Clone, Debug)]
1115pub struct Segment {
1116 pub vertical: bool,
1117 pub at: Sp, // x of a vertical segment, y of a horizontal one
1118 pub from: Sp,
1119 pub to: Sp,
1120 pub pen: Pen,
1121}
1122
1123/// Rows that stay together: tracks `start..end`, never split by a page break.
1124#[derive(Clone, Debug)]
1125pub struct Group {
1126 pub start: usize,
1127 pub end: usize,
1128 pub part: Part,
1129 pub top: Sp,
1130 pub height: Sp,
1131 pub cells: Vec<PlacedCell>,
1132 pub fills: Vec<FillRect>,
1133 pub lines: Vec<Segment>,
1134}
1135
1136/// The grid laid out: track sizes and the row groups, in the grid's frame.
1137#[derive(Clone, Debug)]
1138pub struct GridPlan {
1139 pub width: Sp,
1140 pub cols: Vec<Sp>,
1141 pub rows: Vec<Sp>,
1142 pub groups: Vec<Group>,
1143}
1144
1145fn rel_sp(r: &Relative, whole: Sp, font_pt: f64) -> Sp {
1146 Sp::from_pt(r.resolve(whole.to_pt(), font_pt))
1147}
1148
1149fn sum(v: &[Sp]) -> Sp {
1150 v.iter().fold(Sp::ZERO, |a, b| a + *b)
1151}
1152
1153fn share(total: Sp, part: f64, whole: f64) -> Sp {
1154 if whole <= 0.0 {
1155 return Sp::ZERO;
1156 }
1157 Sp((total.0 as f64 * part / whole).round() as i32)
1158}
1159
1160/// Sizes every track and sets every cell, then groups the rows and resolves fills and lines.
1161pub fn plan<L: CellLayout>(
1162 engine: &mut Engine,
1163 grid: &CellGrid,
1164 styles: &StyleChain,
1165 region: Region,
1166 cells: &mut L,
1167)
1168 -> Outcome<GridPlan>
1169{
1170 let fpt = grid.font_pt;
1171 let cols = res!(size_columns(engine, grid, styles, region, cells));
1172 let width = sum(&cols);
1173 let rows = res!(size_rows(engine, grid, styles, region, &cols, cells));
1174
1175 let mut xs = vec![Sp::ZERO];
1176 for w in &cols {
1177 let last = xs.last().copied().unwrap_or(Sp::ZERO);
1178 xs.push(last + *w);
1179 }
1180 let mut ys = vec![Sp::ZERO];
1181 for h in &rows {
1182 let last = ys.last().copied().unwrap_or(Sp::ZERO);
1183 ys.push(last + *h);
1184 }
1185 let at = |v: &[Sp], i: usize| v.get(i).copied().unwrap_or(Sp::ZERO);
1186
1187 // Groups: header and footer sections whole, then body rows welded by any rowspan crossing them. A
1188 // gutter track between groups belongs to neither: it is the glue the page may break at.
1189 let mut groups: Vec<Group> = Vec::new();
1190 let section_of = |yt: usize| grid.sections.iter().find(|s| {
1191 let (a, b) = grid.track_span(s.start, (s.end - s.start).max(1));
1192 s.end > s.start && yt >= a && yt < b
1193 });
1194 let mut yt = 0;
1195 while yt < grid.rows.len() {
1196 if grid.gutter && yt % 2 == 1 {
1197 yt += 1;
1198 continue;
1199 }
1200 let (mut end, part) = match section_of(yt) {
1201 Some(s) => (grid.track_span(s.start, s.end - s.start).1, s.part),
1202 None => (yt + 1, Part::Body),
1203 };
1204 // Extend over any rowspan that crosses the group's lower boundary.
1205 loop {
1206 let mut grown = end;
1207 for c in &grid.cells {
1208 let (_, (y0, y1)) = grid.cell_tracks(c);
1209 if y0 < end && y1 > end && y0 >= yt {
1210 grown = grown.max(y1);
1211 }
1212 }
1213 if grown == end {
1214 break;
1215 }
1216 end = grown;
1217 }
1218 groups.push(Group {
1219 start: yt, end, part, top: at(&ys, yt), height: at(&ys, end) - at(&ys, yt),
1220 cells: Vec::new(), fills: Vec::new(), lines: Vec::new(),
1221 });
1222 yt = end;
1223 }
1224
1225 for g in groups.iter_mut() {
1226 for (i, c) in grid.cells.iter().enumerate() {
1227 let ((x0, x1), (y0, y1)) = grid.cell_tracks(c);
1228 if y0 < g.start || y0 >= g.end {
1229 continue;
1230 }
1231 let (x, y) = (at(&xs, x0), at(&ys, y0));
1232 let (w, h) = (at(&xs, x1) - x, at(&ys, y1) - y);
1233 if let Some(paint) = &c.fill {
1234 g.fills.push(FillRect { x, y, w, h, paint: paint.clone() });
1235 }
1236 let r = Region { width: w, height: h, base: (w, h), expand_x: true, expand_y: true };
1237 let nodes = res!(cells.layout(engine, &c.elem, styles, r));
1238 g.cells.push(PlacedCell { index: i, x, y, w, h, nodes });
1239 }
1240 // Vertical lines first, horizontal over them, as Typst draws. A group also inks the row gutter below
1241 // it, which only an explicit line crosses: the gutter is glue, and glue carries no ink.
1242 let mut ink_end = g.end;
1243 while ink_end < grid.rows.len() && grid.gutter && ink_end % 2 == 1 {
1244 ink_end += 1;
1245 }
1246 for bx in 0..=grid.cols.len() {
1247 let mut run: Option<(usize, Pen)> = None;
1248 for yt in g.start..=ink_end {
1249 let pen = if yt < ink_end { vline_pen(grid, bx, yt, fpt) } else { None };
1250 run = flush(run, pen, yt, &mut g.lines, |a, b, p| Segment {
1251 vertical: true, at: at(&xs, bx),
1252 from: at(&ys, a) - half(p.thickness), to: at(&ys, b) + half(p.thickness), pen: p,
1253 });
1254 }
1255 }
1256 for by in g.start..=g.end {
1257 let mut run: Option<(usize, Pen)> = None;
1258 for xt in 0..=grid.cols.len() {
1259 let pen = if xt < grid.cols.len() { hline_pen(grid, by, xt, fpt) } else { None };
1260 run = flush(run, pen, xt, &mut g.lines, |a, b, p| Segment {
1261 vertical: false, at: at(&ys, by),
1262 from: at(&xs, a) - half(p.thickness), to: at(&xs, b) + half(p.thickness), pen: p,
1263 });
1264 }
1265 }
1266 }
1267 Ok(GridPlan { width, cols, rows, groups })
1268}
1269
1270fn half(t: Sp) -> Sp { Sp(t.0 / 2) }
1271
1272/// Extends the current run of equal pens, or closes it into a segment and starts another.
1273fn flush<F: Fn(usize, usize, Pen) -> Segment>(
1274 run: Option<(usize, Pen)>,
1275 pen: Option<Pen>,
1276 i: usize,
1277 out: &mut Vec<Segment>,
1278 make: F,
1279)
1280 -> Option<(usize, Pen)>
1281{
1282 match (run, pen) {
1283 (Some((a, p)), Some(q)) if p.same(&q) => Some((a, p)),
1284 (Some((a, p)), next) => {
1285 out.push(make(a, i, p));
1286 next.map(|q| (i, q))
1287 }
1288 (None, next) => next.map(|q| (i, q)),
1289 }
1290}
1291
1292fn pen_of(s: &Stroke, font_pt: f64) -> Option<Pen> {
1293 let thickness = Sp::from_pt(s.thickness.map(|l| l.resolve(font_pt)).unwrap_or(1.0));
1294 if thickness <= Sp::ZERO {
1295 return None;
1296 }
1297 Some(Pen {
1298 paint: s.paint.clone().unwrap_or(Paint::Color(crate::eval::value::Color {
1299 space: crate::eval::value::ColorSpace::Luma, c: [0.0; 4], alpha: 1.0 })),
1300 thickness,
1301 cap: s.cap.unwrap_or(LineCap::Butt),
1302 join: s.join.unwrap_or(LineJoin::Miter),
1303 dash: s.dash.clone().flatten(),
1304 miter: s.miter_limit.unwrap_or(4.0),
1305 })
1306}
1307
1308/// The two cells' strokes at a shared edge: the prioritised one over the other, the later cell winning a
1309/// tie; either alone when the other gives none.
1310fn cell_edge(first: Option<(Option<Stroke>, bool)>, second: Option<(Option<Stroke>, bool)>) -> Option<Stroke> {
1311 let (fs, fp) = first.unwrap_or((None, false));
1312 let (ss, sp) = second.unwrap_or((None, false));
1313 let (hi, lo) = if fp && !sp { (fs, ss) } else { (ss, fs) };
1314 match (hi, lo) {
1315 (Some(a), Some(b)) => Some(fold_stroke(&a, &b)),
1316 (Some(a), None) => Some(a),
1317 (None, b) => b,
1318 }
1319}
1320
1321/// The explicit line at a boundary covering a track, the last given winning.
1322fn explicit<'a>(lines: &'a [Line], at: usize, t: usize) -> Option<&'a Line> {
1323 lines.iter().rev().find(|l| l.at == at && t >= l.start && t < l.end)
1324}
1325
1326fn with_line(line: Option<&Line>, cell: Option<Stroke>) -> Option<Stroke> {
1327 match line {
1328 Some(Line { stroke: Some(s), .. }) => Some(match &cell {
1329 Some(c) => fold_stroke(s, c),
1330 None => s.clone(),
1331 }),
1332 Some(Line { stroke: None, .. }) => None,
1333 None => cell,
1334 }
1335}
1336
1337fn vline_pen(grid: &CellGrid, bx: usize, yt: usize, fpt: f64) -> Option<Pen> {
1338 let w = grid.cols.len();
1339 if bx != 0 && bx != w {
1340 // A colspan through this boundary hides the line there, explicit or not.
1341 // In a gutter the cell that decides is the one past a gutter column and above a gutter row.
1342 let (ax, ay) = if grid.gutter { (bx + bx % 2, yt - yt % 2) } else { (bx, yt) };
1343 if let Some(p) = grid.parent(ax, ay) {
1344 if grid.track(p.x) < bx {
1345 return None;
1346 }
1347 }
1348 }
1349 let left = if bx > 0 { grid.parent(bx - 1, yt).map(|c| (c.stroke.right.clone(), c.prioritised.right)) } else { None };
1350 let right = if bx < w { grid.parent(bx, yt).map(|c| (c.stroke.left.clone(), c.prioritised.left)) } else { None };
1351 let stroke = with_line(explicit(&grid.vlines, bx, yt), cell_edge(left, right));
1352 stroke.and_then(|s| pen_of(&s, fpt))
1353}
1354
1355fn hline_pen(grid: &CellGrid, by: usize, xt: usize, fpt: f64) -> Option<Pen> {
1356 let h = grid.rows.len();
1357 if by != 0 && by != h {
1358 let (ax, ay) = if grid.gutter { (xt - xt % 2, by + by % 2) } else { (xt, by) };
1359 if let Some(p) = grid.parent(ax, ay) {
1360 if grid.track(p.y) < by {
1361 return None;
1362 }
1363 }
1364 }
1365 let above = if by > 0 { grid.parent(xt, by - 1).map(|c| (c.stroke.bottom.clone(), c.prioritised.bottom)) } else { None };
1366 let below = if by < h { grid.parent(xt, by).map(|c| (c.stroke.top.clone(), c.prioritised.top)) } else { None };
1367 let stroke = with_line(explicit(&grid.hlines, by, xt), cell_edge(above, below));
1368 stroke.and_then(|s| pen_of(&s, fpt))
1369}
1370
1371/// Column widths: relative against the region's base, auto from the cells, fractions from what remains.
1372fn size_columns<L: CellLayout>(
1373 engine: &mut Engine,
1374 grid: &CellGrid,
1375 styles: &StyleChain,
1376 region: Region,
1377 cells: &mut L,
1378)
1379 -> Outcome<Vec<Sp>>
1380{
1381 let fpt = grid.font_pt;
1382 let mut rcols = vec![Sp::ZERO; grid.cols.len()];
1383 let mut rel = Sp::ZERO;
1384 let mut fr = 0.0;
1385 for (i, s) in grid.cols.iter().enumerate() {
1386 match s {
1387 Sizing::Auto => (),
1388 Sizing::Rel(r) => {
1389 rcols[i] = rel_sp(r, region.base.0, fpt);
1390 rel += rcols[i];
1391 }
1392 Sizing::Fr(f) => fr += f,
1393 }
1394 }
1395 let available = region.width - rel;
1396 if available < Sp::ZERO {
1397 return Ok(rcols);
1398 }
1399
1400 // Auto columns, left to right; a colspan's excess over what it already covers lands on its last auto.
1401 let mut auto = Sp::ZERO;
1402 let mut count = 0usize;
1403 for x in 0..grid.cols.len() {
1404 if !grid.cols[x].is_auto() {
1405 continue;
1406 }
1407 let mut resolved = Sp::ZERO;
1408 for cell in &grid.cells {
1409 let ((x0, x1), (y0, y1)) = grid.cell_tracks(cell);
1410 if x < x0 || x >= x1 {
1411 continue;
1412 }
1413 let last_auto = (x0..x1).rev().find(|i| grid.cols[*i].is_auto());
1414 if last_auto != Some(x) {
1415 continue;
1416 }
1417 // A cell that spans a fractional column asks nothing of the auto columns: the fraction takes what it needs.
1418 if grid.cols[x0..x1].iter().any(|c| matches!(c, Sizing::Fr(_))) {
1419 continue;
1420 }
1421 // A cell spanning only relative rows knows its height; otherwise the region's is the guess.
1422 let mut height = Sp::ZERO;
1423 let mut fixed = true;
1424 for yt in y0..y1 {
1425 match grid.rows.get(yt) {
1426 Some(Sizing::Rel(r)) => height += rel_sp(r, region.base.1, fpt),
1427 _ => fixed = false,
1428 }
1429 }
1430 if !fixed {
1431 height = region.base.1;
1432 }
1433 let r = Region { width: available, height, base: (available, height), expand_x: false, expand_y: false };
1434 let size = res!(cells.measure(engine, &cell.elem, styles, r));
1435 let covered = sum(&rcols[x0..x1]) - rcols[x];
1436 let need = size.width - covered;
1437 if need > resolved {
1438 resolved = need;
1439 }
1440 }
1441 rcols[x] = resolved;
1442 auto += resolved;
1443 count += 1;
1444 }
1445
1446 let remaining = available - auto;
1447 if remaining >= Sp::ZERO {
1448 if fr > 0.0 {
1449 for (i, s) in grid.cols.iter().enumerate() {
1450 if let Sizing::Fr(f) = s {
1451 rcols[i] = share(remaining, *f, fr);
1452 }
1453 }
1454 }
1455 } else {
1456 shrink_auto(grid, &mut rcols, available, count);
1457 }
1458 Ok(rcols)
1459}
1460
1461/// Typst's fair shrink: auto columns no wider than an equal share keep their width, the rest share what
1462/// is left equally, repeated until nothing changes.
1463fn shrink_auto(grid: &CellGrid, rcols: &mut [Sp], available: Sp, count: usize) {
1464 let mut last;
1465 let mut fair = i64::MIN;
1466 let mut redistribute = available.0 as i64;
1467 let mut overlarge = count as i64;
1468 let mut changed = true;
1469 while changed && overlarge > 0 {
1470 changed = false;
1471 last = fair;
1472 fair = redistribute / overlarge;
1473 for (i, s) in grid.cols.iter().enumerate() {
1474 let w = rcols[i].0 as i64;
1475 if s.is_auto() && w <= fair && w > last {
1476 redistribute -= w;
1477 overlarge -= 1;
1478 changed = true;
1479 }
1480 }
1481 }
1482 for (i, s) in grid.cols.iter().enumerate() {
1483 if s.is_auto() && (rcols[i].0 as i64) > fair {
1484 rcols[i] = Sp(fair as i32);
1485 }
1486 }
1487}
1488
1489/// Row heights: relative against the region's base, auto from the cells (a rowspan's excess on its last
1490/// auto row), fractions sharing what the region has left.
1491fn size_rows<L: CellLayout>(
1492 engine: &mut Engine,
1493 grid: &CellGrid,
1494 styles: &StyleChain,
1495 region: Region,
1496 cols: &[Sp],
1497 cells: &mut L,
1498)
1499 -> Outcome<Vec<Sp>>
1500{
1501 let fpt = grid.font_pt;
1502 let mut rrows = vec![Sp::ZERO; grid.rows.len()];
1503 let mut fr = 0.0;
1504 for (i, s) in grid.rows.iter().enumerate() {
1505 match s {
1506 Sizing::Rel(r) => rrows[i] = rel_sp(r, region.base.1, fpt),
1507 Sizing::Fr(f) => fr += f,
1508 Sizing::Auto => (),
1509 }
1510 }
1511 // Natural heights, measured once per cell at its spanned width.
1512 let mut natural = Vec::with_capacity(grid.cells.len());
1513 for cell in &grid.cells {
1514 let ((x0, x1), (y0, y1)) = grid.cell_tracks(cell);
1515 if !(y0..y1).any(|y| grid.rows[y].is_auto()) {
1516 natural.push(Sp::ZERO);
1517 continue;
1518 }
1519 let w = sum(&cols[x0..x1]);
1520 // The height is not the region's: a row's natural height is its content's, however little room is
1521 // left, and the row is broken where it does not fit.
1522 let r = Region { width: w, height: Sp(i32::MAX), base: (w, region.base.1), expand_x: true, expand_y: false };
1523 let d = res!(cells.measure(engine, &cell.elem, styles, r));
1524 natural.push(d.vextent());
1525 }
1526 for y in 0..grid.rows.len() {
1527 if !grid.rows[y].is_auto() {
1528 continue;
1529 }
1530 let mut h = Sp::ZERO;
1531 for (cell, nat) in grid.cells.iter().zip(&natural) {
1532 let (_, (y0, y1)) = grid.cell_tracks(cell);
1533 if y < y0 || y >= y1 {
1534 continue;
1535 }
1536 let last_auto = (y0..y1).rev().find(|i| grid.rows[*i].is_auto());
1537 if last_auto != Some(y) {
1538 continue;
1539 }
1540 let covered = sum(&rrows[y0..y1]) - rrows[y];
1541 let need = *nat - covered;
1542 if need > h {
1543 h = need;
1544 }
1545 }
1546 rrows[y] = h;
1547 }
1548 if fr > 0.0 {
1549 let remaining = region.height - sum(&rrows);
1550 if remaining > Sp::ZERO {
1551 for (i, s) in grid.rows.iter().enumerate() {
1552 if let Sizing::Fr(f) = s {
1553 rrows[i] = share(remaining, *f, fr);
1554 }
1555 }
1556 }
1557 }
1558 Ok(rrows)
1559}
1560
1561// Lowering
1562
1563fn paint_ink(engine: &mut Engine, span: Span, p: &Paint) -> Outcome<Ink> {
1564 match p {
1565 Paint::Color(c) => Ok(c.to_ink()),
1566 Paint::Gradient(g) => {
1567 // `DrawOp` carries a flat colour only; the first stop stands in, and the loss is said.
1568 engine.warn(DiagnosticKind::Unsupported, span, "gradients in grid fills and strokes are drawn in their first colour");
1569 match g.stops.first() {
1570 Some((c, _)) => Ok(c.to_ink()),
1571 None => Ok(Ink::BLACK),
1572 }
1573 }
1574 Paint::Tiling(_) => {
1575 engine.warn(DiagnosticKind::Unsupported, span, "tilings in grid fills and strokes are not drawn yet");
1576 Ok(Rgba::TRANSPARENT.into())
1577 }
1578 }
1579}
1580
1581fn f(sp: Sp) -> f32 { sp.to_pt() as f32 }
1582
1583fn segment_path(s: &Segment) -> Outcome<Path> {
1584 let mut b = PathBuilder::new();
1585 if s.vertical {
1586 b.move_to(Pt::new(f(s.at), f(s.from)));
1587 b.line_to(Pt::new(f(s.at), f(s.to)));
1588 } else {
1589 b.move_to(Pt::new(f(s.from), f(s.at)));
1590 b.line_to(Pt::new(f(s.to), f(s.at)));
1591 }
1592 b.finish()
1593}
1594
1595/// A drawing the size of a group's box, placed at its top left, which the vertical list then steps back
1596/// over so what follows starts at the same top.
1597fn overlay(ops: Vec<DrawOp>, w: Sp, h: Sp, list: &mut Vec<Node>) {
1598 if ops.is_empty() {
1599 return;
1600 }
1601 list.push(Node::Leaf(Leaf::graphic(Graphic::new(ops, Dims::new(w, h, Sp::ZERO)))));
1602 list.push(Node::Glue(Glue::fixed(-h)));
1603}
1604
1605/// What a cell sets in one part of a row: where it stands across and the nodes it draws.
1606struct CellPart {
1607 x: Sp,
1608 w: Sp,
1609 h: Sp,
1610 nodes: Vec<Node>,
1611}
1612
1613/// One row group as an unbreakable box: its fills, then each cell's content at its place, then its lines.
1614fn group_box(engine: &mut Engine, grid: &CellGrid, plan: &GridPlan, g: &Group) -> Outcome<BoxNode> {
1615 let cells = g.cells.iter().map(|pc| CellPart { x: pc.x, w: pc.w, h: pc.h, nodes: pc.nodes.clone() }).collect();
1616 let ys = g.cells.iter().map(|pc| pc.y - g.top).collect();
1617 part_box(engine, grid, plan, g, cells, ys, g.height, true, true)
1618}
1619
1620/// A part of a row group as a box, `h` tall. A whole group is one part,
1621/// first and last; a row broken across regions has one part for each, taking the fills of its cells and the
1622/// row's lines, a vertical line running the part's height.
1623#[allow(clippy::too_many_arguments)]
1624fn part_box(
1625 engine: &mut Engine,
1626 grid: &CellGrid,
1627 plan: &GridPlan,
1628 g: &Group,
1629 cells: Vec<CellPart>,
1630 ys: Vec<Sp>,
1631 h: Sp,
1632 first: bool,
1633 last: bool,
1634)
1635 -> Outcome<BoxNode>
1636{
1637 let span = grid.span;
1638 let w = plan.width;
1639 let whole = first && last;
1640 let mut list = Vec::new();
1641
1642 let mut ops = Vec::new();
1643 for r in &g.fills {
1644 let c = res!(paint_ink(engine, span, &r.paint));
1645 let (y, rh) = if whole { (r.y - g.top, r.h) } else { (Sp::ZERO, h) };
1646 let path = res!(Path::rect(Bounds::new(f(r.x), f(y), f(r.x + r.w), f(y + rh))));
1647 ops.push(DrawOp::Fill { path, colour: c });
1648 }
1649 overlay(ops, w, h, &mut list);
1650
1651 // Each cell stepped to its place: down, across, its box, then back up to the part's top.
1652 for (pc, y) in cells.iter().zip(ys.iter()) {
1653 let y = *y;
1654 list.push(Node::Glue(Glue::fixed(y)));
1655 let cell = Node::VBox(BoxNode::new(pc.nodes.clone(), Dims::new(pc.w, pc.h, Sp::ZERO)));
1656 list.push(Node::HBox(BoxNode::new(
1657 vec![Node::Glue(Glue::fixed(pc.x)), cell],
1658 Dims::new(pc.x + pc.w, pc.h, Sp::ZERO))));
1659 list.push(Node::Glue(Glue::fixed(-(y + pc.h))));
1660 }
1661
1662 let mut ops = Vec::new();
1663 for s in &g.lines {
1664 let mut s2 = s.clone();
1665 if whole {
1666 if !s.vertical {
1667 s2.at = s.at - g.top;
1668 } else {
1669 s2.from = s.from - g.top;
1670 s2.to = s.to - g.top;
1671 }
1672 } else if s.vertical {
1673 s2.from = if first { s.from - g.top } else { Sp::ZERO };
1674 s2.to = if last { h + (s.to - g.top - g.height) } else { h };
1675 } else if (s.at - g.top).0 * 2 < g.height.0 {
1676 // A part carries the row's top line and its bottom line, each at its own edge, so a break between
1677 // two parts is ruled on both pages.
1678 s2.at = Sp::ZERO;
1679 } else {
1680 s2.at = h;
1681 }
1682 if s.pen.dash.is_some() {
1683 engine.warn(DiagnosticKind::Unsupported, span, "dashed grid lines are drawn solid");
1684 }
1685 let c = res!(paint_ink(engine, span, &s.pen.paint));
1686 ops.push(DrawOp::Stroke { path: res!(segment_path(&s2)), colour: c, width: f(s.pen.thickness) });
1687 }
1688 overlay(ops, w, h, &mut list);
1689 list.push(Node::Glue(Glue::fixed(h)));
1690 Ok(BoxNode::new(list, Dims::new(w, h, Sp::ZERO)))
1691}
1692
1693/// The plan as vertical material. Rows break between groups only; a header is welded to the row after it
1694/// and armed to repeat, a subheader replacing any header of its level or deeper; the footer is welded to
1695/// the row before it.
1696pub fn lower(engine: &mut Engine, grid: &CellGrid, plan: &GridPlan) -> Outcome<Vec<Node>> {
1697 Ok(res!(lower_rows(engine, grid, plan)).0)
1698}
1699
1700/// [`lower`], with for each node the group it is the box of when that group is a single body row that
1701/// may break across regions: an automatically sized row, which Typst breaks where its cells do.
1702pub fn lower_rows(engine: &mut Engine, grid: &CellGrid, plan: &GridPlan) -> Outcome<(Vec<Node>, Vec<Option<usize>>)> {
1703 let mut out: Vec<Node> = Vec::new();
1704 let mut rows: Vec<Option<usize>> = Vec::new();
1705 let mut active: Vec<(i64, BoxNode)> = Vec::new();
1706 let mut armed = false;
1707 let mut weld = false;
1708 let mut prev_end: Option<usize> = None;
1709 for (gi, g) in plan.groups.iter().enumerate() {
1710 let bx = res!(group_box(engine, grid, plan, g));
1711 if let Some(pe) = prev_end {
1712 if matches!(g.part, Part::Footer { .. }) || weld {
1713 out.push(Node::Penalty(Penalty::new(Penalty::INFINITY, false)));
1714 }
1715 let gap = sum(&plan.rows[pe..g.start]);
1716 out.push(Node::Glue(Glue::fixed(gap)));
1717 }
1718 weld = false;
1719 out.push(Node::VBox(bx.clone()));
1720 let breaks = g.part == Part::Body && g.end == g.start + 1 && grid.rows[g.start].is_auto();
1721 rows.resize(out.len() - 1, None);
1722 rows.push(if breaks { Some(gi) } else { None });
1723 if let Part::Header { level, repeat } = g.part {
1724 weld = true;
1725 active.retain(|(l, _)| *l < level);
1726 if repeat {
1727 active.push((level, bx));
1728 }
1729 if !active.is_empty() {
1730 let h = active.iter().fold(Sp::ZERO, |a, (_, b)| a + b.dims.height);
1731 let list = active.iter().map(|(_, b)| Node::VBox(b.clone())).collect();
1732 out.push(Node::RepeatHead(Some(Box::new(BoxNode::new(list, Dims::new(plan.width, h, Sp::ZERO))))));
1733 armed = true;
1734 } else if armed {
1735 out.push(Node::RepeatHead(None));
1736 armed = false;
1737 }
1738 }
1739 prev_end = Some(g.end);
1740 }
1741 if armed {
1742 out.push(Node::RepeatHead(None));
1743 }
1744 rows.resize(out.len(), None);
1745 Ok((out, rows))
1746}