ferri-pdf 0.1.6

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
// Copyright 2021 the Resvg Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

#![allow(clippy::comparison_chain)]

use roxmltree::Error;

use super::parse::{Source, parse_svg_element};
use super::{AId, Document, EId, NodeId, NodeKind, Placement, SvgNode};
use crate::style::WhiteSpaceCollapse;

const XLINK_NS: &str = "http://www.w3.org/1999/xlink";

/// Parses the content of the `text` element `parent`, which is `parent_id` in the tree and
/// whose child elements go where `placement` says.
pub(crate) fn parse_svg_text_element<'input>(
    parent: roxmltree::Node<'_, 'input>,
    parent_id: NodeId,
    placement: Placement,
    style_sheet: &super::css::StyleSheet,
    doc: &mut Document<'input>,
) -> Result<(), Error> {
    debug_assert_eq!(parent.tag_name().name(), "text");

    let space = doc
        .get(parent_id)
        .ancestors()
        .find_map(own_space)
        .unwrap_or_default();

    parse_svg_text_element_impl(
        parent,
        parent_id,
        placement,
        style_sheet,
        space,
        &mut None,
        doc,
    )?;

    trim_text_nodes(parent_id, space, doc);
    parse_first_line(parent, parent_id, placement, style_sheet, space, doc)
}

/// Where the first-letter text of a `text` element stands while its first formatted line's
/// contents are parsed.
enum Letter<'a, 'input> {
    /// Not found yet: rules of the originating `text` element style it.
    Pending(roxmltree::Node<'a, 'input>),
    /// Found, or the line holds none.
    Done,
}

/// Parses the copy of `text` element `text_id`, parsed from `xml`, whose contents its first
/// formatted line styles: inside its `::first-line` box, with its first-letter text in its
/// `::first-letter` box (CSS Pseudo-Elements 4 §2.1.3, §2.2.3). A written document gives that
/// line as its last first-line child; a standalone one, as its rules select the pseudo-elements.
fn parse_first_line<'input>(
    xml: roxmltree::Node<'_, 'input>,
    text_id: NodeId,
    placement: Placement,
    style_sheet: &super::css::StyleSheet,
    space: WhiteSpaceCollapse,
    doc: &mut Document<'input>,
) -> Result<(), Error> {
    use crate::style::PseudoElement;
    let written = xml.children().rfind(is_written_first_line);
    let line = style_sheet.styles_pseudo(xml, PseudoElement::FirstLine);
    let letter = [
        PseudoElement::FirstLetter,
        PseudoElement::FirstLetterPrefix,
        PseudoElement::FirstLetterSuffix,
    ]
    .into_iter()
    .any(|pseudo| style_sheet.styles_pseudo(xml, pseudo));
    if written.is_none() && !line && !letter {
        return Ok(());
    }
    let root = doc.detached_copy(text_id);
    let copied = placement.inside(root);
    let (source, container, mut letter) = match written {
        Some(written) => {
            let element = Source::Element { ignore_ids: true };
            let id = parse_svg_element(written, root, EId::Tspan, style_sheet, element, None, doc)?;
            (written, id, None)
        }
        None if line => {
            let pseudo = Source::Pseudo(PseudoElement::FirstLine);
            let id = parse_svg_element(xml, root, EId::Tspan, style_sheet, pseudo, None, doc)?;
            (xml, id, letter.then_some(Letter::Pending(xml)))
        }
        None => (xml, root, Some(Letter::Pending(xml))),
    };
    let placement = if container == root {
        copied
    } else {
        copied.children(container)
    };
    parse_svg_text_element_impl(
        source,
        container,
        placement,
        style_sheet,
        space,
        &mut letter,
        doc,
    )?;
    trim_text_nodes(root, space, doc);
    doc.first_lines.insert(text_id.get_usize(), root);
    Ok(())
}

/// Whether `node` is the written `::first-line` box of its `text` element.
fn is_written_first_line(node: &roxmltree::Node<'_, '_>) -> bool {
    node.is_element() && node.has_attribute(crate::svg::FIRST_LINE_ATTRIBUTE)
}

