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
//! Defines the [PdfRect] struct, a rectangle measured in [PdfPoints].

use crate::bindgen::{FPDF_BOOL, FS_RECTF};
use crate::bindings::PdfiumLibraryBindings;
use crate::error::{PdfiumError, PdfiumInternalError};
use crate::matrix::PdfMatrix;
use crate::points::PdfPoints;
use iter_tools::{max, min};
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};

/// A rectangle measured in [PdfPoints].
///
/// The coordinate space of a `PdfPage` has its origin (0,0) at the bottom left of the page,
/// with x values increasing as coordinates move horizontally to the right and
/// y values increasing as coordinates move vertically up.
#[derive(Debug, Copy, Clone)]
pub struct PdfRect {
    pub bottom: PdfPoints,
    pub left: PdfPoints,
    pub top: PdfPoints,
    pub right: PdfPoints,
}

impl PdfRect {
    /// A [PdfRect] object with the identity value (0.0, 0.0, 0.0, 0.0).
    pub const ZERO: PdfRect = PdfRect::zero();

    /// A [PdfRect] object that encloses the entire addressable `PdfPage` coordinate space of
    /// ([-PdfPoints::MAX], [-PdfPoints::MAX], [PdfPoints::MAX], [PdfPoints::MAX]).
    pub const MAX: PdfRect = PdfRect::new(
        PdfPoints::MIN,
        PdfPoints::MIN,
        PdfPoints::MAX,
        PdfPoints::MAX,
    );

    #[inline]
    pub(crate) fn from_pdfium(rect: FS_RECTF) -> Self {
        Self {
            bottom: PdfPoints::new(rect.bottom),
            left: PdfPoints::new(rect.left),
            top: PdfPoints::new(rect.top),
            right: PdfPoints::new(rect.right),
        }
    }

    #[inline]
    pub(crate) fn from_pdfium_as_result(
        result: FPDF_BOOL,
        rect: FS_RECTF,
        bindings: &dyn PdfiumLibraryBindings,
    ) -> Result<PdfRect, PdfiumError> {
        if !bindings.is_true(result) {
            Err(PdfiumError::PdfiumLibraryInternalError(
                PdfiumInternalError::Unknown,
            ))
        } else {
            Ok(PdfRect::from_pdfium(rect))
        }
    }

    /// Creates a new [PdfRect] from the given [PdfPoints] measurements.
    ///
    /// The coordinate space of a `PdfPage` has its origin (0,0) at the bottom left of the page,
    /// with x values increasing as coordinates move horizontally to the right and
    /// y values increasing as coordinates move vertically up.
    #[inline]
    pub const fn new(bottom: PdfPoints, left: PdfPoints, top: PdfPoints, right: PdfPoints) -> Self {
        Self {
            bottom,
            left,
            top,
            right,
        }
    }

    /// Creates a new [PdfRect] from the given raw points values.
    ///
    /// The coordinate space of a `PdfPage` has its origin (0,0) at the bottom left of the page,
    /// with x values increasing as coordinates move horizontally to the right and
    /// y values increasing as coordinates move vertically up.
    #[inline]
    pub const fn new_from_values(bottom: f32, left: f32, top: f32, right: f32) -> Self {
        Self::new(
            PdfPoints::new(bottom),
            PdfPoints::new(left),
            PdfPoints::new(top),
            PdfPoints::new(right),
        )
    }

    /// Creates a new [PdfRect] object with all values set to 0.0.
    ///
    /// Consider using the compile-time constant value [PdfRect::ZERO]
    /// rather than calling this function directly.
    #[inline]
    pub const fn zero() -> Self {
        Self::new_from_values(0.0, 0.0, 0.0, 0.0)
    }

    /// Returns the width of this [PdfRect].
    #[inline]
    pub fn width(&self) -> PdfPoints {
        self.right - self.left
    }

    /// Returns the height of this [PdfRect].
    #[inline]
    pub fn height(&self) -> PdfPoints {
        self.top - self.bottom
    }

    #[inline]
    /// Returns `true` if the given point lies inside this [PdfRect].
    pub fn contains(&self, x: PdfPoints, y: PdfPoints) -> bool {
        self.contains_x(x) && self.contains_y(y)
    }

    #[inline]
    /// Returns `true` if the given horizontal coordinate lies inside this [PdfRect].
    pub fn contains_x(&self, x: PdfPoints) -> bool {
        self.left <= x && self.right >= x
    }

    #[inline]
    /// Returns `true` if the given vertical coordinate lies inside this [PdfRect].
    pub fn contains_y(&self, y: PdfPoints) -> bool {
        self.bottom <= y && self.top >= y
    }

    /// Returns `true` if the bounds of this [PdfRect] lie entirely within the given rectangle.
    #[inline]
    pub fn is_inside(&self, other: &PdfRect) -> bool {
        self.left >= other.left
            && self.right <= other.right
            && self.top <= other.top
            && self.bottom >= other.bottom
    }

