1
//! CSS Paged Media page decoration: headers, footers, margin boxes, and counters.
2
//!
3
//! This module is the canonical home for paged-media page *decoration*. It provides:
4
//!
5
//! - `FakePageConfig` / `HeaderFooterConfig` — programmatic header/footer setup (a temporary
6
//!   interface until full CSS `@page` rule parsing exists)
7
//! - `MarginBoxContent` / `CounterFormat` — the CSS GCPM margin-box content model and page-counter
8
//!   number formatting (formatting delegates to `super::counters`)
9
//! - `PageInfo` — per-page metadata passed to content generators
10
//! - `TableHeaderInfo` / `TableHeaderTracker` — repeated table headers across pages
11
//!
12
//! The actual page *splitting* is performed by the display-list slicer
13
//! (`paginate_display_list_with_slicer_and_breaks` in `super::display_list`), which
14
//! consumes `HeaderFooterConfig` via its `SlicerConfig`. The continuous-vs-paged media
15
//! decision and page geometry are carried by `crate::paged::FragmentationContext`, and
16
//! CSS break properties are read via `super::getters` (`get_break_before`,
17
//! `get_break_after`, `is_forced_page_break`).
18
//!
19
//! **Note:** Running elements, named strings, and per-page `@page` selectors are not
20
//! yet implemented; only page counters and header/footer configuration are functional.
21
//!
22
//! See: <https://www.w3.org/TR/css-gcpm-3>/
23

            
24
pub use azul_core::paged::PageMargins;
25
use azul_core::refany::{OptionRefAny, RefAny};
26
use azul_css::{impl_option_inner, props::basic::ColorU, AzString, OptionString};
27

            
28
/// Content that can appear in a page margin box.
29
///
30
/// This enum represents the various types of content that CSS GCPM
31
/// allows in margin boxes.
32
#[derive(Clone, PartialEq)]
33
#[repr(C, u8)] // in the C API (9g-ii-f-i): a data-carrying enum
34
pub enum MarginBoxContent {
35
    /// Empty margin box
36
    None,
37
    /// A running element referenced by name: `content: element(header)`
38
    RunningElement(AzString),
39
    /// A named string: `content: string(chapter)`
40
    NamedString(AzString),
41
    /// Page counter: `content: counter(page)`
42
    PageCounter,
43
    /// Total pages counter: `content: counter(pages)`
44
    PagesCounter,
45
    /// Page counter with format: `content: counter(page, lower-roman)`
46
    PageCounterFormatted(CounterFormat),
47
    /// Combined content (e.g., "Page " counter(page) " of " counter(pages))
48
    Combined(MarginBoxContentVec),
49
    /// Literal text
50
    Text(AzString),
51
    /// Custom callback for dynamic content generation (9g-ii-f): the ordinary
52
    /// azul callback shape - a C function pointer plus the app's `RefAny`,
53
    /// which the callback downcasts - so a margin box's text can come from
54
    /// any binding language, not only a Rust closure.
55
    Custom(MarginBoxCustom),
56
}
57

            
58
/// A margin box's custom generator with its data (9g-ii-f): one struct so the
59
/// enum variant carries exactly one field, as the C API requires.
60
#[derive(Clone, PartialEq)]
61
#[repr(C)]
62
pub struct MarginBoxCustom {
63
    /// The generator; called once per occurrence per page.
64
    pub callback: MarginBoxCallback,
65
    /// The app's data, handed to `callback` (shared: a refcount bump per
66
    /// clone of the content, never a deep copy).
67
    pub data: RefAny,
68
}
69

            
70
impl core::fmt::Debug for MarginBoxCustom {
71
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
72
        write!(f, "MarginBoxCustom(<callback>)")
73
    }
74
}
75

            
76
/// The C shape of a margin-box content generator (9g-ii-f): the app's data
77
/// and the page, out comes the text.
78
pub type MarginBoxCallbackType = extern "C" fn(&mut RefAny, PageInfo) -> AzString;
79

            
80
/// A margin-box content generator plus the foreign callable a binding
81
/// language stores in `ctx` (native Rust and C leave it `None`).
82
#[repr(C)]
83
pub struct MarginBoxCallback {
84
    pub cb: MarginBoxCallbackType,
85
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
86
    pub ctx: OptionRefAny,
87
}
88

            
89
azul_core::impl_callback!(MarginBoxCallback, MarginBoxCallbackType);
90

            
91
azul_css::impl_option!(
92
    MarginBoxContent,
93
    OptionMarginBoxContent,
94
    copy = false,
95
    [Debug, Clone, PartialEq]
96
);
97
azul_css::impl_vec!(
98
    MarginBoxContent,
99
    MarginBoxContentVec,
100
    MarginBoxContentVecDestructor,
101
    MarginBoxContentVecDestructorType,
102
    MarginBoxContentVecSlice,
103
    OptionMarginBoxContent
104
);
105
azul_css::impl_vec_clone!(
106
    MarginBoxContent,
107
    MarginBoxContentVec,
108
    MarginBoxContentVecDestructor
109
);
110
azul_css::impl_vec_partialeq!(MarginBoxContent, MarginBoxContentVec);
111
azul_css::impl_vec_debug!(MarginBoxContent, MarginBoxContentVec);
112

            
113
impl MarginBoxContent {
114
    /// `Combined` from a Rust vector.
115
    #[must_use]
116
160
    pub fn combined(parts: Vec<Self>) -> Self {
117
160
        Self::Combined(parts.into())
118
160
    }
119

            
120
    /// Literal text.
121
    #[must_use]
122
7
    pub fn text(text: impl Into<String>) -> Self {
123
7
        Self::Text(AzString::from(text.into()))
124
7
    }
125

            
126
    /// A custom generator from a C callback and the data it downcasts.
127
    #[must_use]
128
2
    pub fn custom(cb: MarginBoxCallbackType, data: RefAny) -> Self {
129
2
        Self::Custom(MarginBoxCustom {
130
2
            callback: MarginBoxCallback::from(cb),
131
2
            data,
132
2
        })
133
2
    }
134
}
135

            
136
impl std::fmt::Debug for MarginBoxContent {
137
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138
        match self {
139
            Self::None => write!(f, "None"),
140
            Self::RunningElement(s) => f.debug_tuple("RunningElement").field(s).finish(),
141
            Self::NamedString(s) => f.debug_tuple("NamedString").field(s).finish(),
142
            Self::PageCounter => write!(f, "PageCounter"),
143
            Self::PagesCounter => write!(f, "PagesCounter"),
144
            Self::PageCounterFormatted(format) => f
145
                .debug_struct("PageCounterFormatted")
146
                .field("format", format)
147
                .finish(),
148
            Self::Combined(v) => f.debug_tuple("Combined").field(v).finish(),
149
            Self::Text(s) => f.debug_tuple("Text").field(s).finish(),
150
            Self::Custom(_) => write!(f, "Custom(<callback>)"),
151
        }
152
    }
