ferri-pdf 0.1.10

HTML and CSS to PDF renderer for print, in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Content laid out once at the column width and sliced into column boxes at its break
//! offsets: the bodies a footnote area holds and the content of a page-margin box, which no
//! flow fragments (CSS Multi-column Layout 1 §7, CSS Fragmentation 3 §5.4).
use super::{ColumnGeometry, WrapRows};
use crate::graphics::{Border, BoxPaint, Clip, DisplayItem, Rect};
use crate::layout::TextLine;
use crate::layout::pagination::{FRAGMENTATION_TOLERANCE_PT, overflows};
use crate::style::ColumnFill;

#[cfg(test)]
mod tests;

/// Laid-out content that a column box takes whole or breaks inside.
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct Run<'b> {
    /// The offsets in the content that the run spans.
    pub top: f32,
    pub bottom: f32,
    /// The offsets in the content where a column break may fall, ascending.
    pub breaks: &'b [f32],
    /// The block-start and block-end edges of a box that clones its decoration at breaks,
    /// which each slice starting or ending at a break repeats.
    pub cloned: [f32; 2],
    /// The repeated edges the run starts and ends with.
    pub repeated: [f32; 2],
}
impl Run<'_> {
    /// Content `height` tall that no column break falls inside.
    pub(in crate::layout) fn whole(height: f32) -> Self {
        Self {
            top: 0.0,
            bottom: height,
            breaks: &[],
            cloned: [0.0; 2],
            repeated: [0.0; 2],
        }
    }
    fn height(&self) -> f32 {
        self.bottom - self.top + self.repeated[0] + self.repeated[1]
    }
}

/// The offsets in content ending at `end` where a break may fall: the bottoms of its
/// `line_boxes` that leave at least `orphans` lines before them and `widows` after them (CSS
/// Fragmentation 3 §3.3) and lie inside no line box or `monolithic` extent, then `end`;
/// ascending.
pub(in crate::layout) fn line_breaks(
    line_boxes: &[[f32; 2]],
    monolithic: impl IntoIterator<Item = [f32; 2]>,
    [orphans, widows]: [usize; 2],
    end: f32,
) -> Vec<f32> {
    let mut bottoms: Vec<f32> = line_boxes.iter().map(|[_, bottom]| *bottom).collect();
    bottoms.sort_by(f32::total_cmp);
    let mut extents: Vec<[f32; 2]> = line_boxes.iter().copied().chain(monolithic).collect();
    extents.sort_by(|a, b| a[0].total_cmp(&b[0]));
    // Overlapping extents merge into disjoint spans, which a break may touch but not cut.
    let mut spans: Vec<[f32; 2]> = Vec::with_capacity(extents.len());
    for [top, bottom] in extents {
        match spans.last_mut() {
            Some(span) if top < span[1] => span[1] = span[1].max(bottom),
            _ => spans.push([top, bottom]),
        }
    }
    let cuts = |offset: f32| {
        let after = spans.partition_point(|span| span[0] < offset);
        after > 0 && offset < spans[after - 1][1]
    };
    let total = bottoms.len();
    let mut breaks: Vec<f32> = bottoms
        .iter()
        .copied()
        .filter(|&offset| {
            let before = bottoms.partition_point(|&bottom| bottom <= offset);
            before >= orphans && total - before >= widows && !cuts(offset)
        })
        .chain([end])
        .collect();
    breaks.sort_by(f32::total_cmp);
    breaks.dedup();
    breaks
}

/// The clip of content laid out once to its slice `window`, open in the inline axis, whose
/// content overflows a column box visibly there (§8.1).
pub(in crate::layout) fn slice_clip(window: Rect) -> DisplayItem {
    DisplayItem::PushClip(Clip {
        rect: window,
        radii: crate::graphics::Radii::default(),
        outline: None,
        axes: [false, true],
        reference_box: None,
    })
}

