Skip to main content

lightweight_pdf_layout/layoutable/
column.rs

1//! Column: vertical main axis. Splittable (Text/Column children only, per
2//! phase-2 plan step 1), widow/orphan + keep_with_next + forced-page-break
3//! fallback for atomic elements bigger than a page (Grundprinzip 7/9).
4
5use super::shared::{
6    clip_to_fixed_height, line_height_pt, measure_at_width, push_warning, resolve_auto_size, resolve_bound, shrink_and_bound_height,
7    wrap_children, EPS,
8};
9use super::{LayoutCtx, LayoutResult, Layoutable};
10use crate::geometry::{Constraints, Rect, Size};
11use crate::render_node::{align_offset, RenderNode};
12use crate::warnings::{LayoutWarning, LayoutWarningKind};
13use lightweight_pdf_core::{Align, Column, Common, Element};
14
15impl Layoutable for Column {
16    fn measure(&self, ctx: &LayoutCtx, constraints: Constraints) -> Size {
17        // Cross-axis "auto" width is shrink-to-fit (widest child), not
18        // fill-available: `Column::layout` already fills its own children
19        // to the full cross-axis width it's given (see below), but *this*
20        // method answers "how much space does this Column want", which a
21        // `Row` parent needs to distribute flex siblings correctly — always
22        // claiming the full bound here would starve any flex sibling.
23        let (bound_width, inner_width) = resolve_bound(self.common.width, constraints.max_width, self.common.padding);
24        let mut total_height = 0.0f32;
25        let mut max_child_width = 0.0f32;
26        let n = self.children.len();
27        for (i, child) in self.children.iter().enumerate() {
28            if let Element::PageBreak = child {
29                continue;
30            }
31            let (w, h) = if let Element::Spacer(s) = child {
32                (0.0, s.size)
33            } else {
34                let size = measure_at_width(ctx, child, inner_width);
35                (size.width, size.height)
36            };
37            max_child_width = max_child_width.max(w);
38            total_height += h;
39            if i + 1 < n {
40                total_height += self.gap;
41            }
42        }
43        Size {
44            width: self
45                .common
46                .width
47                .unwrap_or((max_child_width + 2.0 * self.common.padding).min(bound_width)),
48            height: resolve_auto_size(self.common.height, total_height, self.common.padding),
49        }
50    }
51
52    fn layout(&self, ctx: &LayoutCtx, area: Rect, warnings: &mut Vec<LayoutWarning>, page: usize) -> LayoutResult {
53        let (inner, bound_height) = shrink_and_bound_height(area, self.common.height, self.common.padding);
54
55        let mut rendered = Vec::new();
56        let mut cursor_y = 0.0f32;
57
58        for (i, child) in self.children.iter().enumerate() {
59            if let Element::PageBreak = child {
60                let remainder_children: Vec<Element> = self.children[i + 1..].to_vec();
61                return finish_page(self, area, cursor_y, rendered, remainder_children, warnings, page);
62            }
63
64            let child_width = child
65                .common()
66                .and_then(|c| c.width)
67                .unwrap_or(inner.width - self.common.padding.min(inner.width));
68            let child_width = if child.common().and_then(|c| c.width).is_some() {
69                child_width
70            } else {
71                inner.width
72            };
73
74            if let Element::Spacer(s) = child {
75                cursor_y += s.size + self.gap;
76                continue;
77            }
78
79            let remaining_height = (bound_height - cursor_y).max(0.0);
80            let natural = measure_at_width(ctx, child, child_width);
81
82            let fits_fully = natural.height <= remaining_height + EPS;
83            let keep_ok = !fits_fully
84                || !child.common().map(|c| c.keep_with_next).unwrap_or(false)
85                || keep_with_next_satisfied(self, ctx, i, child_width, remaining_height - natural.height - self.gap);
86
87            if fits_fully && keep_ok {
88                let child_area = column_child_rect(inner, self.align, cursor_y, child_width, natural.height);
89                match child.layout(ctx, child_area, warnings, page) {
90                    LayoutResult::Fit(node) => {
91                        rendered.push(node);
92                        cursor_y += natural.height + self.gap;
93                    }
94                    // Shouldn't normally happen (it fit), but handle
95                    // defensively: keep what we got, move the rest on.
96                    LayoutResult::Split { current, remainder } => {
97                        let split = ChildSplit {
98                            current,
99                            remainder,
100                            remaining_siblings: &self.children[i + 1..],
101                        };
102                        return split_child_and_finish_page(self, area, cursor_y, rendered, split, warnings, page);
103                    }
104                }
105                continue;
106            }
107
108            // Does not fit fully on this page (or keep_with_next failed).
109            let splittable = matches!(child, Element::Text(_) | Element::Column(_) | Element::Table(_));
110            let min_unit = match child {
111                Element::Text(t) => line_height_pt(&t.style),
112                Element::Table(t) => crate::table::table_min_unit(ctx, t, child_width),
113                _ => natural.height,
114            };
115
116            if cursor_y > EPS && (remaining_height < min_unit - EPS || !keep_ok) {
117                // Not worth attempting here: move this whole child (and
118                // everything after it) to the next page.
119                let mut remainder_children = vec![child.clone()];
120                remainder_children.extend(self.children[i + 1..].to_vec());
121                return finish_page(self, area, cursor_y, rendered, remainder_children, warnings, page);
122            }
123
124            if !splittable {
125                // Either an atomic element that doesn't fit even a full,
126                // empty page (force placement, clip, warn — Grundprinzip
127                // 7), or one whose `keep_with_next` couldn't be honored at
128                // the very start of a page (nothing to defer to, place at
129                // its natural size instead of stretching it).
130                let forced_height = if fits_fully { natural.height } else { remaining_height.max(0.0) };
131                let child_area = column_child_rect(inner, self.align, cursor_y, child_width, forced_height);
132                if let LayoutResult::Fit(node) = child.layout(ctx, child_area, warnings, page) {
133                    rendered.push(node);
134                }
135                if !fits_fully {
136                    push_warning(
137                        warnings,
138                        LayoutWarningKind::ForcedPageBreak,
139                        page,
140                        "atomic element larger than one page",
141                    );
142                }
143                cursor_y += forced_height + self.gap;
144                continue;
145            }
146
147            // Splittable (Text/Column) and we're at/near the top of a
148            // fresh page budget: attempt the real split.
149            let child_area = column_child_rect(inner, self.align, cursor_y, child_width, remaining_height);
150            match child.layout(ctx, child_area, warnings, page) {
151                LayoutResult::Fit(node) => {
152                    rendered.push(node);
153                    cursor_y += natural.height.min(remaining_height) + self.gap;
154                }
155                // `current` may hold real, sized content (the normal case
156                // for a child that partially fits) — folded into `cursor_y`
157                // by the helper so `finish_page` doesn't see a stale
158                // (too-small) cursor and wrongly discard it as "empty".
159                LayoutResult::Split { current, remainder } => {
160                    let split = ChildSplit {
161                        current,
162                        remainder,
163                        remaining_siblings: &self.children[i + 1..],
164                    };
165                    return split_child_and_finish_page(self, area, cursor_y, rendered, split, warnings, page);
166                }
167            }
168        }
169
170        let outer_height = self
171            .common
172            .height
173            .unwrap_or(cursor_y.max(0.0) - self.gap.min(cursor_y) + 2.0 * self.common.padding)
174            .max(0.0);
175        let outer_height = if cursor_y <= EPS { 0.0 } else { outer_height };
176        LayoutResult::Fit(wrap_children(area, outer_height, &self.common, rendered))
177    }
178}
179
180/// Builds a child's placement `Rect` within `Column::layout`'s content
181/// box: cross-axis-aligned (`align`) within `inner`'s width, stacked at
182/// `cursor_y` — all three of `Column::layout`'s placement sites (fits
183/// fully, forced atomic, split attempt) build this identically, differing
184/// only in the height they hand the child.
185fn column_child_rect(inner: Rect, align: Align, cursor_y: f32, child_width: f32, height: f32) -> Rect {
186    let x_offset = align_offset(align, inner.width, child_width);
187    Rect {
188        x: inner.x + x_offset,
189        y: inner.y + cursor_y,
190        width: child_width,
191        height,
192    }
193}
194
195/// A child's `Split` halves plus the siblings still waiting after it — the
196/// data `split_child_and_finish_page` needs, grouped so the function
197/// doesn't need one positional parameter per field (mirrors
198/// `RowRenderParams` in `table.rs`).
199struct ChildSplit<'a> {
200    current: RenderNode,
201    remainder: Element,
202    remaining_siblings: &'a [Element],
203}
204
205/// Handles a child that itself `Split` mid-placement inside
206/// `Column::layout` (both the "fits fully" and "near top of page, real
207/// split attempt" call sites end up here identically): keeps whatever
208/// fit, folds its already-consumed height into `cursor_y`, and ends the
209/// page. `cursor_y` must include `current`'s consumed height — otherwise
210/// `finish_page` sees a stale (too-small) cursor and can wrongly discard
211/// already-rendered content as "empty".
212fn split_child_and_finish_page(
213    col: &Column,
214    area: Rect,
215    cursor_y: f32,
216    mut rendered: Vec<RenderNode>,
217    split: ChildSplit,
218    warnings: &mut Vec<LayoutWarning>,
219    page: usize,
220) -> LayoutResult {
221    let consumed = split.current.height();
222    if !matches!(split.current, RenderNode::Empty) {
223        rendered.push(split.current);
224    }
225    let mut remainder_children = vec![split.remainder];
226    remainder_children.extend(split.remaining_siblings.to_vec());
227    finish_page(col, area, cursor_y + consumed, rendered, remainder_children, warnings, page)
228}
229
230/// Peeks at the sibling right after index `i` to decide whether
231/// `keep_with_next` is satisfiable: does its minimal content (one line for
232/// Text, full natural height otherwise) fit in the space left after
233/// placing the current child?
234fn keep_with_next_satisfied(col: &Column, ctx: &LayoutCtx, i: usize, width: f32, leftover: f32) -> bool {
235    let Some(next) = col.children.get(i + 1) else {
236        return true;
237    };
238    let min_needed = match next {
239        Element::Text(t) => line_height_pt(&t.style),
240        Element::Spacer(s) => s.size,
241        _ => measure_at_width(ctx, next, width).height,
242    };
243    leftover + EPS >= min_needed
244}
245
246/// Ends the current page's placement for a `Column`. An auto-sized/
247/// pagination-driven `Column` (no explicit `.height()`) produces a real
248/// `Split` so the remainder continues on the next page. A `Column` with an
249/// explicit fixed height instead clips right here and stays a `Fit` — its
250/// overflow is governed by `overflow`/Grundprinzip 3, not by pagination
251/// (mirrors the same distinction made for `Text`, see `layout_fixed_overflow`).
252fn finish_page(
253    col: &Column,
254    outer_area: Rect,
255    cursor_y: f32,
256    rendered: Vec<RenderNode>,
257    remainder_children: Vec<Element>,
258    warnings: &mut Vec<LayoutWarning>,
259    page: usize,
260) -> LayoutResult {
261    if let Some(fixed_height) = col.common.height {
262        let overflow_hint = (!remainder_children.is_empty()).then_some("Column content exceeds its fixed height");
263        return clip_to_fixed_height(outer_area, fixed_height, &col.common, rendered, warnings, page, overflow_hint);
264    }
265
266    let outer_height = if cursor_y <= EPS {
267        0.0
268    } else {
269        (cursor_y - col.gap.min(cursor_y) + 2.0 * col.common.padding).max(0.0)
270    };
271    let current = wrap_children(outer_area, outer_height, &col.common, rendered);
272    let remainder = Column {
273        children: remainder_children,
274        gap: col.gap,
275        align: col.align,
276        common: Common {
277            height: None,
278            ..col.common
279        },
280    };
281    LayoutResult::Split {
282        current: if cursor_y <= EPS { RenderNode::Empty } else { current },
283        remainder: Element::Column(remainder),
284    }
285}