Skip to main content

rsvg/
length.rs

1//! CSS length values.
2//!
3//! [`CssLength`] is the struct librsvg uses to represent CSS lengths.
4//! See its documentation for examples of how to construct it.
5//!
6//! `CssLength` values need to know whether they will be normalized with respect to the width,
7//! height, or both dimensions of the current viewport.  `CssLength` values can be signed or
8//! unsigned.  So, a `CssLength` has two type parameters, [`Normalize`] and [`Validate`];
9//! the full type is `CssLength<N: Normalize, V: Validate>`.  We provide [`Horizontal`],
10//! [`Vertical`], and [`Both`] implementations of [`Normalize`]; these let length values know
11//! how to normalize themselves with respect to the current viewport.  We also provide
12//! [`Signed`] and [`Unsigned`] implementations of [`Validate`].
13//!
14//! For ease of use, we define two type aliases [`Length`] and [`ULength`] corresponding to
15//! signed and unsigned.
16//!
17//! For example, the implementation of [`Circle`][crate::shapes::Circle] defines this
18//! structure with fields for the `(center_x, center_y, radius)`:
19//!
20//! ```
21//! # use rsvg::doctest_only::{Length,ULength,Horizontal,Vertical,Both};
22//! pub struct Circle {
23//!     cx: Length<Horizontal>,
24//!     cy: Length<Vertical>,
25//!     r: ULength<Both>,
26//! }
27//! ```
28//!
29//! This means that:
30//!
31//! * `cx` and `cy` define the center of the circle, they can be positive or negative, and
32//!   they will be normalized with respect to the current viewport's width and height,
33//!   respectively.  If the SVG document specified `<circle cx="50%" cy="30%">`, the values
34//!   would be normalized to be at 50% of the the viewport's width, and 30% of the viewport's
35//!   height.
36//!
37//! * `r` is non-negative and needs to be resolved against the [normalized diagonal][diag]
38//!   of the current viewport.
39//!
40//! The `N` type parameter of `CssLength<N, I>` is enough to know how to normalize a length
41//! value; the [`CssLength::to_user`] method will handle it automatically.
42//!
43//! [diag]: https://www.w3.org/TR/SVG/coords.html#Units
44
45use cssparser::{Parser, Token, match_ignore_ascii_case};
46use std::f64::consts::*;
47use std::fmt;
48use std::marker::PhantomData;
49
50use crate::dpi::Dpi;
51use crate::drawing_ctx::Viewport;
52use crate::error::*;
53use crate::parsers::{Parse, finite_f32};
54use crate::properties::{ComputedValues, FontSize, TextOrientation, WritingMode};
55use crate::rect::Rect;
56use crate::viewbox::ViewBox;
57
58/// Units for length values.
59// This needs to be kept in sync with `rsvg.h:RsvgUnit`.
60#[non_exhaustive]
61#[repr(C)]
62#[derive(Debug, PartialEq, Copy, Clone)]
63pub enum LengthUnit {
64    /// `1.0` means 100%
65    Percent,
66
67    /// Pixels, or the CSS default unit
68    Px,
69
70    /// Size of the current font
71    Em,
72
73    /// x-height of the current font
74    Ex,
75
76    /// Inches (25.4 mm)
77    In,
78
79    /// Centimeters
80    Cm,
81
82    /// Millimeters
83    Mm,
84
85    /// Points (1/72 inch)
86    Pt,
87
88    /// Picas (12 points)
89    Pc,
90
91    /// Advance measure of a '0' character (depends on the text orientation)
92    Ch,
93}
94
95/// A CSS length value.
96///
97/// This is equivalent to [CSS lengths].
98///
99/// [CSS lengths]: https://www.w3.org/TR/CSS22/syndata.html#length-units
100///
101/// It is up to the calling application to convert lengths in non-pixel units (i.e. those
102/// where the [`unit`][RsvgLength::unit] field is not [`LengthUnit::Px`]) into something
103/// meaningful to the application.  For example, if your application knows the
104/// dots-per-inch (DPI) it is using, it can convert lengths with [`unit`] in
105/// [`LengthUnit::In`] or other physical units.
106// Keep this in sync with rsvg.h:RsvgLength
107#[repr(C)]
108#[derive(Debug, PartialEq, Copy, Clone)]
109pub struct RsvgLength {
110    /// Numeric part of the length
111    pub length: f64,
112
113    /// Unit part of the length
114    pub unit: LengthUnit,
115}
116
117impl RsvgLength {
118    /// Constructs a CSS length value.
119    pub fn new(l: f64, unit: LengthUnit) -> RsvgLength {
120        RsvgLength { length: l, unit }
121    }
122}
123
124/// Used for the `N` type parameter of `CssLength<N: Normalize, V: Validate>`.
125pub trait Normalize {
126    /// Computes an orientation-based scaling factor.
127    ///
128    /// This is used in the [`CssLength::to_user`] method to resolve lengths with percentage
129    /// units; they need to be resolved with respect to the width, height, or [normalized
130    /// diagonal][diag] of the current viewport.
131    ///
132    /// [diag]: https://www.w3.org/TR/SVG/coords.html#Units
133    fn normalize(x: f64, y: f64) -> f64;
134}
135
136/// Allows declaring `CssLength<Horizontal>`.
137#[derive(Debug, PartialEq, Copy, Clone)]
138pub struct Horizontal;
139
140/// Allows declaring `CssLength<Vertical>`.
141#[derive(Debug, PartialEq, Copy, Clone)]
142pub struct Vertical;
143
144/// Allows declaring `CssLength<Both>`.
145#[derive(Debug, PartialEq, Copy, Clone)]
146pub struct Both;
147
148impl Normalize for Horizontal {
149    #[inline]
150    fn normalize(x: f64, _y: f64) -> f64 {
151        x
152    }
153}
154
155impl Normalize for Vertical {
156    #[inline]
157    fn normalize(_x: f64, y: f64) -> f64 {
158        y
159    }
160}
161
162impl Normalize for Both {
163    #[inline]
164    fn normalize(x: f64, y: f64) -> f64 {
165        viewport_percentage(x, y)
166    }
167}
168
169/// Used for the `V` type parameter of `CssLength<N: Normalize, V: Validate>`.
170pub trait Validate {
171    /// Checks if the specified value is acceptable
172    ///
173    /// This is used when parsing a length value
174    fn validate(v: f64) -> Result<f64, ValueErrorKind> {
175        Ok(v)
176    }
177}
178
179/// Used to implement `CssLength<N, Signed>`.
180///
181/// Signed lengths do not require validation, so they use the default implementation of of
182/// [Validate].
183#[derive(Debug, PartialEq, Copy, Clone)]
184pub struct Signed;
185
186impl Validate for Signed {}
187
188/// Used to implement `CssLength<N, Unsigned>`.
189///
190/// Unsigned lengths need validation to ensure that their value is non-negative,
191/// so they have a custom implementation of [Validate].
192#[derive(Debug, PartialEq, Copy, Clone)]
193pub struct Unsigned;
194
195impl Validate for Unsigned {
196    fn validate(v: f64) -> Result<f64, ValueErrorKind> {
197        if v >= 0.0 {
198            Ok(v)
199        } else {
200            Err(ValueErrorKind::Value(
201                "value must be non-negative".to_string(),
202            ))
203        }
204    }
205}
206
207/// A CSS length value.
208///
209/// This is equivalent to [CSS lengths].
210///
211/// [CSS lengths]: https://www.w3.org/TR/CSS22/syndata.html#length-units
212///
213/// `CssLength` implements the [`Parse`] trait, so it can be parsed out of a
214/// [`cssparser::Parser`].
215///
216/// This type will be normally used through the type aliases [`Length`] and [`ULength`]
217///
218/// Examples of construction:
219///
220/// ```
221/// # use rsvg::doctest_only::{Length,ULength,LengthUnit,Horizontal,Vertical,Both};
222/// # use rsvg::doctest_only::Parse;
223/// // Explicit type
224/// let width: Length<Horizontal> = Length::new(42.0, LengthUnit::Cm);
225///
226/// // Inferred type
227/// let height = Length::<Vertical>::new(42.0, LengthUnit::Cm);
228///
229/// // Parsed
230/// let radius = ULength::<Both>::parse_str("5px").unwrap();
231/// ```
232///
233/// During the rendering phase, a `CssLength` needs to be converted to user-space
234/// coordinates with the [`CssLength::to_user`] method.
235#[derive(Debug, PartialEq, Copy, Clone)]
236pub struct CssLength<N: Normalize, V: Validate> {
237    /// Numeric part of the length
238    pub length: f64,
239
240    /// Unit part of the length
241    pub unit: LengthUnit,
242
243    /// Dummy; used internally for the type parameter `N`
244    orientation: PhantomData<N>,
245
246    /// Dummy; used internally for the type parameter `V`
247    validation: PhantomData<V>,
248}
249
250impl<N: Normalize, V: Validate> From<CssLength<N, V>> for RsvgLength {
251    fn from(l: CssLength<N, V>) -> RsvgLength {
252        RsvgLength {
253            length: l.length,
254            unit: l.unit,
255        }
256    }
257}
258
259impl<N: Normalize, V: Validate> Default for CssLength<N, V> {
260    fn default() -> Self {
261        CssLength::new(0.0, LengthUnit::Px)
262    }
263}
264
265pub const POINTS_PER_INCH: f64 = 72.0;
266const CM_PER_INCH: f64 = 2.54;
267const MM_PER_INCH: f64 = 25.4;
268const PICA_PER_INCH: f64 = 6.0;
269
270impl<N: Normalize, V: Validate> Parse for CssLength<N, V> {
271    fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<CssLength<N, V>, ParseError<'i>> {
272        let token = parser.next()?.clone();
273
274        let (l_value, l_unit) = match token {
275            Token::Number { value, .. } => (value, LengthUnit::Px),
276
277            Token::Percentage { unit_value, .. } => (unit_value, LengthUnit::Percent),
278
279            Token::Dimension {
280                value, ref unit, ..
281            } => (
282                value,
283                match_ignore_ascii_case! {unit.as_ref(),
284                    "px" => LengthUnit::Px,
285                    "em" => LengthUnit::Em,
286                    "ex" => LengthUnit::Ex,
287                    "in" => LengthUnit::In,
288                    "cm" => LengthUnit::Cm,
289                    "mm" => LengthUnit::Mm,
290                    "pt" => LengthUnit::Pt,
291                    "pc" => LengthUnit::Pc,
292                    "ch" => LengthUnit::Ch,
293
294                    _ => return Err(parser.new_unexpected_token_error(token)),
295                },
296            ),
297
298            _ => return Err(parser.new_unexpected_token_error(token)),
299        };
300
301        let l_value = f64::from(finite_f32(l_value).map_err(|e| parser.new_custom_error(e))?);
302
303        <V as Validate>::validate(l_value)
304            .map_err(|e| parser.new_custom_error(e))
305            .map(|l_value| CssLength::new(l_value, l_unit))
306    }
307}
308
309/// Parameters for length normalization extracted from [`ComputedValues`].
310///
311/// This is a precursor to [`NormalizeParams::from_values`], for cases where it is inconvenient
312/// to keep a [`ComputedValues`] around.
313pub struct NormalizeValues {
314    font_size: FontSize,
315    is_vertical_text: bool,
316}
317
318impl NormalizeValues {
319    pub fn new(values: &ComputedValues) -> NormalizeValues {
320        let is_vertical_text = matches!(
321            (values.writing_mode(), values.text_orientation()),
322            (WritingMode::VerticalLr, TextOrientation::Upright)
323                | (WritingMode::VerticalRl, TextOrientation::Upright)
324        );
325
326        NormalizeValues {
327            font_size: values.font_size(),
328            is_vertical_text,
329        }
330    }
331}
332
333/// Parameters to normalize [`Length`] values to user-space distances.
334pub struct NormalizeParams {
335    vbox: ViewBox,
336    font_size: f64,
337    dpi: Dpi,
338    is_vertical_text: bool,
339}
340
341impl NormalizeParams {
342    /// Extracts the information needed to normalize [`Length`] values from a set of
343    /// [`ComputedValues`] and the viewport size in [`Viewport`].
344    pub fn new(values: &ComputedValues, viewport: &Viewport) -> NormalizeParams {
345        let v = NormalizeValues::new(values);
346        NormalizeParams::from_values(&v, viewport)
347    }
348
349    pub fn from_values(v: &NormalizeValues, viewport: &Viewport) -> NormalizeParams {
350        NormalizeParams {
351            vbox: viewport.vbox,
352            font_size: font_size_from_values(v, viewport.dpi),
353            dpi: viewport.dpi,
354            is_vertical_text: v.is_vertical_text,
355        }
356    }
357
358    /// Just used by rsvg-convert, where there is no font size nor viewport.
359    pub fn from_dpi(dpi: Dpi) -> NormalizeParams {
360        NormalizeParams {
361            vbox: ViewBox::from(Rect::default()),
362            font_size: 1.0,
363            dpi,
364            is_vertical_text: false,
365        }
366    }
367}
368
369impl<N: Normalize, V: Validate> CssLength<N, V> {
370    /// Creates a CssLength.
371    ///
372    /// The compiler needs to know the type parameters `N` and `V` which represents the
373    /// length's orientation and validation.
374    /// You can specify them explicitly, or call the parametrized method:
375    ///
376    /// ```
377    /// # use rsvg::doctest_only::{Length,LengthUnit,Horizontal,Vertical};
378    /// // Explicit type
379    /// let width: Length<Horizontal> = Length::new(42.0, LengthUnit::Cm);
380    ///
381    /// // Inferred type
382    /// let height = Length::<Vertical>::new(42.0, LengthUnit::Cm);
383    /// ```
384    pub fn new(l: f64, unit: LengthUnit) -> CssLength<N, V> {
385        CssLength {
386            length: l,
387            unit,
388            orientation: PhantomData,
389            validation: PhantomData,
390        }
391    }
392
393    /// Convert a Length with units into user-space coordinates.
394    ///
395    /// Lengths may come with non-pixel units, and when rendering, they need to be normalized
396    /// to pixels based on the current viewport (e.g. for lengths with percent units), and
397    /// based on the current element's set of [`ComputedValues`] (e.g. for lengths with `Em`
398    /// units that need to be resolved against the current font size).
399    ///
400    /// Those parameters can be obtained with [`NormalizeParams::new()`].
401    pub fn to_user(&self, params: &NormalizeParams) -> f64 {
402        match self.unit {
403            LengthUnit::Px => self.length,
404
405            LengthUnit::Percent => {
406                self.length * <N as Normalize>::normalize(params.vbox.width(), params.vbox.height())
407            }
408
409            LengthUnit::Em => self.length * params.font_size,
410
411            LengthUnit::Ex => self.length * params.font_size / 2.0,
412
413            // how far "0" advances the text, so it varies depending on orientation
414            // we're using the 0.5em or 1.0em (based on orientation) fallback from the spec
415            LengthUnit::Ch => {
416                if params.is_vertical_text {
417                    self.length * params.font_size
418                } else {
419                    self.length * params.font_size / 2.0
420                }
421            }
422
423            LengthUnit::In => self.length * <N as Normalize>::normalize(params.dpi.x, params.dpi.y),
424
425            LengthUnit::Cm => {
426                self.length * <N as Normalize>::normalize(params.dpi.x, params.dpi.y) / CM_PER_INCH
427            }
428
429            LengthUnit::Mm => {
430                self.length * <N as Normalize>::normalize(params.dpi.x, params.dpi.y) / MM_PER_INCH
431            }
432
433            LengthUnit::Pt => {
434                self.length * <N as Normalize>::normalize(params.dpi.x, params.dpi.y)
435                    / POINTS_PER_INCH
436            }
437
438            LengthUnit::Pc => {
439                self.length * <N as Normalize>::normalize(params.dpi.x, params.dpi.y)
440                    / PICA_PER_INCH
441            }
442        }
443    }
444
445    /// Converts a Length to points.  Pixels are taken to be respect with the DPI.
446    ///
447    /// # Panics
448    ///
449    /// Will panic if the length is in Percent, Em, or Ex units.
450    pub fn to_points(&self, params: &NormalizeParams) -> f64 {
451        match self.unit {
452            LengthUnit::Px => {
453                self.length / <N as Normalize>::normalize(params.dpi.x, params.dpi.y) * 72.0
454            }
455
456            LengthUnit::Percent => {
457                panic!("Cannot convert a percentage length into an absolute length");
458            }
459
460            LengthUnit::Em => {
461                panic!("Cannot convert an Em length into an absolute length");
462            }
463
464            LengthUnit::Ex => {
465                panic!("Cannot convert an Ex length into an absolute length");
466            }
467
468            LengthUnit::In => self.length * POINTS_PER_INCH,
469
470            LengthUnit::Cm => self.length / CM_PER_INCH * POINTS_PER_INCH,
471
472            LengthUnit::Mm => self.length / MM_PER_INCH * POINTS_PER_INCH,
473
474            LengthUnit::Pt => self.length,
475
476            LengthUnit::Pc => self.length / PICA_PER_INCH * POINTS_PER_INCH,
477
478            LengthUnit::Ch => {
479                panic!("Cannot convert a Ch length into an absolute length");
480            }
481        }
482    }
483
484    pub fn to_inches(&self, params: &NormalizeParams) -> f64 {
485        self.to_points(params) / POINTS_PER_INCH
486    }
487
488    pub fn to_cm(&self, params: &NormalizeParams) -> f64 {
489        self.to_inches(params) * CM_PER_INCH
490    }
491
492    pub fn to_mm(&self, params: &NormalizeParams) -> f64 {
493        self.to_inches(params) * MM_PER_INCH
494    }
495
496    pub fn to_picas(&self, params: &NormalizeParams) -> f64 {
497        self.to_inches(params) * PICA_PER_INCH
498    }
499}
500
501fn font_size_from_values(values: &NormalizeValues, dpi: Dpi) -> f64 {
502    let v = values.font_size.value();
503
504    match v.unit {
505        LengthUnit::Percent => unreachable!("ComputedValues can't have a relative font size"),
506
507        LengthUnit::Px => v.length,
508
509        // The following implies that our default font size is 12, which
510        // matches the default from the FontSize property.
511        LengthUnit::Em => v.length * 12.0,
512        LengthUnit::Ex => v.length * 12.0 / 2.0,
513        LengthUnit::Ch => v.length * 12.0 / 2.0,
514
515        // FontSize always is a Both, per properties.rs
516        LengthUnit::In => v.length * Both::normalize(dpi.x, dpi.y),
517        LengthUnit::Cm => v.length * Both::normalize(dpi.x, dpi.y) / CM_PER_INCH,
518        LengthUnit::Mm => v.length * Both::normalize(dpi.x, dpi.y) / MM_PER_INCH,
519        LengthUnit::Pt => v.length * Both::normalize(dpi.x, dpi.y) / POINTS_PER_INCH,
520        LengthUnit::Pc => v.length * Both::normalize(dpi.x, dpi.y) / PICA_PER_INCH,
521    }
522}
523
524fn viewport_percentage(x: f64, y: f64) -> f64 {
525    // https://www.w3.org/TR/SVG/coords.html#Units
526    // "For any other length value expressed as a percentage of the viewport, the
527    // percentage is calculated as the specified percentage of
528    // sqrt((actual-width)**2 + (actual-height)**2))/sqrt(2)."
529    (x * x + y * y).sqrt() / SQRT_2
530}
531
532/// Alias for `CssLength` types that can have negative values
533pub type Length<N> = CssLength<N, Signed>;
534
535/// Alias for `CssLength` types that are non negative
536pub type ULength<N> = CssLength<N, Unsigned>;
537
538#[derive(Debug, Default, PartialEq, Copy, Clone)]
539pub enum LengthOrAuto<N: Normalize> {
540    #[default]
541    Auto,
542    Length(CssLength<N, Unsigned>),
543}
544
545impl<N: Normalize> Parse for LengthOrAuto<N> {
546    fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<LengthOrAuto<N>, ParseError<'i>> {
547        if parser
548            .try_parse(|i| i.expect_ident_matching("auto"))
549            .is_ok()
550        {
551            Ok(LengthOrAuto::Auto)
552        } else {
553            Ok(LengthOrAuto::Length(CssLength::parse(parser)?))
554        }
555    }
556}
557
558impl fmt::Display for LengthUnit {
559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560        let unit = match &self {
561            LengthUnit::Percent => "%",
562            LengthUnit::Px => "px",
563            LengthUnit::Em => "em",
564            LengthUnit::Ex => "ex",
565            LengthUnit::In => "in",
566            LengthUnit::Cm => "cm",
567            LengthUnit::Mm => "mm",
568            LengthUnit::Pt => "pt",
569            LengthUnit::Pc => "pc",
570            LengthUnit::Ch => "ch",
571        };
572
573        write!(f, "{unit}")
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    use crate::properties::{ParsedProperty, SpecifiedValue, SpecifiedValues};
582    use crate::{assert_approx_eq_cairo, float_eq_cairo::ApproxEqCairo};
583
584    #[test]
585    fn parses_default() {
586        assert_eq!(
587            Length::<Horizontal>::parse_str("42").unwrap(),
588            Length::<Horizontal>::new(42.0, LengthUnit::Px)
589        );
590
591        assert_eq!(
592            Length::<Horizontal>::parse_str("-42px").unwrap(),
593            Length::<Horizontal>::new(-42.0, LengthUnit::Px)
594        );
595    }
596
597    #[test]
598    fn parses_percent() {
599        assert_eq!(
600            Length::<Horizontal>::parse_str("50.0%").unwrap(),
601            Length::<Horizontal>::new(0.5, LengthUnit::Percent)
602        );
603    }
604
605    #[test]
606    fn parses_font_em() {
607        assert_eq!(
608            Length::<Vertical>::parse_str("22.5em").unwrap(),
609            Length::<Vertical>::new(22.5, LengthUnit::Em)
610        );
611    }
612
613    #[test]
614    fn parses_font_ex() {
615        assert_eq!(
616            Length::<Vertical>::parse_str("22.5ex").unwrap(),
617            Length::<Vertical>::new(22.5, LengthUnit::Ex)
618        );
619    }
620
621    #[test]
622    fn parses_font_ch() {
623        assert_eq!(
624            Length::<Vertical>::parse_str("22.5ch").unwrap(),
625            Length::<Vertical>::new(22.5, LengthUnit::Ch)
626        );
627    }
628
629    #[test]
630    fn parses_physical_units() {
631        assert_eq!(
632            Length::<Both>::parse_str("72pt").unwrap(),
633            Length::<Both>::new(72.0, LengthUnit::Pt)
634        );
635
636        assert_eq!(
637            Length::<Both>::parse_str("-22.5in").unwrap(),
638            Length::<Both>::new(-22.5, LengthUnit::In)
639        );
640
641        assert_eq!(
642            Length::<Both>::parse_str("-254cm").unwrap(),
643            Length::<Both>::new(-254.0, LengthUnit::Cm)
644        );
645
646        assert_eq!(
647            Length::<Both>::parse_str("254mm").unwrap(),
648            Length::<Both>::new(254.0, LengthUnit::Mm)
649        );
650
651        assert_eq!(
652            Length::<Both>::parse_str("60pc").unwrap(),
653            Length::<Both>::new(60.0, LengthUnit::Pc)
654        );
655    }
656
657    #[test]
658    fn parses_unsigned() {
659        assert_eq!(
660            ULength::<Horizontal>::parse_str("42").unwrap(),
661            ULength::<Horizontal>::new(42.0, LengthUnit::Px)
662        );
663
664        assert_eq!(
665            ULength::<Both>::parse_str("0pt").unwrap(),
666            ULength::<Both>::new(0.0, LengthUnit::Pt)
667        );
668
669        assert!(ULength::<Horizontal>::parse_str("-42px").is_err());
670    }
671
672    #[test]
673    fn empty_length_yields_error() {
674        assert!(Length::<Both>::parse_str("").is_err());
675    }
676
677    #[test]
678    fn invalid_unit_yields_error() {
679        assert!(Length::<Both>::parse_str("8furlong").is_err());
680    }
681
682    #[test]
683    fn normalize_default_works() {
684        let viewport = Viewport::new(Dpi::new(40.0, 40.0), 100.0, 100.0);
685        let values = ComputedValues::default();
686        let params = NormalizeParams::new(&values, &viewport);
687
688        assert_approx_eq_cairo!(
689            Length::<Both>::new(10.0, LengthUnit::Px).to_user(&params),
690            10.0
691        );
692    }
693
694    #[test]
695    fn normalize_absolute_units_works() {
696        let viewport = Viewport::new(Dpi::new(40.0, 50.0), 100.0, 100.0);
697        let values = ComputedValues::default();
698        let params = NormalizeParams::new(&values, &viewport);
699
700        assert_approx_eq_cairo!(
701            Length::<Horizontal>::new(10.0, LengthUnit::In).to_user(&params),
702            400.0
703        );
704        assert_approx_eq_cairo!(
705            Length::<Vertical>::new(10.0, LengthUnit::In).to_user(&params),
706            500.0
707        );
708
709        assert_approx_eq_cairo!(
710            Length::<Horizontal>::new(10.0, LengthUnit::Cm).to_user(&params),
711            400.0 / CM_PER_INCH
712        );
713        assert_approx_eq_cairo!(
714            Length::<Horizontal>::new(10.0, LengthUnit::Mm).to_user(&params),
715            400.0 / MM_PER_INCH
716        );
717        assert_approx_eq_cairo!(
718            Length::<Horizontal>::new(10.0, LengthUnit::Pt).to_user(&params),
719            400.0 / POINTS_PER_INCH
720        );
721        assert_approx_eq_cairo!(
722            Length::<Horizontal>::new(10.0, LengthUnit::Pc).to_user(&params),
723            400.0 / PICA_PER_INCH
724        );
725    }
726
727    #[test]
728    fn normalize_percent_works() {
729        let viewport = Viewport::new(Dpi::new(40.0, 40.0), 100.0, 200.0);
730        let values = ComputedValues::default();
731        let params = NormalizeParams::new(&values, &viewport);
732
733        assert_approx_eq_cairo!(
734            Length::<Horizontal>::new(0.05, LengthUnit::Percent).to_user(&params),
735            5.0
736        );
737        assert_approx_eq_cairo!(
738            Length::<Vertical>::new(0.05, LengthUnit::Percent).to_user(&params),
739            10.0
740        );
741    }
742
743    #[test]
744    fn normalize_font_em_ex_ch_works() {
745        let mut values = ComputedValues::default();
746        let viewport = Viewport::new(Dpi::new(40.0, 40.0), 100.0, 200.0);
747        let mut params = NormalizeParams::new(&values, &viewport);
748
749        // These correspond to the default size for the font-size
750        // property and the way we compute Em/Ex from that.
751
752        assert_approx_eq_cairo!(
753            Length::<Vertical>::new(1.0, LengthUnit::Em).to_user(&params),
754            12.0
755        );
756
757        assert_approx_eq_cairo!(
758            Length::<Vertical>::new(1.0, LengthUnit::Ex).to_user(&params),
759            6.0
760        );
761
762        assert_approx_eq_cairo!(
763            Length::<Vertical>::new(1.0, LengthUnit::Ch).to_user(&params),
764            6.0
765        );
766
767        // check for vertical upright text
768        let mut specified = SpecifiedValues::default();
769        specified.set_parsed_property(&ParsedProperty::TextOrientation(SpecifiedValue::Specified(
770            TextOrientation::Upright,
771        )));
772        specified.set_parsed_property(&ParsedProperty::WritingMode(SpecifiedValue::Specified(
773            WritingMode::VerticalLr,
774        )));
775        specified.to_computed_values(&mut values);
776        params = NormalizeParams::new(&values, &viewport);
777        assert_approx_eq_cairo!(
778            Length::<Vertical>::new(1.0, LengthUnit::Ch).to_user(&params),
779            12.0
780        );
781    }
782
783    #[test]
784    fn to_points_works() {
785        let params = NormalizeParams::from_dpi(Dpi::new(40.0, 96.0));
786
787        assert_approx_eq_cairo!(
788            Length::<Horizontal>::new(80.0, LengthUnit::Px).to_points(&params),
789            2.0 * 72.0
790        );
791        assert_approx_eq_cairo!(
792            Length::<Vertical>::new(192.0, LengthUnit::Px).to_points(&params),
793            2.0 * 72.0
794        );
795    }
796}