/// `items`, whose text lines are `lines`, without the untransformed text whose line lies
/// outside the block-axis `window` that clips them, so that each slice of content laid out
/// once copies only the lines it shows, with the lines the rest paint.
pub(in crate::layout) fn windowed(
    items: &[DisplayItem],
    lines: &[TextLine],
    [top, bottom]: [f32; 2],
) -> (Vec<DisplayItem>, Vec<TextLine>) {
    // The planes of a 3D scene paint lines of the flow as well.
    if items
        .iter()
        .any(|item| matches!(item, DisplayItem::Scene(_)))
    {
        return (items.to_vec(), lines.to_vec());
    }
    let mut kept = vec![None; lines.len()];
    let mut kept_lines = Vec::new();
    let mut output = Vec::with_capacity(items.len());
    // Whether each open push transforms what it holds.
    let mut open = Vec::new();
    for item in items {
        match item {
            DisplayItem::Pop => {
                open.pop();
            }
            DisplayItem::PushTransform(_) | DisplayItem::PushProjection(_) => open.push(true),
            item if item.is_push() => open.push(false),
            DisplayItem::Text { line } => {
                let source = &lines[*line];
                // The line box lies within a line height of the baseline either way.
                if !open.contains(&true)
                    && (source.baseline + source.height <= top
                        || source.baseline - source.height >= bottom)
                {
                    continue;
                }
                let index = *kept[*line].get_or_insert_with(|| {
                    kept_lines.push(source.clone());
                    kept_lines.len() - 1
                });
                output.push(DisplayItem::Text { line: index });
                continue;
            }
            _ => {}
        }
        output.push(item.clone());
    }
    (output, kept_lines)
}

/// The part `[top, bottom)` of run `run` that one column box holds.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(in crate::layout) struct Slice {
    pub run: usize,
    pub top: f32,
    pub bottom: f32,
    pub repeated: [f32; 2],
    /// The offset of the slice from the top of its column box.
    pub y: f32,
}
impl Slice {
    pub(in crate::layout) fn height(&self) -> f32 {
        self.bottom - self.top + self.repeated[0] + self.repeated[1]
    }
}

/// A column box and the slices it holds.
#[derive(Clone, Debug, Default)]
pub(in crate::layout) struct ColumnBox {
    /// The row of columns it lies in, and its index in the row; columns past the column count
    /// overflow in the inline direction (§8.2).
    pub row: usize,
    pub index: usize,
    pub slices: Vec<Slice>,
    /// The block size its slices take.
    pub extent: f32,
}

/// How content fills its column boxes.
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct Plan {
    pub count: usize,
    /// A fixed column height: `column-height`, the container's definite height, or the most
    /// that `column-fill: auto` fills.
    pub height: Option<f32>,
    /// The fixed height is the row's own rather than only the most its columns take.
    pub definite: bool,
    pub fill: ColumnFill,
    pub wrap: Option<WrapRows>,
}

