ferri-pdf 0.3.0

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
//! CSS Text 4 §8.4 `text-autospace`: spacing between characters of the classes it names that
//! adjoin on a line, without an intervening box edge, atomic inline or other character. It
//! is inserted after bidi reordering (§8.4.2), between visually adjacent characters.
use crate::document::Paragraph;
use crate::fonts::{FALLBACK_IDEOGRAPH_ADVANCE_EM, WATER_IDEOGRAPH};
use crate::style::{Style, TextAutospace, has_primary_language};
use crate::text::line_boxes::{Arranged, Slot};
use crate::text::shaping::NARROW_SPACE_FACTOR;
use crate::text::{TextContext, TextError};
use icu_properties::{
    CodePointMapData,
    props::{EastAsianWidth, GeneralCategory, GeneralCategoryGroup},
};
use std::cell::OnceCell;
use std::ops::RangeInclusive;
use unicode_script::{Script, UnicodeScript};

/// §8.4.1: inter-script spacing is 1/8 of the CJK advance measure.
const INTER_SCRIPT_IC: f32 = 0.125;
/// §8.4.1 ideographs outside the Han script: kana that are not punctuation, CJK strokes and
/// Katakana phonetic extensions.
const KANA: RangeInclusive<char> = '\u{3041}'..='\u{30ff}';
const STROKES_AND_PHONETIC_EXTENSIONS: RangeInclusive<char> = '\u{31c0}'..='\u{31ff}';
const SPACE: char = ' ';
const NO_BREAK_SPACE: char = '\u{a0}';
const FRENCH: &str = "fr";
/// French typography sets a narrow no-break space before these and after opening guillemets,
/// and a no-break space before the colon.
const NARROW_BEFORE: [char; 5] = [';', '!', '?', '\u{bb}', '\u{203a}'];
const NARROW_AFTER: [char; 2] = ['\u{ab}', '\u{2039}'];
const NO_BREAK_BEFORE: char = ':';

/// §8.4.1 character classes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Class {
    Ideograph,
    Letter,
    Numeral,
    Other,
}

fn ideograph(ch: char) -> bool {
    if ch.is_ascii() {
        return false;
    }
    // A quotation mark or other punctuation between characters suppresses the spacing.
    let punctuation = || {
        GeneralCategoryGroup::Punctuation
            .contains(CodePointMapData::<GeneralCategory>::new().get(ch))
    };
    // Common and Inherited characters have every script in their extension set.
    let extensions = ch.script_extension();
    let han = !extensions.is_common()
        && !extensions.is_inherited()
        && extensions.contains_script(Script::Han);
    STROKES_AND_PHONETIC_EXTENSIONS.contains(&ch) || ((KANA.contains(&ch) || han) && !punctuation())
}

fn class(ch: char) -> Class {
    if ideograph(ch) {
        return Class::Ideograph;
    }
    let category = CodePointMapData::<GeneralCategory>::new().get(ch);
    let width = CodePointMapData::<EastAsianWidth>::new().get(ch);
    if (GeneralCategoryGroup::Letter.contains(category)
        || GeneralCategoryGroup::Mark.contains(category))
        && !matches!(width, EastAsianWidth::Wide | EastAsianWidth::Fullwidth)
    {
        Class::Letter
    } else if category == GeneralCategory::DecimalNumber && width != EastAsianWidth::Fullwidth {
        Class::Numeral
    } else {
        Class::Other
    }
}

fn separator(ch: char) -> bool {
    GeneralCategoryGroup::Separator.contains(CodePointMapData::<GeneralCategory>::new().get(ch))
}

fn french_punctuation(ch: char) -> bool {
    NARROW_BEFORE.contains(&ch) || NARROW_AFTER.contains(&ch) || ch == NO_BREAK_BEFORE
}

/// The spacing between two characters.
#[derive(Clone, Copy)]
pub(crate) enum Gap {
    InterScript,
    Narrow,
    NoBreak,
}

/// The advance of `ch` in the font that renders it for `style`, in points.
pub(super) fn advance(
    context: &TextContext<'_>,
    style: &Style,
    ch: char,
) -> Result<Option<f32>, TextError> {
    Ok(context
        .fonts
        .advance(
            style.font_candidates(),
            style.font_selection(),
            &style.font_adjustments,
            style.size,
            (ch, false),
            context.resolver,
        )?
        .map(|(advance, scale)| advance * scale * style.size))
}

/// The value in `cell`, measured on first use.
fn measured<T: Copy, E>(
    cell: &OnceCell<T>,
    measure: impl FnOnce() -> Result<T, E>,
) -> Result<T, E> {
    if let Some(value) = cell.get() {
        return Ok(*value);
    }
    let value = measure()?;
    Ok(*cell.get_or_init(|| value))
}

