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
//! Handling of `preserveAspectRatio` values.
//!
//! This module handles `preserveAspectRatio` values [per the SVG specification][spec].
//! We have an [`AspectRatio`] struct which encapsulates such a value.
//!
//! ```
//! # use rsvg::doctest_only::AspectRatio;
//! # use rsvg::doctest_only::Parse;
//! assert_eq!(
//!     AspectRatio::parse_str("xMidYMid").unwrap(),
//!     AspectRatio::default()
//! );
//! ```
//!
//! [spec]: https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute

use cssparser::{BasicParseError, Parser};
use std::ops::Deref;

use crate::error::*;
use crate::parse_identifiers;
use crate::parsers::Parse;
use crate::rect::Rect;
use crate::transform::{Transform, ValidTransform};
use crate::viewbox::ViewBox;

#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
enum FitMode {
    #[default]
    Meet,
    Slice,
}

#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
enum Align1D {
    Min,
    #[default]
    Mid,
    Max,
}

#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
struct X(Align1D);
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
struct Y(Align1D);

impl Deref for X {
    type Target = Align1D;

    fn deref(&self) -> &Align1D {
        &self.0
    }
}

impl Deref for Y {
    type Target = Align1D;

    fn deref(&self) -> &Align1D {
        &self.0
    }
}

impl Align1D {
    fn compute(self, dest_pos: f64, dest_size: f64, obj_size: f64) -> f64 {
        match self {
            Align1D::Min => dest_pos,
            Align1D::Mid => dest_pos + (dest_size - obj_size) / 2.0,
            Align1D::Max => dest_pos + dest_size - obj_size,
        }
    }
}

#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
struct Align {
    x: X,
    y: Y,
    fit: FitMode,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct AspectRatio {
    defer: bool,
    align: Option<Align>,
}

impl Default for AspectRatio {
    fn default() -> AspectRatio {
        AspectRatio {
            defer: false,
            align: Some(Align::default()),
        }
    }
}

impl AspectRatio {
    /// Produces the equivalent of `preserveAspectRatio="none"`.
    pub fn none() -> AspectRatio {
        AspectRatio {
            defer: false,
            align: None,
        }
    }

    pub fn is_slice(&self) -> bool {
        matches!(
            self.align,
            Some(Align {
                fit: FitMode::Slice,
                ..
            })
        )
    }

    pub fn compute(&self, vbox: &ViewBox, viewport: &Rect) -> Rect {
        match self.align {
            None => *viewport,

            Some(Align { x, y, fit }) => {
                let (vb_width, vb_height) = vbox.size();
                let (vp_width, vp_height) = viewport.size();

                let w_factor = vp_width / vb_width;
                let h_factor = vp_height / vb_height;

                let factor = match fit {
                    FitMode::Meet => w_factor.min(h_factor),
                    FitMode::Slice => w_factor.max(h_factor),
                };

                let w = vb_width * factor;
                let h = vb_height * factor;

                let xpos = x.compute(viewport.x0, vp_width, w);
                let ypos = y.compute(viewport.y0, vp_height, h);

                Rect::new(xpos, ypos, xpos + w, ypos + h)
            }
        }
    }