/// Parses the content of `parent`, which is `parent_id` in the tree and whose child elements go
/// where `placement` says, without recursion.
fn parse_svg_text_element_impl<'a, 'input>(
    parent: roxmltree::Node<'a, 'input>,
    parent_id: NodeId,
    placement: Placement,
    style_sheet: &super::css::StyleSheet,
    space: WhiteSpaceCollapse,
    letter: &mut Option<Letter<'a, 'input>>,
    doc: &mut Document<'input>,
) -> Result<(), Error> {
    let mut pending = Vec::new();
    content(parent, parent_id, placement, space, true, &mut pending);
    while let Some(Content {
        node,
        owner,
        placement,
        space,
        letters,
    }) = pending.pop()
    {
        if node.is_text() {
            let text = trim_text(node.text().unwrap(), space);
            match letter.as_ref().filter(|_| letters) {
                Some(Letter::Pending(origin)) => {
                    let origin = *origin;
                    if split_first_letter(text, owner, origin, style_sheet, space, doc)? {
                        *letter = Some(Letter::Done);
                    }
                }
                _ => {
                    doc.append(owner, NodeKind::Text(text));
                }
            }
            continue;
        }

        let mut tag_name = match super::parse::parse_tag_name(node) {
            Some(v) => v,
            None => continue,
        };

        if tag_name == EId::A {
            // Treat links as simple text.
            tag_name = EId::Tspan;
        }

        if !matches!(tag_name, EId::Tspan | EId::Tref | EId::TextPath)
            || is_written_first_line(&node)
        {
            continue;
        }

        // `textPath` must be a direct `text` child.
        if tag_name == EId::TextPath
            && doc
                .get(placement.parent)
                .ancestors()
                .find(|node| !node.is_contents() && !node.is_first_line())
                .and_then(|node| node.tag_name())
                != Some(EId::Text)
        {
            continue;
        }

        // We are converting `tref` into `tspan` to simplify later use.
        let mut is_tref = false;
        if tag_name == EId::Tref {
            tag_name = EId::Tspan;
            is_tref = true;
        }

        let node_id = parse_svg_element(
            node,
            placement.parent,
            tag_name,
            style_sheet,
            Source::Element { ignore_ids: false },
            None,
            doc,
        )?;
        let space = get_xmlspace(doc, node_id, space);

        if is_tref {
            // A first letter follows no other content (CSS Pseudo-Elements 4 §2.2.2).
            if letters && letter.is_some() {
                *letter = Some(Letter::Done);
            }
            let link_value = node
                .attribute((XLINK_NS, "href"))
                .or_else(|| node.attribute("href"));

            if let Some(href) = link_value {
                if let Some(text) = resolve_tref_text(node.document(), href) {
                    let text = trim_text(&text, space);
                    doc.append(node_id, NodeKind::Text(text));
                }
            }
        } else {
            let inner = placement.children(node_id);
            doc.limits.flattened |= inner.parent != node_id
                && node
                    .children()
                    .any(|child| super::parse::parse_tag_name(child).is_some());
            // Content that renders nothing holds no first letter.
            let letters =
                letters && doc.get(node_id).attribute::<&str>(AId::Display) != Some(DISPLAY_NONE);
            content(node, node_id, inner, space, letters, &mut pending);
        }
    }

    Ok(())
}

/// A node of a `text` element's content to parse: its text goes in `owner`, the element it is
/// in, and an element where `placement` says; `letters` where it may hold the first letter.
struct Content<'a, 'input> {
    node: roxmltree::Node<'a, 'input>,
    owner: NodeId,
    placement: Placement,
    space: WhiteSpaceCollapse,
    letters: bool,
}

/// Adds the children of `element`, which is `owner` in the tree, to `pending` so that they
/// parse in order.
fn content<'a, 'input>(
    element: roxmltree::Node<'a, 'input>,
    owner: NodeId,
    placement: Placement,
    space: WhiteSpaceCollapse,
    letters: bool,
    pending: &mut Vec<Content<'a, 'input>>,
) {
    pending.extend(element.children().rev().map(|node| Content {
        node,
        owner,
        placement,
        space,
        letters,
    }));
}

