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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use crate::fonts::{FontFeature, FontId, FontSynthesis, FontVariation};
use crate::style::{FontVariantEmoji, FontVariantPosition, POINTS_PER_PIXEL, Style};
use crate::text::features::{self, CapsPlan, FaceFeatures};
use crate::text::{GlyphRun, PositionedGlyph, TextError};

use crate::work::{self, Work};
use icu_properties::{
    CodePointMapData, CodePointSetData,
    props::{DefaultIgnorableCodePoint, EmojiPresentation, GeneralCategory, VariationSelector},
};
use rustybuzz::{
    BufferFlags, Direction, Face, Feature, GlyphBuffer, Language, UnicodeBuffer, ttf_parser::Tag,
};
use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::Arc;
use unicode_script::{Script, UnicodeScript};

pub(super) const NARROW_NO_BREAK_SPACE: char = '\u{202f}';
pub(super) const NARROW_SPACE_FACTOR: f32 = 0.5;
const MAX_LIGATURE_TRACKING_EM: f32 = 0.025;
const WORD_SPACE: char = ' ';
/// The glyph that shows a missing character.
const NOTDEF: u32 = 0;
/// UA synthesis policy for `font-variant-position` (§6.5): sizes up to the small size keep
/// more of their size than sizes from the large size, with linear interpolation between.
const POSITION_SMALL_SIZE: f32 = 20.0 * POINTS_PER_PIXEL;
const POSITION_LARGE_SIZE: f32 = 45.0 * POINTS_PER_PIXEL;
const POSITION_SMALL_SCALE: f32 = 0.82;
const POSITION_LARGE_SCALE: f32 = 2.0 / 3.0;
/// Synthesized superscripts rise and subscripts drop by these fractions of the unreduced em.
const SUPERSCRIPT_RISE_EM: f32 = 0.34;
const SUBSCRIPT_DROP_EM: f32 = 0.2;
/// Text and emoji presentation selectors (UTS #51 §1.4.3).
const TEXT_PRESENTATION: char = '\u{fe0e}';
const EMOJI_PRESENTATION: char = '\u{fe0f}';

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum MissingGlyphs {
    Reject,
    Substitute,
}

pub(super) fn private_use(ch: char) -> bool {
    !ch.is_ascii()
        && CodePointMapData::<GeneralCategory>::new().get(ch) == GeneralCategory::PrivateUse
}

pub(crate) fn variation_selector(ch: char) -> bool {
    !ch.is_ascii() && CodePointSetData::new::<VariationSelector>().contains(ch)
}

/// The presentation selector `font-variant-emoji` appends after `ch`, which text supplies
/// itself when a presentation selector follows (§9.3).
pub(crate) fn implied_presentation(
    emoji: FontVariantEmoji,
    ch: char,
    next: Option<char>,
) -> Option<char> {
    if emoji == FontVariantEmoji::Normal
        || matches!(next, Some(TEXT_PRESENTATION | EMOJI_PRESENTATION))
        || crate::spec_data::emoji::VARIATION_BASES
            .binary_search(&u32::from(ch))
            .is_err()
    {
        return None;
    }
    let emoji_default = || CodePointSetData::new::<EmojiPresentation>().contains(ch);
    Some(match emoji {
        FontVariantEmoji::Emoji => EMOJI_PRESENTATION,
        FontVariantEmoji::Unicode if emoji_default() => EMOJI_PRESENTATION,
        FontVariantEmoji::Normal | FontVariantEmoji::Text | FontVariantEmoji::Unicode => {
            TEXT_PRESENTATION
        }
    })
}

/// Whether the face has every variation sequence in `text`, including the presentation
/// selectors `emoji` implies.
pub(crate) fn supports_variations(
    face: &Face<'_>,
    text: &str,
    emoji: Option<FontVariantEmoji>,
) -> bool {
    let mut previous = None;
    let mut chars = text.chars().peekable();
    while let Some(ch) = chars.next() {
        if variation_selector(ch)
            // Mongolian free selectors are handled by the script shaper through GSUB.
            && ch.script() != Script::Mongolian
            && let Some(base) = previous
            && !variation_selector(base)
            && face.glyph_variation_index(base, ch).is_none()
        {
            return false;
        }
        if let Some(selector) =
            emoji.and_then(|emoji| implied_presentation(emoji, ch, chars.peek().copied()))
            && face.glyph_variation_index(ch, selector).is_none()
        {
            return false;
        }
        previous = Some(ch);
    }
    true
}

