1
//! Page-break analysis as a standalone, pure computation.
2
//!
3
//! Extracted from `display_list.rs::calculate_page_break_positions` so that
4
//! embedders (document editors, printpdf) can compute pagination *without*
5
//! generating any per-page display list, and so the slicer becomes a consumer
6
//! of the same analysis it used to inline.
7
//!
8
//! Three latent defects were fixed in the extraction (each pinned by a test):
9
//!
10
//! 1. the sort now uses `f32::total_cmp` — the old `partial_cmp().unwrap()` was a panic path if a
11
//!    NaN ever survived the input filter;
12
//! 2. when a forced break and an interval break land within the 1px merge window, the FORCED break
13
//!    survives (CSS Fragmentation: forced breaks win). The old positional dedup kept whichever
14
//!    sorted first, so an author's `break-before: always` could be silently replaced by the
15
//!    interval break up to 1px above it;
16
//! 3. `normal_page_content_height <= 0` (header + footer at least as tall as the page, with
17
//!    `skip_first_page` making the first page valid) made the old interval loop `y += normal` never
18
//!    terminate. Interval generation now stops after the first-page break when the normal height is
19
//!    not positive.
20

            
21
use azul_core::{dom::NodeId, id::OptionNodeId};
22
use azul_css::impl_option_inner;
23

            
24
use crate::solver3::display_list::{calculate_display_list_height, DisplayList, SlicerConfig};
25

            
26
/// Why a page ends where it does.
27
#[derive(Debug, Clone, Copy, PartialEq)]
28
#[repr(C, u8)]
29
pub enum BreakKind {
30
    /// A CSS `break-before/after: always` (or legacy `page-break-*`) forced
31
    /// this break.
32
    Forced,
33
    /// The page was simply full (regular interval break).
34
    Interval,
35
    /// The page was full at `pushed_from`, but the break moved UP to honor an
36
    /// avoid-rule (`break-inside: avoid`, line atomicity, widows/orphans).
37
    Avoided(f32),
38
}
39

            
40
/// One page boundary in document space.
41
#[derive(Debug, Clone, Copy, PartialEq)]
42
#[repr(C)] // in the C API through `PaginationInfo` (9g-ii-f-i); the 8-aligned
43
           // option first so it is not padded after two 4-byte fields
44
pub struct PageBreakPosition {
45
    /// For [`BreakKind::Forced`]: the node whose break property caused it,
46
    /// when known. `None` in the display-list-only path - the display list
47
    /// records only the Y positions of forced breaks.
48
    pub causing_node: OptionNodeId,
49
    /// Document-space Y where the page ENDS (content at or below `y` belongs
50
    /// to the next page).
51
    pub y: f32,
52
    pub kind: BreakKind,
53
}
54

            
55
/// Page geometry the break computation needs.
56
///
57
/// [`PageConstraints::from_slicer_config`] performs the header/footer
58
/// subtraction that used to be inlined in
59
/// `paginate_display_list_with_slicer_and_breaks`.
60
#[derive(Debug, Clone, Copy, PartialEq)]
61
pub struct PageConstraints {
62
    /// Content height available on the first page (differs from
63
    /// `normal_page_content_height` when headers/footers skip the first page).
64
    pub first_page_content_height: f32,
65
    /// Content height available on every page after the first.
66
    pub normal_page_content_height: f32,
67
}
68

            
69
impl PageConstraints {
70
    /// Derive the per-page content heights from a slicer config: subtract
71
    /// header/footer space, and give the first page the full height when
72
    /// `skip_first_page` is set.
73
    #[must_use]
74
1646
    pub fn from_slicer_config(cfg: &SlicerConfig) -> Self {
75
1646
        let base_header_space = if cfg.header_footer.show_header {
76
4
            cfg.header_footer.header_height
77
        } else {
78
1642
            0.0
79
        };
80
1646
        let base_footer_space = if cfg.header_footer.show_footer {
81
6
            cfg.header_footer.footer_height
82
        } else {
83
1640
            0.0
84
        };
85
1646
        let normal_page_content_height =
86
1646
            cfg.page_content_height - base_header_space - base_footer_space;
87
1646
        let first_page_content_height = if cfg.header_footer.skip_first_page {
88
            // First page has full height when skipping headers/footers
89
2
            cfg.page_content_height
90
        } else {
91
1644
            normal_page_content_height
92
        };
93
1646
        Self {
94
1646
            first_page_content_height,
95
1646
            normal_page_content_height,
96
1646
        }
97
1646
    }
98
}
99

            
100
/// Breaks within this distance are the same boundary and are merged — a
101
/// duplicate would produce a zero-height page.
102
const MERGE_WINDOW_PX: f32 = 1.0;
103

            
104
/// Break-awareness policy.
105
///
106
/// ALL flags off (the default) reproduces the plain forced ∪ interval
107
/// algorithm exactly — that is how this type can ship ahead of the behaviors
108
/// it gates (each lands in its own stage and flips on in printpdf with a
109
/// changelog entry, never silently).
110
#[derive(Debug, Clone, Copy, PartialEq)]
111
#[allow(clippy::struct_excessive_bools)] // independent feature flags; mirrors the C-ABI struct layout
112
#[repr(C)] // in the C API through `FakePageConfig` (9g-ii-f-i); the f32 first
113
pub struct BreakPolicy {
114
    /// Upper bound on how far a break may be pushed UP to satisfy
115
    /// avoid-rules, as a fraction of the page height (guards pathological
116
    /// cascades; beyond it the plain candidate snap applies).
117
    pub max_push_distance: f32,
118
    /// Honor `break-inside: avoid` (push boxes below the break intact).
119
    pub honor_break_inside: bool,
120
    /// Honor `widows` / `orphans` line constraints.
121
    pub widows_orphans: bool,
122
    /// Never tear a line box across pages (snap to line boundaries).
123
    pub atomic_lines: bool,
124
    /// Never tear a table row across pages.
125
    pub atomic_table_rows: bool,
126
    /// Repeat `<thead>` on continuation pages.
127
    pub repeat_table_headers: bool,
128
}
129

            
130
impl Default for BreakPolicy {
131
261
    fn default() -> Self {
132
261
        Self {
133
261
            honor_break_inside: false,
134
261
            widows_orphans: false,
135
261
            atomic_lines: false,
136
261
            atomic_table_rows: false,
137
261
            repeat_table_headers: false,
138
261
            max_push_distance: 0.33,
139
261
        }
140
261
    }
141
}
142

            
143
/// The richer inputs break-awareness needs (geometry beyond the display
144
/// list: box rects and break properties). The display-list-only path stays
145
/// available via [`compute_page_breaks_from_display_list`].
146
#[derive(Debug)]
147
pub struct PageBreakInput<'a> {
148
    /// Item geometry + forced break positions.
149
    pub display_list: &'a DisplayList,
150
    /// Box rects + line boxes for future break-candidate stages. v1
151
    /// break-awareness derives all geometry from the display list, so this
152
    /// may be `None`.
153
    pub layout_tree: Option<&'a crate::solver3::layout_tree::LayoutTree>,
154
    /// Break properties (`break-inside`, `widows`, `orphans`, …).
155
    pub styled_dom: &'a azul_core::styled_dom::StyledDom,
156
    /// Registered table headers (`collect_table_headers`) — continuation
157
    /// pages that start inside a table reserve the repeated thead's height.
158
    /// `None` when `repeat_table_headers` is off.
159
    pub table_headers: Option<&'a crate::solver3::pagination::TableHeaderTracker>,