const DISPLAY_NONE: &str = "none";

/// Appends `text`, a text node's contents in element `parent_id`, wrapping the first-letter
/// text it begins with in the `::first-letter` box of `origin`, with its punctuation in the
/// box's `::prefix` and `::suffix` (CSS Pseudo-Elements 4 §2.2). Returns whether the search
/// for the first letter ends: the text holds it, or other content precedes it.
fn split_first_letter<'input>(
    text: String,
    parent_id: NodeId,
    origin: roxmltree::Node<'_, 'input>,
    style_sheet: &super::css::StyleSheet,
    space: WhiteSpaceCollapse,
    doc: &mut Document<'input>,
) -> Result<bool, Error> {
    use crate::document::first_letter::{FirstLetter, find};
    use crate::style::PseudoElement;
    let language = doc
        .get(parent_id)
        .ancestors()
        .find_map(|node| node.attribute::<&str>(AId::Lang))
        .unwrap_or_default()
        .to_owned();
    let (prefix, letter, suffix) = match find(&text, space, &language) {
        FirstLetter::Pending => {
            doc.append(parent_id, NodeKind::Text(text));
            return Ok(false);
        }
        FirstLetter::None => {
            doc.append(parent_id, NodeKind::Text(text));
            return Ok(true);
        }
        FirstLetter::Found {
            prefix,
            letter,
            suffix,
        } => (prefix, letter, suffix),
    };
    let append = |parent: NodeId, part: &str, doc: &mut Document<'input>| {
        if !part.is_empty() {
            doc.append(parent, NodeKind::Text(part.to_owned()));
        }
    };
    append(parent_id, &text[..prefix.start], doc);
    let pseudo = |pseudo| Source::Pseudo(pseudo);
    let boxed = parse_svg_element(
        origin,
        parent_id,
        EId::Tspan,
        style_sheet,
        pseudo(PseudoElement::FirstLetter),
        None,
        doc,
    )?;
    for (range, part) in [
        (prefix, Some(PseudoElement::FirstLetterPrefix)),
        (letter, None),
        (suffix.clone(), Some(PseudoElement::FirstLetterSuffix)),
    ] {
        let parent = match part
            .filter(|&part| !range.is_empty() && style_sheet.styles_pseudo(origin, part))
        {
            Some(part) => parse_svg_element(
                origin,
                boxed,
                EId::Tspan,
                style_sheet,
                pseudo(part),
                None,
                doc,
            )?,
            None => boxed,
        };
        append(parent, &text[range], doc);
    }
    append(parent_id, &text[suffix.end..], doc);
    Ok(true)
}

fn resolve_tref_text(xml: &roxmltree::Document, href: &str) -> Option<String> {
    let id = svgtypes::IRI::from_str(href).ok()?.0;

    // Find linked element in the original tree.
    let node = xml.descendants().find(|n| n.attribute("id") == Some(id))?;

    // `tref` should be linked to an SVG element.
    super::parse::parse_tag_name(node)?;

    // 'All character data within the referenced element, including character data enclosed
    // within additional markup, will be rendered.'
    //
    // So we don't care about attributes and everything. Just collecting text nodes data.
    //
    // Note: we have to filter nodes by `is_text()` first since `text()` will look up
    // for text nodes in element children therefore we will get duplicates.
    let text: String = node
        .descendants()
        .filter(|n| n.is_text())
        .filter_map(|n| n.text())
        .collect();
    if text.is_empty() { None } else { Some(text) }
}

/// The `white-space-collapse` an element sets: its `white-space` property, else its legacy
/// `xml:space` attribute (SVG 2 §11.10.3); `None` where it inherits.
fn own_space(node: SvgNode) -> Option<WhiteSpaceCollapse> {
    if let Some(value) = node.attribute::<&str>(AId::WhiteSpace) {
        return crate::style::svg_values::white_space_collapse(value);
    }
    node.attribute::<&str>(AId::Space).map(|value| {
        if value == XML_SPACE_PRESERVE {
            WhiteSpaceCollapse::PreserveSpaces
        } else {
            WhiteSpaceCollapse::Collapse
        }
    })
}

