ferri-pdf 0.1.4

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
use crate::document::{MAX_INLINE_TEXT_BYTES, Paragraph};
use crate::style::{Style, UnicodeBidi};
use crate::text::TextError;
use std::{cell::Cell, ops::Range};
use unicode_bidi::{BidiClass, BidiInfo, Level, ParagraphBidiInfo, ParagraphInfo, bidi_class};

const LRE: &str = "\u{202a}";
const RLE: &str = "\u{202b}";
const PDF: &str = "\u{202c}";
const LRO: &str = "\u{202d}";
const RLO: &str = "\u{202e}";
const LRI: &str = "\u{2066}";
const RLI: &str = "\u{2067}";
const FSI: &str = "\u{2068}";
const PDI: &str = "\u{2069}";
const FSI_LRO: &str = "\u{2068}\u{202d}";
const FSI_RLO: &str = "\u{2068}\u{202e}";
const PDF_PDI: &str = "\u{202c}\u{2069}";

type Controls = (&'static str, &'static str);

#[derive(Clone, Copy, Debug)]
pub(crate) struct ExpansionLimit;
impl From<ExpansionLimit> for TextError {
    fn from(_: ExpansionLimit) -> Self {
        Self::BidiExpansionLimit {
            limit: MAX_INLINE_TEXT_BYTES,
        }
    }
}

fn controls(style: &Style, root: bool) -> Controls {
    match style.unicode_bidi {
        UnicodeBidi::Normal => ("", ""),
        UnicodeBidi::Embed if !root => (if style.used_rtl() { RLE } else { LRE }, PDF),
        UnicodeBidi::Isolate if !root => (if style.used_rtl() { RLI } else { LRI }, PDI),
        UnicodeBidi::BidiOverride => (if style.used_rtl() { RLO } else { LRO }, PDF),
        UnicodeBidi::IsolateOverride if !root => {
            (if style.used_rtl() { FSI_RLO } else { FSI_LRO }, PDF_PDI)
        }
        UnicodeBidi::IsolateOverride => (if style.used_rtl() { RLO } else { LRO }, PDF),
        UnicodeBidi::Plaintext if !root => (FSI, PDI),
        _ => ("", ""),
    }
}

struct Event {
    offset: usize,
    controls: Controls,
    opening: bool,
    rank: u8,
}

/// Strong left-to-right characters of each UTF-8 width, which stand for upright text so that its
/// source offsets carry over.
const STRONG_LTR_BY_WIDTH: [char; 4] = ['A', '\u{0100}', '\u{4e00}', '\u{20000}'];

/// The ranges of `paragraph` set upright in vertical text, whose characters bidi reordering
/// treats as strong left-to-right (CSS Writing Modes 4 §5.1).
fn upright_ranges(paragraph: &Paragraph) -> Vec<Range<usize>> {
    paragraph
        .spans()
        .iter()
        .filter(|span| {
            matches!(
                span.style.used_writing_mode(),
                crate::style::logical::WritingMode::VerticalRl
                    | crate::style::logical::WritingMode::VerticalLr
            ) && span.style.text_orientation == crate::style::logical::TextOrientation::Upright
                && span.atomic.is_none()
        })
        .map(|span| span.range.clone())
        .collect()
}

fn events(paragraph: &Paragraph) -> Vec<Event> {
    let mut result = Vec::new();
    let mut stack: Vec<usize> = Vec::new();
    let boxes = paragraph.boxes();
    let close = |index: usize, events: &mut Vec<Event>| {
        let item = &boxes[index];
        let pair = controls(&item.style, false);
        if !pair.0.is_empty() {
            events.push(Event {
                offset: item.range.end,
                controls: pair,
                opening: false,
                rank: 0,
            });
        }
    };
    for (index, item) in boxes.iter().enumerate() {
        while stack.last().copied() != item.parent {
            close(
                stack.pop().expect("inline box ancestry is in tree order"),
                &mut result,
            );
        }
        let pair = controls(&item.style, false);
        if !pair.0.is_empty() {
            result.push(Event {
                offset: item.range.start,
                controls: pair,
                opening: true,
                rank: 0,
            });
        }
        stack.push(index);
    }
    for index in stack.into_iter().rev() {
        close(index, &mut result);
    }
    for group in crate::text::combine::groups(paragraph) {
        let pair = (FSI_LRO, PDF_PDI);
        result.push(Event {
            offset: group.range.start,
            controls: pair,
            opening: true,
            rank: 2,
        });
        result.push(Event {
            offset: group.range.end,
            controls: pair,
            opening: false,
            rank: 2,
        });
    }
    result.sort_by_key(|event| {
        (
            event.offset,
            match (event.rank, event.opening) {
                (0, _) => 1,
                (_, false) => 0,
                (_, true) => 2,
            },
        )
    });
    result
}

