1#[derive(Debug, Clone, Copy, PartialEq, Default)]
6pub struct Rect {
7 pub x: f64,
9 pub y: f64,
11 pub width: f64,
13 pub height: f64,
15}
16
17impl Rect {
18 pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
20 Self { x, y, width, height }
21 }
22
23 pub fn is_empty(&self) -> bool {
25 self.width <= 0.0 || self.height <= 0.0
26 }
27
28 pub fn intersection(&self, other: &Rect) -> Option<Rect> {
30 let x0 = self.x.max(other.x);
31 let y0 = self.y.max(other.y);
32 let x1 = (self.x + self.width).min(other.x + other.width);
33 let y1 = (self.y + self.height).min(other.y + other.height);
34 (x1 > x0 && y1 > y0).then(|| Rect::new(x0, y0, x1 - x0, y1 - y0))
35 }
36
37 pub fn snapped(&self, scale: f64) -> Rect {
42 let snap = |v: f64| (v * scale).round() / scale;
43 let (x0, y0) = (snap(self.x), snap(self.y));
44 Rect::new(x0, y0, snap(self.x + self.width) - x0, snap(self.y + self.height) - y0)
45 }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct Frames {
52 pub clip: Rect,
54 pub view: Rect,
56}
57
58pub fn frames(bounds: Rect, visible: Rect, scale: f64, content_height: f64, content_flipped: bool) -> Frames {
62 let v = visible.snapped(scale);
63 let b = bounds.snapped(scale);
64 let clip_y = if content_flipped { v.y } else { content_height - v.y - v.height };
65 Frames {
66 clip: Rect::new(v.x, clip_y, v.width, v.height),
67 view: Rect::new(b.x - v.x, b.y - v.y, b.width, b.height),
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn snapping_keeps_edges_on_the_grid() {
77 let r = Rect::new(265.43, 407.40, 120.5, 40.0).snapped(2.0);
78 assert_eq!(r, Rect::new(265.5, 407.5, 120.5, 40.0));
79 let r = Rect::new(265.43, 407.40, 120.5, 40.0).snapped(1.0);
80 assert_eq!(r, Rect::new(265.0, 407.0, 121.0, 40.0));
81 }
82
83 #[test]
84 fn adjacent_rects_stay_adjacent() {
85 let a = Rect::new(10.3, 0.0, 99.25, 10.0).snapped(1.0);
86 let b = Rect::new(109.55, 0.0, 50.0, 10.0).snapped(1.0);
87 assert_eq!(a.x + a.width, b.x);
88 }
89
90 #[test]
91 fn unflipped_content_measures_from_the_bottom() {
92 let f = frames(Rect::new(10.0, 20.0, 100.0, 50.0), Rect::new(10.0, 20.0, 100.0, 50.0), 2.0, 600.0, false);
93 assert_eq!(f.clip, Rect::new(10.0, 530.0, 100.0, 50.0));
94 assert_eq!(f.view, Rect::new(0.0, 0.0, 100.0, 50.0));
95 }
96
97 #[test]
98 fn clipped_view_is_offset_inside_its_container() {
99 let f = frames(Rect::new(0.0, -30.0, 200.0, 100.0), Rect::new(0.0, 0.0, 200.0, 70.0), 2.0, 600.0, true);
101 assert_eq!(f.clip, Rect::new(0.0, 0.0, 200.0, 70.0));
102 assert_eq!(f.view, Rect::new(0.0, -30.0, 200.0, 100.0));
103 }
104}