    /// Returns `true` if the bounds of this [PdfRect] lie at least partially within
    /// the given rectangle.
    #[inline]
    pub fn does_overlap(&self, other: &PdfRect) -> bool {
        // As per https://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other

        self.left < other.right
            && self.right > other.left
            && self.top > other.bottom
            && self.bottom < other.top
    }

    /// Returns the result of applying the given [PdfMatrix] to each corner point of this [PdfRect].
    #[inline]
    pub fn transform(&self, matrix: PdfMatrix) -> PdfRect {
        let (x1, y1) = matrix.apply_to_points(self.left, self.top);
        let (x2, y2) = matrix.apply_to_points(self.left, self.bottom);
        let (x3, y3) = matrix.apply_to_points(self.right, self.top);
        let (x4, y4) = matrix.apply_to_points(self.right, self.bottom);

        PdfRect::new(
            min([y1, y2, y3, y4]).unwrap_or(PdfPoints::ZERO),
            min([x1, x2, x3, x4]).unwrap_or(PdfPoints::ZERO),
            max([y1, y2, y3, y4]).unwrap_or(PdfPoints::ZERO),
            max([x1, x2, x3, x4]).unwrap_or(PdfPoints::ZERO),
        )
    }

    #[inline]
    pub(crate) fn as_pdfium(&self) -> FS_RECTF {
        FS_RECTF {
            left: self.left.value,
            top: self.top.value,
            right: self.right.value,
            bottom: self.bottom.value,
        }
    }
}

// We could derive PartialEq automatically, but it's good practice to implement PartialEq
// by hand when implementing Hash.

impl PartialEq for PdfRect {
    fn eq(&self, other: &Self) -> bool {
        self.bottom == other.bottom
            && self.left == other.left
            && self.top == other.top
            && self.right == other.right
    }
}

// The f32 values inside PdfRect will never be NaN or Infinity, so these implementations
// of Eq and Hash are safe.

impl Eq for PdfRect {}

impl Hash for PdfRect {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u32(self.bottom.value.to_bits());
        state.write_u32(self.left.value.to_bits());
        state.write_u32(self.top.value.to_bits());
        state.write_u32(self.right.value.to_bits());
    }
}

impl Display for PdfRect {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "PdfRect(bottom: {}, left: {}, top: {}, right: {}",
            self.bottom.value, self.left.value, self.top.value, self.right.value
        ))
    }
}

#[cfg(test)]
mod tests {
    use crate::matrix::PdfMatrix;
    use crate::points::PdfPoints;
    use crate::rect::PdfRect;

    #[test]
    fn test_rect_is_inside() {
        assert!(PdfRect::new_from_values(3.0, 3.0, 9.0, 9.0)
            .is_inside(&PdfRect::new_from_values(2.0, 2.0, 10.0, 10.0)));

        assert!(!PdfRect::new_from_values(2.0, 2.0, 10.0, 10.0)
            .is_inside(&PdfRect::new_from_values(3.0, 3.0, 9.0, 9.0)));

        assert!(!PdfRect::new_from_values(2.0, 2.0, 7.0, 7.0)
            .is_inside(&PdfRect::new_from_values(5.0, 4.0, 10.0, 10.0)));

        assert!(!PdfRect::new_from_values(2.0, 2.0, 7.0, 7.0)
            .is_inside(&PdfRect::new_from_values(8.0, 4.0, 10.0, 10.0)));

        assert!(!PdfRect::new_from_values(2.0, 2.0, 7.0, 7.0)
            .is_inside(&PdfRect::new_from_values(5.0, 8.0, 10.0, 10.0)));
    }

    #[test]
    fn test_rect_does_overlap() {
        assert!(PdfRect::new_from_values(2.0, 2.0, 7.0, 7.0)
            .does_overlap(&PdfRect::new_from_values(5.0, 4.0, 10.0, 10.0)));

        assert!(!PdfRect::new_from_values(2.0, 2.0, 7.0, 7.0)
            .does_overlap(&PdfRect::new_from_values(8.0, 4.0, 10.0, 10.0)));

        assert!(!PdfRect::new_from_values(2.0, 2.0, 7.0, 7.0)
            .does_overlap(&PdfRect::new_from_values(5.0, 8.0, 10.0, 10.0)));
    }

    #[test]
    fn test_transform_rect() {
        let delta_x = PdfPoints::new(50.0);
        let delta_y = PdfPoints::new(-25.0);

        let matrix = PdfMatrix::identity().translate(delta_x, delta_y).unwrap();

        let bottom = PdfPoints::new(100.0);
        let top = PdfPoints::new(200.0);
        let left = PdfPoints::new(300.0);
        let right = PdfPoints::new(400.0);

        let rect = PdfRect::new(bottom, left, top, right);

        let result = rect.transform(matrix);

        assert_eq!(result.bottom, bottom + delta_y);
        assert_eq!(result.top, top + delta_y);
        assert_eq!(result.left, left + delta_x);
        assert_eq!(result.right, right + delta_x);
    }
}