153
}
154

            
155
/// Counter formatting styles (subset of CSS list-style-type).
156
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
157
#[repr(C)] // in the C API (9g-ii-f-i)
158
pub enum CounterFormat {
159
    #[default]
160
    Decimal,
161
    DecimalLeadingZero,
162
    LowerRoman,
163
    UpperRoman,
164
    LowerAlpha,
165
    UpperAlpha,
166
    LowerGreek,
167
}
168

            
169
impl CounterFormat {
170
    /// Format a number according to this counter style.
171
    #[must_use]
172
16090
    pub fn format(&self, n: usize) -> String {
173
        use super::counters::{to_alphabetic, to_greek, to_roman};
174
16090
        match self {
175
12
            Self::Decimal => n.to_string(),
176
14
            Self::DecimalLeadingZero => format!("{n:02}"),
177
4012
            Self::LowerRoman => to_roman(n, false),
178
4011
            Self::UpperRoman => to_roman(n, true),
179
3014
            Self::LowerAlpha => to_alphabetic(n, false),
180
3014
            Self::UpperAlpha => to_alphabetic(n, true),
181
2013
            Self::LowerGreek => to_greek(n, false),
182
        }
183
16090
    }
184
}
185

            
186
/// Information about the current page, passed to content generators.
187
#[derive(Debug, Clone, Copy)]
188
#[repr(C)] // crosses the MarginBoxCallback C boundary (9g-ii-f)
189
#[allow(clippy::struct_excessive_bools)] // independent page-position flags (first/last/left/right)
190
pub struct PageInfo {
191
    /// Current page number (1-indexed for display)
192
    pub page_number: usize,
193
    /// Total number of pages (may be 0 if unknown during first pass)
194
    pub total_pages: usize,
195
    /// Whether this is the first page
196
    pub is_first: bool,
197
    /// Whether this is the last page
198
    pub is_last: bool,
199
    /// Whether this is a left (verso) page (for duplex printing)
200
    pub is_left: bool,
201
    /// Whether this is a right (recto) page
202
    pub is_right: bool,
203
    /// Whether this is a blank page (inserted for left/right alignment)
204
    pub is_blank: bool,
205
}
206

            
207
impl PageInfo {
208
    /// Create `PageInfo` for a specific page.
209
    #[must_use]
210
1582
    pub const fn new(page_number: usize, total_pages: usize) -> Self {
211
        Self {
212
1582
            page_number,
213
1582
            total_pages,
214
1582
            is_first: page_number == 1,
215
1582
            is_last: total_pages > 0 && page_number == total_pages,
216
1582
            is_left: page_number.is_multiple_of(2), // Even pages are left (verso)
217
1582
            is_right: page_number % 2 == 1,         // Odd pages are right (recto)
218
            is_blank: false,
219
        }
220
1582
    }
221
}
222

            
223
/// Default height for page headers and footers (in points).
224
const DEFAULT_HEADER_FOOTER_HEIGHT: f32 = 30.0;
225

            
226
/// Default font size for header/footer text (in points).
227
const DEFAULT_HEADER_FOOTER_FONT_SIZE: f32 = 10.0;
228

            
229
/// Configuration for page headers and footers.
230
///
231
/// This is a simplified interface for the common case of adding
232
/// headers and footers, consumed by the display-list slicer via its `SlicerConfig`.
233
#[derive(Debug, Clone, PartialEq)]
234
#[repr(C)] // in the C API through `PageSetup` (9g-ii-f-i); widest fields first
235
pub struct HeaderFooterConfig {
236
    /// Content generator for the header
237
    pub header_content: MarginBoxContent,
238
    /// Content generator for the footer
239
    pub footer_content: MarginBoxContent,
240
    /// Height of the header area (if shown)
241
    pub header_height: f32,
242
    /// Height of the footer area (if shown)  
243
    pub footer_height: f32,
244
    /// Font size for header/footer text
245
    pub font_size: f32,
246
    /// Text color for header/footer
247
    pub text_color: ColorU,
248
    /// Whether to show a header on each page
249
    pub show_header: bool,
250
    /// Whether to show a footer on each page
251
    pub show_footer: bool,
252
    /// Whether to skip header/footer on first page
253
    pub skip_first_page: bool,
254
}
255

            
256
impl Default for HeaderFooterConfig {
257
63
    fn default() -> Self {
258
63
        Self {
259
63
            show_header: false,
260
63
            show_footer: false,
261
63
            header_height: DEFAULT_HEADER_FOOTER_HEIGHT,
262
63
            footer_height: DEFAULT_HEADER_FOOTER_HEIGHT,
263
63
            header_content: MarginBoxContent::None,
264
63
            footer_content: MarginBoxContent::None,
265
63
            font_size: DEFAULT_HEADER_FOOTER_FONT_SIZE,
266
63
            text_color: ColorU {
267
63
                r: 0,
268
63
                g: 0,
269
63
                b: 0,
270
63
                a: 255,
271
63
            },
272
63
            skip_first_page: false,
273
63
        }
274
63
    }
275
}
276

            
277
impl HeaderFooterConfig {
278
    /// Create a config with page numbers in the footer.
279
    #[must_use]
280
2
    pub fn with_page_numbers() -> Self {
281
2
        Self {
282
2
            show_footer: true,
283
2
            footer_content: MarginBoxContent::combined(vec![
284
2
                MarginBoxContent::Text("Page ".into()),
285
2
                MarginBoxContent::PageCounter,
286
2
                MarginBoxContent::Text(" of ".into()),
287
2
                MarginBoxContent::PagesCounter,
288
2
            ]),
289
2
            ..Default::default()
290
2
        }
291
2
    }
292

            
293
    /// Create a config with page numbers in both header and footer.
294
    #[must_use]
295
2
    pub fn with_header_and_footer_page_numbers() -> Self {
296
2
        Self {
297
2
            show_header: true,
298
2
            show_footer: true,
299
2
            header_content: MarginBoxContent::combined(vec![
300
2
                MarginBoxContent::Text("Page ".into()),
301
2
                MarginBoxContent::PageCounter,
302
2
            ]),
303
2
            footer_content: MarginBoxContent::combined(vec![
304
2
                MarginBoxContent::Text("Page ".into()),
305
2
                MarginBoxContent::PageCounter,
306
2
                MarginBoxContent::Text(" of ".into()),
307
2
                MarginBoxContent::PagesCounter,
308
2
            ]),
309
2
            ..Default::default()
310
2
        }
311
2
    }
312

            
313
    /// Set custom header text.
314
    #[must_use]
315
4
    pub fn with_header_text(mut self, text: impl Into<String>) -> Self {
316
4
        self.show_header = true;
317
4
        self.header_content = MarginBoxContent::text(text);
318
4
        self
319
4
    }
320

            
321
    /// Set custom footer text.
322
    #[must_use]
323
2
    pub fn with_footer_text(mut self, text: impl Into<String>) -> Self {
324
2
        self.show_footer = true;
325
2
        self.footer_content = MarginBoxContent::text(text);
326
2
        self
327
2
    }
328

            
329
    /// Generate the text content for a margin box given page info.
330
    // `&self` is only reached via the recursive Combined arm; it is kept because this is a
331
    // public method and converting to an associated fn would break the `x.generate_content(..)`
332
    // API.
333
    #[allow(clippy::only_used_in_recursion)]
334
    #[must_use]
335
350
    pub fn generate_content(&self, content: &MarginBoxContent, info: PageInfo) -> String {
336
350
        match content {
337
2
            MarginBoxContent::None => String::new(),
338
93
            MarginBoxContent::Text(s) => s.as_str().to_string(),
339
39
            MarginBoxContent::PageCounter => info.page_number.to_string(),
340
            MarginBoxContent::PagesCounter => {
341
30
                if info.total_pages > 0 {
342
28
                    info.total_pages.to_string()
343
                } else {
344
2
                    "?".to_string()
345
                }
346
            }
347
8
            MarginBoxContent::PageCounterFormatted(format) => format.format(info.page_number),
348
174
            MarginBoxContent::Combined(parts) => parts
349
174
                .iter()
350
283
                .map(|p| self.generate_content(p, info))
351
174
                .collect(),
352
1
            MarginBoxContent::NamedString(name) => {
353
                // TODO: Look up named string from document context
354
1
                format!("[string:{}]", name.as_str())
355
            }
356
1
            MarginBoxContent::RunningElement(name) => {
357
                // Running elements are rendered as display items, not text
358
1
                format!("[element:{}]", name.as_str())
359
            }
360
2
            MarginBoxContent::Custom(custom) => {
361
                // The callback gets its own handle to the shared data (a
362
                // refcount bump), as every azul callback does.
363
2
                let mut data = custom.data.clone();
364
2
                (custom.callback.cb)(&mut data, info).as_str().to_string()
365
            }
366
        }
367
350
    }
368

            
369
    /// Get the header text for a specific page.
370
    #[must_use]
371
26
    pub fn header_text(&self, info: PageInfo) -> String {
372
26
        if !self.show_header {
373
4
            return String::new();
374
22
        }
375
22
        if self.skip_first_page && info.is_first {
376
2
            return String::new();
377
20
        }
378
20
        self.generate_content(&self.header_content, info)
379
26
    }
380

            
381
    /// Get the footer text for a specific page.
382
    #[must_use]
383
39
    pub fn footer_text(&self, info: PageInfo) -> String {
384
39
        if !self.show_footer {
385
3
            return String::new();
386
36
        }
387
36
        if self.skip_first_page && info.is_first {
388
2
            return String::new();
389
34
        }
390
34
        self.generate_content(&self.footer_content, info)
391
39
    }
392
}
393

            
394
/// Temporary configuration for page headers/footers without CSS `@page` parsing.
395
///
396
/// Provides programmatic control over page decoration until full CSS `@page`
397
/// rule support is implemented.
398
///
399
/// ## Supported Features
400
///
401
/// - Page numbers in header and/or footer
402
/// - Custom text in header and/or footer
403
/// - Number format (decimal, roman numerals, alphabetic, greek)
404
/// - Skip first page option
405
///
406
/// ## Example
407
///
408
/// ```rust
409
/// use azul_layout::solver3::pagination::FakePageConfig;
410
///
411
/// let config = FakePageConfig::new()
412
///     .with_footer_page_numbers()
413
///     .with_header_text("My Document")
414
///     .skip_first_page(true);
415
///
416
/// let header_footer = config.to_header_footer_config();
417
/// ```
418
#[derive(Debug, Clone, PartialEq)]
419
#[repr(C)] // `CallbackInfo::query_pagination`'s argument (9g-ii-f-i); widest fields first
420
#[allow(clippy::struct_excessive_bools)] // independent header/footer toggle flags
421
pub struct FakePageConfig {
422
    /// office-suite-style per-page setup sequence (`None` = uniform pages from
423
    /// the fields above).
424
    pub page_sequence: OptionPageSequence,
425
    /// Header text (static text, or None for page numbers only)
426
    pub header_text: OptionString,
427
    /// Footer text (static text, or None for page numbers only)
428
    pub footer_text: OptionString,
429
    /// Header height in points
430
    pub header_height: f32,
431
    /// Footer height in points
432
    pub footer_height: f32,
433
    /// Font size for header/footer text
434
    pub font_size: f32,
435
    /// Number format for page counters
436
    pub number_format: CounterFormat,
437
    /// Break-awareness policy for pagination (all-off default = plain
438
    /// interval slicing; printpdf flips the flags on with a changelog entry).
439
    pub break_policy: crate::solver3::page_breaks::BreakPolicy,
440
    /// Text color for header/footer
441
    pub text_color: ColorU,
442
    /// Show header on pages
443
    pub show_header: bool,
444
    /// Show footer on pages
445
    pub show_footer: bool,
446
    /// Include page number in header
447
    pub header_page_number: bool,
448
    /// Include page number in footer
449
    pub footer_page_number: bool,
450
    /// Include total pages count ("of Y") in header
451
    pub header_total_pages: bool,
452
    /// Include total pages count ("of Y") in footer
453
    pub footer_total_pages: bool,
454
    /// Skip header/footer on first page
455
    pub skip_first_page: bool,
456
}
457

            
458
impl Default for FakePageConfig {
459
213
    fn default() -> Self {
460
213
        Self {
461
213
            show_header: false,
462
213
            show_footer: false,
463
213
            header_text: OptionString::None,
464
213
            footer_text: OptionString::None,
465
213
            header_page_number: false,
466
213
            footer_page_number: false,
467
213
            header_total_pages: false,
468
213
            footer_total_pages: false,
469
213
            number_format: CounterFormat::Decimal,
470
213
            skip_first_page: false,
471
213
            header_height: DEFAULT_HEADER_FOOTER_HEIGHT,
472
213
            footer_height: DEFAULT_HEADER_FOOTER_HEIGHT,
473
213
            font_size: DEFAULT_HEADER_FOOTER_FONT_SIZE,
474
213
            text_color: ColorU {
475
213
                r: 0,
476
213
                g: 0,
477
213
                b: 0,
478
213
                a: 255,
479
213
            },
480
213
            break_policy: crate::solver3::page_breaks::BreakPolicy::default(),
481
213
            page_sequence: OptionPageSequence::None,
482
213
        }
483
213
    }
484
}
485

            
486
impl FakePageConfig {
487
    /// Create a new empty configuration (no headers/footers).
488
    #[must_use]
489
213
    pub fn new() -> Self {
490
213
        Self::default()
491
213
    }
492

            
493
    /// Enable footer with "Page X of Y" format.
494
    #[must_use]
495
7
    pub const fn with_footer_page_numbers(mut self) -> Self {
496
7
        self.show_footer = true;
497
7
        self.footer_page_number = true;
498
7
        self.footer_total_pages = true;
499
7
        self
500
7
    }
501

            
502
    /// Enable header with "Page X" format.
503
    #[must_use]
504
7
    pub const fn with_header_page_numbers(mut self) -> Self {
505
7
        self.show_header = true;
506
7
        self.header_page_number = true;
507
7
        self
508
7
    }
509

            
510
    /// Enable both header and footer with page numbers.
511
    #[must_use]
512
3
    pub const fn with_header_and_footer_page_numbers(mut self) -> Self {
513
3
        self.show_header = true;
514
3
        self.show_footer = true;
515
3
        self.header_page_number = true;
516
3
        self.footer_page_number = true;
517
3
        self.footer_total_pages = true;
518
3
        self
519
3
    }
520

            
521
    /// Set custom header text.
522
    #[must_use]
523
3
    pub fn with_header_text(mut self, text: impl Into<String>) -> Self {
524
3
        self.show_header = true;
525
3
        self.header_text = OptionString::Some(AzString::from(text.into()));
526
3
        self
527
3
    }
528

            
529
    /// Set custom footer text.
530
    #[must_use]
531
3
    pub fn with_footer_text(mut self, text: impl Into<String>) -> Self {
532
3
        self.show_footer = true;
533
3
        self.footer_text = OptionString::Some(AzString::from(text.into()));
534
3
        self
535
3
    }
536

            
537
    /// Set the number format for page counters.
538
    #[must_use]
539
4
    pub const fn with_number_format(mut self, format: CounterFormat) -> Self {
540
4
        self.number_format = format;
541
4
        self
542
4
    }
543

            
544
    /// Skip header/footer on the first page.
545
    #[must_use]
546
5
    pub const fn skip_first_page(mut self, skip: bool) -> Self {
547
5
        self.skip_first_page = skip;
548
5
        self
549
5
    }
550

            
551
    /// Set header height.
552
    #[must_use]
553
5
    pub const fn with_header_height(mut self, height: f32) -> Self {
554
5
        self.header_height = height;
555
5
        self
556
5
    }
557

            
558
    /// Set footer height.
559
    #[must_use]
560
4
    pub const fn with_footer_height(mut self, height: f32) -> Self {
561
4
        self.footer_height = height;
562
4
        self
563
4
    }
564

            
565
    /// Set font size for header/footer text.
566
    #[must_use]
567
2
    pub const fn with_font_size(mut self, size: f32) -> Self {
568
2
        self.font_size = size;
569
2
        self
570
2
    }
571

            
572
    /// Set text color for header/footer.
573
    #[must_use]
574
1
    pub const fn with_text_color(mut self, color: ColorU) -> Self {
575
1
        self.text_color = color;
576
1
        self
577
1
    }
578

            
579
    /// Convert this fake config to the internal `HeaderFooterConfig`.
580
    ///
581
    /// This is the bridge between the user-facing API and the internal
582
    /// pagination engine.
583
    #[must_use]
584
1662
    pub fn to_header_footer_config(&self) -> HeaderFooterConfig {
585
1662
        HeaderFooterConfig {
586
1662
            show_header: self.show_header,
587
1662
            show_footer: self.show_footer,
588
1662
            header_height: self.header_height,
589
1662
            footer_height: self.footer_height,
590
1662
            header_content: self.build_header_content(),
591
1662
            footer_content: self.build_footer_content(),
592
1662
            skip_first_page: self.skip_first_page,
593
1662
            font_size: self.font_size,
594
1662
            text_color: self.text_color,
595
1662
        }
596
1662
    }
597

            
598
    /// Build the `MarginBoxContent` for the header.
599
1663
    fn build_header_content(&self) -> MarginBoxContent {
600
1663
        Self::build_margin_content(
601
1663
            self.header_text.as_ref().map(AzString::as_str),
602
1663
            self.header_page_number,
603
1663
            self.header_total_pages,
604
1663
            self.number_format,
605
        )
606
1663
    }
607

            
608
    /// Build the `MarginBoxContent` for the footer.
609
1663
    fn build_footer_content(&self) -> MarginBoxContent {
610
1663
        Self::build_margin_content(
611
1663
            self.footer_text.as_ref().map(AzString::as_str),
612
1663
            self.footer_page_number,
613
1663
            self.footer_total_pages,
614
1663
            self.number_format,
615
        )
616
1663
    }
617

            
618
    /// Shared helper for building header/footer margin box content.
619
3331
    fn build_margin_content(
620
3331
        text: Option<&str>,
621
3331
        page_number: bool,
622
3331
        total_pages: bool,
623
3331
        number_format: CounterFormat,
624
3331
    ) -> MarginBoxContent {
625
3331
        let mut parts = Vec::new();
626

            
627
3331
        if let Some(text) = text {
628
11
            parts.push(MarginBoxContent::Text(text.into()));
629
11
            if page_number {
630
4
                parts.push(MarginBoxContent::Text(" - ".into()));
631
7
            }
632
3320
        }
633

            
634
3331
        if page_number {
635
24
            parts.push(MarginBoxContent::Text("Page ".into()));
636
24
            if number_format == CounterFormat::Decimal {
637
16
                parts.push(MarginBoxContent::PageCounter);
638
16
            } else {
639
8
                parts.push(MarginBoxContent::PageCounterFormatted(number_format));
640
8
            }
641

            
642
24
            if total_pages {
643
13
                parts.push(MarginBoxContent::Text(" of ".into()));
644
13
                parts.push(MarginBoxContent::PagesCounter);
645
13
            }
646
3307
        }
647

            
648
3331
        if parts.is_empty() {
649
3300
            MarginBoxContent::None
650
31
        } else if parts.len() == 1 {
651
7
            parts.pop().unwrap()
652
        } else {
653
24
            MarginBoxContent::combined(parts)
654
        }
655
3331
    }
656
}
657

            
658
/// Information about a table that may need header repetition.
659
#[derive(Debug, Clone)]
660
pub struct TableHeaderInfo {
661
    /// The table's node index in the layout tree
662
    pub table_node_index: usize,
663
    /// The Y position where the table starts
664
    pub table_start_y: f32,
665
    /// The Y position where the table ends
666
    pub table_end_y: f32,
667
    /// The thead's display list items (captured during initial render)
668
    pub thead_items: Vec<super::display_list::DisplayListItem>,
669
    /// Height of the thead
670
    pub thead_height: f32,
671
    /// The Y position of the thead relative to table start
672
    pub thead_offset_y: f32,
673
}
674

            
675
/// Context for tracking table headers across pages.
676
#[derive(Debug, Default, Clone)]
677
pub struct TableHeaderTracker {
678
    /// All tables with theads that might need repetition
679
    pub tables: Vec<TableHeaderInfo>,
680
}
681

            
682
impl TableHeaderTracker {
683
    #[must_use]
684
19
    pub fn new() -> Self {
685
19
        Self::default()
686
19
    }
687

            
688
    /// Register a table's thead for potential repetition.
689
1088
    pub fn register_table_header(&mut self, info: TableHeaderInfo) {
690
1088
        self.tables.push(info);
691
1088
    }
692

            
693
    /// Get theads that should be repeated on a specific page.
694
    ///
695
    /// Returns the thead items that need to be injected at the top of the page,
696
    /// along with the Y offset where they should appear.
697
    ///
698
    /// Kept for compatibility: offsets are the LEGACY vertical stack (each
699
    /// thead below the previous). The slicer now uses
700
    /// [`Self::straddling_tables_for_page`] and places theads X-aware
701
    /// (side-by-side tables keep their own column, nested ones stack).
702
    #[must_use]
703
41
    pub fn get_repeated_headers_for_page(
704
41
        &self,
705
41
        page_index: usize,
706
41
        page_top_y: f32,
707
41
        page_bottom_y: f32,
708
41
    ) -> Vec<(f32, &[super::display_list::DisplayListItem], f32)> {
709
41
        let mut stack_offset = 0.0_f32;
710
41
        self.straddling_tables_for_page(page_index, page_top_y, page_bottom_y)
711
41
            .into_iter()
712
71
            .map(|t| {
713
71
                let entry = (stack_offset, t.thead_items.as_slice(), t.thead_height);
714
71
                stack_offset += t.thead_height;
715
71
                entry
716
71
            })
717
41
            .collect()
718
41
    }
719

            
720
    /// The tables whose content STRADDLES this page top (started strictly
721
    /// above, still continuing) — the ones whose thead must repeat here.
722
    /// Two SIBLING tables can only both straddle when they sit side by side
723
    /// (or nested); the slicer decides placement from their x-extents.
724
    #[must_use]
725
1564
    pub fn straddling_tables_for_page(
726
1564
        &self,
727
1564
        page_index: usize,
728
1564
        page_top_y: f32,
729
1564
        page_bottom_y: f32,
730
1564
    ) -> Vec<&TableHeaderInfo> {
731
        // Page 0 never repeats anything (the original thead is on it), and a
732
        // degenerate/inverted page has no room for a header.
733
1564
        if page_index == 0 || page_bottom_y <= page_top_y {
734
1362
            return Vec::new();
735
202
        }
736
202
        self.tables
737
202
            .iter()
738
202
            .filter(|table| table.table_start_y < page_top_y && table.table_end_y > page_top_y)
739
202
            .collect()
740
1564
    }
741
}
742

            
743
/// ONE page's complete setup — size (orientation = which side is longer),
744
/// margins, and header/footer decoration. The classic office suites "page setup" unit.
745
#[derive(Debug, Clone, PartialEq)]
746
#[repr(C)] // in the C API through `PageSequence` (9g-ii-f-i); the 8-aligned config first
747
pub struct PageSetup {
748
    /// Header/footer decoration for pages using this setup (heights count
749
    /// against the content area; text/numbering render per page).
750
    pub header_footer: HeaderFooterConfig,
751
    /// Full page size INCLUDING margins (swap the sides for landscape).
752
    pub page_size: azul_core::geom::LogicalSize,
753
    /// Page margins in logical px (CSS order).
754
    pub margins: PageMargins,
755
}
756

            
757
azul_css::impl_option!(
758
    PageSetup,
759
    OptionPageSetup,
760
    copy = false,
761
    [Debug, Clone, PartialEq]
762
);
763

            
764
/// One page's explicit setup in a [`PageSequence`] (9g-ii-f-i): the C shape
765
/// of what was a `BTreeMap<usize, PageSetup>` entry.
766
#[derive(Debug, Clone, PartialEq)]
767
#[repr(C)]
768
pub struct PageSetupOverride {
769
    /// Zero-based page index.
770
    pub page: usize,
771
    pub setup: PageSetup,
772
}
773

            
774
azul_css::impl_option!(
775
    PageSetupOverride,
776
    OptionPageSetupOverride,
777
    copy = false,
778
    [Debug, Clone, PartialEq]
779
);
780
azul_css::impl_vec!(
781
    PageSetupOverride,
782
    PageSetupOverrideVec,
783
    PageSetupOverrideVecDestructor,
784
    PageSetupOverrideVecDestructorType,
785
    PageSetupOverrideVecSlice,
786
    OptionPageSetupOverride
787
);
788
azul_css::impl_vec_clone!(
789
    PageSetupOverride,
790
    PageSetupOverrideVec,
791
    PageSetupOverrideVecDestructor
792
);
793
azul_css::impl_vec_partialeq!(PageSetupOverride, PageSetupOverrideVec);
794
azul_css::impl_vec_debug!(PageSetupOverride, PageSetupOverrideVec);
795

            
796
impl PageSetup {
797
    /// Content height = page height − vertical margins − active header/footer.
798
    #[must_use]
799
2122
    pub fn content_height(&self) -> f32 {
800
2122
        let header = if self.header_footer.show_header {
801
            self.header_footer.header_height
802
        } else {
803
2122
            0.0
804
        };
805
2122
        let footer = if self.header_footer.show_footer {
806
1
            self.header_footer.footer_height
807
        } else {
808
2121
            0.0
809
        };
810
2122
        (self.page_size.height - self.margins.top - self.margins.bottom - header - footer).max(0.0)
811
2122
    }
812

            
813
    /// Content width = page width − horizontal margins.
814
    #[must_use]
815
2076
    pub fn content_width(&self) -> f32 {
816
2076
        (self.page_size.width - self.margins.left - self.margins.right).max(0.0)
817
2076
    }
818
}
819

            
820
/// The document's page-setup SEQUENCE: one default + sparse overrides.
821
///
822
/// The classic office suites model ("default = A4 portrait, 2cm footer, 1.5cm margins;
823
/// page 345 is landscape"). Resolution precedence per page:
824
/// explicit override > first-page setup > odd/even parity > default.
825
///
826
/// pdf2html maps its HTML dataset annotations (e.g. `data-az-page-*` on
827
/// section elements) + CSS onto this structure and hands it to the paged
828
/// pipeline.
829
///
830
/// FRAGMENTAINER-FLOW STAGING: per-page HEIGHT differences are fully live
831
/// (the break forward-pass consumes per-index content heights — same
832
/// mechanism as the repeated-thead reserve). Per-page WIDTH differences
833
/// (true landscape re-wrap) require laying out INTO the fragmentainer
834
/// sequence with re-measure at boundaries — an engine stage; until then a
835
/// non-uniform width falls back to the default width and says so once.
836
#[derive(Debug, Clone, PartialEq)]
837
#[repr(C)] // in the C API through `FakePageConfig::page_sequence` (9g-ii-f-i)
838
pub struct PageSequence {
839
    pub default: PageSetup,
840
    /// Explicit per-page overrides (0-based page index). Strongest.
841
    pub overrides: PageSetupOverrideVec,
842
    /// the classic office-suite "different first page".
843
    pub first_page: OptionPageSetup,
844
    /// the classic office-suite "different odd & even": odd = 0-based EVEN indices (page 1,
845
    /// 3, … in 1-based speech) — stored by the 1-based convention users
846
    /// think in: `odd_pages` applies to 1-based odd page numbers.
847
    pub odd_pages: OptionPageSetup,
848
    pub even_pages: OptionPageSetup,
849
}
850

            
851
azul_css::impl_option!(
852
    PageSequence,
853
    OptionPageSequence,
854
    copy = false,
855
    [Debug, Clone, PartialEq]
856
);
857

            
858
impl PageSequence {
859
    /// A uniform sequence (every page identical).
860
    #[must_use]
861
11
    pub const fn uniform(default: PageSetup) -> Self {
862
11
        Self {
863
11
            default,
864
11
            overrides: PageSetupOverrideVec::from_const_slice(&[]),
865
11
            first_page: OptionPageSetup::None,
866
11
            odd_pages: OptionPageSetup::None,
867
11
            even_pages: OptionPageSetup::None,
868
11
        }
869
11
    }
870

            
871
    /// Give page `page` (zero-based) its own setup, replacing an earlier
872
    /// override of the same page.
873
5
    pub fn set_override(&mut self, page: usize, setup: PageSetup) {
874
5
        let mut entries = core::mem::take(&mut self.overrides).into_library_owned_vec();
875
5
        match entries.iter_mut().find(|o| o.page == page) {
876
            Some(existing) => existing.setup = setup,
877
5
            None => entries.push(PageSetupOverride { page, setup }),
878
        }
879
5
        self.overrides = entries.into();
880
5
    }
881

            
882
    /// The explicit override for page `page`, if one was set.
883
    #[must_use]
884
1099
    pub fn override_for(&self, page: usize) -> Option<&PageSetup> {
885
1099
        self.overrides
886
1099
            .iter()
887
1099
            .find(|o| o.page == page)
888
1099
            .map(|o| &o.setup)
889
1099
    }
890

            
891
    /// The setup for 0-based page `index`:
892
    /// override > first > odd/even (1-based parity) > default.
893
    #[must_use]
894
1099
    pub fn setup_for_page(&self, index: usize) -> &PageSetup {
895
1099
        if let Some(explicit) = self.override_for(index) {
896
9
            return explicit;
897
1090
        }
898
1090
        if index == 0 {
899
15
            if let Some(first) = self.first_page.as_ref() {
900
2
                return first;
901
13
            }
902
1075
        }
903
1088
        let one_based = index + 1;
904
1088
        if one_based % 2 == 1 {
905
548
            if let Some(odd) = self.odd_pages.as_ref() {
906
                return odd;
907
548
            }
908
540
        } else if let Some(even) = self.even_pages.as_ref() {
909
8
            return even;
910
532
        }
911
1080
        &self.default
912
1099
    }
913

            
914
    /// Whether every page shares the default's content WIDTH (the
915
    /// fragmentainer-flow precondition for the current single-measure
916
    /// layout). Announces the degradation once when violated.
917
    #[must_use]
918
7
    pub fn has_uniform_width(&self) -> bool {
919
7
        let w = self.default.content_width();
920
7
        let all = self
921
7
            .overrides
922
7
            .iter()
923
7
            .map(|o| &o.setup)
924
7
            .chain(self.first_page.as_ref())
925
7
            .chain(self.odd_pages.as_ref())
926
7
            .chain(self.even_pages.as_ref())
927
7
            .all(|s| (s.content_width() - w).abs() < 0.5);
928
7
        if !all {
929
            static ANNOUNCE: std::sync::Once = std::sync::Once::new();
930
1
            ANNOUNCE.call_once(|| {
931
1
                eprintln!(
932
1
                    "[azul][pagination] this PageSequence varies the CONTENT WIDTH                      between pages (landscape override / different margins).                      Re-wrapping text per fragmentainer is not implemented yet —                      content lays out at the DEFAULT width on every page; page                      heights, margins and headers/footers still apply per page                      (announced once)."
933
                );
934
1
            });
935
6
        }
936
7
        all
937
7
    }
938

            
939
    /// Partition the page sequence into WIDTH SECTIONS — maximal runs of
940
    /// consecutive pages sharing a content width. This is the fragmentainer
941
    /// unit for width re-wrap: content lays out ONCE per section at that
942
    /// section's width and is cut at the section boundary (the classic office suites model,
943
    /// where page setup changes at section breaks).
944
    ///
945
    /// The last section is open-ended (`page_count: None`): once every
946
    /// per-page override / parity variation has been passed, the width is
947
    /// constant forever. `max_scan` bounds the scan (parity alternation
948
    /// yields one section per page up to the bound — such sequences degrade
949
    /// to per-page sections and remain correct, just not cheap).
950
    #[must_use]
951
4
    pub fn width_sections(&self, max_scan: usize) -> Vec<WidthSection> {
952
4
        let mut out: Vec<WidthSection> = Vec::new();
953
        // Past the largest explicit override AND the first page AND parity
954
        // variation, the width can still alternate (odd/even) — only treat
955
        // the run as final when parity widths agree with the default.
956
4
        let parity_uniform = {
957
4
            let w = self.default.content_width();
958
4
            self.odd_pages
959
4
                .as_ref()
960
4
                .into_iter()
961
4
                .chain(self.even_pages.as_ref())
962
4
                .all(|s| (s.content_width() - w).abs() < 0.5)
963
        };
964
4
        let last_override = self.overrides.iter().map(|o| o.page).max().unwrap_or(0);
965
8
        for page in 0..max_scan.max(1) {
966
8
            let w = self.setup_for_page(page).content_width();
967
8
            match out.last_mut() {
968
4
                Some(sec) if (sec.content_width - w).abs() < 0.5 => {
969
2
                    if let Some(n) = sec.page_count.as_mut() {
970
2
                        *n += 1;
971
2
                    }
972
                }
973
6
                _ => out.push(WidthSection {
974
6
                    first_page: page,
975
6
                    page_count: Some(1),
976
6
                    content_width: w,
977
6
                }),
978
            }
979
            // Stable tail: no more overrides ahead, first-page passed, parity
980
            // constant — the current section runs forever.
981
8
            if page > last_override && page > 0 && parity_uniform {
982
4
                if let Some(sec) = out.last_mut() {
983
4
                    sec.page_count = None;
984
4
                }
985
4
                break;
986
4
            }
987
        }
988
4
        out
989
4
    }
990
}
991

            
992
/// A maximal run of consecutive pages sharing a content width — the
993
/// fragmentainer unit for width re-wrap. See [`PageSequence::width_sections`].
994
#[derive(Debug, Clone, Copy, PartialEq)]
995
pub struct WidthSection {
996
    /// 0-based index of the first page of the run.
997
    pub first_page: usize,
998
    /// Number of pages in the run; `None` = open-ended (runs to the end of
999
    /// the document).
    pub page_count: Option<usize>,
    pub content_width: f32,
}
/// Capture every table's `<thead>` from the master display list so the
/// slicer can repeat it on continuation pages.
///
/// The REGISTRATION side the tracker always lacked (its
/// `register_table_header` had zero production callers, so
/// `repeat_table_headers` could never do anything).
///
/// Detection is structural: `NodeType::THead` nodes and their owning
/// `NodeType::Table` ancestor; geometry comes from the display list via
/// `node_mapping` (thead items are stored REBASED to thead-local Y, which is
/// what the paginate-time `offset_display_item_y(+page offset)` expects).
#[must_use]
2
pub fn collect_table_headers(
2
    display_list: &super::display_list::DisplayList,
2
    styled_dom: &azul_core::styled_dom::StyledDom,
2
) -> TableHeaderTracker {
    use std::collections::BTreeMap;
    use azul_core::dom::{NodeId, NodeType};
    // Per table: bounds union; per (table with thead): thead item indices +
    // thead bounds union.
    struct Acc {
        table_top: f32,
        table_bottom: f32,
        thead_top: f32,
        thead_bottom: f32,
        thead_items: Vec<usize>,
    }
2
    let node_data = styled_dom.node_data.as_container();
2
    let hierarchy = styled_dom.node_hierarchy.as_container();
    // Memoized classification: which table / thead subtree (if any) a node
    // belongs to.
2
    let mut owner_cache: BTreeMap<NodeId, (Option<NodeId>, Option<NodeId>)> = BTreeMap::new();
15
    let mut classify = |node: NodeId| -> (Option<NodeId>, Option<NodeId>) {
15
        if let Some(hit) = owner_cache.get(&node) {
            return *hit;
15
        }
15
        let mut table = None;
15
        let mut thead = None;
15
        let mut current = Some(node);
45
        while let Some(n) = current {
45
            match node_data
45
                .get(n)
45
                .map(azul_core::dom::NodeData::get_node_type)
            {
2
                Some(NodeType::THead) if thead.is_none() => thead = Some(n),
                Some(NodeType::Table) => {
15
                    table = Some(n);
15
                    break; // the NEAREST table owns; don't escape nested tables
                }
28
                _ => {}
            }
30
            current = hierarchy
30
                .get(n)
30
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
        }
15
        let result = (table, thead);
15
        owner_cache.insert(node, result);
15
        result
15
    };
2
    let mut per_table: BTreeMap<NodeId, Acc> = BTreeMap::new();
15
    for (idx, item) in display_list.items.iter().enumerate() {
15
        let Some(node) = display_list.node_mapping.get(idx).copied().flatten() else {
            continue;
        };
15
        let Some(bounds) = item.bounds() else {
            continue;
        };
15
        let (table, thead) = classify(node);
15
        let Some(table) = table else { continue };
15
        let acc = per_table.entry(table).or_insert(Acc {
15
            table_top: f32::MAX,
15
            table_bottom: f32::MIN,
15
            thead_top: f32::MAX,
15
            thead_bottom: f32::MIN,
15
            thead_items: Vec::new(),
15
        });
15
        let top = bounds.origin.y;
15
        let bottom = bounds.origin.y + bounds.size.height;
15
        acc.table_top = acc.table_top.min(top);
15
        acc.table_bottom = acc.table_bottom.max(bottom);
15
        if thead.is_some() {
2
            acc.thead_top = acc.thead_top.min(top);
2
            acc.thead_bottom = acc.thead_bottom.max(bottom);
2
            acc.thead_items.push(idx);
13
        }
    }
2
    let mut tracker = TableHeaderTracker::default();
4
    for (table_node, acc) in per_table {
2
        if acc.thead_items.is_empty() || acc.table_bottom <= acc.table_top {
            continue;
2
        }
        // Rebase the thead's items to thead-local Y (paginate re-offsets
        // them to each continuation page's top).
2
        let items: Vec<super::display_list::DisplayListItem> = acc
2
            .thead_items
2
            .iter()
2
            .map(|&i| {
2
                super::display_list::offset_display_item_y(&display_list.items[i], -acc.thead_top)
2
            })
2
            .collect();
2
        tracker.register_table_header(TableHeaderInfo {
2
            table_node_index: table_node.index(),
2
            table_start_y: acc.table_top,
2
            table_end_y: acc.table_bottom,
2
            thead_height: (acc.thead_bottom - acc.thead_top).max(0.0),
2
            thead_offset_y: acc.thead_top - acc.table_top,
2
            thead_items: items,
2
        });
    }
2
    tracker
2
}
/// The vertical ranges of every table ROW (`<tr>`), for
/// `BreakPolicy::atomic_table_rows` (a break may not slice a row).
#[must_use]
2
pub fn collect_table_row_ranges(
2
    display_list: &super::display_list::DisplayList,
2
    styled_dom: &azul_core::styled_dom::StyledDom,
2
) -> Vec<(f32, f32)> {
    use std::collections::BTreeMap;
    use azul_core::dom::{NodeId, NodeType};
2
    let node_data = styled_dom.node_data.as_container();
2
    let hierarchy = styled_dom.node_hierarchy.as_container();
2
    let mut owner_cache: BTreeMap<NodeId, Option<NodeId>> = BTreeMap::new();
10
    let mut owning_row = |node: NodeId| -> Option<NodeId> {
10
        if let Some(hit) = owner_cache.get(&node) {
            return *hit;
10
        }
10
        let mut row = None;
10
        let mut current = Some(node);
10
        while let Some(n) = current {
10
            match node_data
10
                .get(n)
10
                .map(azul_core::dom::NodeData::get_node_type)
            {
                Some(NodeType::Tr) => {
10
                    row = Some(n);
10
                    break;
                }
                Some(NodeType::Table) => break, // rows don't escape their table
                _ => {}
            }
            current = hierarchy
                .get(n)
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
        }
10
        owner_cache.insert(node, row);
10
        row
10
    };
2
    let mut per_row: BTreeMap<NodeId, (f32, f32)> = BTreeMap::new();
10
    for (idx, item) in display_list.items.iter().enumerate() {
10
        let Some(node) = display_list.node_mapping.get(idx).copied().flatten() else {
            continue;
        };
10
        let Some(bounds) = item.bounds() else {
            continue;
        };
10
        let Some(row) = owning_row(node) else {
            continue;
        };
10
        let top = bounds.origin.y;
10
        let bottom = bounds.origin.y + bounds.size.height;
10
        per_row
10
            .entry(row)
10
            .and_modify(|(t, b)| {
                *t = t.min(top);
                *b = b.max(bottom);
            })
10
            .or_insert((top, bottom));
    }
10
    per_row.into_values().filter(|(t, b)| b > t).collect()
2
}
#[cfg(test)]
mod autotest_generated {
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };
    use super::{super::display_list::DisplayListItem, *};
    // ------------------------------------------------------------------
    // Independent decoders — used to round-trip `CounterFormat::format`
    // without reusing the encoder's own arithmetic.
    // ------------------------------------------------------------------
    /// Decode a lowercase roman numeral. Uses `i64` so the subtractive
    /// prefix ("iv") cannot underflow the accumulator.
    fn decode_roman(s: &str) -> Option<i64> {
        let mut vals = Vec::new();
        for c in s.chars() {
            vals.push(match c {
                'i' => 1_i64,
                'v' => 5,
                'x' => 10,
                'l' => 50,
                'c' => 100,
                'd' => 500,
                'm' => 1000,
                _ => return None,
            });
        }
        let mut total = 0_i64;
        for i in 0..vals.len() {
            if i + 1 < vals.len() && vals[i] < vals[i + 1] {
                total -= vals[i];
            } else {
                total += vals[i];
            }
        }
        Some(total)
    }
    /// Decode a lowercase bijective base-26 string ("a" == 1, "z" == 26, "aa" == 27).
    fn decode_alpha(s: &str) -> Option<usize> {
        if s.is_empty() {
            return None;
        }
        let mut n = 0_usize;
        for c in s.chars() {
            let digit = match c {
                'a'..='z' => c as usize - 'a' as usize + 1,
                _ => return None,
            };
            n = n.checked_mul(26)?.checked_add(digit)?;
        }
        Some(n)
    }
    /// Decode a lowercase bijective base-24 greek string ("α" == 1, "ω" == 24, "αα" == 25).
    fn decode_greek(s: &str) -> Option<usize> {
        const LOWER: &[char] = &[
            'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ',
            'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω',
        ];
        if s.is_empty() {
            return None;
        }
        let mut n = 0_usize;
        for c in s.chars() {
            let digit = LOWER.iter().position(|l| *l == c)? + 1;
            n = n.checked_mul(LOWER.len())?.checked_add(digit)?;
        }
        Some(n)
    }
    fn table(start_y: f32, end_y: f32, thead_height: f32) -> TableHeaderInfo {
        TableHeaderInfo {
            table_node_index: 0,
            table_start_y: start_y,
            table_end_y: end_y,
            thead_items: vec![DisplayListItem::PopClip],
            thead_height,
            thead_offset_y: 0.0,
        }
    }
    // ==================================================================
    // CounterFormat::format — serializer: edge values, huge n, round-trip
    // ==================================================================
    #[test]
    fn counter_format_decimal_handles_zero_and_usize_max() {
        assert_eq!(CounterFormat::Decimal.format(0), "0");
        assert_eq!(CounterFormat::Decimal.format(1), "1");
        assert_eq!(
            CounterFormat::Decimal.format(usize::MAX),
            usize::MAX.to_string()
        );
    }
    #[test]
    fn counter_format_default_is_decimal_and_does_not_panic_on_zero() {
        let default = CounterFormat::default();
        assert_eq!(default, CounterFormat::Decimal);
        assert_eq!(default.format(0), "0");
    }
    #[test]
    fn counter_format_leading_zero_pads_to_two_but_never_truncates() {
        assert_eq!(CounterFormat::DecimalLeadingZero.format(0), "00");
        assert_eq!(CounterFormat::DecimalLeadingZero.format(7), "07");
        assert_eq!(CounterFormat::DecimalLeadingZero.format(9), "09");
        assert_eq!(CounterFormat::DecimalLeadingZero.format(10), "10");
        // A width-2 pad must not *clip* wider numbers.
        assert_eq!(CounterFormat::DecimalLeadingZero.format(12345), "12345");
        assert_eq!(
            CounterFormat::DecimalLeadingZero.format(usize::MAX),
            usize::MAX.to_string()
        );
    }
    #[test]
    fn counter_format_every_variant_survives_zero_one_and_usize_max() {
        // The contract we are pinning: no panic, no hang, output is valid UTF-8
        // with all char boundaries intact for every (variant, extreme) pair.
        let variants = [
            CounterFormat::Decimal,
            CounterFormat::DecimalLeadingZero,
            CounterFormat::LowerRoman,
            CounterFormat::UpperRoman,
            CounterFormat::LowerAlpha,
            CounterFormat::UpperAlpha,
            CounterFormat::LowerGreek,
        ];
        for v in variants {
            for n in [0_usize, 1, 25, 26, 27, 3999, 4000, usize::MAX] {
                let s = v.format(n);
                assert!(
                    s.is_char_boundary(0) && s.is_char_boundary(s.len()),
                    "{v:?}.format({n}) produced a malformed string"
                );
            }
        }
    }
    #[test]
    fn counter_format_alphabetic_and_greek_return_empty_at_zero() {
        // KNOWN DIVERGENCE (asserted, not papered over): `format_counter` in
        // `super::counters` applies a CSS decimal fallback when an alphabetic or
        // greek style cannot represent a value, but `CounterFormat::format` does
        // not — so a page counter at 0 renders as a *blank* margin box here while
        // roman renders "0". Page numbers are 1-indexed so this is unreachable in
        // the current pipeline; the test exists to catch it becoming reachable.
        assert_eq!(CounterFormat::LowerAlpha.format(0), "");
        assert_eq!(CounterFormat::UpperAlpha.format(0), "");
        assert_eq!(CounterFormat::LowerGreek.format(0), "");
        assert_eq!(CounterFormat::LowerRoman.format(0), "0");
        assert_eq!(CounterFormat::UpperRoman.format(0), "0");
    }
    #[test]
    fn counter_format_roman_falls_back_to_decimal_past_3999() {
        assert_eq!(CounterFormat::LowerRoman.format(3999), "mmmcmxcix");
        assert_eq!(CounterFormat::UpperRoman.format(3999), "MMMCMXCIX");
        // 4000 is not representable -> decimal, in *both* cases (no stray casing).
        assert_eq!(CounterFormat::LowerRoman.format(4000), "4000");
        assert_eq!(CounterFormat::UpperRoman.format(4000), "4000");
        assert_eq!(
            CounterFormat::UpperRoman.format(usize::MAX),
            usize::MAX.to_string()
        );
    }
    #[test]
    fn counter_format_roman_round_trips_over_its_whole_representable_range() {
        for n in 1..=3999_usize {
            let lower = CounterFormat::LowerRoman.format(n);
            let upper = CounterFormat::UpperRoman.format(n);
            assert_eq!(
                decode_roman(&lower),
                Some(n as i64),
                "lower-roman round-trip failed for {n} -> {lower}"
            );
            assert_eq!(upper, lower.to_uppercase(), "casing mismatch for {n}");
        }
    }
    #[test]
    fn counter_format_alphabetic_round_trips_and_is_injective() {
        let mut seen = std::collections::HashSet::new();
        for n in 1..=3000_usize {
            let lower = CounterFormat::LowerAlpha.format(n);
            let upper = CounterFormat::UpperAlpha.format(n);
            assert_eq!(
                decode_alpha(&lower),
                Some(n),
                "lower-alpha round-trip failed for {n} -> {lower}"
            );
            assert_eq!(upper, lower.to_uppercase(), "casing mismatch for {n}");
            assert!(seen.insert(lower), "two page numbers collided at {n}");
        }
        // Bijective base-26 boundaries — the classic off-by-one zone.
        assert_eq!(CounterFormat::LowerAlpha.format(26), "z");
        assert_eq!(CounterFormat::LowerAlpha.format(27), "aa");
        assert_eq!(CounterFormat::LowerAlpha.format(52), "az");
        assert_eq!(CounterFormat::LowerAlpha.format(53), "ba");
    }
    #[test]
    fn counter_format_greek_round_trips_and_emits_whole_code_points() {
        for n in 1..=2000_usize {
            let s = CounterFormat::LowerGreek.format(n);
            assert_eq!(
                decode_greek(&s),
                Some(n),
                "lower-greek round-trip failed for {n} -> {s}"
            );
            // Every greek letter is 2 bytes: byte len must be exactly 2x char count,
            // i.e. the encoder's `insert(0, ..)` never split a code point.
            assert_eq!(s.len(), s.chars().count() * 2, "sliced a code point at {n}");
        }
        assert_eq!(CounterFormat::LowerGreek.format(24), "ω");
        assert_eq!(CounterFormat::LowerGreek.format(25), "αα");
    }
    #[test]
    fn counter_format_usize_max_terminates_for_the_positional_styles() {
        // `(n - 1) / base` strictly decreases, so these must halt rather than hang.
        let alpha = CounterFormat::LowerAlpha.format(usize::MAX);
        let greek = CounterFormat::LowerGreek.format(usize::MAX);
        assert!(!alpha.is_empty() && alpha.chars().all(|c| c.is_ascii_lowercase()));
        assert!(!greek.is_empty());
        assert_eq!(greek.len(), greek.chars().count() * 2);
    }
    // ==================================================================
    // PageInfo::new — constructor invariants
    // ==================================================================
    #[test]
    fn page_info_new_sets_flags_for_a_representative_page() {
        let info = PageInfo::new(1, 3);
        assert_eq!(info.page_number, 1);
        assert_eq!(info.total_pages, 3);
        assert!(info.is_first);
        assert!(!info.is_last);
        assert!(info.is_right, "page 1 (odd) is a recto page");
        assert!(!info.is_left);
        assert!(!info.is_blank);
    }
    #[test]
    fn page_info_left_and_right_are_always_mutually_exclusive() {
        for n in [0_usize, 1, 2, 3, 100, 101, usize::MAX - 1, usize::MAX] {
            let info = PageInfo::new(n, 0);
            assert!(
                info.is_left != info.is_right,
                "page {n} claimed to be both/neither verso and recto"
            );
            assert_eq!(info.is_left, n % 2 == 0);
            assert!(!info.is_blank, "new() must never fabricate a blank page");
        }
    }
    #[test]
    fn page_info_is_last_is_false_when_the_total_is_unknown() {
        // total_pages == 0 means "unknown during the first pass" — nothing is last.
        for n in [0_usize, 1, 7, usize::MAX] {
            assert!(
                !PageInfo::new(n, 0).is_last,
                "page {n} of 0 claimed is_last"
            );
        }
    }
    #[test]
    fn page_info_page_zero_is_degenerate_but_does_not_panic() {
        let info = PageInfo::new(0, 0);
        assert!(!info.is_first, "1-indexed: page 0 is not the first page");
        assert!(!info.is_last);
        assert!(info.is_left, "0 is even, so it lands on the verso branch");
    }
    #[test]
    fn page_info_out_of_range_page_number_does_not_claim_to_be_last() {
        // page_number > total_pages is nonsense input; it must not silently
        // become `is_last` (which would duplicate the last-page decoration).
        let info = PageInfo::new(9, 3);
        assert!(!info.is_last);
        assert!(!info.is_first);
    }
    #[test]
    fn page_info_usize_max_extremes_do_not_overflow() {
        let info = PageInfo::new(usize::MAX, usize::MAX);
        assert!(
            info.is_last,
            "the final page of a MAX-page document is last"
        );
        assert!(!info.is_first);
        assert!(info.is_right, "usize::MAX is odd");
        let single = PageInfo::new(1, 1);
        assert!(single.is_first && single.is_last);
    }
    // ==================================================================
    // HeaderFooterConfig — constructors + content generation
    // ==================================================================
    #[test]
    fn header_footer_default_renders_nothing_on_any_page() {
        let cfg = HeaderFooterConfig::default();
        assert!(!cfg.show_header && !cfg.show_footer);
        assert!(matches!(cfg.header_content, MarginBoxContent::None));
        assert!(matches!(cfg.footer_content, MarginBoxContent::None));
        assert_eq!(cfg.header_text(PageInfo::new(1, 1)), "");
        assert_eq!(cfg.footer_text(PageInfo::new(usize::MAX, usize::MAX)), "");
        assert_eq!(cfg.text_color.a, 255);
    }
    #[test]
    fn header_footer_with_page_numbers_only_enables_the_footer() {
        let cfg = HeaderFooterConfig::with_page_numbers();
        assert!(cfg.show_footer);
        assert!(
            !cfg.show_header,
            "with_page_numbers must not enable a header"
        );
        assert_eq!(cfg.footer_text(PageInfo::new(2, 7)), "Page 2 of 7");
        assert_eq!(cfg.header_text(PageInfo::new(2, 7)), "");
    }
    #[test]
    fn header_footer_unknown_total_renders_a_question_mark_not_a_zero() {
        let cfg = HeaderFooterConfig::with_page_numbers();
        assert_eq!(cfg.footer_text(PageInfo::new(1, 0)), "Page 1 of ?");
    }
    #[test]
    fn header_footer_with_header_and_footer_page_numbers_fills_both() {
        let cfg = HeaderFooterConfig::with_header_and_footer_page_numbers();
        assert!(cfg.show_header && cfg.show_footer);
        let info = PageInfo::new(3, 10);
        assert_eq!(cfg.header_text(info), "Page 3");
        assert_eq!(cfg.footer_text(info), "Page 3 of 10");
        // Extremes must not panic or produce truncated numbers.
        let extreme = PageInfo::new(usize::MAX, usize::MAX);
        assert_eq!(cfg.header_text(extreme), format!("Page {}", usize::MAX));
    }
    #[test]
    fn header_footer_with_text_enables_the_box_and_preserves_unicode_exactly() {
        let text = "Ünïcödé — 日本語 🎉\u{200b}\u{0}";
        let cfg = HeaderFooterConfig::default()
            .with_header_text(text)
            .with_footer_text(text);
        assert!(cfg.show_header && cfg.show_footer);
        let info = PageInfo::new(1, 1);
        // Byte-for-byte: no normalization, no NUL truncation, no BOM stripping.
        assert_eq!(cfg.header_text(info), text);
        assert_eq!(cfg.footer_text(info), text);
        assert_eq!(cfg.header_text(info).len(), text.len());
    }
    #[test]
    fn header_footer_empty_text_still_switches_the_box_on() {
        // Quirk worth pinning: an empty string is indistinguishable from "no header"
        // in the rendered output, yet it *does* flip `show_header` — so the slicer
        // will still reserve `header_height` for a blank box.
        let cfg = HeaderFooterConfig::default().with_header_text("");
        assert!(cfg.show_header);
        assert_eq!(cfg.header_text(PageInfo::new(1, 1)), "");
        assert!(cfg.header_height > 0.0);
    }
    #[test]
    fn header_footer_text_of_huge_length_round_trips_without_truncation() {
        let huge = "x".repeat(200_000);
        let cfg = HeaderFooterConfig::default().with_footer_text(huge.clone());
        assert_eq!(cfg.footer_text(PageInfo::new(1, 1)).len(), huge.len());
    }
    #[test]
    fn header_footer_last_builder_call_wins() {
        let cfg = HeaderFooterConfig::default()
            .with_header_text("first")
            .with_header_text("second");
        assert_eq!(cfg.header_text(PageInfo::new(1, 1)), "second");
    }
    #[test]
    fn header_footer_skip_first_page_blanks_only_page_one() {
        let mut cfg = HeaderFooterConfig::with_header_and_footer_page_numbers();
        cfg.skip_first_page = true;
        assert_eq!(cfg.header_text(PageInfo::new(1, 5)), "");
        assert_eq!(cfg.footer_text(PageInfo::new(1, 5)), "");
        assert_eq!(cfg.header_text(PageInfo::new(2, 5)), "Page 2");
        assert_eq!(cfg.footer_text(PageInfo::new(2, 5)), "Page 2 of 5");
        // The gate keys off `is_first`, not off `page_number == 1`: a hand-built
        // PageInfo with is_first forced on is skipped regardless of its number.
        let mut forged = PageInfo::new(4, 5);
        forged.is_first = true;
        assert_eq!(cfg.header_text(forged), "");
    }
    #[test]
    fn header_footer_generate_content_covers_every_margin_box_variant() {
        let cfg = HeaderFooterConfig::default();
        let info = PageInfo::new(4, 9);
        assert_eq!(cfg.generate_content(&MarginBoxContent::None, info), "");
        assert_eq!(cfg.generate_content(&MarginBoxContent::text(""), info), "");
        assert_eq!(
            cfg.generate_content(&MarginBoxContent::PageCounter, info),
            "4"
        );
        assert_eq!(
            cfg.generate_content(&MarginBoxContent::PagesCounter, info),
            "9"
        );
        assert_eq!(
            cfg.generate_content(
                &MarginBoxContent::PageCounterFormatted(CounterFormat::LowerRoman),
                info
            ),
            "iv"
        );
        // Not-yet-implemented variants must degrade to a placeholder, not panic.
        assert_eq!(
            cfg.generate_content(&MarginBoxContent::NamedString("chapter".into()), info),
            "[string:chapter]"
        );
        assert_eq!(
            cfg.generate_content(&MarginBoxContent::RunningElement("hdr".into()), info),
            "[element:hdr]"
        );
    }
    #[test]
    fn header_footer_generate_content_of_an_empty_combined_is_empty() {
        let cfg = HeaderFooterConfig::default();
        assert_eq!(
            cfg.generate_content(&MarginBoxContent::combined(Vec::new()), PageInfo::new(1, 1)),
            ""
        );
    }
    #[test]
    fn header_footer_generate_content_recurses_through_nested_combined() {
        // `Combined` recursion is unbounded in the impl; a deeply nested tree (as could
        // arrive from a future @page parser) must still resolve. Depth is kept modest
        // on purpose — a stack overflow would abort the whole test binary, so this
        // pins "reasonable nesting works" rather than probing for the cliff.
        let cfg = HeaderFooterConfig::default();
        let mut content = MarginBoxContent::PageCounter;
        for _ in 0..128 {
            content = MarginBoxContent::combined(vec![content]);
        }
        assert_eq!(cfg.generate_content(&content, PageInfo::new(42, 99)), "42");
    }
    #[test]
    fn header_footer_generate_content_calls_a_custom_hook_exactly_once() {
        extern "C" fn page_of_total(data: &mut RefAny, info: PageInfo) -> AzString {
            let calls = data
                .downcast_ref::<Arc<AtomicUsize>>()
                .expect("the app's data");
            calls.fetch_add(1, Ordering::SeqCst);
            format!("{}/{}", info.page_number, info.total_pages).into()
        }
        let calls = Arc::new(AtomicUsize::new(0));
        let content = MarginBoxContent::custom(page_of_total, RefAny::new(Arc::clone(&calls)));
        let cfg = HeaderFooterConfig::default();
        assert_eq!(cfg.generate_content(&content, PageInfo::new(2, 5)), "2/5");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        // Nested inside a Combined, it is still invoked (once per occurrence).
        let combined = MarginBoxContent::combined(vec![
            MarginBoxContent::Text("[".into()),
            content,
            MarginBoxContent::Text("]".into()),
        ]);
        assert_eq!(
            cfg.generate_content(&combined, PageInfo::new(2, 5)),
            "[2/5]"
        );
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }
    #[test]
    fn header_footer_hidden_box_short_circuits_before_generating_content() {
        // show_header == false must win even when header_content would panic-free
        // produce text — otherwise a disabled box still costs a callback call.
        extern "C" fn leaked(data: &mut RefAny, _: PageInfo) -> AzString {
            let calls = data
                .downcast_ref::<Arc<AtomicUsize>>()
                .expect("the app's data");
            calls.fetch_add(1, Ordering::SeqCst);
            "leaked".into()
        }
        let calls = Arc::new(AtomicUsize::new(0));
        let mut cfg = HeaderFooterConfig {
            header_content: MarginBoxContent::custom(leaked, RefAny::new(Arc::clone(&calls))),
            ..Default::default()
        };
        assert_eq!(cfg.header_text(PageInfo::new(1, 1)), "");
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }
    // ==================================================================
    // FakePageConfig — builders, defaults, and the HeaderFooterConfig bridge
    // ==================================================================
    #[test]
    fn fake_page_new_is_inert_and_matches_default() {
        let cfg = FakePageConfig::new();
        assert!(!cfg.show_header && !cfg.show_footer);
        assert!(cfg.header_text.is_none() && cfg.footer_text.is_none());
        assert!(!cfg.header_page_number && !cfg.footer_page_number);
        assert!(!cfg.header_total_pages && !cfg.footer_total_pages);
        assert!(!cfg.skip_first_page);
        assert_eq!(cfg.number_format, CounterFormat::Decimal);
        let hf = cfg.to_header_footer_config();
        assert!(matches!(hf.header_content, MarginBoxContent::None));
        assert!(matches!(hf.footer_content, MarginBoxContent::None));
        assert_eq!(hf.header_text(PageInfo::new(1, 1)), "");
        assert_eq!(hf.footer_text(PageInfo::new(1, 1)), "");
    }
    #[test]
    fn fake_page_footer_page_numbers_render_page_x_of_y() {
        let hf = FakePageConfig::new()
            .with_footer_page_numbers()
            .to_header_footer_config();
        assert!(hf.show_footer && !hf.show_header);
        assert_eq!(hf.footer_text(PageInfo::new(2, 7)), "Page 2 of 7");
        assert_eq!(hf.footer_text(PageInfo::new(2, 0)), "Page 2 of ?");
    }
    #[test]
    fn fake_page_header_page_numbers_omit_the_total() {
        let hf = FakePageConfig::new()
            .with_header_page_numbers()
            .to_header_footer_config();
        assert_eq!(hf.header_text(PageInfo::new(3, 7)), "Page 3");
        assert_eq!(hf.footer_text(PageInfo::new(3, 7)), "");
    }
    #[test]
    fn fake_page_header_and_footer_page_numbers_agree_with_the_pair_of_setters() {
        let both = FakePageConfig::new()
            .with_header_and_footer_page_numbers()
            .to_header_footer_config();
        let info = PageInfo::new(5, 11);
        assert_eq!(both.header_text(info), "Page 5");
        assert_eq!(both.footer_text(info), "Page 5 of 11");
    }
    #[test]
    fn fake_page_text_and_page_number_are_joined_by_a_separator() {
        let mut cfg = FakePageConfig::new()
            .with_header_text("My Document")
            .with_header_page_numbers();
        cfg.header_total_pages = true;
        let hf = cfg.to_header_footer_config();
        assert_eq!(
            hf.header_text(PageInfo::new(4, 9)),
            "My Document - Page 4 of 9"
        );
    }
    #[test]
    fn fake_page_number_format_flows_into_the_rendered_counter() {
        let hf = FakePageConfig::new()
            .with_footer_page_numbers()
            .with_number_format(CounterFormat::LowerRoman)
            .to_header_footer_config();
        // Only the page counter is formatted; the *total* stays decimal — pin that,
        // because a mismatched pair ("Page iv of 9") is easy to regress into.
        assert_eq!(hf.footer_text(PageInfo::new(4, 9)), "Page iv of 9");
        let greek = FakePageConfig::new()
            .with_header_page_numbers()
            .with_number_format(CounterFormat::LowerGreek)
            .to_header_footer_config();
        assert_eq!(greek.header_text(PageInfo::new(2, 9)), "Page β");
    }
    #[test]
    fn fake_page_decimal_format_takes_the_unformatted_counter_branch() {
        let decimal = FakePageConfig::new().with_header_page_numbers();
        match decimal.to_header_footer_config().header_content {
            MarginBoxContent::Combined(parts) => {
                assert_eq!(parts.len(), 2);
                assert!(matches!(parts.as_ref()[1], MarginBoxContent::PageCounter));
            }
            other => panic!("expected Combined, got {other:?}"),
        }
        let roman = FakePageConfig::new()
            .with_header_page_numbers()
            .with_number_format(CounterFormat::UpperRoman);
        match roman.to_header_footer_config().header_content {
            MarginBoxContent::Combined(parts) => {
                assert!(matches!(
                    parts.as_ref()[1],
                    MarginBoxContent::PageCounterFormatted(CounterFormat::UpperRoman)
                ));
            }
            other => panic!("expected Combined, got {other:?}"),
        }
    }
    #[test]
    fn fake_page_total_pages_without_page_number_is_silently_dropped() {
        // Adversarial: `footer_total_pages` is only honoured *inside* the
        // `page_number` branch of `build_margin_content`. Setting the total flag
        // alone yields an empty box rather than "of Y" — assert the real behavior
        // so a future fix has to update this test deliberately.
        let mut cfg = FakePageConfig::new();
        cfg.show_footer = true;
        cfg.footer_total_pages = true;
        let hf = cfg.to_header_footer_config();
        assert!(matches!(hf.footer_content, MarginBoxContent::None));
        assert_eq!(hf.footer_text(PageInfo::new(1, 5)), "");
    }
    #[test]
    fn fake_page_single_text_part_is_not_wrapped_in_a_combined() {
        let hf = FakePageConfig::new()
            .with_footer_text("plain")
            .to_header_footer_config();
        assert!(
            matches!(hf.footer_content, MarginBoxContent::Text(ref s) if s.as_str() == "plain")
        );
        assert_eq!(hf.footer_text(PageInfo::new(1, 1)), "plain");
    }
    #[test]
    fn fake_page_empty_text_plus_page_number_leaks_a_leading_separator() {
        // Adversarial edge: an empty custom text is still pushed as a `Text("")`
        // part, so the " - " joiner is emitted with nothing before it.
        let hf = FakePageConfig::new()
            .with_header_text("")
            .with_header_page_numbers()
            .to_header_footer_config();
        assert_eq!(hf.header_text(PageInfo::new(1, 1)), " - Page 1");
    }
    #[test]
    fn fake_page_unicode_text_survives_the_bridge_byte_for_byte() {
        let text = "Ünïcödé — 日本語 🎉";
        let hf = FakePageConfig::new()
            .with_header_text(text)
            .with_footer_text(text)
            .to_header_footer_config();
        let info = PageInfo::new(1, 1);
        assert_eq!(hf.header_text(info), text);
        assert_eq!(hf.footer_text(info), text);
    }
    #[test]
    fn fake_page_huge_text_survives_the_bridge() {
        let huge = "λ".repeat(100_000);
        let hf = FakePageConfig::new()
            .with_footer_text(huge.clone())
            .to_header_footer_config();
        let out = hf.footer_text(PageInfo::new(1, 1));
        assert_eq!(out.len(), huge.len());
        assert_eq!(out.chars().count(), 100_000);
    }
    #[test]
    fn fake_page_skip_first_page_toggles_both_ways() {
        let on = FakePageConfig::new()
            .with_footer_page_numbers()
            .skip_first_page(true)
            .to_header_footer_config();
        assert!(on.skip_first_page);
        assert_eq!(on.footer_text(PageInfo::new(1, 3)), "");
        assert_eq!(on.footer_text(PageInfo::new(2, 3)), "Page 2 of 3");
        let off = FakePageConfig::new()
            .with_footer_page_numbers()
            .skip_first_page(true)
            .skip_first_page(false)
            .to_header_footer_config();
        assert!(!off.skip_first_page);
        assert_eq!(off.footer_text(PageInfo::new(1, 3)), "Page 1 of 3");
    }
    #[test]
    fn fake_page_non_finite_geometry_is_stored_and_forwarded_verbatim() {
        // There is no validation/clamping anywhere on this path: NaN and infinite
        // heights reach the slicer unchanged. Pin it so any future clamp is a
        // deliberate, reviewed change rather than a silent behavior swap.
        let cfg = FakePageConfig::new()
            .with_header_height(f32::NAN)
            .with_footer_height(f32::INFINITY)
            .with_font_size(-0.0);
        assert!(cfg.header_height.is_nan());
        let hf = cfg.to_header_footer_config();
        assert!(hf.header_height.is_nan(), "NaN header height was swallowed");
        assert_eq!(hf.footer_height, f32::INFINITY);
        assert_eq!(hf.font_size, -0.0);
    }
    #[test]
    fn fake_page_extreme_but_finite_geometry_is_preserved_exactly() {
        let hf = FakePageConfig::new()
            .with_header_height(f32::MAX)
            .with_footer_height(f32::MIN)
            .with_font_size(f32::MIN_POSITIVE)
            .to_header_footer_config();
        assert_eq!(hf.header_height, f32::MAX);
        assert_eq!(hf.footer_height, f32::MIN);
        assert_eq!(hf.font_size, f32::MIN_POSITIVE);
        let negative = FakePageConfig::new()
            .with_header_height(-100.0)
            .to_header_footer_config();
        assert_eq!(negative.header_height, -100.0);
    }
    #[test]
    fn fake_page_text_color_crosses_the_bridge_unchanged() {
        let color = ColorU {
            r: 1,
            g: 2,
            b: 3,
            a: 0,
        };
        let hf = FakePageConfig::new()
            .with_text_color(color)
            .to_header_footer_config();
        assert_eq!(hf.text_color, color);
        assert_eq!(hf.text_color.a, 0, "a fully transparent color must survive");
    }
    #[test]
    fn fake_page_to_header_footer_config_is_a_pure_read() {
        // The bridge is a getter: calling it repeatedly must be stable and must not
        // mutate the source config.
        let cfg = FakePageConfig::new()
            .with_header_and_footer_page_numbers()
            .with_number_format(CounterFormat::UpperAlpha)
            .skip_first_page(true);
        let info = PageInfo::new(3, 4);
        let first = cfg.to_header_footer_config();
        let second = cfg.to_header_footer_config();
        assert_eq!(first.header_text(info), second.header_text(info));
        assert_eq!(first.footer_text(info), second.footer_text(info));
        assert_eq!(first.header_text(info), "Page C");
        assert!(cfg.show_header && cfg.show_footer && cfg.skip_first_page);
    }
    #[test]
    fn fake_page_build_margin_content_shapes_match_the_part_count() {
        // Private helper, exercised directly: 0 parts -> None, 1 part -> that part,
        // >1 -> Combined. The `parts.pop().unwrap()` in the 1-part arm is the risk.
        assert!(matches!(
            FakePageConfig::build_margin_content(None, false, false, CounterFormat::Decimal),
            MarginBoxContent::None
        ));
        assert!(matches!(
            FakePageConfig::build_margin_content(None, false, true, CounterFormat::Decimal),
            MarginBoxContent::None
        ));
        assert!(matches!(
            FakePageConfig::build_margin_content(Some("t"), false, false, CounterFormat::Decimal),
            MarginBoxContent::Text(ref s) if s.as_str() == "t"
        ));
        assert!(matches!(
            FakePageConfig::build_margin_content(Some(""), false, true, CounterFormat::Decimal),
            MarginBoxContent::Text(ref s) if s.is_empty()
        ));
        match FakePageConfig::build_margin_content(
            Some("Doc"),
            true,
            true,
            CounterFormat::LowerRoman,
        ) {
            MarginBoxContent::Combined(parts) => {
                assert_eq!(parts.len(), 6, "text + sep + label + counter + of + total");
                assert!(
                    matches!(parts.as_ref()[1], MarginBoxContent::Text(ref s) if s.as_str() == " - ")
                );
                assert!(matches!(
                    parts.as_ref()[3],
                    MarginBoxContent::PageCounterFormatted(..)
                ));
                assert!(matches!(parts.as_ref()[5], MarginBoxContent::PagesCounter));
            }
            other => panic!("expected Combined, got {other:?}"),
        }
    }
    #[test]
    fn fake_page_build_header_and_footer_content_read_their_own_fields() {
        // Guards against the classic copy-paste bug: header building from the
        // footer's flags (or vice versa).
        let mut cfg = FakePageConfig::new();
        cfg.header_text = OptionString::Some("H".into());
        cfg.footer_text = OptionString::Some("F".into());
        cfg.header_page_number = true;
        cfg.footer_page_number = false;
        let hf = HeaderFooterConfig::default();
        let info = PageInfo::new(2, 4);
        assert_eq!(
            hf.generate_content(&cfg.build_header_content(), info),
            "H - Page 2"
        );
        assert_eq!(hf.generate_content(&cfg.build_footer_content(), info), "F");
    }
    // ==================================================================
    // TableHeaderTracker — numeric edges on the page-overlap arithmetic
    // ==================================================================
    #[test]
    fn tracker_new_is_empty_and_matches_default() {
        let tracker = TableHeaderTracker::new();
        assert!(tracker.tables.is_empty());
        assert!(TableHeaderTracker::default().tables.is_empty());
        assert!(tracker
            .get_repeated_headers_for_page(0, 0.0, 0.0)
            .is_empty());
    }
    #[test]
    fn tracker_empty_returns_nothing_for_every_extreme_page_geometry() {
        let tracker = TableHeaderTracker::new();
        for page_index in [0_usize, 1, usize::MAX] {
            for y in [
                0.0_f32,
                -0.0,
                f32::MIN,
                f32::MAX,
                f32::INFINITY,
                f32::NEG_INFINITY,
                f32::NAN,
            ] {
                assert!(
                    tracker
                        .get_repeated_headers_for_page(page_index, y, y)
                        .is_empty(),
                    "empty tracker produced a header at page {page_index}, y={y}"
                );
            }
        }
    }
    #[test]
    fn tracker_register_appends_in_order_and_allows_duplicates() {
        let mut tracker = TableHeaderTracker::new();
        for i in 0..1000 {
            let mut info = table(0.0, 100.0, 10.0);
            info.table_node_index = i;
            tracker.register_table_header(info);
        }
        // Same table registered twice must not be deduplicated silently.
        tracker.register_table_header(table(0.0, 100.0, 10.0));
        tracker.register_table_header(table(0.0, 100.0, 10.0));
        assert_eq!(tracker.tables.len(), 1002);
        assert_eq!(tracker.tables[0].table_node_index, 0);
        assert_eq!(tracker.tables[999].table_node_index, 999);
    }
    #[test]
    fn tracker_repeats_only_tables_that_straddle_the_page_top() {
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 500.0, 20.0)); // straddles -> repeat
        tracker.register_table_header(table(0.0, 50.0, 20.0)); // ends above -> no
        tracker.register_table_header(table(200.0, 500.0, 20.0)); // starts on page -> no
        let headers = tracker.get_repeated_headers_for_page(1, 100.0, 900.0);
        assert_eq!(headers.len(), 1);
        let (offset, items, height) = headers[0];
        assert_eq!(offset, 0.0, "a repeated thead sits at the page top");
        assert_eq!(height, 20.0);
        assert_eq!(items.len(), 1);
        assert!(matches!(items[0], DisplayListItem::PopClip));
    }
    #[test]
    fn tracker_page_boundary_comparisons_are_strict() {
        let mut tracker = TableHeaderTracker::new();
        // start_y == page_top: the table *begins* on this page -> its own thead is
        // already there, so no repeat.
        tracker.register_table_header(table(100.0, 500.0, 20.0));
        assert!(tracker
            .get_repeated_headers_for_page(1, 100.0, 900.0)
            .is_empty());
        // end_y == page_top: the table finished exactly at the boundary -> no repeat.
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 100.0, 20.0));
        assert!(tracker
            .get_repeated_headers_for_page(1, 100.0, 900.0)
            .is_empty());
        // One representable step past the boundary on both sides -> repeat. (`f32::EPSILON`
        // is useless here: at magnitude 100 it is far below one ulp and would round
        // straight back to 100.0, silently re-testing the equality case above.)
        let below = f32::from_bits(100.0_f32.to_bits() - 1);
        let above = f32::from_bits(100.0_f32.to_bits() + 1);
        assert!(below < 100.0 && above > 100.0, "ulp step collapsed");
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(below, above, 20.0));
        assert_eq!(
            tracker.get_repeated_headers_for_page(1, 100.0, 900.0).len(),
            1
        );
    }
    #[test]
    fn tracker_nan_page_top_yields_no_headers_and_no_panic() {
        // Every f32 comparison against NaN is false, so both guards fail: the
        // defined result is "no repeated headers" rather than a panic or a
        // spurious header at an unrenderable offset.
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 500.0, 20.0));
        assert!(tracker
            .get_repeated_headers_for_page(1, f32::NAN, 900.0)
            .is_empty());
        // A NaN *bottom* changes nothing, because the bottom is never read.
        assert_eq!(
            tracker
                .get_repeated_headers_for_page(1, 100.0, f32::NAN)
                .len(),
            1
        );
    }
    #[test]
    fn tracker_nan_table_geometry_yields_no_headers() {
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(f32::NAN, 500.0, 20.0));
        tracker.register_table_header(table(0.0, f32::NAN, 20.0));
        tracker.register_table_header(table(f32::NAN, f32::NAN, 20.0));
        assert!(
            tracker
                .get_repeated_headers_for_page(1, 100.0, 900.0)
                .is_empty(),
            "a NaN-positioned table must not be repeated"
        );
    }
    #[test]
    fn tracker_infinite_page_top_behaves_deterministically() {
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 500.0, 20.0));
        // +inf page top: the table starts before it, but nothing can extend past
        // +inf -> no repeat.
        assert!(tracker
            .get_repeated_headers_for_page(1, f32::INFINITY, f32::INFINITY)
            .is_empty());
        // -inf page top: nothing starts before -inf -> no repeat.
        assert!(tracker
            .get_repeated_headers_for_page(1, f32::NEG_INFINITY, 900.0)
            .is_empty());
    }
    #[test]
    fn tracker_infinite_table_extent_repeats_forever_without_overflow() {
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(f32::NEG_INFINITY, f32::INFINITY, f32::INFINITY));
        // A page of positive extent somewhere inside the infinite table.
        let headers = tracker.get_repeated_headers_for_page(usize::MAX, 100.0, 900.0);
        assert_eq!(headers.len(), 1);
        // The thead height is forwarded verbatim — no clamping, no NaN laundering.
        assert!(headers[0].2.is_infinite());
    }
    #[test]
    fn tracker_nan_thead_height_is_forwarded_not_sanitized() {
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 500.0, f32::NAN));
        let headers = tracker.get_repeated_headers_for_page(1, 100.0, 900.0);
        assert_eq!(headers.len(), 1);
        assert!(headers[0].2.is_nan(), "height NaN was silently rewritten");
    }
    #[test]
    fn tracker_page_zero_never_repeats_but_continuation_pages_do() {
        // Page 0 carries the ORIGINAL thead — repeating it there would paint
        // it twice. Continuation pages (any index >= 1 whose top the table
        // straddles) repeat it.
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 500.0, 20.0));
        assert!(tracker
            .get_repeated_headers_for_page(0, 100.0, 900.0)
            .is_empty());
        assert_eq!(
            tracker.get_repeated_headers_for_page(1, 100.0, 900.0).len(),
            1
        );
        assert_eq!(
            tracker
                .get_repeated_headers_for_page(usize::MAX, 100.0, 900.0)
                .len(),
            1
        );
    }
    #[test]
    fn tracker_degenerate_and_inverted_pages_yield_no_headers() {
        // An inverted page (bottom above top) or a zero-extent page has no
        // room for a header — both parameters now gate.
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 500.0, 20.0));
        assert!(tracker
            .get_repeated_headers_for_page(1, 100.0, -900.0)
            .is_empty());
        assert!(tracker
            .get_repeated_headers_for_page(1, 100.0, 100.0)
            .is_empty());
    }
    #[test]
    fn tracker_preserves_registration_order_across_many_straddling_tables() {
        let mut tracker = TableHeaderTracker::new();
        for i in 0..64_u32 {
            #[allow(clippy::cast_precision_loss)]
            tracker.register_table_header(table(0.0, 500.0, i as f32));
        }
        let headers = tracker.get_repeated_headers_for_page(3, 100.0, 900.0);
        assert_eq!(headers.len(), 64);
        // Multiple straddling tables STACK: each header's offset is the sum
        // of the previous headers' heights (offset 0 for all painted every
        // header on top of the previous one), in registration order.
        let mut expected_offset = 0.0_f32;
        for (i, (offset, _, height)) in headers.iter().enumerate() {
            assert_eq!(*offset, expected_offset, "header {i} does not stack");
            #[allow(clippy::cast_precision_loss)]
            let expected = i as f32;
            assert_eq!(*height, expected, "headers came back out of order");
            expected_offset += height;
        }
    }
    #[test]
    fn tracker_zero_height_page_returns_nothing() {
        // A degenerate zero-extent page has no room for a header, whether or
        // not a table straddles its top.
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(0.0, 500.0, 20.0));
        assert!(tracker
            .get_repeated_headers_for_page(1, 0.0, 0.0)
            .is_empty());
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(table(-10.0, 500.0, 20.0));
        assert!(tracker
            .get_repeated_headers_for_page(1, 0.0, 0.0)
            .is_empty());
    }
}