/// Whether the face defines `tag` as a language system of any script.
pub(super) fn has_language_system(face: &Face<'_>, tag: [u8; 4]) -> bool {
    let tag = Tag::from_bytes(&tag);
    [face.tables().gsub, face.tables().gpos]
        .into_iter()
        .flatten()
        .any(|table| {
            table
                .scripts
                .into_iter()
                .any(|script| script.languages.into_iter().any(|system| system.tag == tag))
        })
}

#[derive(Clone, Copy)]
pub(super) struct ShapingFont<'f, 'data> {
    pub face: &'f Face<'data>,
    pub font_id: FontId,
    pub synthesis: FontSynthesis,
    pub oblique_skew: f32,
    pub metrics: crate::fonts::FaceMetrics,
    pub variations: &'f [FontVariation],
    pub narrow_space_advance: Option<f32>,
    pub missing: MissingGlyphs,
    /// The used font size, after `font-size-adjust`.
    pub size: f32,
    pub features: FaceFeatures<'f>,
    pub language: Option<&'f Language>,
    pub palette: Option<&'f Arc<[crate::graphics::Color]>>,
}

/// How a run renders `font-variant-position` (§6.5).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Position {
    Normal,
    Native(FontFeature),
    /// Reduced glyphs shifted by the offset below the baseline, in points.
    Synthetic {
        scale: f32,
        offset: f32,
    },
}

/// The reduction of synthesized superscripts and subscripts at `size`.
fn position_scale(size: f32) -> f32 {
    let progress = ((size - POSITION_SMALL_SIZE) / (POSITION_LARGE_SIZE - POSITION_SMALL_SIZE))
        .clamp(0.0, 1.0);
    POSITION_SMALL_SCALE + (POSITION_LARGE_SCALE - POSITION_SMALL_SCALE) * progress
}

/// The glyphs of each cluster of `text`.
fn clusters(
    face: &Face<'_>,
    text: &str,
    rtl: bool,
    features: &[Feature],
) -> BTreeMap<u32, Vec<u32>> {
    let mut buffer = UnicodeBuffer::new();
    buffer.push_str(text);
    buffer.set_direction(if rtl {
        Direction::RightToLeft
    } else {
        Direction::LeftToRight
    });
    buffer.guess_segment_properties();
    let shaped = shape_buffer(face, features, buffer);
    let mut clusters = BTreeMap::<u32, Vec<u32>>::new();
    for info in shaped.glyph_infos() {
        clusters
            .entry(info.cluster)
            .or_default()
            .push(info.glyph_id);
    }
    clusters
}

/// The glyphs `face` shapes `buffer` into with `features`.
pub(crate) fn shape_buffer(
    face: &Face<'_>,
    features: &[Feature],
    buffer: UnicodeBuffer,
) -> GlyphBuffer {
    work::count(Work::ShapedRun, 1);
    rustybuzz::shape(face, features, buffer)
}

/// Whether `letter_spacing` tracks text of `size` so far apart that common ligatures do not
/// apply (CSS Text 3 §8.2).
pub(crate) fn tracked(letter_spacing: f32, size: f32) -> bool {
    letter_spacing.abs() > size * MAX_LIGATURE_TRACKING_EM
}

pub(crate) fn shaper_features(features: &[FontFeature]) -> Vec<Feature> {
    features
        .iter()
        .map(|feature| Feature::new(Tag::from_bytes(&feature.tag), feature.value, ..))
        .collect()
}

