ferri-pdf 0.1.12

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
use crate::style::{
    Style, StyleError, calc,
    conditions::{Condition, Truth, block_source},
    declaration::{self, Specified},
    grammar::Property,
    media::{Comparison, MediaQuery, comparison, matches_media},
    parser::{failure, substitution_argument},
    print::PrintEnvironment,
    properties,
    registration::{Registration, Registrations},
    selector::Namespaces,
    supports::SupportsCondition,
    units::{self, Dimension, Relative},
    variables::{self, Value},
    wide_keywords::WideKeyword,
};
use cssparser::{Delimiter, Parser, ParserInput, Token};
use std::collections::HashSet;

pub(super) const FUNCTION: &str = "if";

#[derive(Clone)]
pub(super) struct Expression {
    branches: Vec<(Condition<Test>, Value)>,
    dependencies: HashSet<String>,
}

impl std::fmt::Debug for Expression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Conditional")
            .field("branches", &self.branches.len())
            .field("dependencies", &self.dependencies)
            .finish()
    }
}

impl Expression {
    pub(super) fn parse(
        input: &mut Parser<'_, '_>,
        depth: usize,
        property_syntax: bool,
    ) -> Result<Option<Self>, StyleError> {
        let mut branches = Vec::new();
        let mut dependencies = HashSet::new();
        let parsed = input.parse_entirely(|input| {
            while !input.is_exhausted() {
                let (condition, source) = Self::branch_head(input, depth, &mut dependencies)?;
                let value = match Value::parse_context(source, depth, property_syntax) {
                    Ok(Some(value)) => value,
                    Ok(None) => {
                        return Err(input
                            .new_custom_error(StyleError::Invalid("invalid if() branch".into())));
                    }
                    Err(error) => return Err(input.new_custom_error(error)),
                };
                branches.push((condition, value));
            }
            if branches.is_empty() {
                return Err(input.new_custom_error(StyleError::Invalid("empty if()".into())));
            }
            Ok(())
        });
        match parsed.map_err(failure) {
            Ok(()) => Ok(Some(Self {
                branches,
                dependencies,
            })),
            Err(StyleError::Invalid(_)) => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// The condition of the next `<if-branch>` and the source of its value, consuming the
    /// branch. Nested `if()` values recurse through the value, so this work stays in a frame
    /// that has returned by then.
    fn branch_head<'i>(
        input: &mut Parser<'i, '_>,
        depth: usize,
        dependencies: &mut HashSet<String>,
    ) -> Result<(Condition<Test>, &'i str), cssparser::ParseError<'i, StyleError>> {
        let start = input.position();
        loop {
            let before = input.state();
            match input.next()?.clone() {
                Token::Colon => {
                    let condition =
                        Self::condition(input.slice(start..before.position()), depth, dependencies)
                            .map_err(|error| input.new_custom_error(error))?;
                    let source = input.parse_until_before(Delimiter::Semicolon, |input| {
                        substitution_argument(input, false)
                    })?;
                    if !input.is_exhausted() {
                        input.expect_semicolon()?;
                    }
                    return Ok((condition, source));
                }
                Token::Function(_)
                | Token::ParenthesisBlock
                | Token::SquareBracketBlock
                | Token::CurlyBracketBlock => {
                    input.parse_nested_block(|nested| {
                        Ok::<_, cssparser::ParseError<'_, StyleError>>(block_source(nested))
                    })?;
                }
                Token::Semicolon => {
                    return Err(input.new_custom_error(StyleError::Invalid(
                        "if() condition has no colon".into(),
                    )));
                }
                _ => {}
            }
        }
    }

    fn condition(
        source: &str,
        depth: usize,
        dependencies: &mut HashSet<String>,
    ) -> Result<Condition<Test>, StyleError> {
        let mut condition_input = ParserInput::new(source);
        let condition_parser = &mut Parser::new(&mut condition_input);
        let condition = if condition_parser
            .try_parse(|input| {
                input.expect_ident_matching("else")?;
                input.expect_exhausted()
            })
            .is_ok()
        {
            Condition::constant(Truth::True)
        } else {
            Condition::parse_fallible(source, true, Truth::Unknown, Test::parse)?
                .ok_or_else(|| StyleError::Invalid("invalid if() condition".into()))?
        };
        variables::dependencies_in(source, depth, dependencies)?;
        Ok(condition)
    }

    pub(super) fn select(
        &self,
        test: &mut impl FnMut(&Test) -> Result<Truth, StyleError>,
    ) -> Result<Option<&Value>, StyleError> {
        for (condition, value) in &self.branches {
            if condition.try_evaluate(&mut *test)? == Truth::True {
                return Ok(Some(value));
            }
        }
        Ok(None)
    }

    pub(super) fn dependencies(&self, output: &mut HashSet<String>) {
        output.extend(self.dependencies.iter().cloned());
        for (_, value) in &self.branches {
            value.dependencies(output);
        }
    }
}

#[derive(Clone)]
pub(super) enum Test {
    Media(MediaQuery),
    Supports(SupportsCondition),
    Style(StyleQuery),
}

impl Test {
    fn parse(source: &str) -> Result<Option<Self>, StyleError> {
        let mut input = ParserInput::new(source);
        let input = &mut Parser::new(&mut input);
        let Ok(Token::Function(name)) = input.next().cloned() else {
            return Ok(None);
        };
        let result = input
            .parse_nested_block(|input| {
                let source = block_source(input);
                let test = if name.eq_ignore_ascii_case("media") {
                    Some(Self::Media(
                        MediaQuery::parse(source).map_err(|error| input.new_custom_error(error))?,
                    ))
                } else if name.eq_ignore_ascii_case("supports") {
                    let direct = crate::style::supports::SupportTest::declaration(source).is_some();
                    let source = if direct {
                        format!("({source})")
                    } else {
                        source.to_owned()
                    };
                    SupportsCondition::parse_with_namespaces(&source, &Namespaces::default())
                        .map_err(|error| input.new_custom_error(error))?
                        .map(Self::Supports)
                } else if name.eq_ignore_ascii_case("style") {
                    StyleQuery::parse(source)
                        .map_err(|error| input.new_custom_error(error))?
                        .map(Self::Style)
                } else {
                    None
                };
                Ok::<_, cssparser::ParseError<'_, StyleError>>(test)
            })
            .map_err(failure)?;
        if input.expect_exhausted().is_err() {
            return Ok(None);
        }
        Ok(result)
    }

    pub(super) fn evaluate(
        &self,
        environment: &PrintEnvironment,
        namespaces: Option<&Namespaces>,
        values: &impl QueryValues,
    ) -> Result<Truth, StyleError> {
        Ok(match self {
            Self::Media(query) => matches_media(query, environment).into(),
            Self::Supports(query) => query.matches_with(&environment.supports, namespaces).into(),
            Self::Style(query) => query.evaluate(values)?,
        })
    }
}

pub(super) trait QueryValues {
    fn property(&self, property: Property) -> Result<Style, StyleError>;
    fn candidate(&self, property: Property, value: &Specified) -> Result<Style, StyleError>;
    fn custom(&self, name: &str) -> Result<Option<variables::Expanded>, StyleError>;
    fn inherited_custom(&self, name: &str) -> Result<Option<variables::Expanded>, StyleError>;
    fn substitute(
        &self,
        value: &str,
        property_syntax: bool,
    ) -> Result<Option<variables::Expanded>, StyleError>;
    fn scalar(&self, value: &str) -> Result<Option<Scalar>, StyleError>;
    /// `value` as the computed value of `name`, which `registration` types (CSS Properties
    /// and Values API 1 §2.4); `None` when it does not parse by the registered syntax.
    fn registered(
        &self,
        name: &str,
        registration: &Registration,
        value: &variables::Expanded,
    ) -> Result<Option<variables::Expanded>, StyleError>;
    fn registrations(&self) -> &Registrations;
}

#[derive(Clone)]
enum Name {
    Property(Property),
    Custom(String),
}
impl Name {
    fn parse(name: &str) -> Option<Self> {
        if name.starts_with(declaration::CUSTOM_PROPERTY_PREFIX) {
            return (name.len() > declaration::CUSTOM_PROPERTY_PREFIX.len())
                .then(|| Self::Custom(name.to_owned()));
        }
        let property = Property::from_name(name)?;
        declaration::longhands(property)
            .any(properties::supports_property)
            .then_some(Self::Property(property))
    }
}

#[derive(Clone)]
enum Feature {
    Boolean(Name),
    Plain(Name, String),
    Range(Vec<String>, Vec<Comparison>),
}

#[derive(Clone)]
pub(super) struct StyleQuery(Condition<Feature>);
impl StyleQuery {
    fn parse(source: &str) -> Result<Option<Self>, StyleError> {
        Self::parse_general(source, Truth::False)
    }
    /// `<style-query>`, with `<general-enclosed>` evaluating to `general`.
    pub(super) fn parse_general(source: &str, general: Truth) -> Result<Option<Self>, StyleError> {
        if let Some(feature) = Feature::parse(source) {
            return Ok(Some(Self(Condition::value(feature))));
        }
        Ok(Condition::parse(source, true, general, Feature::parse)?.map(Self))
    }
    pub(super) fn evaluate(&self, values: &impl QueryValues) -> Result<Truth, StyleError> {
        self.0
            .try_evaluate(|feature| feature.evaluate(values).map(Truth::from))
    }
}

impl Feature {
    fn parse(source: &str) -> Option<Self> {
        let mut input = ParserInput::new(source);
        let input = &mut Parser::new(&mut input);
        if let Ok(name) = input.try_parse(Parser::expect_ident_cloned)
            && let Some(name) = Name::parse(&name)
        {
            if input.is_exhausted() {
                return Some(Self::Boolean(name));
            }
            if input.try_parse(Parser::expect_colon).is_ok() {
                let value = block_source(input);
                if split_range(value).is_some() {
                    return None;
                }
                return Some(Self::Plain(name, value.to_owned()));
            }
        }
        let (values, comparisons) = split_range(source)?;
        Some(Self::Range(values, comparisons))
    }

    fn evaluate(&self, values: &impl QueryValues) -> Result<bool, StyleError> {
        match self {
            // CSS Conditional 5 §6.2: a custom property holds when it is not its initial
            // value, which a registration gives.
            Self::Boolean(Name::Custom(name)) => Ok(values.custom(name)?
                != values
                    .registrations()
                    .get(name)
                    .and_then(|registration| registration.initial.clone())),
            Self::Plain(Name::Custom(name), source) => {
                let Some(source) = values.substitute(source, false)? else {
                    return Ok(false);
                };
                let registration = values.registrations().get(name);
                let initial = || registration.and_then(|registration| registration.initial.clone());
                let expected = match WideKeyword::parse(source.as_str()) {
                    Some(WideKeyword::Initial) => initial(),
                    Some(WideKeyword::Unset)
                        if registration.is_some_and(|registration| !registration.inherits) =>
                    {
                        initial()
                    }
                    Some(WideKeyword::Inherit | WideKeyword::Unset) => {
                        values.inherited_custom(name)?
                    }
                    Some(WideKeyword::Revert | WideKeyword::RevertLayer) => return Ok(false),
                    None => match registration.filter(|registration| registration.typed()) {
                        Some(registration) => {
                            let Some(computed) = values.registered(name, registration, &source)?
                            else {
                                return Ok(false);
                            };
                            Some(computed)
                        }
                        None => Some(source),
                    },
                };
                Ok(match (values.custom(name)?, expected) {
                    (None, None) => true,
                    (Some(actual), Some(expected)) => actual.as_str() == expected.as_str(),
                    _ => false,
                })
            }
            Self::Boolean(Name::Property(property)) => {
                for longhand in declaration::longhands(*property) {
                    let actual = values.property(longhand)?;
                    let initial =
                        values.candidate(longhand, &Specified::Wide(WideKeyword::Initial))?;
                    if properties::projection(longhand, &actual)
                        != properties::projection(longhand, &initial)
                    {
                        return Ok(true);
                    }
                }
                Ok(false)
            }
            Self::Plain(Name::Property(property), source) => {
                let Some(source) = values.substitute(source, true)? else {
                    return Ok(false);
                };
                let Some(expanded) = declaration::expand_expanded(*property, &source)? else {
                    return Ok(false);
                };
                for (property, value) in expanded {
                    if rollback(&value) {
                        return Ok(false);
                    }
                    let actual = values.property(property)?;
                    let expected = values.candidate(property, &value)?;
                    if properties::projection(property, &actual)
                        != properties::projection(property, &expected)
                    {
                        return Ok(false);
                    }
                }
                Ok(true)
            }
            Self::Range(operands, comparisons) => {
                let mut scalars = Vec::with_capacity(operands.len());
                for operand in operands {
                    let mut input = ParserInput::new(operand);
                    let input = &mut Parser::new(&mut input);
                    let custom = input
                        .try_parse(|input| {
                            let name = input.expect_ident_cloned()?;
                            input.expect_exhausted()?;
                            Ok::<_, cssparser::BasicParseError<'_>>(name)
                        })
                        .ok()
                        .filter(|name| name.starts_with(declaration::CUSTOM_PROPERTY_PREFIX));
                    let source = if let Some(name) = custom {
                        values.custom(&name)?
                    } else {
                        values.substitute(operand, false)?
                    };
                    let Some(source) = source else {
                        return Ok(false);
                    };
                    let Some(scalar) = values.scalar(source.as_str())? else {
                        return Ok(false);
                    };
                    scalars.push(scalar);
                }
                for (pair, comparison) in scalars.windows(2).zip(comparisons) {
                    if !pair[0].compatible(pair[1])
                        || !comparison.compare(pair[0].value.into(), pair[1].value.into())
                    {
                        return Ok(false);
                    }
                }
                Ok(true)
            }
        }
    }
}

fn rollback(value: &Specified) -> bool {
    match value {
        Specified::Wide(WideKeyword::Revert | WideKeyword::RevertLayer) => true,
        Specified::Toggle(values) => values.iter().any(|value| rollback(&value.value)),
        _ => false,
    }
}

fn split_range(source: &str) -> Option<(Vec<String>, Vec<Comparison>)> {
    let mut raw = ParserInput::new(source);
    let input = &mut Parser::new(&mut raw);
    let mut start = input.position();
    let mut values = Vec::new();
    let mut comparisons = Vec::new();
    while !input.is_exhausted() {
        let before = input.state();
        let token = input.next().ok()?.clone();
        if matches!(token, Token::Delim('<' | '>' | '=')) {
            let value = crate::style::parser::trim_value(input.slice(start..before.position()));
            if value.is_empty() {
                return None;
            }
            values.push(value.to_owned());
            input.reset(&before);
            comparisons.push(comparison(input)?);
            start = input.position();
        } else if matches!(
            token,
            Token::Function(_)
                | Token::ParenthesisBlock
                | Token::SquareBracketBlock
                | Token::CurlyBracketBlock
        ) {
            input
                .parse_nested_block(|nested| {
                    Ok::<_, cssparser::ParseError<'_, ()>>(block_source(nested))
                })
                .ok()?;
        }
    }
    let last = crate::style::parser::trim_value(input.slice_from(start));
    if last.is_empty() || comparisons.is_empty() || comparisons.len() > 2 {
        return None;
    }
    if comparisons.len() == 2
        && (comparisons[0].ascending().is_none()
            || comparisons[0].ascending() != comparisons[1].ascending())
    {
        return None;
    }
    values.push(last.to_owned());
    Some((values, comparisons))
}

#[derive(Clone, Copy)]
pub(super) struct Scalar {
    kind: calc::Kind,
    value: f32,
}
impl Scalar {
    fn compatible(self, other: Self) -> bool {
        self.kind == other.kind
            || (self.kind == calc::Kind::Number
                && self.value == 0.0
                && other.kind == calc::Kind::Length)
            || (other.kind == calc::Kind::Number
                && other.value == 0.0
                && self.kind == calc::Kind::Length)
    }

    pub(super) fn parse(source: &str, relative: &Relative<'_>) -> Result<Option<Self>, StyleError> {
        let mut raw = ParserInput::new(source);
        let input = &mut Parser::new(&mut raw);
        if let Some(math) = calc::math_function(
            input,
            calc::Context {
                relative,
                percentage: None,
                channels: &[],
                anchors: None,
            },
        ) {
            let math = match math {
                Ok(math) => math,
                Err(calc::MathError::Invalid(_)) => return Ok(None),
                Err(calc::MathError::Resolution(error)) => return Err(error),
            };
            let Some(kind) = math.kind() else {
                return Ok(None);
            };
            if input.expect_exhausted().is_err() {
                return Ok(None);
            }
            return Ok(Some(Self {
                kind,
                value: math.resolve(1.0, calc::Range::ALL),
            }));
        }
        let (kind, value) = match input.next().cloned() {
            Ok(Token::Number { value, .. }) => (calc::Kind::Number, value),
            Ok(Token::Percentage { unit_value, .. }) => (calc::Kind::Percentage, unit_value),
            Ok(Token::Dimension { value, unit, .. }) => match units::dimension(&unit) {
                Some(Dimension::Length(unit)) => {
                    (calc::Kind::Length, value * relative.per_unit(unit.scale)?)
                }
                Some(Dimension::Angle(scale)) => (calc::Kind::Angle, value * scale),
                Some(Dimension::Time(scale)) => (calc::Kind::Time, value * scale),
                Some(Dimension::Frequency(scale)) => (calc::Kind::Frequency, value * scale),
                Some(Dimension::Resolution(scale)) => (calc::Kind::Resolution, value * scale),
                _ => return Ok(None),
            },
            _ => return Ok(None),
        };
        if input.expect_exhausted().is_err() {
            return Ok(None);
        }
        Ok(Some(Self {
            kind,
            value: crate::paint::Calculation::Value(value).resolve(0.0),
        }))
    }
}