ferri-pdf 0.1.9

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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use crate::document::BlockBox;
use crate::layout::measure::Failure;
use crate::layout::{
    geometry::{Edges, HorizontalBox, SizeConstraints},
    measure::{ItemMetrics, MeasuredBlock, MeasuredCell, Measurer},
};
use crate::style::{Alignment, COLUMNS, OverflowPosition, ROWS, Size, Style};
use std::ops::Range;

pub(crate) struct Item<'a> {
    pub parent: Option<super::ParentContext>,
    pub source: &'a BlockBox,
    pub inline_definite: bool,
    pub geometry: HorizontalBox,
    pub margins: [Option<f32>; 4],
    pub align: Alignment,
    pub align_overflow: OverflowPosition,
}

#[derive(Clone)]
pub(crate) struct BaselineContribution {
    pub contribution: crate::grid::SizingItem,
    pub baseline: f32,
}

pub(super) fn add_baseline_shim(item: &mut crate::grid::SizingItem, shim: f32) {
    item.min_content += shim;
    item.max_content += shim;
    item.minimum += shim;
    item.content_minimum = item.content_minimum.map(|value| value + shim);
}

/// The row baseline-sharing groups (CSS Box Alignment 3 §9.2): first-baseline items share
/// their startmost row, aligning the extents above their first baselines, and last-baseline
/// items share their endmost row, aligning the extents below their last baselines.
pub(super) struct Baselines {
    pub groups: Vec<f32>,
    pub last_groups: Vec<f32>,
    pub items: Vec<(usize, Option<f32>)>,
    pub last_items: Vec<(usize, Option<f32>)>,
}
impl Baselines {
    pub(super) fn new(rows: usize) -> Self {
        Self {
            groups: vec![f32::NEG_INFINITY; rows],
            last_groups: vec![f32::NEG_INFINITY; rows],
            items: Vec::new(),
            last_items: Vec::new(),
        }
    }
    /// Records the next item, in `rows`, by its first-baseline ascent or last-baseline
    /// descent, where it participates in baseline alignment.
    pub(super) fn push(&mut self, rows: &Range<usize>, [baseline, descent]: [Option<f32>; 2]) {
        if let Some(baseline) = baseline {
            self.groups[rows.start] = self.groups[rows.start].max(baseline);
        }
        self.items.push((rows.start, baseline));
        let end = rows.end - 1;
        if let Some(descent) = descent {
            self.last_groups[end] = self.last_groups[end].max(descent);
        }
        self.last_items.push((end, descent));
    }
    pub(super) fn container(
        &self,
        cells: &[MeasuredCell<'_>],
        areas: &[[Range<usize>; 2]],
    ) -> [Option<f32>; 2] {
        [false, true].map(|last| {
            let row = if last {
                areas.iter().map(|area| area[ROWS].end - 1).max()
            } else {
                areas.iter().map(|area| area[ROWS].start).min()
            }?;
            let candidates = areas
                .iter()
                .enumerate()
                .filter(|(_, area)| area[ROWS].contains(&row));
            // The aligned baseline of the last row's last-baseline group gives the last
            // baseline set (CSS Grid 1 §11.8).
            if last
                && let Some((index, _)) = candidates.clone().find(|(index, area)| {
                    area[ROWS].end - 1 == row && self.last_items[*index].1.is_some()
                })
            {
                let cell = &cells[index];
                return Some(cell.offset + cell.block.last_baseline().unwrap_or(cell.block.height));
            }
            let shared = candidates
                .clone()
                .find(|(index, area)| area[ROWS].start == row && self.items[*index].1.is_some());
            let (index, _) = shared.or_else(|| {
                let order = |(index, area): &(usize, &[Range<usize>; 2])| {
                    (area[ROWS].start, area[COLUMNS].start, *index)
                };
                if last {
                    candidates.max_by_key(order)
                } else {
                    candidates.min_by_key(order)
                }
            })?;
            let cell = &cells[index];
            let baseline = if last && shared.is_none() {
                cell.block.last_baseline()
            } else {
                cell.block.first_baseline()
            };
            Some(cell.offset + baseline.unwrap_or(cell.block.height))
        })
    }

    /// The space baseline alignment adds above and below item `index`.
    fn shims(&self, index: usize) -> [f32; 2] {
        let (row, baseline) = self.items[index];
        let (end, descent) = self.last_items[index];
        [
            baseline.map_or(0.0, |baseline| self.groups[row] - baseline),
            descent.map_or(0.0, |descent| self.last_groups[end] - descent),
        ]
    }
    /// The extra size item `index` contributes to its tracks.
    pub(super) fn shim(&self, index: usize) -> f32 {
        self.shims(index).iter().sum()
    }
    /// How far baseline alignment moves item `index` from its fallback position.
    pub(super) fn offset(&self, index: usize) -> f32 {
        let [above, below] = self.shims(index);
        above - below
    }
}

pub(super) fn physical_alignment(
    alignment: Alignment,
    reverse: bool,
    own_reverse: bool,
) -> Alignment {
    let alignment = match alignment {
        Alignment::SelfStart => {
            if own_reverse {
                Alignment::Right
            } else {
                Alignment::Left
            }
        }
        Alignment::SelfEnd => {
            if own_reverse {
                Alignment::Left
            } else {
                Alignment::Right
            }
        }
        alignment => alignment,
    };
    match alignment {
        Alignment::Center => Alignment::Center,
        Alignment::Right => Alignment::Right,
        Alignment::Left => Alignment::Left,
        Alignment::End | Alignment::FlexEnd | Alignment::LastBaseline if !reverse => {
            Alignment::Right
        }
        Alignment::Start
        | Alignment::FlexStart
        | Alignment::Normal
        | Alignment::Stretch
        | Alignment::Auto
            if reverse =>
        {
            Alignment::Right
        }
        _ => Alignment::Left,
    }
}

fn offset(
    (alignment, overflow): (Alignment, OverflowPosition),
    free: f32,
    reverse: bool,
    own_reverse: bool,
) -> f32 {
    // Last-baseline alignment falls back to safe end (CSS Box Alignment 3 §4.2).
    let alignment = if overflow.starts(free) || (alignment == Alignment::LastBaseline && free < 0.0)
    {
        Alignment::Start
    } else {
        alignment
    };
    match physical_alignment(alignment, reverse, own_reverse) {
        Alignment::Center => free / 2.0,
        Alignment::Right => free,
        _ => 0.0,
    }
}

impl<'a> Item<'a> {
    /// The item in its grid `area`, self-aligned by default as the grid `container`'s
    /// `align-items` and `justify-items`, without the margins `margin-trim` discards at the
    /// `trimmed` sides.
    pub(crate) fn new(
        source: &'a BlockBox,
        area: Range<f32>,
        parent: &HorizontalBox,
        container: &Style,
        height: Option<f32>,
        trimmed: [bool; 4],
        measurer: &Measurer<'a>,
    ) -> Result<Self, Failure> {
        let style = source.style();
        let available = area.end - area.start;
        let edges = measurer.box_edges(source, available)?;
        let mut margins = style
            .margin
            .each_ref()
            .map(|value| value.resolve(available));
        for (margin, trimmed) in margins.iter_mut().zip(trimmed) {
            if trimmed {
                *margin = Some(0.0);
            }
        }
        let shared = [ROWS, COLUMNS].map(|axis| super::sizing::shared(style, axis));
        for (axis, sides) in [(ROWS, [0, 2]), (COLUMNS, [3, 1])] {
            if shared[axis] {
                for side in sides {
                    margins[side] = Some(margins[side].unwrap_or(0.0));
                }
            }
        }
        let constraints = super::sizing::constraints(
            style,
            COLUMNS,
            Some(available),
            edges.horizontal(),
            shared[COLUMNS],
        );
        let (justify, justify_overflow) = if shared[COLUMNS] {
            (Alignment::Stretch, OverflowPosition::Default)
        } else {
            style
                .grid
                .used_justify_self(container.grid.default_justify())
        };
        let (align, align_overflow) = if shared[ROWS] {
            (Alignment::Stretch, OverflowPosition::Default)
        } else {
            style.flex.used_align_self(&container.flex)
        };
        let auto = usize::from(margins[1].is_none()) + usize::from(margins[3].is_none());
        let space = (available
            - edges.horizontal()
            - margins[1].unwrap_or(0.0)
            - margins[3].unwrap_or(0.0))
        .max(0.0);
        let constraints = if shared[COLUMNS] {
            constraints
        } else {
            let mut constraints = crate::layout::intrinsic::width_constraints(
                source,
                measurer,
                Some(available),
                edges.horizontal(),
                Some(space),
            )?;
            crate::layout::ratio::transfer_to_width(style, &mut constraints, height, &edges);
            constraints
        };
        // CSS Grid 2 §6.2: with a preferred aspect ratio, `normal` sizes the item as a
        // block-level box, which takes its automatic width from a definite height.
        let ratio_width = if shared[COLUMNS]
            || !matches!(justify, Alignment::Normal | Alignment::Auto)
        {
            None
        } else {
            crate::layout::ratio::width_from_height(measurer, source, available, height, &edges)?
        };
        let width = constraints.constrain(if let Some(width) = constraints.specified {
            width
        } else if let Some(width) = ratio_width {
            width
        } else {
            constraints.preferred(
                if auto == 0
                    && (justify == Alignment::Stretch
                        || (matches!(justify, Alignment::Normal | Alignment::Auto)
                            && source.image().is_none()))
                {
                    space
                } else if source.image().is_some() {
                    crate::layout::images::size(source, available, available, height, None, None)[0]
                } else {
                    let natural = crate::layout::intrinsic::measure(source, measurer, available)?;
                    (natural.max.min(available).max(natural.min)
                        - edges.horizontal()
                        - margins[1].unwrap_or(0.0)
                        - margins[3].unwrap_or(0.0))
                    .max(0.0)
                },
            )
        });
        let free = available
            - width
            - edges.horizontal()
            - margins[1].unwrap_or(0.0)
            - margins[3].unwrap_or(0.0);
        let left = margins[3].unwrap_or(if free > 0.0 {
            free / auto.max(1) as f32
        } else {
            0.0
        }) + if auto == 0 {
            offset(
                (justify, justify_overflow),
                free,
                parent.containing_rtl,
                style.used_rtl(),
            )
        } else {
            0.0
        };
        Ok(Self {
            source,
            inline_definite: !measurer.space.indefinite_inline,
            geometry: HorizontalBox {
                containing_x: parent.x + area.start,
                containing_width: available,
                containing_rtl: parent.containing_rtl,
                x: parent.x + area.start + left + edges.padding[3] + edges.border[3],
                width,
                padding: edges.padding,
                border: edges.border,
                margin: [Some(0.0); 4],
                stretch_margins: [0, 2].map(|side| margins[side].unwrap_or(0.0)),
                beside_floats: None,
            },
            margins,
            align,
            align_overflow,
            parent: None,
        })
    }

