Skip to main content

crabshell_ui/
geometry.rs

1//! Points, sizes and rectangles. Every unit is a logical pixel; the renderer
2//! multiplies by the output's scale.
3
4/// A point in logical pixels, measured from the window's top-left corner.
5#[derive(Clone, Copy, Debug, Default, PartialEq)]
6pub struct Point {
7  /// Distance from the left edge.
8  pub x: f32,
9  /// Distance from the top edge.
10  pub y: f32,
11}
12
13impl Point {
14  /// A point at `x`, `y`.
15  pub const fn new(x: f32, y: f32) -> Point {
16    Point { x, y }
17  }
18}
19
20/// A width and height in logical pixels.
21#[derive(Clone, Copy, Debug, Default, PartialEq)]
22pub struct Size {
23  /// The width.
24  pub width: f32,
25  /// The height.
26  pub height: f32,
27}
28
29impl Size {
30  /// A size of `width` by `height`.
31  pub const fn new(width: f32, height: f32) -> Size {
32    Size { width, height }
33  }
34}
35
36/// A rectangle in logical pixels: its top-left corner and its size.
37#[derive(Clone, Copy, Debug, Default, PartialEq)]
38pub struct Rect {
39  /// The left edge.
40  pub x: f32,
41  /// The top edge.
42  pub y: f32,
43  /// The width.
44  pub width: f32,
45  /// The height.
46  pub height: f32,
47}
48
49impl Rect {
50  /// A rectangle with its top-left corner at `x`, `y`.
51  pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Rect {
52    Rect {
53      x,
54      y,
55      width,
56      height,
57    }
58  }
59
60  /// The right edge.
61  pub fn right(&self) -> f32 {
62    self.x + self.width
63  }
64
65  /// The bottom edge.
66  pub fn bottom(&self) -> f32 {
67    self.y + self.height
68  }
69
70  /// Whether the rectangle covers no area.
71  pub fn is_empty(&self) -> bool {
72    self.width <= 0.0 || self.height <= 0.0
73  }
74
75  /// Whether `point` lies inside. The left and top edges count as inside,
76  /// the right and bottom edges don't, so two rectangles that touch never
77  /// both contain a point.
78  pub fn contains(&self, point: Point) -> bool {
79    point.x >= self.x && point.x < self.right() && point.y >= self.y && point.y < self.bottom()
80  }
81
82  /// The smallest rectangle that covers both. An empty rectangle adds
83  /// nothing.
84  pub fn union(&self, other: Rect) -> Rect {
85    if other.is_empty() {
86      return *self;
87    }
88    if self.is_empty() {
89      return other;
90    }
91    let x = self.x.min(other.x);
92    let y = self.y.min(other.y);
93    Rect::new(
94      x,
95      y,
96      self.right().max(other.right()) - x,
97      self.bottom().max(other.bottom()) - y,
98    )
99  }
100}