/// Content laid out in rows of column boxes.
#[derive(Clone, Debug)]
pub(in crate::layout) struct Distribution {
    pub columns: Vec<ColumnBox>,
    /// The block size of each row of columns.
    pub rows: Vec<f32>,
    pub row_gap: f32,
    /// The content needs columns past the count, or a slice is taller than its column.
    pub overflows: bool,
}
impl Distribution {
    /// Lays `runs` out in column boxes as `plan` fills them (§7.1): sequentially where the
    /// column height is fixed and `column-fill` is `auto`, else balanced in the last row.
    pub(in crate::layout) fn of(runs: &[Run<'_>], plan: Plan) -> Self {
        let mut distribution = Self {
            columns: Vec::new(),
            rows: Vec::new(),
            row_gap: plan.wrap.map_or(0.0, |wrap| wrap.gap),
            overflows: false,
        };
        let Some(start) = Cursor::start(runs) else {
            return distribution;
        };
        let balanced = plan.fill != ColumnFill::Auto;
        if let Some(wrap) = plan.wrap {
            let mut next = Some(start);
            while let Some(cursor) = next {
                let row = fill(runs, cursor, wrap.height, Some(plan.count));
                next = row.end;
                let row = if next.is_none() && balanced {
                    balance(runs, cursor, plan.count, Some(wrap.height))
                } else {
                    row
                };
                distribution.push_row(row, wrap.height);
            }
            return distribution;
        }
        let Some(height) = plan.height else {
            let row = balance(runs, start, plan.count, None);
            let extent = row.extent();
            distribution.push_row(row, extent);
            return distribution;
        };
        let sequential = fill(runs, start, height, None);
        let fits = sequential.columns.len() <= plan.count && !sequential.forced;
        let row = if fits && balanced {
            balance(runs, start, plan.count, Some(height))
        } else {
            sequential
        };
        let extent = if plan.definite { height } else { row.extent() };
        distribution.push_row(row, extent);
        distribution.overflows |= !fits;
        distribution
    }
    fn push_row(&mut self, filled: Filled, height: f32) {
        let row = self.rows.len();
        self.overflows |= filled.forced;
        self.columns.extend(
            filled
                .columns
                .into_iter()
                .map(|column| ColumnBox { row, ..column }),
        );
        self.rows.push(height);
    }
    /// The block size of the rows with the gaps between them.
    pub(in crate::layout) fn height(&self) -> f32 {
        self.rows.iter().sum::<f32>() + self.row_gap * self.rows.len().saturating_sub(1) as f32
    }
    /// The offset of row `row` from the top of the first.
    pub(in crate::layout) fn row_offset(&self, row: usize) -> f32 {
        self.rows[..row].iter().sum::<f32>() + self.row_gap * row as f32
    }
    /// Each slice with the top left of its place in its column box, from the content box's.
    pub(in crate::layout) fn placed(
        &self,
        geometry: ColumnGeometry,
    ) -> impl Iterator<Item = (Slice, [f32; 2])> + '_ {
        self.columns.iter().flat_map(move |column| {
            let [x, y] = [geometry.left(column.index), self.row_offset(column.row)];
            column
                .slices
                .iter()
                .map(move |slice| (*slice, [x, y + slice.y]))
        })
    }
    /// Where the content that the first `count` columns of the rows inside a block size of
    /// `extent` hold ends: a container that discards the content after its region break
    /// keeps that (CSS Overflow 4 §5.3).
    pub(in crate::layout) fn held(&self, count: usize, extent: f32) -> f32 {
        self.columns
            .iter()
            .filter(|column| {
                column.index < count
                    && !overflows(self.row_offset(column.row) + self.rows[column.row], extent)
            })
            .filter_map(|column| column.slices.last())
            .map(|slice| slice.bottom)
            .fold(0.0, f32::max)
    }
    /// The rules of `geometry`'s gaps between adjacent columns of a row that both hold
    /// content (§4), as tall as the row, from `origin`, the top left of the content box.
    pub(in crate::layout) fn rules(
        &self,
        geometry: &ColumnGeometry,
        rule: Border,
        origin: [f32; 2],
    ) -> Vec<BoxPaint> {
        if rule.used_width() <= 0.0 {
            return Vec::new();
        }
        self.columns
            .windows(2)
            .filter(|pair| {
                pair[0].row == pair[1].row && pair.iter().all(|column| !column.slices.is_empty())
            })
            .map(|pair| {
                let row = pair[0].row;
                super::rule_paint(
                    rule,
                    origin[0] + geometry.rule_x(pair[0].index),
                    origin[1] + self.row_offset(row),
                    self.rows[row],
                )
            })
            .collect()
    }
}