160
}
161

            
162
/// A vertical range a break may not enter, with the Y to snap up to
163
/// (`top`) when one lands inside.
164
#[derive(Debug, Clone, Copy)]
165
struct AvoidRange {
166
    top: f32,
167
    bottom: f32,
168
    /// The node that owns the range (diagnostics).
169
    node: Option<NodeId>,
170
}
171

            
172
/// The line boxes of one paragraph (for widows/orphans), sorted by top.
173
#[derive(Debug, Clone)]
174
struct ParagraphLines {
175
    node: NodeId,
176
    /// `(top, bottom)` of each line, sorted by top, deduplicated.
177
    lines: Vec<(f32, f32)>,
178
    widows: u32,
179
    orphans: u32,
180
}
181

            
182
/// Compute page breaks with break-awareness `policy`. With the default
183
/// (all-off) policy this is exactly [`compute_page_breaks_from_display_list`].
184
///
185
/// With flags on, interval breaks run as a single FORWARD pass (matching the
186
/// slicer's "breaks only move up, content never moves" model): the naive
187
/// break `prev + page_height` snaps UP out of avoid-ranges
188
/// (`break-inside: avoid` boxes, atomic line boxes) and back for
189
/// widows/orphans, bounded by `policy.max_push_distance` (beyond it the
190
/// naive break stands — a bounded fallback, never a loop). Forced breaks
191
/// never move. Boxes taller than the page are torn regardless (the monolith
192
/// rule — an unbreakable box that cannot fit must still paginate).
193
#[must_use]
194
1652
pub fn compute_page_breaks(
195
1652
    input: &PageBreakInput<'_>,
196
1652
    constraints: &PageConstraints,
197
1652
    policy: &BreakPolicy,
198
1652
) -> Vec<PageBreakPosition> {
199
1652
    compute_page_breaks_impl(input, *constraints, policy, None, None)
200
1652
}
201

            
202
/// Why an element could not be kept intact across a page boundary (E21).
203
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204
pub enum MonolithReason {
205
    /// A `break-inside: avoid` box taller than the page content area —
206
    /// no break position can satisfy it, so it tears.
207
    AvoidBoxTallerThanPage,
208
    /// An atomic table row taller than the page content area.
209
    RowTallerThanPage,
210
}
211

            
212
/// E21: one element the break pass had to TEAR despite a keep-intact rule.
213
/// The exporter surfaces these as "element X could not be kept intact".
214
#[derive(Debug, Clone, Copy, PartialEq)]
215
pub struct MonolithWarning {
216
    /// The node whose rule was violated (None = anonymous, e.g. a row range
217
    /// derived without a node mapping).
218
    pub node: Option<NodeId>,
219
    /// Document-space extent of the torn box.
220
    pub top: f32,
221
    pub bottom: f32,
222
    pub reason: MonolithReason,
223
}
224

            
225
/// [`compute_page_breaks`] + the E21 monolith report: elements whose
226
/// keep-intact rules (`break-inside: avoid`, atomic rows) could not be
227
/// honored because they are taller than the page. The breaks are identical
228
/// to [`compute_page_breaks`] — the report only ADDS information.
229
#[must_use]
230
2
pub fn compute_page_breaks_with_report(
231
2
    input: &PageBreakInput<'_>,
232
2
    constraints: &PageConstraints,
233
2
    policy: &BreakPolicy,
234
2
) -> (Vec<PageBreakPosition>, Vec<MonolithWarning>) {
235
2
    let mut warnings = Vec::new();
236
2
    let breaks = compute_page_breaks_impl(input, *constraints, policy, None, Some(&mut warnings));
237
2
    (breaks, warnings)
238
2
}
239

            
240
/// [`compute_page_breaks`] with an office-suite-style [`PageSequence`].
241
///
242
/// Every page's content HEIGHT comes from `setup_for_page(index)` (default /
243
/// explicit override / different-first / odd-even parity), so "page 345 is
244
/// landscape-height with a 2cm footer" flows straight into the break
245
/// positions. Content WIDTH must be uniform for now (the fragmentainer
246
/// re-wrap stage) — a non-uniform sequence announces once and lays out at
247
/// the default width.
248
#[must_use]
249
7
pub fn compute_page_breaks_with_sequence(
250
7
    input: &PageBreakInput<'_>,
251
7
    sequence: &crate::solver3::pagination::PageSequence,
252
7
    policy: &BreakPolicy,
253
7
) -> Vec<PageBreakPosition> {
254
7
    let _ = sequence.has_uniform_width(); // announce the width degradation once
255
7
    let default_h = sequence.default.content_height();
256
7
    let constraints = PageConstraints {
257
7
        first_page_content_height: sequence.setup_for_page(0).content_height(),
258
7
        normal_page_content_height: default_h,
259
7
    };
260
7
    compute_page_breaks_impl(input, constraints, policy, Some(sequence), None)
261
7
}
262

            
263
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
264
                                 // (one branch per case)
