summaryrefslogtreecommitdiff
path: root/rsvg_convert/tests/internal_predicates/svg.rs
blob: 704738124e639dd2c1d29a3876a85319f98aab54 (plain)
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
use float_cmp::approx_eq;
use gio::glib::Bytes;
use gio::MemoryInputStream;
use predicates::prelude::*;
use predicates::reflection::{Case, Child, PredicateReflection, Product};
use std::cmp;
use std::fmt;

use rsvg::{CairoRenderer, Length, Loader, LoadingError, SvgHandle};

/// Checks that the variable of type [u8] can be parsed as a SVG file.
#[derive(Debug)]
pub struct SvgPredicate {}

impl SvgPredicate {
    pub fn with_size(self: Self, width: Length, height: Length) -> DetailPredicate<Self> {
        DetailPredicate::<Self> {
            p: self,
            d: Detail::Size(Dimensions {
                w: width,
                h: height,
            }),
        }
    }
}

fn svg_from_bytes(data: &[u8]) -> Result<SvgHandle, LoadingError> {
    let bytes = Bytes::from(data);
    let stream = MemoryInputStream::from_bytes(&bytes);
    Loader::new().read_stream(&stream, None::<&gio::File>, None::<&gio::Cancellable>)
}

impl Predicate<[u8]> for SvgPredicate {
    fn eval(&self, data: &[u8]) -> bool {
        svg_from_bytes(data).is_ok()
    }

    fn find_case<'a>(&'a self, _expected: bool, data: &[u8]) -> Option<Case<'a>> {
        match svg_from_bytes(data) {
            Ok(_) => None,
            Err(e) => Some(Case::new(Some(self), false).add_product(Product::new("Error", e))),
        }
    }
}

impl PredicateReflection for SvgPredicate {}

impl fmt::Display for SvgPredicate {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "is an SVG")
    }
}

/// Extends a SVG Predicate by a check for its size
#[derive(Debug)]
pub struct DetailPredicate<SvgPredicate> {
    p: SvgPredicate,
    d: Detail,
}

#[derive(Debug)]
enum Detail {
    Size(Dimensions),
}

/// SVG's dimensions
#[derive(Debug)]
struct Dimensions {
    w: Length,
    h: Length,
}

impl Dimensions {
    pub fn width(self: &Self) -> f64 {
        self.w.length
    }

    pub fn height(self: &Self) -> f64 {
        self.h.length
    }
}

impl fmt::Display for Dimensions {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}{} x {}{}",
            self.width(),
            self.w.unit,
            self.height(),
            self.h.unit
        )
    }
}

impl cmp::PartialEq for Dimensions {
    fn eq(&self, other: &Self) -> bool {
        approx_eq!(f64, self.width(), other.width(), epsilon = 0.000_001)
            && approx_eq!(f64, self.height(), other.height(), epsilon = 0.000_001)
            && (self.w.unit == self.h.unit)
            && (self.h.unit == other.h.unit)
            && (other.h.unit == other.w.unit)
    }
}

impl cmp::Eq for Dimensions {}

trait Details {
    fn get_size(&self) -> Option<Dimensions>;
}

impl DetailPredicate<SvgPredicate> {
    fn eval_doc(&self, handle: &SvgHandle) -> bool {
        match &self.d {
            Detail::Size(d) => {
                let renderer = CairoRenderer::new(handle);
                let dimensions = renderer.intrinsic_dimensions();
                (dimensions.width, dimensions.height) == (d.w, d.h)
            }
        }
    }

    fn find_case_for_doc<'a>(&'a self, expected: bool, handle: &SvgHandle) -> Option<Case<'a>> {
        if self.eval_doc(handle) == expected {
            let product = self.product_for_doc(handle);
            Some(Case::new(Some(self), false).add_product(product))
        } else {
            None
        }
    }

    fn product_for_doc(&self, handle: &SvgHandle) -> Product {
        match &self.d {
            Detail::Size(_) => {
                let renderer = CairoRenderer::new(handle);
                let dimensions = renderer.intrinsic_dimensions();

                Product::new(
                    "actual size",
                    format!(
                        "width={:?}, height={:?}",
                        dimensions.width, dimensions.height
                    ),
                )
            }
        }
    }
}

impl Predicate<[u8]> for DetailPredicate<SvgPredicate> {
    fn eval(&self, data: &[u8]) -> bool {
        match svg_from_bytes(data) {
            Ok(handle) => self.eval_doc(&handle),
            _ => false,
        }
    }

    fn find_case<'a>(&'a self, expected: bool, data: &[u8]) -> Option<Case<'a>> {
        match svg_from_bytes(data) {
            Ok(handle) => self.find_case_for_doc(expected, &handle),
            Err(e) => Some(Case::new(Some(self), false).add_product(Product::new("Error", e))),
        }
    }
}

impl PredicateReflection for DetailPredicate<SvgPredicate> {
    fn children<'a>(&'a self) -> Box<dyn Iterator<Item = Child<'a>> + 'a> {
        let params = vec![Child::new("predicate", &self.p)];
        Box::new(params.into_iter())
    }
}

impl fmt::Display for DetailPredicate<SvgPredicate> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.d {
            Detail::Size(d) => write!(f, "is an SVG sized {}", d),
        }
    }
}