pub(crate) enum ResolvedParagraph<'p> {
    Plain(BidiInfo<'p>),
    Controlled(Controlled),
}
pub(crate) struct Controlled {
    source_levels: Vec<Level>,
    text: String,
    classes: Vec<BidiClass>,
    levels: Vec<Level>,
    paragraphs: Vec<ParagraphInfo>,
    chunks: Vec<SourceChunk>,
}

fn reorder(
    text: &str,
    classes: &[BidiClass],
    levels: &[Level],
    paragraphs: &[ParagraphInfo],
    range: Range<usize>,
) -> Vec<(Range<usize>, bool)> {
    let paragraph =
        &paragraphs[paragraphs.partition_point(|paragraph| paragraph.range.end <= range.start)];
    let line = ParagraphBidiInfo {
        text: &text[range.clone()],
        original_classes: classes[range.clone()].to_vec(),
        levels: levels[range.clone()].to_vec(),
        paragraph_level: paragraph.level,
        is_pure_ltr: false,
    };
    let (levels, visual) = line.visual_runs(0..range.len());
    visual
        .into_iter()
        .map(|run| {
            let rtl = levels[run.start].is_rtl();
            (range.start + run.start..range.start + run.end, rtl)
        })
        .collect()
}
impl ResolvedParagraph<'_> {
    pub(super) fn has_controls(&self) -> bool {
        matches!(self, Self::Controlled(_))
    }
    pub(crate) fn level(&self, offset: usize) -> Level {
        match self {
            Self::Plain(source) => source.levels[offset],
            Self::Controlled(controlled) => controlled.source_levels[offset],
        }
    }
    pub(super) fn has_rtl(&self) -> bool {
        match self {
            Self::Plain(source) => source.has_rtl(),
            Self::Controlled(controlled) => controlled.levels.iter().any(Level::is_rtl),
        }
    }
    pub(crate) fn visual_runs(&self, range: Range<usize>) -> Vec<(Range<usize>, bool)> {
        let controlled = match self {
            Self::Plain(source) => {
                return reorder(
                    source.text,
                    &source.original_classes,
                    &source.levels,
                    &source.paragraphs,
                    range,
                );
            }
            Self::Controlled(controlled) => controlled,
        };
        let first = controlled
            .chunks
            .partition_point(|chunk| chunk.source.end <= range.start);
        let last = controlled
            .chunks
            .partition_point(|chunk| chunk.source.start < range.end)
            - 1;
        let left = &controlled.chunks[first];
        let right = &controlled.chunks[last];
        let virtual_range = left.virtual_start + range.start - left.source.start
            ..right.virtual_start + range.end - right.source.start;
        let mut result = Vec::new();
        for (run, rtl) in reorder(
            &controlled.text,
            &controlled.classes,
            &controlled.levels,
            &controlled.paragraphs,
            virtual_range,
        ) {
            let first = controlled
                .chunks
                .partition_point(|chunk| chunk.virtual_start + chunk.source.len() <= run.start);
            let mut pieces = Vec::new();
            for chunk in controlled.chunks[first..]
                .iter()
                .take_while(|chunk| chunk.virtual_start < run.end)
            {
                let start = run.start.max(chunk.virtual_start);
                let end = run.end.min(chunk.virtual_start + chunk.source.len());
                if start < end {
                    pieces.push((
                        chunk.source.start + start - chunk.virtual_start
                            ..chunk.source.start + end - chunk.virtual_start,
                        rtl,
                    ));
                }
            }
            if rtl {
                pieces.reverse();
            }
            result.extend(pieces);
        }
        result
    }
}

struct SourceChunk {
    source: Range<usize>,
    virtual_start: usize,
}