265
1661
fn compute_page_breaks_impl(
266
1661
    input: &PageBreakInput<'_>,
267
1661
    constraints: PageConstraints,
268
1661
    policy: &BreakPolicy,
269
1661
    sequence: Option<&crate::solver3::pagination::PageSequence>,
270
1661
    mut monolith_report: Option<&mut Vec<MonolithWarning>>,
271
1661
) -> Vec<PageBreakPosition> {
272
1661
    let any_awareness = policy.honor_break_inside
273
1655
        || policy.atomic_lines
274
1654
        || policy.widows_orphans
275
1652
        || policy.atomic_table_rows
276
1650
        || policy.repeat_table_headers
277
        // A page sequence varies heights per page — the forward pass is the
278
        // only correct evaluator even with all avoid-rules off.
279
1649
        || sequence.is_some();
280
1661
    if !any_awareness {
281
1642
        return compute_page_breaks_from_display_list(input.display_list, &constraints);
282
19
    }
283

            
284
19
    let total_height = calculate_display_list_height(input.display_list);
285
19
    let first = constraints.first_page_content_height;
286
19
    let normal = constraints.normal_page_content_height;
287
19
    if total_height <= 0.0 || first <= 0.0 {
288
        return Vec::new();
289
19
    }
290

            
291
19
    let mut avoid_ranges =
292
19
        collect_avoid_ranges(input, constraints, policy, monolith_report.as_deref_mut());
293
19
    if policy.atomic_table_rows {
294
        // A break may not slice a table row (monolith rule still applies:
295
        // a row taller than the page tears).
296
2
        let page_h = constraints.normal_page_content_height.max(1.0);
297
10
        for (top, bottom) in crate::solver3::pagination::collect_table_row_ranges(
298
2
            input.display_list,
299
2
            input.styled_dom,
300
        ) {
301
10
            if bottom - top <= page_h {
302
8
                avoid_ranges.push(AvoidRange {
303
8
                    top,
304
8
                    bottom,
305
8
                    node: None,
306
8
                });
307
8
            } else if let Some(report) = monolith_report.as_deref_mut() {
308
                report.push(MonolithWarning {
309
                    node: None,
310
                    top,
311
                    bottom,
312
                    reason: MonolithReason::RowTallerThanPage,
313
                });
314
2
            }
315
        }
316
6
        avoid_ranges.sort_by(|a, b| a.top.total_cmp(&b.top));
317
17
    }
318

            
319
    // Tables whose continuation pages must reserve repeated-thead height.
320
19
    let reserved_tables: Vec<(f32, f32, f32)> = if policy.repeat_table_headers {
321
1
        input
322
1
            .table_headers
323
1
            .map(|t| {
324
1
                t.tables
325
1
                    .iter()
326
1
                    .map(|info| (info.table_start_y, info.table_end_y, info.thead_height))
327
1
                    .collect()
328
1
            })
329
1
            .unwrap_or_default()
330
    } else {
331
18
        Vec::new()
332
    };
333
19
    let paragraphs = if policy.widows_orphans {
334
2
        collect_paragraph_lines(input)
335
    } else {
336
17
        Vec::new()
337
    };
338

            
339
    // Forced breaks, ascending (they are hard walls the forward pass emits
340
    // verbatim — CSS Fragmentation: forced always wins over avoid).
341
19
    let mut forced: Vec<crate::solver3::display_list::ForcedBreak> = input
342
19
        .display_list
343
19
        .forced_page_breaks
344
19
        .iter()
345
19
        .copied()
346
19
        .filter(|b| b.y > 0.0 && b.y < total_height)
347
19
        .collect();
348
19
    forced.sort_by(|a, b| a.y.total_cmp(&b.y));
349

            
350
19
    let mut breaks: Vec<PageBreakPosition> = Vec::new();
351
19
    let mut prev_end = 0.0_f32;
352
19
    let mut page_height = first;
353
19
    let mut page_index: usize = 0;
354
19
    let mut forced_iter = forced.into_iter().peekable();
355

            
356
    loop {
357
        // Per-page setup (classic office suites model): the sequence overrides the height
358
        // for THIS page index (explicit / first / parity / default).
359
77
        if let Some(seq) = sequence {
360
33
            page_height = seq.setup_for_page(page_index).content_height();
361
44
        }
362
        // A page STARTING inside a table shows that table's repeated thead —
363
        // its content area shrinks by the header stack's height.
364
77
        let reserve: f32 = reserved_tables
365
77
            .iter()
366
77
            .filter(|(start, end, _)| *start < prev_end && *end > prev_end)
367
77
            .map(|(_, _, h)| *h)
368
77
            .sum();
369
77
        let effective_height = (page_height - reserve).max(MERGE_WINDOW_PX);
370
77
        let naive = prev_end + effective_height;
371

            
372
        // A forced break before (or at) the naive position ends the page there.
373
77
        if let Some(&fb) = forced_iter.peek() {
374
1
            if fb.y <= naive + MERGE_WINDOW_PX {
375
1
                forced_iter.next();
376
1
                if fb.y > prev_end + MERGE_WINDOW_PX {
377
1
                    breaks.push(PageBreakPosition {
378
1
                        y: fb.y,
379
1
                        kind: BreakKind::Forced,
380
1
                        causing_node: fb.causing_node.into(),
381
1
                    });
382
1
                    prev_end = fb.y;
383
1
                    page_height = normal;
384
1
                    page_index += 1;
385
1
                }
386
1
                continue;
387
            }
388
76
        }
389

            
390
76
        if naive >= total_height {
391
19
            break;
392
57
        }
393

            
394
57
        let max_push = (policy.max_push_distance.max(0.0)) * page_height;
395
57
        let floor = (naive - max_push).max(prev_end + MERGE_WINDOW_PX);
396
57
        let adjusted = snap_break_up(naive, floor, &avoid_ranges, &paragraphs, policy);
397

            
398
57
        let kind = if (adjusted - naive).abs() < f32::EPSILON {
399
51
            BreakKind::Interval
400
        } else {
401
6
            BreakKind::Avoided(naive)
402
        };
403
57
        breaks.push(PageBreakPosition {
404
57
            y: adjusted,
405
57
            kind,
406
57
            causing_node: OptionNodeId::None,
407
57
        });
408
57
        prev_end = adjusted;
409
57
        page_height = normal;
410
57
        page_index += 1;
411
        // `!(x > 0.0)` semantics kept explicitly: a NaN height must also stop
412
        // the loop, so test `<= 0.0 || is_nan` instead of the negation.
413
57
        if sequence.is_none() && (normal <= 0.0 || normal.is_nan()) {
414
            break;
415
57
        }
416
57
        if sequence.is_some() {
417
26
            let next_height = page_height_floor(sequence, page_index, normal);
418
26
            if next_height <= 0.0 || next_height.is_nan() {
419
                break;
420
26
            }
421
31
        }
422
    }
423

            
424
    // Any forced breaks past the last interval position still apply.
425
19
    for fb in forced_iter {
426
        if fb.y > prev_end + MERGE_WINDOW_PX {
427
            breaks.push(PageBreakPosition {
428
                y: fb.y,
429
                kind: BreakKind::Forced,
430
                causing_node: fb.causing_node.into(),
431
            });
432
            prev_end = fb.y;
433
        }
434
    }
435

            
436
19
    breaks
437
1661
}
438

            
439
/// Termination guard: the NEXT page's height (sequence-aware). A sequence
440
/// page with non-positive content height would loop forever, same as the
441
/// plain `normal <= 0` case.
442
26
fn page_height_floor(
443
26
    sequence: Option<&crate::solver3::pagination::PageSequence>,
444
26
    page_index: usize,
445
26
    normal: f32,
446
26
) -> f32 {
447
26
    sequence.map_or(normal, |s| s.setup_for_page(page_index).content_height())
448
26
}
449

            
450
/// Collect the vertical ranges a break may not enter.
451
19
fn collect_avoid_ranges(
452
19
    input: &PageBreakInput<'_>,
453
19
    constraints: PageConstraints,
454
19
    policy: &BreakPolicy,
455
19
    mut monolith_report: Option<&mut Vec<MonolithWarning>>,
456
19
) -> Vec<AvoidRange> {
457
    use azul_css::props::layout::fragmentation::BreakInside;
458

            
459
    use crate::solver3::getters::get_break_inside;
460

            
461
19
    let mut ranges: Vec<AvoidRange> = Vec::new();
462
19
    let page_height = constraints.normal_page_content_height.max(1.0);
463

            
464
19
    if policy.honor_break_inside {
465
        // Union the bounds of every display item a break-inside:avoid node
466
        // produced (document-space Ys come from the DL — no positions map
467
        // needed). One range per node.
468
6
        let mut per_node: std::collections::BTreeMap<NodeId, (f32, f32)> =
469
6
            std::collections::BTreeMap::new();
470
12
        for (idx, item) in input.display_list.items.iter().enumerate() {
471
12
            let Some(node) = input.display_list.node_mapping.get(idx).copied().flatten() else {
472
6
                continue;
473
            };
474
6
            let Some(bounds) = item.bounds() else {
475
                continue;
476
            };
477
6
            if get_break_inside(input.styled_dom, Some(node)) != BreakInside::Avoid {
478
                continue;
479
6
            }
480
6
            let top = bounds.origin.y;
481
6
            let bottom = bounds.origin.y + bounds.size.height;
482
6
            per_node
483
6
                .entry(node)
484
6
                .and_modify(|(t, b)| {
485
                    *t = t.min(top);
486
                    *b = b.max(bottom);
487
                })
488
6
                .or_insert((top, bottom));
489
        }
490
12
        for (node, (top, bottom)) in per_node {
491
            // Monolith rule: a box taller than the page may be torn — an
492
            // avoid-range that can never be satisfied would push forever.
493
            // E21: the tear is no longer SILENT — it lands in the report.
494
6
            if bottom - top > page_height {
495
3
                if let Some(report) = monolith_report.as_deref_mut() {
496
1
                    report.push(MonolithWarning {
497
1
                        node: Some(node),
498
1
                        top,
499
1
                        bottom,
500
1
                        reason: MonolithReason::AvoidBoxTallerThanPage,
501
1
                    });
502
2
                }
503
3
                continue;
504
3
            }
505
3
            ranges.push(AvoidRange {
506
3
                top,
507
3
                bottom,
508
3
                node: Some(node),
509
3
            });
510
        }
511
13
    }
512

            
513
19
    if policy.atomic_lines {
514
        // Every text item's rect is a line-box fragment; a break through one
515
        // slices a line (the "baseline-sliced line" artifact). Snap to its top.
516
4
        for item in &input.display_list.items {
517
3
            if let crate::solver3::display_list::DisplayListItem::Text { clip_rect, .. } = item {
518
2
                let r = clip_rect.inner();
519
2
                if r.size.height > 0.0 {
520
2
                    ranges.push(AvoidRange {
521
2
                        top: r.origin.y,
522
2
                        bottom: r.origin.y + r.size.height,
523
2
                        node: None,
524
2
                    });
525
2
                }
526
1
            }
527
        }
528
18
    }
529

            
530
19
    ranges.sort_by(|a, b| a.top.total_cmp(&b.top));
531
19
    ranges
532
19
}
533

            
534
/// Group text-item rects per source node into line boxes for widows/orphans.
535
2
fn collect_paragraph_lines(input: &PageBreakInput<'_>) -> Vec<ParagraphLines> {
536
    use crate::solver3::getters::{get_orphans, get_widows};
537

            
538
2
    let mut per_node: std::collections::BTreeMap<NodeId, Vec<(f32, f32)>> =
539
2
        std::collections::BTreeMap::new();
540
8
    for (idx, item) in input.display_list.items.iter().enumerate() {
541
8
        let crate::solver3::display_list::DisplayListItem::Text { clip_rect, .. } = item else {
542
2
            continue;
543
        };
544
6
        let Some(node) = input.display_list.node_mapping.get(idx).copied().flatten() else {
545
            continue;
546
        };
547
6
        let r = clip_rect.inner();
548
6
        if r.size.height <= 0.0 {
549
            continue;
550
6
        }
551
6
        per_node
552
6
            .entry(node)
553
6
            .or_default()
554
6
            .push((r.origin.y, r.origin.y + r.size.height));
555
    }
556

            
557
2
    per_node
558
2
        .into_iter()
559
2
        .filter_map(|(node, mut rects)| {
560
4
            rects.sort_by(|a, b| a.0.total_cmp(&b.0));
561
            // Merge run-rects sharing a line (tops within 0.5px).
562
2
            let mut lines: Vec<(f32, f32)> = Vec::new();
563
8
            for (top, bottom) in rects {
564
6
                match lines.last_mut() {
565
4
                    Some((lt, lb)) if (top - *lt).abs() < 0.5 => *lb = lb.max(bottom),
566
6
                    _ => lines.push((top, bottom)),
567
                }
568
            }
569
2
            if lines.len() < 2 {
570
                return None; // single-line paragraphs have no widow/orphan case
571
2
            }
572
2
            Some(ParagraphLines {
573
2
                node,
574
2
                widows: get_widows(input.styled_dom, Some(node)).max(1),
575
2
                orphans: get_orphans(input.styled_dom, Some(node)).max(1),
576
2
                lines,
577
2
            })
578
2
        })
579
2
        .collect()
580
2
}
581

            
582
/// Snap a naive break Y up out of avoid-ranges and widow/orphan violations.
583
/// Iterates to a fixpoint (a snap can land inside ANOTHER range) but never
584
/// below `floor` — beyond the push budget the current candidate stands.
585
57
fn snap_break_up(
586
57
    naive: f32,
587
57
    floor: f32,
588
57
    avoid_ranges: &[AvoidRange],
589
57
    paragraphs: &[ParagraphLines],
590
57
    policy: &BreakPolicy,
591
57
) -> f32 {
592
57
    let mut y = naive;
593
    // Bounded iterations: each snap strictly decreases y and range/paragraph
594
    // counts are finite; 32 covers any sane nesting without risking a loop.
595
63
    for _ in 0..32 {
596
63
        let mut moved = false;
597

            
598
110
        for range in avoid_ranges {
599
            // STRICTLY inside (a break AT an edge is fine).
600
47
            if y > range.top + f32::EPSILON && y < range.bottom - f32::EPSILON {
601
4
                let _ = range.node;
602
4
                if range.top >= floor {
603
4
                    y = range.top;
604
4
                    moved = true;
605
4
                } // else: budget exceeded — the naive break stands mid-range
606
43
            }
607
        }
608

            
609
63
        if policy.widows_orphans {
610
12
            for para in paragraphs {
611
6
                let first_top = para.lines[0].0;
612
6
                let last_bottom = para.lines[para.lines.len() - 1].1;
613
6
                if y <= first_top || y >= last_bottom {
614
3
                    continue;
615
3
                }
616
                // Lines fully above the break stay; the rest move to the next page.
617
3
                let total_lines = u32::try_from(para.lines.len()).unwrap_or(u32::MAX);
618
9
                let before_count = para.lines.iter().filter(|(_, b)| *b <= y + 0.5).count();
619
3
                let before = u32::try_from(before_count).unwrap_or(u32::MAX);
620
3
                let after = total_lines - before;
621
3
                if before > 0 && before < para.orphans {
622
                    // Too few lines kept: the whole paragraph moves.
623
1
                    if first_top >= floor {
624
1
                        y = first_top;
625
1
                        moved = true;
626
1
                    }
627
2
                } else if after > 0 && after < para.widows {
628
                    // Too few lines moved: push more lines over the break.
629
1
                    let needed = total_lines - para.widows;
630
1
                    let target = para
631
1
                        .lines
632
1
                        .get(needed as usize)
633
1
                        .map_or(first_top, |(t, _)| *t);
634
1
                    if target < y && target >= floor {
635
1
                        y = target;
636
1
                        moved = true;
637
1
                    }
638
1
                }
639
            }
640
57
        }
641

            
642
63
        if !moved {
643
57
            break;
644
6
        }
645
    }
646
57
    y
647
57
}
648

            
649
/// Incremental re-break after an edit.
650
///
651
/// Recompute (always — correctness under
652
/// ANY input change, and the break pass is cheap next to the relayout that
653
/// preceded it), then NORMALIZE against the previous run — every fresh break
654
/// that matches a previous break within the merge window returns the
655
/// PREVIOUS value bit-for-bit. Unchanged pages therefore compare value-equal
656
/// against the old spans, which is the signal a paged viewer uses to keep
657
/// its cached page surfaces.
658
///
659
/// `dirty_y_start` (the topmost document-space Y whose content changed — the
660
/// editing IFC root's top, see `LayoutWindow::take_pagination_dirty_from`)
661
/// is a DEBUG contract: breaks above it must come out identical, and a
662
/// mismatch there means the caller under-reported the dirty region — the
663
/// fresh value wins (correctness over reuse).
664
#[must_use]
665
2
pub fn recompute_page_breaks_from(
666
2
    prev: &[PageBreakPosition],
667
2
    input: &PageBreakInput<'_>,
668
2
    constraints: &PageConstraints,
669
2
    policy: &BreakPolicy,
670
2
    dirty_y_start: f32,
671
2
) -> Vec<PageBreakPosition> {
672
2
    let fresh = compute_page_breaks(input, constraints, policy);
673

            
674
2
    let mut out: Vec<PageBreakPosition> = Vec::with_capacity(fresh.len());
675
2
    let mut prev_iter = prev.iter().peekable();
676
21
    for fb in fresh {
677
19
        while prev_iter
678
19
            .peek()
679
19
            .is_some_and(|pb| pb.y < fb.y - MERGE_WINDOW_PX)
680
        {
681
            prev_iter.next();
682
        }
683
19
        match prev_iter.peek() {
684
19
            Some(pb) if (pb.y - fb.y).abs() < MERGE_WINDOW_PX => {
685
18
                // Value-identical reuse — above the dirty bound this is the
686
18
                // guaranteed case; below it, it means the page converged.
687
18
                out.push(**pb);
688
18
                prev_iter.next();
689
18
            }
690
            _ => {
691
1
                debug_assert!(
692
                    fb.y >= dirty_y_start - MERGE_WINDOW_PX,
693
                    "a break above dirty_y_start changed ({} < {dirty_y_start}) — the caller \
694
                     under-reported the dirty region",
695
                    fb.y
696
                );
697
1
                out.push(fb);
698
            }
699
        }
700
    }
701
2
    out
702
2
}
703

            
704
/// Which page a document-space Y coordinate lands on.
705
///
706
/// Given the break list (page 0 = before the first break). The
707
/// document-editor query: "what page is this node on?" WITHOUT materializing
708
/// any per-page display list.
709
#[must_use]
710
7
pub fn page_of_y(breaks: &[PageBreakPosition], y: f32) -> usize {
711
12
    breaks.iter().take_while(|b| b.y <= y).count()
712
7
}
713

            
714
/// Precomputed pagination facts for a document — everything a viewer needs
715
/// to draw page chrome and schedule lazy page materialization, with NO
716
/// per-page display list generated.
717
#[derive(Debug, Clone, PartialEq)]
718
#[repr(C)] // `CallbackInfo::query_pagination`'s answer (9g-ii-f-i)
719
pub struct PaginationInfo {
720
    pub breaks: PageBreakPositionVec,
721
    pub page_count: usize,
722
    pub total_content_height: f32,
723
}
724

            
725
azul_css::impl_option!(
726
    PageBreakPosition,
727
    OptionPageBreakPosition,
728
    [Debug, Copy, Clone, PartialEq]
729
);
730
azul_css::impl_vec!(
731
    PageBreakPosition,
732
    PageBreakPositionVec,
733
    PageBreakPositionVecDestructor,
734
    PageBreakPositionVecDestructorType,
735
    PageBreakPositionVecSlice,
736
    OptionPageBreakPosition
737
);
738
azul_css::impl_vec_clone!(
739
    PageBreakPosition,
740
    PageBreakPositionVec,
741
    PageBreakPositionVecDestructor
742
);
743
azul_css::impl_vec_partialeq!(PageBreakPosition, PageBreakPositionVec);
744
azul_css::impl_vec_debug!(PageBreakPosition, PageBreakPositionVec);
745

            
746
azul_css::impl_option!(
747
    PaginationInfo,
748
    OptionPaginationInfo,
749
    copy = false,
750
    [Debug, Clone, PartialEq]
751
);
752

            
753
/// Compute page breaks for a display list: CSS-forced breaks
754
/// (`DisplayList::forced_page_breaks`) plus regular interval breaks wherever
755
/// the page runs full.
756
///
757
/// Returns an empty vector when the document has no content or the first-page
758
/// height is not positive — [`page_spans`] then yields the single-page result.
759
#[must_use]
760
1653
pub fn compute_page_breaks_from_display_list(
761
1653
    display_list: &DisplayList,
762
1653
    constraints: &PageConstraints,
763
1653
) -> Vec<PageBreakPosition> {
764
1653
    compute_page_breaks_from_forced(
765
1653
        &display_list.forced_page_breaks,
766
1653
        constraints,
767
1653
        calculate_display_list_height(display_list),
768
    )
769
1653
}
770

            
771
/// The display-list-independent pagination core.
772
///
773
/// Consumes forced break Y positions plus page heights plus total content
774
/// height. Also the seat for later break-awareness stages, which add richer
775
/// inputs without touching this contract.
776
#[must_use]
777
17
pub fn compute_page_breaks_from_positions(
778
17
    forced_breaks: &[f32],
779
17
    constraints: &PageConstraints,
780
17
    total_height: f32,
781
17
) -> Vec<PageBreakPosition> {
782
17
    let typed: Vec<crate::solver3::display_list::ForcedBreak> = forced_breaks
783
17
        .iter()
784
17
        .map(|&y| crate::solver3::display_list::ForcedBreak {
785
14
            y,
786
14
            causing_node: None,
787
14
        })
788
17
        .collect();
789
17
    compute_page_breaks_from_forced(&typed, constraints, total_height)
790
17
}
791

            
792
/// [`compute_page_breaks_from_positions`] with the causing node carried
793
/// through to [`PageBreakPosition::causing_node`].
794
#[must_use]
795
1670
pub fn compute_page_breaks_from_forced(
796
1670
    forced_breaks: &[crate::solver3::display_list::ForcedBreak],
797
1670
    constraints: &PageConstraints,
798
1670
    total_height: f32,
799
1670
) -> Vec<PageBreakPosition> {
800
1670
    let first = constraints.first_page_content_height;
801
1670
    let normal = constraints.normal_page_content_height;
802

            
803
1670
    if total_height <= 0.0 || first <= 0.0 {
804
6
        return Vec::new();
805
1664
    }
806

            
807
1664
    let mut breaks: Vec<PageBreakPosition> = Vec::new();
808

            
809
    // Forced breaks from CSS break-before/after: always.
810
    // The range check also filters NaN (both comparisons are false for NaN).
811
1718
    for fb in forced_breaks {
812
54
        if fb.y > 0.0 && fb.y < total_height {
813
42
            breaks.push(PageBreakPosition {
814
42
                y: fb.y,
815
42
                kind: BreakKind::Forced,
816
42
                causing_node: fb.causing_node.into(),
817
42
            });
818
42
        }
819
    }
820

            
821
    // Regular interval breaks. A non-positive normal height cannot advance the
822
    // cursor — emit the first-page break once and stop (defect 3: the old loop
823
    // never terminated here).
824
1664
    let mut y = first;
825
    #[allow(clippy::while_float)]
826
    // intentional bounded float loop; an integer counter would be artificial
827
2453
    while y < total_height {
828
792
        breaks.push(PageBreakPosition {
829
792
            y,
830
792
            kind: BreakKind::Interval,
831
792
            causing_node: OptionNodeId::None,
832
792
        });
833
        // `!(normal > 0.0)` semantics kept explicitly: NaN must also stop.
834
792
        if normal <= 0.0 || normal.is_nan() {
835
3
            break;
836
789
        }
837
789
        y += normal;
838
    }
839

            
840
1774
    breaks.sort_by(|a, b| a.y.total_cmp(&b.y));
841

            
842
    // Merge breaks within the 1px window. A forced break replaces an interval
843
    // break in the same window (defect 2: forced breaks win); otherwise the
844
    // first break of a run is kept, matching the old positional dedup.
845
1664
    let mut merged: Vec<PageBreakPosition> = Vec::with_capacity(breaks.len());
846
2498
    for b in breaks {
847
834
        match merged.last_mut() {
848
489
            Some(last) if (b.y - last.y).abs() < MERGE_WINDOW_PX => {
849
14
                if last.kind == BreakKind::Interval && b.kind == BreakKind::Forced {
850
2
                    *last = b;
851
12
                }
852
            }
853
820
            _ => merged.push(b),
854
        }
855
    }
856
1664
    merged
857
1670
}
858

            
859
/// Convert break positions into per-page `(start_y, end_y)` spans — what the
860
/// slicer consumes. Breaks at or below a previous break (and at Y=0) are
861
/// skipped rather than producing empty pages.
862
///
863
/// May return an empty vector when `total_height <= 0` and there are no
864
/// breaks; pagination entry points map that to their single-page fallback.
865
#[must_use]
866
1677
pub fn page_spans(breaks: &[PageBreakPosition], total_height: f32) -> Vec<(f32, f32)> {
867
1677
    let mut spans: Vec<(f32, f32)> = Vec::with_capacity(breaks.len() + 1);
868
1677
    let mut page_start = 0.0f32;
869

            
870
2506
    for b in breaks {
871
829
        if b.y > page_start {
872
827
            spans.push((page_start, b.y));
873
827
            page_start = b.y;
874
827
        }
875
    }
876

            
877
1677
    if page_start < total_height {
878
1674
        spans.push((page_start, total_height));
879
1674
    }
880

            
881
1677
    spans
882
1677
}
883

            
884
#[cfg(test)]
885
mod tests {
886
    use super::*;
887

            
888
33
    fn constraints(first: f32, normal: f32) -> PageConstraints {
889
33
        PageConstraints {
890
33
            first_page_content_height: first,
891
33
            normal_page_content_height: normal,
892
33
        }
893
33
    }
894

            
895
10
    fn ys(breaks: &[PageBreakPosition]) -> Vec<f32> {
896
10
        breaks.iter().map(|b| b.y).collect()
897
10
    }
898

            
899
    /// The pre-extraction algorithm, verbatim (minus the NaN-panic sort), as
900
    /// the golden reference. Differences are allowed ONLY where the named
901
    /// defects fire.
902
17
    fn reference_spans(
903
17
        forced: &[f32],
904
17
        first_page_height: f32,
905
17
        normal_page_height: f32,
906
17
        total_height: f32,
907
17
    ) -> Vec<(f32, f32)> {
908
17
        if total_height <= 0.0 || first_page_height <= 0.0 {
909
4
            return vec![(0.0, total_height.max(first_page_height))];
910
13
        }
911
13
        let mut break_points: Vec<f32> = Vec::new();
912
26
        for &forced_break_y in forced {
913
13
            if forced_break_y > 0.0 && forced_break_y < total_height {
914
7
                break_points.push(forced_break_y);
915
7
            }
916
        }
917
13
        let mut y = first_page_height;
918
55
        while y < total_height {
919
42
            break_points.push(y);
920
            // Guard added ONLY to keep the reference terminating; the shipped
921
            // code hung here (defect 3), which the corpus below avoids by
922
            // never combining normal<=0 with the reference.
923
            // `!(x > 0.0)` semantics kept explicitly: NaN must also stop.
924
42
            if normal_page_height <= 0.0 || normal_page_height.is_nan() {
925
                break;
926
42
            }
927
42
            y += normal_page_height;
928
        }
929
13
        break_points.sort_by(f32::total_cmp);
930
40
        break_points.dedup_by(|a, b| (*a - *b).abs() < 1.0);
931
13
        let mut page_breaks: Vec<(f32, f32)> = Vec::new();
932
13
        let mut page_start = 0.0f32;
933
60
        for break_y in break_points {
934
47
            if break_y > page_start {
935
47
                page_breaks.push((page_start, break_y));
936
47
                page_start = break_y;
937
47
            }
938
        }
939
13
        if page_start < total_height {
940
13
            page_breaks.push((page_start, total_height));
941
13
        }
942
13
        if page_breaks.is_empty() {
943
            page_breaks.push((0.0, total_height.max(first_page_height)));
944
13
        }
945
13
        page_breaks
946
17
    }
947

            
948
    /// New-path spans including the entry-point fallback, so the comparison is
949
    /// against what callers actually observe.
950
16
    fn new_spans(forced: &[f32], first: f32, normal: f32, total: f32) -> Vec<(f32, f32)> {
951
16
        if total <= 0.0 || first <= 0.0 {
952
4
            return vec![(0.0, total.max(first))];
953
12
        }
954
12
        let breaks = compute_page_breaks_from_positions(forced, &constraints(first, normal), total);
955
12
        let mut spans = page_spans(&breaks, total);
956
12
        if spans.is_empty() {
957
            spans.push((0.0, total.max(first)));
958
12
        }
959
12
        spans
960
16
    }
961

            
962
    #[test]
963
1
    fn golden_corpus_matches_the_old_algorithm_where_no_defect_fires() {
964
        // (forced, first, normal, total) — no forced-vs-interval collisions
965
        // within 1px, normal > 0: behavior must be IDENTICAL.
966
1
        let corpus: &[(&[f32], f32, f32, f32)] = &[
967
1
            (&[], 100.0, 100.0, 250.0),
968
1
            (&[], 100.0, 100.0, 100.0),
969
1
            (&[], 100.0, 100.0, 99.0),
970
1
            (&[], 100.0, 50.0, 1000.0),
971
1
            (&[], 50.0, 100.0, 1000.0),
972
1
            (&[50.0], 100.0, 100.0, 250.0),
973
1
            (&[50.0, 150.0], 100.0, 100.0, 250.0),
974
1
            (
975
1
                &[-10.0, 0.0, 250.0, 9999.0, f32::NAN, f32::INFINITY],
976
1
                100.0,
977
1
                100.0,
978
1
                250.0,
979
1
            ),
980
1
            (&[50.0, 50.4], 100.0, 100.0, 250.0), // forced-forced merge: first wins in both
981
1
            (&[249.5], 100.0, 100.0, 250.0),
982
1
            (&[], 0.0, 100.0, 250.0),      // degenerate: single page
983
1
            (&[], -50.0, 100.0, 250.0),    // degenerate: single page
984
1
            (&[], 100.0, 100.0, 0.0),      // empty document
985
1
            (&[], 100.0, 100.0, -5.0),     // negative height
986
1
            (&[], f32::NAN, 100.0, 250.0), // NaN first: one unsplit page in both
987
1
            (&[], 100.0, 100.0, 50.0),     // total < first
988
1
        ];
989
17
        for &(forced, first, normal, total) in corpus {
990
16
            assert_eq!(
991
16
                new_spans(forced, first, normal, total),
992
16
                reference_spans(forced, first, normal, total),
993
                "case: forced={forced:?} first={first} normal={normal} total={total}"
994
            );
995
        }
996
1
    }
997

            
998
    #[test]
999
1
    fn defect_2_forced_break_within_1px_of_interval_break_survives() {
        // Old behavior: sorted [100.0 (interval), 100.5 (forced)] → dedup kept
        // 100.0 and the author's forced break vanished. New behavior: the
        // forced break replaces the interval break in the merge window.
1
        let breaks =
1
            compute_page_breaks_from_positions(&[100.5], &constraints(100.0, 100.0), 250.0);
1
        assert_eq!(ys(&breaks), vec![100.5, 200.0]);
1
        assert_eq!(breaks[0].kind, BreakKind::Forced);
1
        assert_eq!(breaks[1].kind, BreakKind::Interval);
1
        assert_eq!(
1
            page_spans(&breaks, 250.0),
1
            vec![(0.0, 100.5), (100.5, 200.0), (200.0, 250.0)]
        );
        // …and the old behavior really was the swallow (regression witness):
1
        let old = reference_spans(&[100.5], 100.0, 100.0, 250.0);
1
        assert_eq!(old, vec![(0.0, 100.0), (100.0, 200.0), (200.0, 250.0)]);
        // Forced break BELOW the interval break in the window: same outcome.
1
        let breaks = compute_page_breaks_from_positions(&[99.6], &constraints(100.0, 100.0), 250.0);
1
        assert_eq!(ys(&breaks), vec![99.6, 200.0]);
1
        assert_eq!(breaks[0].kind, BreakKind::Forced);
1
    }
    #[test]
1
    fn defect_3_non_positive_normal_height_terminates() {
        // Old behavior: `y += normal` with normal <= 0 never terminated when
        // skip_first_page made the first page valid. New behavior: the
        // first-page break is emitted once, everything else lands on page 2.
4
        for normal in [0.0, -20.0, f32::NAN] {
3
            let breaks =
3
                compute_page_breaks_from_positions(&[], &constraints(100.0, normal), 250.0);
3
            assert_eq!(ys(&breaks), vec![100.0], "normal={normal}");
3
            assert_eq!(
3
                page_spans(&breaks, 250.0),
3
                vec![(0.0, 100.0), (100.0, 250.0)],
                "normal={normal}"
            );
        }
1
    }
    #[test]
1
    fn from_slicer_config_reproduces_the_inlined_subtraction() {
        use crate::solver3::pagination::HeaderFooterConfig;
1
        let mut cfg = SlicerConfig::simple(800.0);
1
        let c = PageConstraints::from_slicer_config(&cfg);
1
        assert_eq!(c.first_page_content_height, 800.0);
1
        assert_eq!(c.normal_page_content_height, 800.0);
1
        cfg.header_footer = HeaderFooterConfig {
1
            show_header: true,
1
            header_height: 50.0,
1
            show_footer: true,
1
            footer_height: 30.0,
1
            ..Default::default()
1
        };
1
        let c = PageConstraints::from_slicer_config(&cfg);
1
        assert_eq!(c.first_page_content_height, 720.0);
1
        assert_eq!(c.normal_page_content_height, 720.0);
1
        cfg.header_footer.skip_first_page = true;
1
        let c = PageConstraints::from_slicer_config(&cfg);
1
        assert_eq!(c.first_page_content_height, 800.0);
1
        assert_eq!(c.normal_page_content_height, 720.0);
1
    }
    // ==================================================================
    // B3: break-awareness (policy-gated)
    // ==================================================================
    use azul_core::{
        geom::{LogicalPosition, LogicalRect, LogicalSize},
        styled_dom::StyledDom,
    };
    use azul_css::props::basic::ColorU;
    use crate::solver3::display_list::{
        BorderRadius as DlBorderRadius, DisplayList, DisplayListItem,
    };
50
    fn rect(y: f32, h: f32) -> LogicalRect {
50
        LogicalRect {
50
            origin: LogicalPosition { x: 0.0, y },
50
            size: LogicalSize {
50
                width: 100.0,
50
                height: h,
50
            },
50
        }
50
    }
42
    fn rect_item(y: f32, h: f32) -> DisplayListItem {
42
        DisplayListItem::Rect {
42
            bounds: rect(y, h).into(),
42
            color: ColorU {
42
                r: 0,
42
                g: 0,
42
                b: 0,
42
                a: 255,
42
            },
42
            border_radius: DlBorderRadius::default(),
42
        }
42
    }
8
    fn text_item(y: f32, h: f32) -> DisplayListItem {
8
        DisplayListItem::Text {
8
            glyphs: Vec::new(),
8
            font_hash: crate::font_traits::FontHash::from_hash(1),
8
            font_size_px: 12.0,
8
            color: ColorU {
8
                r: 0,
8
                g: 0,
8
                b: 0,
8
                a: 255,
8
            },
8
            clip_rect: rect(y, h).into(),
8
            source_node_index: None,
8
        }
8
    }
    /// A DOM whose node 1 is `.avoid { break-inside: avoid; }`, plus a
    /// display list of `(item, source node)` pairs.
9
    fn avoid_fixture(items: Vec<(DisplayListItem, Option<usize>)>) -> (StyledDom, DisplayList) {
9
        let mut dom = azul_core::dom::Dom::create_div();
9
        dom.add_child(
9
            azul_core::dom::Dom::create_div().with_ids_and_classes(
9
                vec![azul_core::dom::IdOrClass::Class("avoid".into())].into(),
            ),
        );
9
        let (css, _warnings) = azul_css::parser2::new_from_str(
9
            ".avoid { break-inside: avoid; } p { widows: 2; orphans: 2; }",
9
        );
9
        let styled = StyledDom::create(&mut dom, css);
9
        let mut dl = DisplayList::default();
26
        for (item, node) in items {
17
            dl.items.push(item);
17
            dl.node_mapping.push(node.map(NodeId::new));
17
        }
9
        (styled, dl)
9
    }
5
    fn breaks_with(
5
        styled: &StyledDom,
5
        dl: &DisplayList,
5
        policy: &BreakPolicy,
5
        first: f32,
5
        normal: f32,
5
    ) -> Vec<PageBreakPosition> {
5
        compute_page_breaks(
5
            &PageBreakInput {
5
                display_list: dl,
5
                layout_tree: None,
5
                styled_dom: styled,
5
                table_headers: None,
5
            },
5
            &constraints(first, normal),
5
            policy,
        )
5
    }
    #[test]
1
    fn policy_off_is_byte_identical_to_the_plain_algorithm() {
1
        let (styled, dl) = avoid_fixture(vec![
1
            (rect_item(0.0, 250.0), None),
1
            (rect_item(80.0, 60.0), Some(1)), // avoid-box straddling y=100
1
        ]);
1
        let plain = compute_page_breaks_from_display_list(&dl, &constraints(100.0, 100.0));
1
        let off = breaks_with(&styled, &dl, &BreakPolicy::default(), 100.0, 100.0);
1
        assert_eq!(plain, off);
1
    }
    #[test]
1
    fn break_inside_avoid_box_is_pushed_intact() {
        // Page 100; the avoid-box spans 80..140 — the naive break at 100 cuts
        // it, so the break snaps UP to the box top (80).
1
        let (styled, dl) = avoid_fixture(vec![
1
            (rect_item(0.0, 250.0), None),
1
            (rect_item(80.0, 60.0), Some(1)),
1
        ]);
1
        let policy = BreakPolicy {
1
            honor_break_inside: true,
1
            ..Default::default()
1
        };
1
        let breaks = breaks_with(&styled, &dl, &policy, 100.0, 100.0);
1
        assert_eq!(
1
            breaks[0].y, 80.0,
            "the break must land at the avoid-box top, got {breaks:?}"
        );
1
        assert!(
1
            matches!(breaks[0].kind, BreakKind::Avoided(pushed_from) if (pushed_from - 100.0).abs() < 0.01)
        );
        // Following pages re-flow from the moved break.
1
        assert_eq!(breaks[1].y, 180.0);
1
    }
    #[test]
1
    fn taller_than_page_avoid_box_is_torn() {
        // The avoid-box spans 0..180 with a 100 page: satisfying it is
        // impossible (monolith rule) — the naive interval stands.
1
        let (styled, dl) = avoid_fixture(vec![
1
            (rect_item(0.0, 250.0), None),
1
            (rect_item(0.0, 180.0), Some(1)),
1
        ]);
1
        let policy = BreakPolicy {
1
            honor_break_inside: true,
1
            ..Default::default()
1
        };
1
        let breaks = breaks_with(&styled, &dl, &policy, 100.0, 100.0);
1
        assert_eq!(breaks[0].y, 100.0);
1
        assert!(matches!(breaks[0].kind, BreakKind::Interval));
1
    }
    #[test]
1
    fn forced_break_wins_over_avoid() {
        // Forced break at 90 INSIDE the avoid-box: forced always applies
        // (CSS Fragmentation §resolution), the avoid-range cannot move it.
1
        let (styled, mut dl) = avoid_fixture(vec![
1
            (rect_item(0.0, 250.0), None),
1
            (rect_item(80.0, 60.0), Some(1)),
1
        ]);
1
        dl.forced_page_breaks = vec![crate::solver3::display_list::ForcedBreak {
1
            y: 90.0,
1
            causing_node: None,
1
        }];
1
        let policy = BreakPolicy {
1
            honor_break_inside: true,
1
            ..Default::default()
1
        };
1
        let breaks = breaks_with(&styled, &dl, &policy, 100.0, 100.0);
1
        assert_eq!(breaks[0].y, 90.0);
1
        assert!(matches!(breaks[0].kind, BreakKind::Forced));
1
    }
    #[test]
1
    fn atomic_lines_never_slice_a_text_rect() {
        // Lines at 90..106 and 106..122; page 100 cuts the first line — the
        // break snaps to its top (90).
1
        let (styled, dl) = avoid_fixture(vec![
1
            (rect_item(0.0, 250.0), None),
1
            (text_item(90.0, 16.0), None),
1
            (text_item(106.0, 16.0), None),
1
        ]);
1
        let policy = BreakPolicy {
1
            atomic_lines: true,
1
            ..Default::default()
1
        };
1
        let breaks = breaks_with(&styled, &dl, &policy, 100.0, 100.0);
1
        assert_eq!(breaks[0].y, 90.0, "{breaks:?}");
1
        assert!(matches!(breaks[0].kind, BreakKind::Avoided(..)));
1
    }
    #[test]
1
    fn orphans_move_the_whole_paragraph() {
        // Paragraph (node 1) with 3 lines at 84..100, 100..116, 116..132;
        // orphans: 2 (from the p rule — attach the class to make it node 1).
        // The naive break at 100 keeps ONE line — fewer than orphans — so the
        // whole paragraph moves (break at its top, 84).
1
        let mut dom = azul_core::dom::Dom::create_div();
1
        dom.add_child(azul_core::dom::Dom::create_p());
1
        let (css, _warnings) = azul_css::parser2::new_from_str("p { widows: 2; orphans: 2; }");
1
        let styled = StyledDom::create(&mut dom, css);
1
        let mut dl = DisplayList::default();
4
        for (item, node) in [
1
            (rect_item(0.0, 250.0), None),
1
            (text_item(84.0, 16.0), Some(1)),
1
            (text_item(100.0, 16.0), Some(1)),
1
            (text_item(116.0, 16.0), Some(1)),
4
        ] {
4
            dl.items.push(item);
4
            dl.node_mapping.push(node.map(NodeId::new));
4
        }
1
        let policy = BreakPolicy {
1
            widows_orphans: true,
1
            ..Default::default()
1
        };
1
        let breaks = compute_page_breaks(
1
            &PageBreakInput {
1
                display_list: &dl,
1
                layout_tree: None,
1
                styled_dom: &styled,
1
                table_headers: None,
1
            },
1
            &constraints(100.0, 100.0),
1
            &policy,
        );
1
        assert_eq!(breaks[0].y, 84.0, "{breaks:?}");
1
        assert!(matches!(breaks[0].kind, BreakKind::Avoided(..)));
1
    }
    #[test]
1
    fn widows_pull_enough_lines_onto_the_next_page() {
        // E20 counterpart to the orphans test. Paragraph (node 1) with 3
        // lines at 68..84, 84..100, 100..116; widows: 2, orphans: 1.
        // The naive break at 100 carries ONE line to the next page — fewer
        // than widows — so the break moves UP one line (84): 1 line stays
        // (orphans: 1 satisfied), 2 lines carry over (widows: 2 satisfied).
1
        let mut dom = azul_core::dom::Dom::create_div();
1
        dom.add_child(azul_core::dom::Dom::create_p());
1
        let (css, _warnings) = azul_css::parser2::new_from_str("p { widows: 2; orphans: 1; }");
1
        let styled = StyledDom::create(&mut dom, css);
1
        let mut dl = DisplayList::default();
4
        for (item, node) in [
1
            (rect_item(0.0, 250.0), None),
1
            (text_item(68.0, 16.0), Some(1)),
1
            (text_item(84.0, 16.0), Some(1)),
1
            (text_item(100.0, 16.0), Some(1)),
4
        ] {
4
            dl.items.push(item);
4
            dl.node_mapping.push(node.map(NodeId::new));
4
        }
1
        let policy = BreakPolicy {
1
            widows_orphans: true,
1
            ..Default::default()
1
        };
1
        let breaks = compute_page_breaks(
1
            &PageBreakInput {
1
                display_list: &dl,
1
                layout_tree: None,
1
                styled_dom: &styled,
1
                table_headers: None,
1
            },
1
            &constraints(100.0, 100.0),
1
            &policy,
        );
1
        assert_eq!(breaks[0].y, 84.0, "{breaks:?}");
1
        assert!(matches!(breaks[0].kind, BreakKind::Avoided(..)));
1
    }
    #[test]
1
    fn taller_than_page_avoid_box_lands_in_the_monolith_report() {
        // E21: the tear itself is unchanged (monolith rule), but it is no
        // longer silent. Avoid-box node 1 spans 250px on 100px pages.
1
        let (styled, dl) = avoid_fixture(vec![
1
            (rect_item(0.0, 400.0), None),
1
            (rect_item(20.0, 250.0), Some(1)),
1
        ]);
1
        let policy = BreakPolicy {
1
            honor_break_inside: true,
1
            ..Default::default()
1
        };
1
        let input = PageBreakInput {
1
            display_list: &dl,
1
            layout_tree: None,
1
            styled_dom: &styled,
1
            table_headers: None,
1
        };
1
        let (breaks, warnings) =
1
            compute_page_breaks_with_report(&input, &constraints(100.0, 100.0), &policy);
1
        assert_eq!(
            breaks,
1
            compute_page_breaks(&input, &constraints(100.0, 100.0), &policy),
            "the report only ADDS information, breaks are identical"
        );
1
        assert_eq!(warnings.len(), 1, "{warnings:?}");
1
        assert_eq!(warnings[0].node, Some(NodeId::new(1)));
1
        assert_eq!(warnings[0].reason, MonolithReason::AvoidBoxTallerThanPage);
1
        assert_eq!((warnings[0].top, warnings[0].bottom), (20.0, 270.0));
        // A box that FITS the page produces no warning.
1
        let (styled2, dl2) = avoid_fixture(vec![
1
            (rect_item(0.0, 400.0), None),
1
            (rect_item(20.0, 60.0), Some(1)),
1
        ]);
1
        let input2 = PageBreakInput {
1
            display_list: &dl2,
1
            layout_tree: None,
1
            styled_dom: &styled2,
1
            table_headers: None,
1
        };
1
        let (_, warnings2) =
1
            compute_page_breaks_with_report(&input2, &constraints(100.0, 100.0), &policy);
1
        assert!(warnings2.is_empty(), "{warnings2:?}");
1
    }
    /// A synthetic table DOM + display list: div > table > (thead > tr,
    /// tbody > tr×3), with one rect item per row (and one for the thead),
    /// mapped to the right nodes.
4
    fn table_fixture(thead_h: f32, row_h: f32, rows: usize) -> (StyledDom, DisplayList) {
        use azul_core::dom::Dom;
4
        let tag = azul_core::xml::tag_to_node_type;
4
        let mut table = Dom::create_node(tag("table"));
4
        let mut thead = Dom::create_node(tag("thead"));
4
        thead.add_child(Dom::create_node(tag("tr")));
4
        table.add_child(thead);
4
        let mut tbody = Dom::create_node(tag("tbody"));
21
        for _ in 0..rows {
21
            tbody.add_child(Dom::create_node(tag("tr")));
21
        }
4
        table.add_child(tbody);
4
        let mut root = Dom::create_div();
4
        root.add_child(table);
4
        let styled = StyledDom::create_from_dom(root);
        // Locate node ids structurally: thead's tr + tbody's trs.
4
        let container = styled.node_data.as_container();
4
        let trs: Vec<NodeId> = (0..container.len())
4
            .map(NodeId::new)
41
            .filter(|n| matches!(container[*n].get_node_type(), azul_core::dom::NodeType::Tr))
4
            .collect();
4
        assert_eq!(trs.len(), rows + 1, "thead tr + body trs");
4
        let mut dl = DisplayList::default();
        // thead row rect at the table top.
4
        dl.items.push(rect_item(0.0, thead_h));
4
        dl.node_mapping.push(Some(trs[0]));
        // body rows stacked below.
21
        for (i, tr) in trs[1..].iter().enumerate() {
21
            dl.items.push(rect_item(thead_h + i as f32 * row_h, row_h));
21
            dl.node_mapping.push(Some(*tr));
21
        }
4
        (styled, dl)
4
    }
    #[test]
1
    fn collect_table_headers_registers_the_thead_rebased() {
1
        let (styled, dl) = table_fixture(20.0, 30.0, 3);
1
        let tracker = crate::solver3::pagination::collect_table_headers(&dl, &styled);
1
        assert_eq!(tracker.tables.len(), 1, "one table registered");
1
        let info = &tracker.tables[0];
1
        assert_eq!(info.thead_height, 20.0);
1
        assert_eq!(info.table_start_y, 0.0);
1
        assert_eq!(info.table_end_y, 20.0 + 3.0 * 30.0);
        // Items stored REBASED to thead-local Y.
1
        let first = info.thead_items[0].bounds().expect("bounds");
1
        assert_eq!(first.origin.y, 0.0);
1
    }
    #[test]
1
    fn continuation_pages_inside_a_table_reserve_the_thead_height() {
        // Table spans 0..320 (thead 20 + 10 rows × 30); page height 100.
1
        let (styled, dl) = table_fixture(20.0, 30.0, 10);
1
        let tracker = crate::solver3::pagination::collect_table_headers(&dl, &styled);
1
        let policy = BreakPolicy {
1
            repeat_table_headers: true,
1
            ..Default::default()
1
        };
1
        let breaks = compute_page_breaks(
1
            &PageBreakInput {
1
                display_list: &dl,
1
                layout_tree: None,
1
                styled_dom: &styled,
1
                table_headers: Some(&tracker),
1
            },
1
            &constraints(100.0, 100.0),
1
            &policy,
        );
        // Page 1 ends at 100 (starts OUTSIDE any table continuation). Every
        // page STARTING inside the table reserves the 20px repeated thead:
        // 100 + 80 = 180, then 260 (the table ends at 320; the page starting
        // at 260 is still inside → 260 + 80 = 340 > 320 → last page).
1
        assert_eq!(ys(&breaks), vec![100.0, 180.0, 260.0], "{breaks:?}");
        // Control: flag off → plain 100/200/300.
1
        let plain = compute_page_breaks(
1
            &PageBreakInput {
1
                display_list: &dl,
1
                layout_tree: None,
1
                styled_dom: &styled,
1
                table_headers: Some(&tracker),
1
            },
1
            &constraints(100.0, 100.0),
1
            &BreakPolicy::default(),
        );
1
        assert_eq!(ys(&plain), vec![100.0, 200.0, 300.0]);
1
    }
    #[test]
1
    fn atomic_table_rows_snap_the_break_to_the_row_top() {
        // Rows at 20..50, 50..80, 80..110, 110..140…: the naive break at 100
        // slices the 80..110 row → snaps to 80.
1
        let (styled, dl) = table_fixture(20.0, 30.0, 6);
1
        let policy = BreakPolicy {
1
            atomic_table_rows: true,
1
            ..Default::default()
1
        };
1
        let breaks = compute_page_breaks(
1
            &PageBreakInput {
1
                display_list: &dl,
1
                layout_tree: None,
1
                styled_dom: &styled,
1
                table_headers: None,
1
            },
1
            &constraints(100.0, 100.0),
1
            &policy,
        );
1
        assert_eq!(breaks[0].y, 80.0, "{breaks:?}");
1
        assert!(matches!(breaks[0].kind, BreakKind::Avoided(..)));
        // Monolith rule: a row TALLER than the page still tears.
1
        let (styled, dl) = table_fixture(20.0, 300.0, 2);
1
        let breaks = compute_page_breaks(
1
            &PageBreakInput {
1
                display_list: &dl,
1
                layout_tree: None,
1
                styled_dom: &styled,
1
                table_headers: None,
1
            },
1
            &constraints(100.0, 100.0),
1
            &policy,
        );
1
        assert_eq!(breaks[0].y, 100.0);
1
        assert!(matches!(breaks[0].kind, BreakKind::Interval));
1
    }
    #[test]
1
    fn page_sequence_heights_flow_into_break_positions() {
        use azul_core::geom::LogicalSize;
        use crate::solver3::pagination::{PageMargins, PageSequence, PageSetup};
1
        let setup = |h: f32| PageSetup {
9
            page_size: LogicalSize::new(200.0, h),
9
            margins: PageMargins::default(),
9
            header_footer: Default::default(),
9
        };
1
        let (styled, dl) = avoid_fixture(vec![(rect_item(0.0, 500.0), None)]);
1
        let input = PageBreakInput {
1
            display_list: &dl,
1
            layout_tree: None,
1
            styled_dom: &styled,
1
            table_headers: None,
1
        };
        // Default 100-high pages, but PAGE 2 (0-based index 1) is 150 high:
        // breaks at 100, 250, 350, 450 (the classic office-suite "page 345 is different").
1
        let mut seq = PageSequence::uniform(setup(100.0));
1
        seq.set_override(1, setup(150.0));
1
        let breaks = compute_page_breaks_with_sequence(&input, &seq, &BreakPolicy::default());
1
        assert_eq!(ys(&breaks), vec![100.0, 250.0, 350.0, 450.0], "{breaks:?}");
        // Odd/even parity: 1-based odd pages 100 high, even pages 60 high:
        // breaks 100, 160, 260, 320, 420, 480 (alternating).
1
        let mut seq = PageSequence::uniform(setup(100.0));
1
        seq.even_pages = crate::solver3::pagination::OptionPageSetup::Some(setup(60.0));
1
        let breaks = compute_page_breaks_with_sequence(&input, &seq, &BreakPolicy::default());
1
        assert_eq!(
1
            ys(&breaks),
1
            vec![100.0, 160.0, 260.0, 320.0, 420.0, 480.0],
            "{breaks:?}"
        );
        // Different-first-page: first 40 high, rest 100: 40, 140, 240, …
1
        let mut seq = PageSequence::uniform(setup(100.0));
1
        seq.first_page = crate::solver3::pagination::OptionPageSetup::Some(setup(40.0));
1
        let breaks = compute_page_breaks_with_sequence(&input, &seq, &BreakPolicy::default());
1
        assert_eq!(
1
            ys(&breaks),
1
            vec![40.0, 140.0, 240.0, 340.0, 440.0],
            "{breaks:?}"
        );
        // Precedence: explicit override BEATS parity on the same index.
1
        let mut seq = PageSequence::uniform(setup(100.0));
1
        seq.even_pages = crate::solver3::pagination::OptionPageSetup::Some(setup(60.0));
1
        seq.set_override(1, setup(150.0)); // page 2 (even) overridden
1
        let breaks = compute_page_breaks_with_sequence(&input, &seq, &BreakPolicy::default());
1
        assert_eq!(breaks[1].y, 250.0, "override wins over parity: {breaks:?}");
1
    }
    #[test]
1
    fn page_setup_content_height_subtracts_margins_and_decoration() {
        use azul_core::geom::LogicalSize;
        use crate::solver3::pagination::{HeaderFooterConfig, PageMargins, PageSetup};
1
        let setup = PageSetup {
1
            page_size: LogicalSize::new(210.0, 297.0),
1
            margins: PageMargins {
1
                top: 20.0,
1
                right: 15.0,
1
                bottom: 20.0,
1
                left: 15.0,
1
            },
1
            header_footer: HeaderFooterConfig {
1
                show_footer: true,
1
                footer_height: 20.0,
1
                ..Default::default()
1
            },
1
        };
1
        assert_eq!(setup.content_height(), 297.0 - 40.0 - 20.0);
1
        assert_eq!(setup.content_width(), 210.0 - 30.0);
1
    }
    #[test]
1
    fn recompute_reuses_previous_values_where_pages_converge() {
        // A 1000-tall document, page 100: breaks at 100..900.
1
        let (styled, dl) = avoid_fixture(vec![(rect_item(0.0, 1000.0), None)]);
1
        let input = PageBreakInput {
1
            display_list: &dl,
1
            layout_tree: None,
1
            styled_dom: &styled,
1
            table_headers: None,
1
        };
1
        let c = constraints(100.0, 100.0);
1
        let policy = BreakPolicy::default();
1
        let prev = compute_page_breaks(&input, &c, &policy);
1
        assert_eq!(prev.len(), 9);
        // Edit on "page 3" (dirty from 250) that does NOT move any break:
        // the result must be VALUE-identical to prev — every span reusable.
1
        let again = recompute_page_breaks_from(&prev, &input, &c, &policy, 250.0);
1
        assert_eq!(again, prev, "no break moved → full value reuse");
        // A forced break appears at 450 (content change at 450): breaks
        // above stay value-identical, the region re-flows from the forced
        // break, and positions that happen to coincide again converge.
1
        let mut dl2 = dl.clone();
1
        dl2.forced_page_breaks = vec![crate::solver3::display_list::ForcedBreak {
1
            y: 450.0,
1
            causing_node: None,
1
        }];
1
        let input2 = PageBreakInput {
1
            display_list: &dl2,
1
            layout_tree: None,
1
            styled_dom: &styled,
1
            table_headers: None,
1
        };
1
        let re = recompute_page_breaks_from(&prev, &input2, &c, &policy, 450.0);
1
        assert_eq!(&re[..4], &prev[..4], "breaks above the change are reused");
1
        assert_eq!(re[4].y, 450.0, "{re:?}");
1
        assert!(matches!(re[4].kind, BreakKind::Forced));
        // The PLAIN algorithm keeps interval positions fixed (500, 600, …),
        // so every break below the insertion converges with prev and comes
        // back as prev's VALUES — the reuse signal a paged viewer caches on.
1
        assert_eq!(&re[5..], &prev[4..], "converged tail is value-reused");
1
    }
    #[test]
1
    fn page_of_y_counts_breaks_at_or_below_y() {
1
        let b = |y: f32, kind: BreakKind| PageBreakPosition {
3
            y,
3
            kind,
3
            causing_node: OptionNodeId::None,
3
        };
1
        let breaks = [
1
            b(100.0, BreakKind::Interval),
1
            b(180.0, BreakKind::Forced),
1
            b(280.0, BreakKind::Interval),
1
        ];
1
        assert_eq!(page_of_y(&breaks, 0.0), 0);
1
        assert_eq!(page_of_y(&breaks, 99.9), 0);
        // A break at EXACTLY y sends the content to the next page
        // ("content at or below y belongs to the next page").
1
        assert_eq!(page_of_y(&breaks, 100.0), 1);
1
        assert_eq!(page_of_y(&breaks, 179.0), 1);
1
        assert_eq!(page_of_y(&breaks, 200.0), 2);
1
        assert_eq!(page_of_y(&breaks, 9999.0), 3);
1
        assert_eq!(page_of_y(&[], 50.0), 0, "no breaks: everything is page 0");
1
    }
    #[test]
1
    fn default_break_policy_is_all_off() {
1
        let p = BreakPolicy::default();
1
        assert!(
1
            !p.honor_break_inside
1
                && !p.widows_orphans
1
                && !p.atomic_lines
1
                && !p.atomic_table_rows
1
                && !p.repeat_table_headers,
            "defaults-off is the bug-compat contract B2 ships under"
        );
1
    }
    #[test]
1
    fn page_spans_skips_zero_height_pages_and_may_be_empty() {
1
        let b = |y: f32| PageBreakPosition {
4
            y,
4
            kind: BreakKind::Interval,
4
            causing_node: OptionNodeId::None,
4
        };
        // Break at 0 and duplicate breaks produce no empty page.
1
        assert_eq!(
1
            page_spans(&[b(0.0), b(100.0), b(100.0)], 250.0),
1
            vec![(0.0, 100.0), (100.0, 250.0)]
        );
        // Break beyond the end: final span still lands on total_height only
        // if content remains.
1
        assert_eq!(page_spans(&[b(250.0)], 250.0), vec![(0.0, 250.0)]);
        // No content, no breaks: empty (callers add the single-page fallback).
1
        assert_eq!(page_spans(&[], 0.0), Vec::<(f32, f32)>::new());
1
    }
}