/// Native variants apply only where `face`, contributing `face_features`, has them for every
/// character of the run other than spaces; otherwise the whole run is synthesized at the used
/// size `size`, if synthesis is allowed (§6.5, §2.8.4).
pub(crate) fn position_form(
    face: &Face<'_>,
    face_features: FaceFeatures<'_>,
    size: f32,
    text: &str,
    rtl: bool,
    style: &Style,
    caps: CapsPlan,
) -> Position {
    let position = style.font_features.position;
    let Some(feature) = features::position_feature(position) else {
        return Position::Normal;
    };
    if !style.font_synthesis.position {
        return Position::Native(feature);
    }
    let face_features = FaceFeatures {
        caps: caps.features,
        ..face_features
    };
    let plain = clusters(
        face,
        text,
        rtl,
        &shaper_features(&features::run_features(style, face_features, false)),
    );
    let variant = clusters(
        face,
        text,
        rtl,
        &shaper_features(&features::run_features(
            style,
            FaceFeatures {
                position: Some(feature),
                ..face_features
            },
            false,
        )),
    );
    let ignorables = CodePointSetData::new::<DefaultIgnorableCodePoint>();
    let boundaries =
        crate::fonts::cluster_boundaries(plain.keys().map(|cluster| *cluster as usize), text.len());
    let complete = boundaries.windows(2).all(|bounds| {
        let source = &text[bounds[0]..bounds[1]];
        let cluster = u32::try_from(bounds[0]).expect("text offsets fit the shaper's clusters");
        source
            .chars()
            .all(|ch| ch.is_whitespace() || ignorables.contains(ch))
            || plain.get(&cluster) != variant.get(&cluster)
    });
    if complete {
        return Position::Native(feature);
    }
    let em = size;
    Position::Synthetic {
        scale: position_scale(em),
        offset: match position {
            FontVariantPosition::Super => -SUPERSCRIPT_RISE_EM * em,
            FontVariantPosition::Sub | FontVariantPosition::Normal => SUBSCRIPT_DROP_EM * em,
        },
    }
}

pub(super) fn shape_runs(
    font: ShapingFont<'_, '_>,
    paragraph: &str,
    range: Range<usize>,
    rtl: bool,
    style: &Style,
) -> Result<Vec<GlyphRun>, TextError> {
    if !style.vertical_typographic_mode() {
        return shape_variants(font, paragraph, range, rtl, style, false);
    }
    let mut pieces = style.text_orientation.ranges(
        paragraph,
        range,
        crate::fonts::has_feature(font.face, *b"vert")
            || crate::fonts::has_feature(font.face, *b"vrt2"),
    );
    if rtl {
        pieces.reverse();
    }
    let mut runs = Vec::new();
    for (range, upright) in pieces {
        runs.extend(shape_variants(font, paragraph, range, rtl, style, upright)?);
    }
    Ok(runs)
}

fn shape_variants(
    font: ShapingFont<'_, '_>,
    paragraph: &str,
    range: Range<usize>,
    rtl: bool,
    style: &Style,
    upright: bool,
) -> Result<Vec<GlyphRun>, TextError> {
    let caps = features::caps_plan(
        style.font_variant_caps,
        |tag| crate::fonts::has_feature(font.face, tag),
        style.font_synthesis.small_caps,
    );
    let position = position_form(
        font.face,
        font.features,
        font.size,
        &paragraph[range.clone()],
        rtl,
        style,
        caps,
    );
    if !caps.synthetic() {
        return shape_run(
            font, paragraph, range, rtl, style, caps, position, false, upright,
        )
        .map(|run| vec![run]);
    }
    let mut pieces = caps.pieces(paragraph, range);
    if rtl {
        pieces.reverse();
    }
    pieces
        .into_iter()
        .map(|(range, small)| {
            shape_run(
                font, paragraph, range, rtl, style, caps, position, small, upright,
            )
        })
        .collect()
}