    pub(super) fn inherit(
        &mut self,
        parent: Option<super::ParentContext>,
        tracks: [Option<std::rc::Rc<super::TrackGeometry>>; 2],
    ) {
        let left = self.geometry.x - self.geometry.containing_x;
        let right = self.geometry.containing_width - self.geometry.width - left;
        let vertical = [0, 2].map(|side| {
            self.geometry.padding[side]
                + self.geometry.border[side]
                + self.margins[side].unwrap_or(0.0)
        });
        self.parent = parent.map(|parent| parent.with_geometry(tracks, [vertical, [left, right]]));
    }

    pub(crate) fn measure(
        &self,
        measurer: &mut Measurer<'a>,
        height: Option<f32>,
        used_height: Option<f32>,
    ) -> Result<MeasuredBlock<'a>, Failure> {
        let mut space = measurer.space;
        space.indefinite_inline &= !self.inline_definite;
        measurer.with_space(space, |measurer| {
            measurer.with_grid_parent(self.parent.clone(), |measurer| {
                measurer.with_sized_item(self.source, |measurer| {
                    self.measure_contents(measurer, height, used_height)
                })
            })
        })
    }

    fn measure_contents(
        &self,
        measurer: &mut Measurer<'a>,
        height: Option<f32>,
        used_height: Option<f32>,
    ) -> Result<MeasuredBlock<'a>, Failure> {
        if self.source.style().display.is_table() {
            crate::layout::tables::measure_wrapper(
                measurer,
                used_height,
                |measurer, used_height| {
                    crate::layout::tables::measure_format(
                        measurer,
                        self.source,
                        &self.geometry,
                        height,
                        used_height,
                    )
                },
            )
        } else {
            measurer.measure_format(
                self.source,
                self.geometry.clone(),
                true,
                height,
                used_height,
            )
        }
    }

    pub(crate) fn measure_area(
        &self,
        measurer: &mut Measurer<'a>,
        available: f32,
    ) -> Result<MeasuredBlock<'a>, Failure> {
        let used = self.stretch().then(|| {
            let heights = self.height(Some(available));
            heights.constrain(
                heights.preferred(
                    (available
                        - self.vertical_edges()
                        - self.margins[0].unwrap_or(0.0)
                        - self.margins[2].unwrap_or(0.0))
                    .max(0.0),
                ),
            )
        });
        self.measure(measurer, Some(available), used)
    }

    /// The height constraints in a grid area `available` tall, which a `stretch` size fills
    /// with the item's margin box (CSS Sizing 3 §4.2).
    pub(crate) fn height(&self, available: Option<f32>) -> SizeConstraints {
        let style = self.source.style();
        let edges = self.vertical_edges();
        let margins = self.margins[0].unwrap_or(0.0) + self.margins[2].unwrap_or(0.0);
        super::sizing::constraints(
            style,
            ROWS,
            available,
            edges,
            super::sizing::shared(style, ROWS),
        )
        .with_stretch(
            [&style.height, &style.min_height, &style.max_height],
            available.map(|area| (area - margins - edges).max(0.0)),
        )
    }

    pub(super) fn row_edges(&self) -> [f32; 2] {
        [0, 2].map(|side| {
            self.geometry.padding[side]
                + self.geometry.border[side]
                + self.margins[side].unwrap_or(0.0)
        })
    }

    pub(super) fn project_rows(
        &self,
        rows: &[crate::grid::SizingItem],
        parent: Range<usize>,
        parent_gap: f32,
        measurer: &Measurer<'_>,
    ) -> Result<Vec<crate::grid::SizingItem>, Failure> {
        let child_gap = self.source.style().flex.gap[ROWS].resolve_normal(0.0, parent_gap);
        measurer.work.spend(rows.len().saturating_mul(4).max(1))?;
        Ok(crate::grid::subgrid_contributions(
            rows,
            parent,
            false,
            self.row_edges(),
            child_gap - parent_gap,
        )?)
    }

    pub(crate) fn vertical_edges(&self) -> f32 {
        self.geometry.padding[0]
            + self.geometry.padding[2]
            + self.geometry.border[0]
            + self.geometry.border[2]
    }

    /// Whether a percentage height cycles through the intrinsic tracks it sizes, which keeps
    /// the item out of baseline alignment.
    fn cyclic_height(&self, intrinsic_tracks: bool) -> bool {
        let style = self.source.style();
        intrinsic_tracks
            && [&style.height, &style.min_height, &style.max_height]
                .into_iter()
                .any(|size| {
                    matches!(size.basis(), Size::Value(_)) && size.resolve_definite(None).is_none()
                })
    }

    pub(crate) fn baseline(&self, measured: &ItemMetrics, intrinsic_tracks: bool) -> Option<f32> {
        let cyclic = self.cyclic_height(intrinsic_tracks);
        (self.align == Alignment::Baseline
            && self.margins[0].is_some()
            && self.margins[2].is_some()
            && !cyclic)
            .then(|| measured.baseline.unwrap_or(measured.height) + self.margins[0].unwrap_or(0.0))
    }

    /// The extent below a last-baseline item's last baseline, to its margin box's end
    /// (CSS Box Alignment 3 §9.3).
    pub(crate) fn last_descent(
        &self,
        measured: &ItemMetrics,
        intrinsic_tracks: bool,
    ) -> Option<f32> {
        let cyclic = self.cyclic_height(intrinsic_tracks);
        (self.align == Alignment::LastBaseline
            && self.margins[0].is_some()
            && self.margins[2].is_some()
            && !cyclic)
            .then(|| {
                measured.height - measured.last_baseline.unwrap_or(measured.height)
                    + self.margins[2].unwrap_or(0.0)
            })
    }

    pub(crate) fn stretch(&self) -> bool {
        (super::sizing::shared(self.source.style(), ROWS)
            || self
                .source
                .style()
                .height
                .is_auto_block_size(self.source.image().is_some()))
            && self.margins[0].is_some()
            && self.margins[2].is_some()
            && (self.align == Alignment::Stretch
                || (matches!(self.align, Alignment::Normal | Alignment::Auto)
                    && self.source.image().is_none()
                    && crate::layout::ratio::PreferredRatio::of_box(
                        self.source.style(),
                        &Edges {
                            padding: self.geometry.padding,
                            border: self.geometry.border,
                        },
                    )
                    .is_none()))
    }

    pub(crate) fn top(&self, available: f32, height: f32) -> f32 {
        let free =
            available - height - self.margins[0].unwrap_or(0.0) - self.margins[2].unwrap_or(0.0);
        let auto = usize::from(self.margins[0].is_none()) + usize::from(self.margins[2].is_none());
        self.margins[0].unwrap_or(if free > 0.0 {
            free / auto.max(1) as f32
        } else {
            0.0
        }) + if auto == 0 {
            offset((self.align, self.align_overflow), free, false, false)
        } else {
            0.0
        }
    }
}