/// What an element's `text-autospace` inserts at the boundaries it contains. Gap widths are
/// measured on first use, so that no font is loaded for lines that are never laid out.
pub(crate) struct Spacing<'p> {
    style: &'p Style,
    value: TextAutospace,
    /// `punctuation` spacing applies: the content language is French.
    french: bool,
    /// The inter-script gap and the narrow and ordinary no-break space gaps, in points.
    inter_script: OnceCell<f32>,
    spaces: OnceCell<[f32; 2]>,
}
impl<'p> Spacing<'p> {
    pub(crate) fn new(style: &'p Style) -> Self {
        let value = style.text_spacing.autospace;
        Self {
            style,
            value,
            french: value.punctuation && has_primary_language(&style.language, FRENCH),
            inter_script: OnceCell::new(),
            spaces: OnceCell::new(),
        }
    }

    /// Whether the element spaces any boundary of text that has `ideographs` and French
    /// `punctuation`.
    fn active(&self, ideographs: bool, punctuation: bool) -> bool {
        (ideographs && (self.value.ideograph_alpha || self.value.ideograph_numeric))
            || (punctuation && self.french)
    }

    /// Whether the spacing replaces a single space between the characters it separates.
    pub(crate) fn replaces(&self) -> bool {
        self.value.replace
    }

    /// The gap between `first` and `second`, in logical order.
    pub(crate) fn gap(&self, first: char, second: char) -> Option<Gap> {
        let classes = [class(first), class(second)];
        if (self.value.ideograph_alpha
            && matches!(
                classes,
                [Class::Ideograph, Class::Letter] | [Class::Letter, Class::Ideograph]
            ))
            || (self.value.ideograph_numeric
                && matches!(
                    classes,
                    [Class::Ideograph, Class::Numeral] | [Class::Numeral, Class::Ideograph]
                ))
        {
            return Some(Gap::InterScript);
        }
        if !self.french || separator(first) || separator(second) {
            None
        } else if NARROW_BEFORE.contains(&second) || NARROW_AFTER.contains(&first) {
            Some(Gap::Narrow)
        } else if second == NO_BREAK_BEFORE {
            Some(Gap::NoBreak)
        } else {
            None
        }
    }

    /// The width of `gap` in units where the element's font size is `size`, `advance`
    /// measuring a character in the element's font where it has one.
    pub(crate) fn width<E>(
        &self,
        gap: Gap,
        size: f32,
        mut advance: impl FnMut(char) -> Result<Option<f32>, E>,
    ) -> Result<f32, E> {
        if let Gap::InterScript = gap {
            return measured(&self.inter_script, || {
                Ok(
                    advance(WATER_IDEOGRAPH)?.unwrap_or(FALLBACK_IDEOGRAPH_ADVANCE_EM * size)
                        * INTER_SCRIPT_IC,
                )
            });
        }
        let [narrow, no_break] = measured(&self.spaces, || {
            let space = advance(SPACE)?.unwrap_or_default();
            Ok([
                space * NARROW_SPACE_FACTOR,
                advance(NO_BREAK_SPACE)?.unwrap_or(space),
            ])
        })?;
        Ok(if let Gap::Narrow = gap {
            narrow
        } else {
            no_break
        })
    }
}

/// Whether `text` is a single space, which `replace` spacing removes.
pub(crate) fn replaceable(text: &str) -> bool {
    let mut characters = text.chars();
    characters.next() == Some(SPACE) && characters.next().is_none()
}

/// The last glyph of a typographic character unit on a line, in visual order.
struct Unit {
    slot: usize,
    run: usize,
    glyph: usize,
    /// Paragraph offset of the unit's base character, which decides logical order.
    offset: usize,
    base: char,
    span: usize,
    /// The unit is a single U+0020, which `replace` removes.
    space: bool,
}

/// Spacing inserted after `unit`, rendered within inline box `owner`, which replaces the
/// `removed` space.
struct Insertion<'a> {
    unit: &'a Unit,
    removed: Option<&'a Unit>,
    owner: Option<usize>,
    width: f32,
}

/// The innermost inline box containing boxes `left` and `right`; `None` is the root.
fn common_box(paragraph: &Paragraph, left: Option<usize>, right: Option<usize>) -> Option<usize> {
    let mut candidate = left;
    while let Some(index) = candidate {
        if right == Some(index) || paragraph.is_within(right, index) {
            return Some(index);
        }
        candidate = paragraph.boxes()[index].parent;
    }
    None
}

/// The `text-autospace` of a paragraph's root inline box, inline boxes and text spans.
pub(crate) struct Autospace<'p, 'c, 'f> {
    context: &'c TextContext<'f>,
    paragraph: &'p Paragraph,
    root: Spacing<'p>,
    boxes: Vec<Spacing<'p>>,
    spans: Vec<Spacing<'p>>,
}