/// How far content is laid out: the run, the offset in it and the edge its next slice
/// repeats at its start.
#[derive(Clone, Copy, Debug)]
struct Cursor {
    run: usize,
    top: f32,
    repeated: f32,
}
impl Cursor {
    fn start(runs: &[Run<'_>]) -> Option<Self> {
        runs.first().map(|run| Self {
            run: 0,
            top: run.top,
            repeated: run.repeated[0],
        })
    }
}

/// Column boxes filled from a cursor, where the content they do not hold resumes, and whether
/// a column holds a slice taller than itself.
struct Filled {
    columns: Vec<ColumnBox>,
    end: Option<Cursor>,
    forced: bool,
}
impl Filled {
    fn extent(&self) -> f32 {
        self.columns
            .iter()
            .map(|column| column.extent)
            .fold(0.0, f32::max)
    }
}

/// Fills column boxes `height` tall in order from `cursor`, at most `limit` of them; a column
/// that no slice fits takes the next one whole, so that filling advances.
fn fill(runs: &[Run<'_>], mut cursor: Cursor, height: f32, limit: Option<usize>) -> Filled {
    let mut columns = vec![ColumnBox::default()];
    let mut forced = false;
    loop {
        let run = &runs[cursor.run];
        let column = columns.last_mut().expect("a column is open");
        let room = height - column.extent;
        let whole = run.bottom - cursor.top + cursor.repeated + run.repeated[1];
        let first = run.breaks.partition_point(|&offset| offset <= cursor.top);
        // A cursor at or past the run's bottom has no break left in it.
        let candidates = &run.breaks[first
            ..run
                .breaks
                .partition_point(|&offset| offset < run.bottom)
                .max(first)];
        let slice = if overflows(whole, room) {
            let fitting = candidates.partition_point(|&offset| {
                !overflows(offset - cursor.top + cursor.repeated + run.cloned[1], room)
            });
            if fitting > 0 {
                Some((candidates[fitting - 1], run.cloned[1]))
            } else if column.slices.is_empty() {
                forced = true;
                Some(
                    candidates
                        .first()
                        .map_or((run.bottom, run.repeated[1]), |&offset| {
                            (offset, run.cloned[1])
                        }),
                )
            } else {
                None
            }
        } else {
            Some((run.bottom, run.repeated[1]))
        };
        if let Some((bottom, end)) = slice {
            let slice = Slice {
                run: cursor.run,
                top: cursor.top,
                bottom,
                repeated: [cursor.repeated, end],
                y: column.extent,
            };
            column.extent += slice.height();
            column.slices.push(slice);
            if bottom >= run.bottom {
                let Some(next) = runs.get(cursor.run + 1) else {
                    return Filled {
                        columns,
                        end: None,
                        forced,
                    };
                };
                cursor = Cursor {
                    run: cursor.run + 1,
                    top: next.top,
                    repeated: next.repeated[0],
                };
                continue;
            }
            cursor.top = bottom;
            cursor.repeated = run.cloned[0];
        }
        if limit.is_some_and(|limit| columns.len() >= limit) {
            return Filled {
                columns,
                end: Some(cursor),
                forced,
            };
        }
        columns.push(ColumnBox {
            index: columns.len(),
            ..ColumnBox::default()
        });
    }
}

/// Fills `count` column boxes from `cursor` to the content's end at the least height, at most
/// `cap`, that holds it (§7.1), or sequentially at that most when none does.
fn balance(runs: &[Run<'_>], cursor: Cursor, count: usize, cap: Option<f32>) -> Filled {
    let current = &runs[cursor.run];
    let total = current.bottom - cursor.top
        + cursor.repeated
        + current.repeated[1]
        + runs[cursor.run + 1..].iter().map(Run::height).sum::<f32>();
    let mut high = cap.map_or(total, |cap| cap.min(total));
    let holds = |height: f32| {
        let filled = fill(runs, cursor, height, Some(count));
        (filled.end.is_none() && !filled.forced).then_some(filled)
    };
    let Some(mut best) = holds(high) else {
        return fill(runs, cursor, high, Some(count));
    };
    if count == 1 {
        return best;
    }
    let mut low = 0.0;
    while high - low > FRAGMENTATION_TOLERANCE_PT {
        let middle = low + (high - low) / 2.0;
        if middle == low || middle == high {
            break;
        }
        match holds(middle) {
            Some(filled) => {
                high = middle;
                best = filled;
            }
            None => low = middle,
        }
    }
    best
}