1
//! Types for rectangles.
2

            
3
use crate::coord_units::CoordUnits;
4
use crate::transform::Transform;
5

            
6
#[allow(clippy::module_inception)]
7
mod rect {
8
    use crate::float_eq_cairo::ApproxEqCairo;
9
    use core::ops::{Add, Range, Sub};
10
    use float_cmp::approx_eq;
11
    use num_traits::Zero;
12

            
13
    // Use our own min() and max() that are acceptable for floating point
14

            
15
3708241
    fn min<T: PartialOrd>(x: T, y: T) -> T {
16
3708241
        if x <= y {
17
480723
            x
18
        } else {
19
3227518
            y
20
        }
21
3708241
    }
22

            
23
3707905
    fn max<T: PartialOrd>(x: T, y: T) -> T {
24
3707905
        if x >= y {
25
2237878
            x
26
        } else {
27
1470027
            y
28
        }
29
3707905
    }
30

            
31
830
    #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
32
    pub struct Rect<T> {
33
415
        pub x0: T,
34
415
        pub y0: T,
35
415
        pub x1: T,
36
415
        pub y1: T,
37
    }
38

            
39
    impl<T> Rect<T> {
40
        #[inline]
41
4281506
        pub fn new(x0: T, y0: T, x1: T, y1: T) -> Self {
42
4281506
            Self { x0, y0, x1, y1 }
43
4281506
        }
44
    }
45

            
46
    impl<T> Rect<T>
47
    where
48
        T: Copy + PartialOrd + PartialEq + Add<T, Output = T> + Sub<T, Output = T> + Zero,
49
    {
50
        #[inline]
51
55006
        pub fn from_size(w: T, h: T) -> Self {
52
55006
            Self {
53
55006
                x0: Zero::zero(),
54
55006
                y0: Zero::zero(),
55
                x1: w,
56
                y1: h,
57
            }
58
55006
        }
59

            
60
        #[inline]
61
2351942
        pub fn width(&self) -> T {
62
2351942
            self.x1 - self.x0
63
2351942
        }
64

            
65
        #[inline]
66
2031530
        pub fn height(&self) -> T {
67
2031530
            self.y1 - self.y0
68
2031530
        }
69

            
70
        #[inline]
71
3120
        pub fn size(&self) -> (T, T) {
72
3120
            (self.width(), self.height())
73
3120
        }
74

            
75
        #[inline]
76
1059
        pub fn x_range(&self) -> Range<T> {
77
1059
            self.x0..self.x1
78
1059
        }
79

            
80
        #[inline]
81
19
        pub fn y_range(&self) -> Range<T> {
82
19
            self.y0..self.y1
83
19
        }
84

            
85
        #[inline]
86
3852227
        pub fn contains(self, x: T, y: T) -> bool {
87
3852227
            x >= self.x0 && x < self.x1 && y >= self.y0 && y < self.y1
88
3852227
        }
89

            
90
        #[inline]
91
2179
        pub fn translate(&self, by: (T, T)) -> Self {
92
2179
            Self {
93
2179
                x0: self.x0 + by.0,
94
2179
                y0: self.y0 + by.1,
95
2179
                x1: self.x1 + by.0,
96
2179
                y1: self.y1 + by.1,
97
            }
98
2179
        }
99

            
100
        #[inline]
101
741
        pub fn intersection(&self, rect: &Self) -> Option<Self> {
102
741
            let (x0, y0, x1, y1) = (
103
741
                max(self.x0, rect.x0),
104
741
                max(self.y0, rect.y0),
105
741
                min(self.x1, rect.x1),
106
741
                min(self.y1, rect.y1),
107
            );
108

            
109
741
            if x1 > x0 && y1 > y0 {
110
737
                Some(Self { x0, y0, x1, y1 })
111
            } else {
112
4
                None
113
            }
114
741
        }
115

            
116
        #[inline]
117
1853173
        pub fn union(&self, rect: &Self) -> Self {
118
1853173
            Self {
119
1853173
                x0: min(self.x0, rect.x0),
120
1853173
                y0: min(self.y0, rect.y0),
121
1853173
                x1: max(self.x1, rect.x1),
122
1853173
                y1: max(self.y1, rect.y1),
123
            }
124
1853173
        }
125
    }
126

            
127
    impl Rect<i32> {
128
        #[inline]
129
3
        pub fn is_empty(&self) -> bool {
130
            // Give an explicit type to the right hand side of the ==, since sometimes
131
            // type inference fails to figure it out.  I have no idea why.
132
3
            self.width() == <i32 as Zero>::zero() || self.height() == <i32 as Zero>::zero()
133
3
        }
134

            
135
        #[inline]
136
5
        pub fn scale(self, x: f64, y: f64) -> Self {
137
5
            Self {
138
5
                x0: (f64::from(self.x0) * x).floor() as i32,
139
5
                y0: (f64::from(self.y0) * y).floor() as i32,
140
5
                x1: (f64::from(self.x1) * x).ceil() as i32,
141
5
                y1: (f64::from(self.y1) * y).ceil() as i32,
142
            }
143
5
        }
144
    }
145

            
146
    impl Rect<f64> {
147
        #[inline]
148
503033
        pub fn is_empty(&self) -> bool {
149
503033
            self.width().approx_eq_cairo(0.0) || self.height().approx_eq_cairo(0.0)
150
503033
        }
151

            
152
        #[inline]
153
        pub fn scale(self, x: f64, y: f64) -> Self {
154
            Self {
155
                x0: self.x0 * x,
156
                y0: self.y0 * y,
157
                x1: self.x1 * x,
158
                y1: self.y1 * y,
159
            }
160
        }
161

            
162
54
        pub fn approx_eq(&self, other: &Self) -> bool {
163
            // FIXME: this is super fishy; shouldn't we be using 2x the epsilon against the width/height
164
            // instead of the raw coordinates?
165
54
            approx_eq!(f64, self.x0, other.x0, epsilon = 0.0001)
166
54
                && approx_eq!(f64, self.y0, other.y0, epsilon = 0.0001)
167
54
                && approx_eq!(f64, self.x1, other.x1, epsilon = 0.0001)
168
54
                && approx_eq!(f64, self.y1, other.y1, epsilon = 0.00012)
169
54
        }
170
    }
171
}
172

            
173
pub type Rect = rect::Rect<f64>;
174

            
175
impl From<Rect> for IRect {
176
    #[inline]
177
689
    fn from(r: Rect) -> Self {
178
689
        Self {
179
689
            x0: r.x0.floor() as i32,
180
689
            y0: r.y0.floor() as i32,
181
689
            x1: r.x1.ceil() as i32,
182
689
            y1: r.y1.ceil() as i32,
183
        }
184
689
    }
185
}
186

            
187
impl From<cairo::Rectangle> for Rect {
188
    #[inline]
189
1148
    fn from(r: cairo::Rectangle) -> Self {
190
1148
        Self {
191
1148
            x0: r.x(),
192
1148
            y0: r.y(),
193
1148
            x1: r.x() + r.width(),
194
1148
            y1: r.y() + r.height(),
195
        }
196
1148
    }
197
}
198

            
199
impl From<Rect> for cairo::Rectangle {
200
    #[inline]
201
677
    fn from(r: Rect) -> Self {
202
677
        Self::new(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0)
203
677
    }
204
}
205

            
206
/// Creates a transform to map to a rectangle.
207
///
208
/// The rectangle is an `Option<Rect>` to indicate the possibility that there is no
209
/// bounding box from where the rectangle could be obtained.
210
///
211
/// This depends on a `CoordUnits` parameter.  When this is
212
/// `CoordUnits::ObjectBoundingBox`, the bounding box must not be empty, since the calling
213
/// code would then not have a usable size to work with.  In that case, if the bbox is
214
/// empty, this function returns `Err(())`.
215
///
216
/// Usually calling code can simply ignore the action it was about to take if this
217
/// function returns an error.
218
243
pub fn rect_to_transform(rect: &Option<Rect>, units: CoordUnits) -> Result<Transform, ()> {
219
243
    match units {
220
146
        CoordUnits::UserSpaceOnUse => Ok(Transform::identity()),
221
        CoordUnits::ObjectBoundingBox => {
222
189
            if rect.as_ref().map_or(true, |r| r.is_empty()) {
223
5
                Err(())
224
            } else {
225
92
                let r = rect.as_ref().unwrap();
226
92
                let t = Transform::new_unchecked(r.width(), 0.0, 0.0, r.height(), r.x0, r.y0);
227

            
228
92
                if t.is_invertible() {
229
92
                    Ok(t)
230
                } else {
231
                    Err(())
232
                }
233
            }
234
        }
235
    }
236
243
}
237

            
238
pub type IRect = rect::Rect<i32>;
239

            
240
impl From<IRect> for Rect {
241
    #[inline]
242
115
    fn from(r: IRect) -> Self {
243
115
        Self {
244
115
            x0: f64::from(r.x0),
245
115
            y0: f64::from(r.y0),
246
115
            x1: f64::from(r.x1),
247
115
            y1: f64::from(r.y1),
248
        }
249
115
    }
250
}
251

            
252
impl From<cairo::Rectangle> for IRect {
253
    #[inline]
254
    fn from(r: cairo::Rectangle) -> Self {
255
        Self {
256
            x0: r.x().floor() as i32,
257
            y0: r.y().floor() as i32,
258
            x1: (r.x() + r.width()).ceil() as i32,
259
            y1: (r.y() + r.height()).ceil() as i32,
260
        }
261
    }
262
}
263

            
264
impl From<IRect> for cairo::Rectangle {
265
    #[inline]
266
167
    fn from(r: IRect) -> Self {
267
167
        Self::new(
268
167
            f64::from(r.x0),
269
167
            f64::from(r.y0),
270
167
            f64::from(r.x1 - r.x0),
271
167
            f64::from(r.y1 - r.y0),
272
        )
273
167
    }
274
}