#[expect(
    clippy::too_many_arguments,
    reason = "a run's text, direction, style and its caps and position forms"
)]
fn shape_run(
    font: ShapingFont<'_, '_>,
    paragraph: &str,
    range: Range<usize>,
    rtl: bool,
    style: &Style,
    caps: CapsPlan,
    position: Position,
    synthetic_caps: bool,
    upright: bool,
) -> Result<GlyphRun, TextError> {
    let ShapingFont {
        face,
        font_id,
        mut synthesis,
        oblique_skew,
        metrics,
        variations,
        narrow_space_advance,
        missing,
        size: used_size,
        features: face_features,
        language,
        palette,
    } = font;
    let text = &paragraph[range.clone()];
    let (position_feature, synthetic_position) = match position {
        Position::Normal => (None, None),
        Position::Native(feature) => (Some(feature), None),
        Position::Synthetic { scale, offset } => (None, Some((scale, offset))),
    };
    let (position_scale, baseline_offset) = synthetic_position.unwrap_or((1.0, 0.0));
    let size = used_size
        * position_scale
        * if synthetic_caps {
            features::SMALL_CAPS_SCALE
        } else {
            1.0
        };
    synthesis.small_caps = synthetic_caps;
    synthesis.position = synthetic_position.is_some();
    let mut buffer = UnicodeBuffer::new();
    let ignorables = CodePointSetData::new::<DefaultIgnorableCodePoint>();
    let display_character = |ch| {
        if missing == MissingGlyphs::Substitute
            && !ignorables.contains(ch)
            && (private_use(ch) || face.glyph_index(ch).is_none())
        {
            char::REPLACEMENT_CHARACTER
        } else {
            ch
        }
    };
    let emoji = style.font_features.emoji;
    let add = |buffer: &mut UnicodeBuffer, ch, next, cluster| {
        buffer.add(display_character(ch), cluster);
        if let Some(selector) = implied_presentation(emoji, ch, next) {
            buffer.add(selector, cluster);
        }
    };
    if synthetic_caps {
        let mapped = features::uppercase_clusters(paragraph, range.clone(), &style.language);
        if mapped
            .iter()
            .map(|(_, cluster)| cluster.len())
            .sum::<usize>()
            > crate::document::MAX_INLINE_TEXT_BYTES
        {
            return Err(TextError::CaseExpansionLimit);
        }
        for (start, cluster) in &mapped {
            let mut chars = cluster.chars().peekable();
            while let Some(ch) = chars.next() {
                add(&mut buffer, ch, chars.peek().copied(), *start as u32);
            }
        }
    } else if missing == MissingGlyphs::Substitute || emoji != FontVariantEmoji::Normal {
        let mut chars = text.char_indices().peekable();
        while let Some((start, ch)) = chars.next() {
            add(
                &mut buffer,
                ch,
                chars.peek().map(|(_, next)| *next),
                start as u32,
            );
        }
    } else {
        buffer.push_str(text);
    }
    buffer.set_flags(BufferFlags::REMOVE_DEFAULT_IGNORABLES);
    buffer.set_pre_context(&paragraph[..range.start]);
    buffer.set_post_context(&paragraph[range.end..]);
    buffer.set_direction(if upright {
        Direction::TopToBottom
    } else if rtl {
        Direction::RightToLeft
    } else {
        Direction::LeftToRight
    });
    if let Some(language) = language {
        buffer.set_language(language.clone());
    }
    buffer.guess_segment_properties();
    // Words shape independently, so no glyph kerns against a word space. Fields are set directly
    // because `Feature::new` stores an inclusive end that its cluster masking treats as exclusive.
    let mut shaper: Vec<Feature> = text
        .match_indices(WORD_SPACE)
        .map(|(start, _)| Feature {
            tag: Tag::from_bytes(&features::KERNING),
            value: 0,
            start: start as u32,
            end: (start + WORD_SPACE.len_utf8()) as u32,
        })
        .collect();
    shaper.extend(shaper_features(&features::run_features(
        style,
        FaceFeatures {
            caps: caps.features,
            position: position_feature,
            ..face_features
        },
        tracked(style.letter_spacing, size),
    )));
    let shaped = shape_buffer(face, &shaper, buffer);
    let boundaries = crate::fonts::cluster_boundaries(
        shaped
            .glyph_infos()
            .iter()
            .map(|glyph| glyph.cluster as usize),
        text.len(),
    );
    let upem = face.units_per_em() as f32;
    let mut width = 0.0;
    let mut glyphs = Vec::new();
    let bounds = face.global_bounding_box();
    let mut ink_bounds: Option<[f32; 2]> = None;
    let mut pen_y = baseline_offset;
    let mut cluster_advance = 0.0;
    let vertical_advance = |pos: &rustybuzz::GlyphPosition| {
        if upright {
            -pos.y_advance as f32
        } else {
            pos.x_advance as f32
        }
    };
    let word_spacing = style.word_spacing.resolve(size);
    let em_offset = if size == 0.0 {
        0.0
    } else {
        baseline_offset / size
    };
    for (index, (info, pos)) in shaped
        .glyph_infos()
        .iter()
        .zip(shaped.glyph_positions())
        .enumerate()
    {
        // A malformed font can map text to glyphs it does not have, which it lacks as surely.
        let id = if info.glyph_id < u32::from(face.number_of_glyphs()) {
            info.glyph_id
        } else {
            NOTDEF
        };
        if id == NOTDEF && size != 0.0 && missing == MissingGlyphs::Reject {
            return Err(TextError::MissingGlyph { text: text.into() });
        }
        let start = info.cluster as usize;
        let end = boundaries[boundaries.binary_search(&start).unwrap() + 1];
        let last_in_cluster = shaped
            .glyph_infos()
            .get(index + 1)
            .is_none_or(|next| next.cluster != info.cluster);
        let advance = if last_in_cluster && text[start..end].starts_with(NARROW_NO_BREAK_SPACE) {
            narrow_space_advance.map_or(vertical_advance(pos) / upem, |width| {
                width - cluster_advance
            })
        } else {
            vertical_advance(pos) / upem
        };
        cluster_advance += advance;
        if last_in_cluster {
            cluster_advance = 0.0;
        }
        let top = pen_y - (f32::from(bounds.y_max) + pos.y_offset as f32) / upem * size;
        let bottom = pen_y - (f32::from(bounds.y_min) + pos.y_offset as f32) / upem * size;
        ink_bounds = Some(match ink_bounds {
            Some([a, b]) => [a.min(top), b.max(bottom)],
            None => [top, bottom],
        });
        pen_y -= pos.y_advance as f32 / upem * size;
        let source = &text[start..end];
        let text_range = if source.is_ascii() {
            start..end
        } else {
            let trim = |ch| ignorables.contains(ch) && !variation_selector(ch);
            let mapped = source.trim_start_matches(trim);
            let mapped_start = start + source.len() - mapped.len();
            let mapped = mapped.trim_end_matches(trim);
            if mapped.is_empty() {
                start..end
            } else {
                mapped_start..mapped_start + mapped.len()
            }
        };
        let x_spacing = if last_in_cluster {
            style.letter_spacing
                + if crate::text::spacing::word_space_text(source) {
                    word_spacing
                } else {
                    0.0
                }
        } else {
            0.0
        };
        width += advance * size + x_spacing;
        if !width.is_finite() {
            return Err(TextError::NonFiniteGeometry);
        }
        let glyph = PositionedGlyph {
            id,
            x_advance: advance,
            x_spacing,
            x_offset: if upright {
                -pos.y_offset as f32 / upem
            } else {
                pos.x_offset as f32 / upem
            },
            y_offset: if upright {
                let sign = if style.used_writing_mode()
                    == crate::style::logical::WritingMode::VerticalLr
                {
                    1.0
                } else {
                    -1.0
                };
                sign * pos.x_offset as f32 / upem
            } else {
                em_offset - pos.y_offset as f32 / upem
            },
            y_advance: if upright {
                0.0
            } else {
                -pos.y_advance as f32 / upem
            },
            text_range,
        };
        if size != 0.0 && glyph.normalized_advance(size).is_none() {
            return Err(TextError::NonFiniteGeometry);
        }
        glyphs.push(glyph);
    }
    let metrics = if upright {
        metrics.upright(face)
    } else {
        metrics
    };
    Ok(GlyphRun {
        leader: false,
        text: text.into(),
        source_range: range.clone(),
        source_span: 0,
        rtl,
        orientation: match (upright, style.writing_mode) {
            (true, crate::style::logical::WritingMode::VerticalLr) => {
                crate::text::GlyphOrientation::UprightLr
            }
            (true, _) => crate::text::GlyphOrientation::UprightRl,
            (false, crate::style::logical::WritingMode::VerticalLr) => {
                crate::text::GlyphOrientation::ReflectedSideways
            }
            (false, _) => crate::text::GlyphOrientation::Horizontal,
        },
        inline_scale: 1.0,
        combined: false,
        bidi_scoped: false,
        x: 0.0,
        width,
        baseline_shift: 0.0,
        font_size: size,
        metric_size: used_size,
        font_id,
        synthesis,
        oblique_skew,
        variations: variations.to_vec(),
        palette: palette.cloned(),
        color: style.text_paint.fill.used,
        stroke: crate::text::TextStroke::of(style),
        marks: Vec::new(),
        mark_shapes: Vec::new(),
        shadows: style.text_paint.shadows.clone(),
        leading: style.line_height.resolve(style.size),
        white_space: style.white_space,
        ink_bounds: if upright {
            Some([-size / 2.0, size / 2.0])
        } else {
            ink_bounds
        },
        ink_sides: [bounds.x_min, bounds.x_max].map(|side| f32::from(side) / upem),
        metrics,
        glyphs,
        removed_spaces: Vec::new(),
    })
}