struct Stream<'budget> {
    work: &'budget Cell<Option<usize>>,
    upright: Vec<Range<usize>>,
    text: String,
    chunks: Vec<SourceChunk>,
    active: Vec<Controls>,
    opened: bool,
}
impl<'budget> Stream<'budget> {
    fn new(work: &'budget Cell<Option<usize>>, upright: Vec<Range<usize>>) -> Self {
        Self {
            work,
            upright,
            text: String::new(),
            chunks: Vec::new(),
            active: Vec::new(),
            opened: false,
        }
    }
    fn push(&mut self, text: &str) -> Result<(), ExpansionLimit> {
        let remaining = self
            .work
            .get()
            .and_then(|work| work.checked_sub(text.len()));
        self.work.set(remaining);
        if remaining.is_none()
            || self
                .text
                .len()
                .checked_add(text.len())
                .is_none_or(|size| size > MAX_INLINE_TEXT_BYTES)
        {
            self.work.set(None);
            return Err(ExpansionLimit);
        }
        self.text.push_str(text);
        Ok(())
    }
    fn open(&mut self) -> Result<(), ExpansionLimit> {
        if !self.opened {
            for index in 0..self.active.len() {
                self.push(self.active[index].0)?;
            }
            self.opened = true;
        }
        Ok(())
    }
    fn close(&mut self) -> Result<(), ExpansionLimit> {
        if self.opened {
            for index in (0..self.active.len()).rev() {
                self.push(self.active[index].1)?;
            }
            self.opened = false;
        }
        Ok(())
    }
    fn source(&mut self, text: &str, range: Range<usize>) -> Result<(), ExpansionLimit> {
        if range.is_empty() {
            return Ok(());
        }
        let virtual_start = self.text.len();
        let mut source = text[range.clone()].to_owned();
        for upright in &self.upright {
            let start = upright.start.max(range.start);
            let end = upright.end.min(range.end);
            if start < end {
                let strong: String = text[start..end]
                    .chars()
                    .map(|ch| STRONG_LTR_BY_WIDTH[ch.len_utf8() - 1])
                    .collect();
                source.replace_range(start - range.start..end - range.start, &strong);
            }
        }
        self.push(&source)?;
        if let Some(last) = self.chunks.last_mut()
            && last.source.end == range.start
            && last.virtual_start + last.source.len() == virtual_start
        {
            last.source.end = range.end;
        } else {
            self.chunks.push(SourceChunk {
                source: range,
                virtual_start,
            });
        }
        Ok(())
    }
    fn append(&mut self, text: &str, range: Range<usize>) -> Result<(), ExpansionLimit> {
        let mut from = range.start;
        for (offset, ch) in text[range.clone()].char_indices() {
            if bidi_class(ch) == BidiClass::B {
                let at = range.start + offset;
                if from != at {
                    self.open()?;
                    self.source(text, from..at)?;
                }
                self.close()?;
                self.source(text, at..at + ch.len_utf8())?;
                from = at + ch.len_utf8();
            }
        }
        if from < range.end {
            self.open()?;
            self.source(text, from..range.end)?;
        }
        Ok(())
    }
    fn project(self, text: &str, base: Option<Level>) -> ResolvedParagraph<'_> {
        let resolved = BidiInfo::new(&self.text, base);
        let mut source_levels = Vec::with_capacity(text.len());
        for chunk in &self.chunks {
            source_levels.extend_from_slice(
                &resolved.levels[chunk.virtual_start..chunk.virtual_start + chunk.source.len()],
            );
        }
        let BidiInfo {
            original_classes,
            levels,
            paragraphs,
            ..
        } = resolved;
        ResolvedParagraph::Controlled(Controlled {
            source_levels,
            text: self.text,
            classes: original_classes,
            levels,
            paragraphs,
            chunks: self.chunks,
        })
    }
}

pub(crate) fn resolve<'p>(
    paragraph: &'p Paragraph,
    work: &Cell<Option<usize>>,
) -> Result<ResolvedParagraph<'p>, ExpansionLimit> {
    if work.get().is_none() {
        return Err(ExpansionLimit);
    }
    let text = paragraph.text();
    let style = paragraph.style();
    let base = (style.unicode_bidi != UnicodeBidi::Plaintext).then(|| {
        if style.used_rtl() {
            Level::rtl()
        } else {
            Level::ltr()
        }
    });
    let root = controls(style, true);
    if text.is_empty()
        || (root.0.is_empty()
            && crate::text::combine::groups(paragraph).is_empty()
            && upright_ranges(paragraph).is_empty()
            && paragraph
                .boxes()
                .iter()
                .all(|item| controls(&item.style, false).0.is_empty()))
    {
        return Ok(ResolvedParagraph::Plain(BidiInfo::new(text, base)));
    }
    let events = events(paragraph);
    let mut stream = Stream::new(work, upright_ranges(paragraph));
    if !root.0.is_empty() {
        stream.active.push(root);
    }
    let mut from = 0;
    for event in events {
        stream.append(text, from..event.offset)?;
        if event.opening {
            stream.open()?;
            stream.push(event.controls.0)?;
            stream.active.push(event.controls);
        } else {
            if stream.opened {
                stream.push(event.controls.1)?;
            }
            stream.active.pop();
        }
        from = event.offset;
    }
    stream.append(text, from..text.len())?;
    stream.close()?;
    Ok(stream.project(text, base))
}