impl<'p, 'c, 'f> Autospace<'p, 'c, 'f> {
    /// `None` when no boundary in `paragraph` can be spaced.
    pub(super) fn of(context: &'c TextContext<'f>, paragraph: &'p Paragraph) -> Option<Self> {
        let text = paragraph.text();
        let ideographs = text.chars().any(ideograph);
        let punctuation = text.chars().any(french_punctuation);
        let autospace = Self {
            context,
            paragraph,
            root: Spacing::new(paragraph.style()),
            boxes: paragraph
                .boxes()
                .iter()
                .map(|inline_box| Spacing::new(&inline_box.style))
                .collect(),
            spans: paragraph
                .spans()
                .iter()
                .map(|span| Spacing::new(&span.style))
                .collect(),
        };
        std::iter::once(&autospace.root)
            .chain(&autospace.boxes)
            .chain(&autospace.spans)
            .any(|spacing| spacing.active(ideographs, punctuation))
            .then_some(autospace)
    }

    /// Typographic character units of the arranged line in visual order; `None` separates
    /// units that do not adjoin.
    fn units(arranged: &Arranged) -> Vec<Option<Unit>> {
        let mut units = Vec::new();
        for (slot, entry) in arranged.order.iter().enumerate() {
            let Slot::Run(index) = *entry else {
                units.push(None);
                continue;
            };
            let run = &arranged.runs[index];
            if run.leader {
                units.push(None);
                continue;
            }
            for (glyph, positioned) in run.glyphs.iter().enumerate() {
                let range = &positioned.text_range;
                if run
                    .glyphs
                    .get(glyph + 1)
                    .is_some_and(|next| next.text_range == *range)
                {
                    continue;
                }
                let text = &run.text[range.clone()];
                units.push(text.chars().next().map(|base| Unit {
                    slot,
                    run: index,
                    glyph,
                    offset: run.source_range.start + range.start,
                    base,
                    span: run.source_span,
                    space: replaceable(text),
                }));
            }
        }
        units
    }

    /// The spacing at the boundary of adjoining `left` and `right`, by the innermost element
    /// containing it, which also renders it.
    fn insertion<'u>(
        &self,
        left: &'u Unit,
        right: &Unit,
        removed: Option<&'u Unit>,
    ) -> Result<Option<Insertion<'u>>, TextError> {
        let spans = self.paragraph.spans();
        let (owner, spacing) = if left.span == right.span {
            (spans[left.span].inline_box, &self.spans[left.span])
        } else {
            let owner = common_box(
                self.paragraph,
                spans[left.span].inline_box,
                spans[right.span].inline_box,
            );
            (owner, owner.map_or(&self.root, |index| &self.boxes[index]))
        };
        if removed.is_some() && !spacing.replaces() {
            return Ok(None);
        }
        let (first, second) = if left.offset <= right.offset {
            (left.base, right.base)
        } else {
            (right.base, left.base)
        };
        let Some(gap) = spacing.gap(first, second) else {
            return Ok(None);
        };
        let width = spacing.width(gap, spacing.style.size, |ch| {
            advance(self.context, spacing.style, ch)
        })?;
        Ok((width != 0.0).then_some(Insertion {
            unit: left,
            removed,
            owner,
            width,
        }))
    }

    /// Spaces the adjoining units of `arranged`, before its inline box fragments are formed.
    pub(super) fn apply(&self, arranged: &mut Arranged) -> Result<(), TextError> {
        let units = Self::units(arranged);
        let mut insertions = Vec::new();
        for (index, left) in units.iter().enumerate() {
            let Some(left) = left else {
                continue;
            };
            let (right, removed) = match units.get(index + 1) {
                Some(Some(next)) if next.space => (units.get(index + 2), Some(next)),
                next => (next, None),
            };
            if let Some(Some(right)) = right
                && let Some(insertion) = self.insertion(left, right, removed)?
            {
                insertions.push(insertion);
            }
        }
        // Later slots first, so that inserted slots leave earlier positions in place.
        for insertion in insertions.into_iter().rev() {
            if let Some(space) = insertion.removed {
                let run = &mut arranged.runs[space.run];
                let range = run.glyphs[space.glyph].text_range.clone();
                for glyph in run
                    .glyphs
                    .iter_mut()
                    .filter(|glyph| glyph.text_range == range)
                {
                    run.width -= glyph.advance(run.font_size);
                    glyph.x_advance = 0.0;
                    glyph.x_spacing = 0.0;
                }
                run.removed_spaces.push(range.start);
            }
            let unit = insertion.unit;
            if self.paragraph.spans()[unit.span].inline_box == insertion.owner {
                let run = &mut arranged.runs[unit.run];
                run.glyphs[unit.glyph].x_spacing += insertion.width;
                run.width += insertion.width;
            } else {
                arranged.order.insert(
                    unit.slot + 1,
                    Slot::Space {
                        owner: insertion.owner,
                        width: insertion.width,
                    },
                );
            }
        }
        Ok(())
    }
}