    /// Computes the viewport to viewbox transformation.
    ///
    /// Given a viewport, returns a transformation that will create a coordinate
    /// space inside it.  The `(vbox.x0, vbox.y0)` will be mapped to the viewport's
    /// upper-left corner, and the `(vbox.x1, vbox.y1)` will be mapped to the viewport's
    /// lower-right corner.
    ///
    /// If the vbox or viewport are empty, returns `Ok(None)`.  Per the SVG spec, either
    /// of those mean that the corresponding element should not be rendered.
    ///
    /// If the vbox would create an invalid transform (say, a vbox with huge numbers that
    /// leads to a near-zero scaling transform), returns an `Err(())`.
    pub fn viewport_to_viewbox_transform(
        &self,
        vbox: Option<ViewBox>,
        viewport: &Rect,
    ) -> Result<Option<ValidTransform>, InvalidTransform> {
        // width or height set to 0 disables rendering of the element
        // https://www.w3.org/TR/SVG/struct.html#SVGElementWidthAttribute
        // https://www.w3.org/TR/SVG/struct.html#UseElementWidthAttribute
        // https://www.w3.org/TR/SVG/struct.html#ImageElementWidthAttribute
        // https://www.w3.org/TR/SVG/painting.html#MarkerWidthAttribute

        if viewport.is_empty() {
            return Ok(None);
        }

        // the preserveAspectRatio attribute is only used if viewBox is specified
        // https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
        let transform = if let Some(vbox) = vbox {
            if vbox.is_empty() {
                // Width or height of 0 for the viewBox disables rendering of the element
                // https://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
                return Ok(None);
            } else {
                let r = self.compute(&vbox, viewport);
                Transform::new_translate(r.x0, r.y0)
                    .pre_scale(r.width() / vbox.width(), r.height() / vbox.height())
                    .pre_translate(-vbox.x0, -vbox.y0)
            }
        } else {
            Transform::new_translate(viewport.x0, viewport.y0)
        };

        ValidTransform::try_from(transform).map(Some)
    }
}

fn parse_align_xy<'i>(parser: &mut Parser<'i, '_>) -> Result<Option<(X, Y)>, BasicParseError<'i>> {
    use self::Align1D::*;

    parse_identifiers!(
        parser,

        "none" => None,

        "xMinYMin" => Some((X(Min), Y(Min))),
        "xMidYMin" => Some((X(Mid), Y(Min))),
        "xMaxYMin" => Some((X(Max), Y(Min))),

        "xMinYMid" => Some((X(Min), Y(Mid))),
        "xMidYMid" => Some((X(Mid), Y(Mid))),
        "xMaxYMid" => Some((X(Max), Y(Mid))),

        "xMinYMax" => Some((X(Min), Y(Max))),
        "xMidYMax" => Some((X(Mid), Y(Max))),
        "xMaxYMax" => Some((X(Max), Y(Max))),
    )
}

fn parse_fit_mode<'i>(parser: &mut Parser<'i, '_>) -> Result<FitMode, BasicParseError<'i>> {
    parse_identifiers!(
        parser,
        "meet" => FitMode::Meet,
        "slice" => FitMode::Slice,
    )
}

impl Parse for AspectRatio {
    fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<AspectRatio, ParseError<'i>> {
        let defer = parser
            .try_parse(|p| p.expect_ident_matching("defer"))
            .is_ok();

        let align_xy = parser.try_parse(parse_align_xy)?;
        let fit = parser.try_parse(parse_fit_mode).unwrap_or_default();
        let align = align_xy.map(|(x, y)| Align { x, y, fit });

        Ok(AspectRatio { defer, align })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::{assert_approx_eq_cairo, float_eq_cairo::ApproxEqCairo};

    #[test]
    fn aspect_ratio_none() {
        assert_eq!(AspectRatio::none(), AspectRatio::parse_str("none").unwrap());
    }

    #[test]
    fn parsing_invalid_strings_yields_error() {
        assert!(AspectRatio::parse_str("").is_err());
        assert!(AspectRatio::parse_str("defer").is_err());
        assert!(AspectRatio::parse_str("defer foo").is_err());
        assert!(AspectRatio::parse_str("defer xMidYMid foo").is_err());
        assert!(AspectRatio::parse_str("xMidYMid foo").is_err());
        assert!(AspectRatio::parse_str("defer xMidYMid meet foo").is_err());
    }

    #[test]
    fn parses_valid_strings() {
        assert_eq!(
            AspectRatio::parse_str("defer none").unwrap(),
            AspectRatio {
                defer: true,
                align: None,
            }
        );

        assert_eq!(
            AspectRatio::parse_str("xMidYMid").unwrap(),
            AspectRatio {
                defer: false,
                align: Some(Align {
                    x: X(Align1D::Mid),
                    y: Y(Align1D::Mid),
                    fit: FitMode::Meet,
                },),
            }
        );

        assert_eq!(
            AspectRatio::parse_str("defer xMidYMid").unwrap(),
            AspectRatio {
                defer: true,
                align: Some(Align {
                    x: X(Align1D::Mid),
                    y: Y(Align1D::Mid),
                    fit: FitMode::Meet,
                },),
            }
        );

        assert_eq!(
            AspectRatio::parse_str("defer xMinYMax").unwrap(),
            AspectRatio {
                defer: true,
                align: Some(Align {
                    x: X(Align1D::Min),
                    y: Y(Align1D::Max),
                    fit: FitMode::Meet,
                },),
            }
        );

        assert_eq!(
            AspectRatio::parse_str("defer xMaxYMid meet").unwrap(),
            AspectRatio {
                defer: true,
                align: Some(Align {
                    x: X(Align1D::Max),
                    y: Y(Align1D::Mid),
                    fit: FitMode::Meet,
                },),
            }
        );

        assert_eq!(
            AspectRatio::parse_str("defer xMinYMax slice").unwrap(),
            AspectRatio {
                defer: true,
                align: Some(Align {
                    x: X(Align1D::Min),
                    y: Y(Align1D::Max),
                    fit: FitMode::Slice,
                },),
            }
        );
    }