const XML_SPACE_PRESERVE: &str = "preserve";

fn get_xmlspace(
    doc: &Document,
    node_id: NodeId,
    default: WhiteSpaceCollapse,
) -> WhiteSpaceCollapse {
    own_space(doc.get(node_id)).unwrap_or(default)
}

trait StrTrim {
    fn remove_first_space(&mut self);
    fn remove_last_space(&mut self);
}

impl StrTrim for String {
    fn remove_first_space(&mut self) {
        debug_assert_eq!(self.chars().next().unwrap(), ' ');
        self.drain(0..1);
    }

    fn remove_last_space(&mut self) {
        debug_assert_eq!(self.chars().next_back().unwrap(), ' ');
        self.pop();
    }
}

/// Prepares text nodes according to the spec: https://www.w3.org/TR/SVG11/text.html#WhiteSpace
///
/// This function handles:
/// - 'xml:space' processing
/// - tabs and newlines removing/replacing
/// - spaces trimming
fn trim_text_nodes(text_elem_id: NodeId, xmlspace: WhiteSpaceCollapse, doc: &mut Document) {
    let mut nodes = Vec::new(); // TODO: allocate only once
    collect_text_nodes(doc.get(text_elem_id), 0, &mut nodes);

    // `trim` method has already collapsed all spaces into a single one,
    // so we have to check only for one leading or trailing space.

    if nodes.len() == 1 {
        // Process element with a single text node child.

        let node_id = nodes[0].0;

        if xmlspace.collapses_spaces() {
            if let NodeKind::Text(ref mut text) = doc.nodes[node_id.get_usize()].kind {
                match text.len() {
                    0 => {} // An empty string. Do nothing.
                    1 => {
                        // If string has only one character and it's a space - clear this string.
                        if text.as_bytes()[0] == b' ' {
                            text.clear();
                        }
                    }
                    _ => {
                        // 'text' has at least 2 bytes, so indexing is safe.
                        let c1 = text.as_bytes()[0];
                        let c2 = text.as_bytes()[text.len() - 1];

                        if c1 == b' ' {
                            text.remove_first_space();
                        }

                        if c2 == b' ' {
                            text.remove_last_space();
                        }
                    }
                }
            }
        } else {
            // Do nothing when xml:space=preserve.
        }
    } else if nodes.len() > 1 {
        // Process element with many text node children.

        // We manage all text nodes as a single text node
        // and trying to remove duplicated spaces across nodes.
        //
        // For example    '<text>Text <tspan> text </tspan> text</text>'
        // is the same is '<text>Text <tspan>text</tspan> text</text>'

        let mut i = 0;
        let len = nodes.len() - 1;
        let mut last_non_empty: Option<NodeId> = None;
        while i < len {
            // Process pairs.
            let (mut node1_id, depth1) = nodes[i];
            let (node2_id, depth2) = nodes[i + 1];

            if doc.get(node1_id).text().is_empty() {
                if let Some(n) = last_non_empty {
                    node1_id = n;
                }
            }

            // Parent of the text node is always an element node and always exist,
            // so unwrap is safe.
            let xmlspace1 = get_xmlspace(doc, doc.get(node1_id).parent().unwrap().id, xmlspace);
            let xmlspace2 = get_xmlspace(doc, doc.get(node2_id).parent().unwrap().id, xmlspace);

            // >text<..>text<
            //  1  2    3  4
            let (c1, c2, c3, c4) = {
                let text1 = doc.get(node1_id).text();
                let text2 = doc.get(node2_id).text();

                let bytes1 = text1.as_bytes();
                let bytes2 = text2.as_bytes();

                let c1 = bytes1.first().cloned();
                let c2 = bytes1.last().cloned();
                let c3 = bytes2.first().cloned();
                let c4 = bytes2.last().cloned();

                (c1, c2, c3, c4)
            };

            // NOTE: xml:space processing is mostly an undefined behavior,
            // because everyone do it differently.
            // We're mimicking the Chrome behavior.

            // Remove space from the second text node if both nodes has bound spaces.
            // From: '<text>Text <tspan> text</tspan></text>'
            // To:   '<text>Text <tspan>text</tspan></text>'
            //
            // See text-tspan-02-b.svg for details.
            if depth1 < depth2 {
                if c3 == Some(b' ') {
                    if xmlspace2.collapses_spaces() {
                        if let NodeKind::Text(ref mut text) = doc.nodes[node2_id.get_usize()].kind {
                            text.remove_first_space();
                        }
                    }
                }
            } else {
                if c2 == Some(b' ') && c2 == c3 {
                    if xmlspace1.collapses_spaces() && xmlspace2.collapses_spaces() {
                        if let NodeKind::Text(ref mut text) = doc.nodes[node1_id.get_usize()].kind {
                            text.remove_last_space();
                        }
                    } else {
                        if !xmlspace1.collapses_spaces() && xmlspace2.collapses_spaces() {
                            if let NodeKind::Text(ref mut text) =
                                doc.nodes[node2_id.get_usize()].kind
                            {
                                text.remove_first_space();
                            }
                        }
                    }
                }
            }

            let is_first = i == 0;
            let is_last = i == len - 1;

            if is_first
                && c1 == Some(b' ')
                && xmlspace1.collapses_spaces()
                && !doc.get(node1_id).text().is_empty()
            {
                // Remove a leading space from a first text node.
                if let NodeKind::Text(ref mut text) = doc.nodes[node1_id.get_usize()].kind {
                    text.remove_first_space();
                }
            } else if is_last
                && c4 == Some(b' ')
                && !doc.get(node2_id).text().is_empty()
                && xmlspace2.collapses_spaces()
            {
                // Remove a trailing space from a last text node.
                // Also check that 'text2' is not empty already.
                if let NodeKind::Text(ref mut text) = doc.nodes[node2_id.get_usize()].kind {
                    text.remove_last_space();
                }
            }

            if is_last
                && c2 == Some(b' ')
                && !doc.get(node1_id).text().is_empty()
                && doc.get(node2_id).text().is_empty()
                && doc.get(node1_id).text().ends_with(' ')
            {
                if let NodeKind::Text(ref mut text) = doc.nodes[node1_id.get_usize()].kind {
                    text.remove_last_space();
                }
            }

            if !doc.get(node1_id).text().trim().is_empty() {
                last_non_empty = Some(node1_id);
            }

            i += 1;
        }
    }

    // TODO: find a way to remove all empty text nodes
}