    fn assert_rect_equal(r1: &Rect, r2: &Rect) {
        assert_approx_eq_cairo!(r1.x0, r2.x0);
        assert_approx_eq_cairo!(r1.y0, r2.y0);
        assert_approx_eq_cairo!(r1.x1, r2.x1);
        assert_approx_eq_cairo!(r1.y1, r2.y1);
    }

    #[test]
    fn aligns() {
        let viewbox = ViewBox::from(Rect::from_size(1.0, 10.0));

        let foo = AspectRatio::parse_str("xMinYMin meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::from_size(0.1, 1.0));

        let foo = AspectRatio::parse_str("xMinYMin slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::from_size(10.0, 100.0));

        let foo = AspectRatio::parse_str("xMinYMid meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::from_size(0.1, 1.0));

        let foo = AspectRatio::parse_str("xMinYMid slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(0.0, -49.5, 10.0, 100.0 - 49.5));

        let foo = AspectRatio::parse_str("xMinYMax meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::from_size(0.1, 1.0));

        let foo = AspectRatio::parse_str("xMinYMax slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(0.0, -99.0, 10.0, 1.0));

        let foo = AspectRatio::parse_str("xMidYMin meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(4.95, 0.0, 4.95 + 0.1, 1.0));

        let foo = AspectRatio::parse_str("xMidYMin slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::from_size(10.0, 100.0));

        let foo = AspectRatio::parse_str("xMidYMid meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(4.95, 0.0, 4.95 + 0.1, 1.0));

        let foo = AspectRatio::parse_str("xMidYMid slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(0.0, -49.5, 10.0, 100.0 - 49.5));

        let foo = AspectRatio::parse_str("xMidYMax meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(4.95, 0.0, 4.95 + 0.1, 1.0));

        let foo = AspectRatio::parse_str("xMidYMax slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(0.0, -99.0, 10.0, 1.0));

        let foo = AspectRatio::parse_str("xMaxYMin meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(9.9, 0.0, 10.0, 1.0));

        let foo = AspectRatio::parse_str("xMaxYMin slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::from_size(10.0, 100.0));

        let foo = AspectRatio::parse_str("xMaxYMid meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(9.9, 0.0, 10.0, 1.0));

        let foo = AspectRatio::parse_str("xMaxYMid slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(0.0, -49.5, 10.0, 100.0 - 49.5));

        let foo = AspectRatio::parse_str("xMaxYMax meet").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(9.9, 0.0, 10.0, 1.0));

        let foo = AspectRatio::parse_str("xMaxYMax slice").unwrap();
        let foo = foo.compute(&viewbox, &Rect::from_size(10.0, 1.0));
        assert_rect_equal(&foo, &Rect::new(0.0, -99.0, 10.0, 1.0));
    }

    #[test]
    fn empty_viewport() {
        let a = AspectRatio::default();
        let t = a
            .viewport_to_viewbox_transform(
                Some(ViewBox::parse_str("10 10 40 40").unwrap()),
                &Rect::from_size(0.0, 0.0),
            )
            .unwrap();

        assert_eq!(t, None);
    }

    #[test]
    fn empty_viewbox() {
        let a = AspectRatio::default();
        let t = a
            .viewport_to_viewbox_transform(
                Some(ViewBox::parse_str("10 10 0 0").unwrap()),
                &Rect::from_size(10.0, 10.0),
            )
            .unwrap();

        assert_eq!(t, None);
    }

    #[test]
    fn valid_viewport_and_viewbox() {
        let a = AspectRatio::default();
        let t = a
            .viewport_to_viewbox_transform(
                Some(ViewBox::parse_str("10 10 40 40").unwrap()),
                &Rect::new(1.0, 1.0, 2.0, 2.0),
            )
            .unwrap();

        assert_eq!(
            t,
            Some(
                ValidTransform::try_from(
                    Transform::identity()
                        .pre_translate(1.0, 1.0)
                        .pre_scale(0.025, 0.025)
                        .pre_translate(-10.0, -10.0)
                )
                .unwrap()
            )
        );
    }

    #[test]
    fn invalid_viewbox() {
        let a = AspectRatio::default();
        let t = a.viewport_to_viewbox_transform(
            Some(ViewBox::parse_str("0 0 6E20 540").unwrap()),
            &Rect::new(1.0, 1.0, 2.0, 2.0),
        );

        assert_eq!(t, Err(InvalidTransform));
    }
}