/// The text nodes in `parent` that white space collapses across, with their depths: those
/// outside elements that render nothing.
fn collect_text_nodes(parent: SvgNode, depth: usize, nodes: &mut Vec<(NodeId, usize)>) {
    for child in parent.children() {
        if child.is_text() {
            nodes.push((child.id, depth));
        } else if child.is_element() && child.attribute::<&str>(AId::Display) != Some(DISPLAY_NONE)
        {
            collect_text_nodes(child, depth + 1, nodes);
        }
    }
}

/// CSS Text 4 §4.1.1: segment breaks are kept where `space` preserves them, tabs where it
/// preserves spaces without converting them; other white space becomes spaces, which collapse
/// and vanish beside a kept segment break where `space` collapses them. A carriage return is a
/// space (CSS Text 3 §4.1).
fn trim_text(text: &str, space: WhiteSpaceCollapse) -> String {
    let mut s = String::with_capacity(text.len());

    let mut prev = '0';
    for c in text.chars() {
        let c = match c {
            SEGMENT_BREAK if space.preserves_breaks() => SEGMENT_BREAK,
            TAB if !space.collapses_spaces() && !space.converts_to_spaces() => TAB,
            '\r' | SEGMENT_BREAK | TAB => ' ',
            _ => c,
        };

        if space.collapses_spaces() {
            if c == ' ' && (prev == ' ' || prev == SEGMENT_BREAK) {
                continue;
            }
            if c == SEGMENT_BREAK && prev == ' ' {
                s.pop();
            }
        }

        prev = c;

        s.push(c);
    }

    s
}

/// The segment break that a preserved line feed forces (CSS Text 3 §4.1.2).
pub(crate) const SEGMENT_BREAK: char = '\n';
const TAB: char = '\t';