Skip to main content

crabshell_ui/
region.rs

1//! [`Region`], the part of a window that takes pointer input.
2
3/// An area of a window in logical pixels, built from rectangles, rounded
4/// rectangles and ellipses joined with [`union`](Self::union),
5/// [`subtract`](Self::subtract), [`intersect`](Self::intersect) and
6/// [`xor`](Self::xor), applied in the order they are called.
7///
8/// [`PanelWindow::mask`](crate::PanelWindow::mask) takes one: pointer
9/// input outside it goes to whatever is below the window.
10///
11/// ```
12/// use crabshell_ui::Region;
13///
14/// // A 200 by 30 bar that only takes clicks at its two rounded ends.
15/// let ends = Region::rect(0, 0, 40, 30)
16///     .radius(8.0)
17///     .union(Region::rect(160, 0, 40, 30).radius(8.0));
18/// ```
19#[derive(Clone, Debug, PartialEq)]
20pub struct Region {
21  shape: Shape,
22  ops: Vec<(Op, Region)>,
23}
24
25#[derive(Clone, Debug, PartialEq)]
26enum Shape {
27  Empty,
28  /// Corner radii clockwise from the top left.
29  Rect([i32; 4], [f32; 4]),
30  Ellipse([i32; 4]),
31}
32
33#[derive(Clone, Copy, Debug, PartialEq)]
34enum Op {
35  Add,
36  Subtract,
37  Intersect,
38  Xor,
39}
40
41/// One row's covered columns: sorted, disjoint, half-open `(start, end)`.
42type Spans = Vec<(i32, i32)>;
43
44impl Region {
45  /// No area at all: a window masked with it lets every click through.
46  pub fn empty() -> Region {
47    Region {
48      shape: Shape::Empty,
49      ops: Vec::new(),
50    }
51  }
52
53  /// The rectangle at `x`, `y`, relative to the window's top left.
54  pub fn rect(x: i32, y: i32, width: u32, height: u32) -> Region {
55    Region {
56      shape: Shape::Rect(bounds(x, y, width, height), [0.0; 4]),
57      ops: Vec::new(),
58    }
59  }
60
61  /// The ellipse that fills the rectangle at `x`, `y`.
62  pub fn ellipse(x: i32, y: i32, width: u32, height: u32) -> Region {
63    Region {
64      shape: Shape::Ellipse(bounds(x, y, width, height)),
65      ops: Vec::new(),
66    }
67  }
68
69  /// Rounds every corner of a [`rect`](Self::rect). It does nothing to
70  /// other shapes.
71  pub fn radius(self, radius: f32) -> Region {
72    self.radii(radius, radius, radius, radius)
73  }
74
75  /// Rounds each corner of a [`rect`](Self::rect) on its own, fitted to
76  /// it as a widget's are ([`Radii::fit`](crate::Radii::fit)). It does
77  /// nothing to other shapes.
78  pub fn radii(
79    mut self,
80    top_left: f32,
81    top_right: f32,
82    bottom_right: f32,
83    bottom_left: f32,
84  ) -> Region {
85    if let Shape::Rect(_, radii) = &mut self.shape {
86      *radii = [top_left, top_right, bottom_right, bottom_left];
87    }
88    self
89  }
90
91  /// Adds `other`'s area.
92  pub fn union(self, other: Region) -> Region {
93    self.then(Op::Add, other)
94  }
95
96  /// Removes `other`'s area.
97  pub fn subtract(self, other: Region) -> Region {
98    self.then(Op::Subtract, other)
99  }
100
101  /// Keeps only the area also in `other`.
102  pub fn intersect(self, other: Region) -> Region {
103    self.then(Op::Intersect, other)
104  }
105
106  /// Keeps the area in exactly one of the two.
107  pub fn xor(self, other: Region) -> Region {
108    self.then(Op::Xor, other)
109  }
110
111  fn then(mut self, op: Op, other: Region) -> Region {
112    self.ops.push((op, other));
113    self
114  }
115
116  /// The region inside a `width` by `height` window as rectangles
117  /// `[x, y, width, height]`, which don't overlap. Curves are followed to
118  /// the nearest whole pixel at each row's center.
119  pub fn rects(&self, width: u32, height: u32) -> Vec<[i32; 4]> {
120    let width = i32::try_from(width).unwrap_or(i32::MAX);
121    let height = i32::try_from(height).unwrap_or(i32::MAX);
122    let mut rects = Vec::new();
123    // Rows with the same spans as the row above grow its rectangles.
124    let mut band: Option<(i32, Spans)> = None;
125    for y in 0..=height {
126      let spans = if y < height {
127        clip(self.spans(y as f32 + 0.5), width)
128      } else {
129        Spans::new()
130      };
131      if band.as_ref().is_some_and(|(_, above)| *above == spans) {
132        continue;
133      }
134      if let Some((top, above)) = band.take() {
135        rects.extend(
136          above
137            .iter()
138            .map(|&(start, end)| [start, top, end - start, y - top]),
139        );
140      }
141      band = Some((y, spans));
142    }
143    rects
144  }
145
146  /// The columns covered on the row whose center is at `y`.
147  fn spans(&self, y: f32) -> Spans {
148    let mut spans = match self.shape {
149      Shape::Empty => Spans::new(),
150      Shape::Rect(rect, radii) => rect_spans(rect, radii, y),
151      Shape::Ellipse(rect) => ellipse_spans(rect, y),
152    };
153    for (op, other) in &self.ops {
154      let keep = match op {
155        Op::Add => |a, b| a || b,
156        Op::Subtract => |a, b: bool| a && !b,
157        Op::Intersect => |a, b| a && b,
158        Op::Xor => |a, b| a != b,
159      };
160      spans = combine(&spans, &other.spans(y), keep);
161    }
162    spans
163  }
164}
165
166/// `[left, top, right, bottom]`, saturating instead of overflowing.
167fn bounds(x: i32, y: i32, width: u32, height: u32) -> [i32; 4] {
168  let side = |side: u32| i32::try_from(side).unwrap_or(i32::MAX);
169  [
170    x,
171    y,
172    x.saturating_add(side(width)),
173    y.saturating_add(side(height)),
174  ]
175}
176
177fn rect_spans([left, top, right, bottom]: [i32; 4], radii: [f32; 4], y: f32) -> Spans {
178  if y < top as f32 || y >= bottom as f32 {
179    return Spans::new();
180  }
181  let (width, height) = (right as f32 - left as f32, bottom as f32 - top as f32);
182  let [top_left, top_right, bottom_right, bottom_left] =
183    crate::style::fit_corners(radii, width, height);
184  // How far a corner of radius `r` cuts into a row `dy` inside its edge.
185  let inset = |r: f32, dy: f32| {
186    if dy >= r {
187      0.0
188    } else {
189      r - (r * r - (r - dy) * (r - dy)).sqrt()
190    }
191  };
192  let (from_top, from_bottom) = (y - top as f32, bottom as f32 - y);
193  let left_inset = inset(top_left, from_top).max(inset(bottom_left, from_bottom));
194  let right_inset = inset(top_right, from_top).max(inset(bottom_right, from_bottom));
195  span(left as f32 + left_inset, right as f32 - right_inset)
196}
197
198fn ellipse_spans([left, top, right, bottom]: [i32; 4], y: f32) -> Spans {
199  let rx = (right as f32 - left as f32) / 2.0;
200  let ry = (bottom as f32 - top as f32) / 2.0;
201  if rx <= 0.0 || ry <= 0.0 {
202    return Spans::new();
203  }
204  let t = (y - (top as f32 + ry)) / ry;
205  if t.abs() >= 1.0 {
206    return Spans::new();
207  }
208  let (cx, dx) = (left as f32 + rx, rx * (1.0 - t * t).sqrt());
209  span(cx - dx, cx + dx)
210}
211
212/// The columns from `start` to `end`, rounded to whole pixels.
213fn span(start: f32, end: f32) -> Spans {
214  let (start, end) = (start.round() as i32, end.round() as i32);
215  if start < end {
216    vec![(start, end)]
217  } else {
218    Spans::new()
219  }
220}
221
222/// `spans` cut to the columns from 0 to `width`.
223fn clip(spans: Spans, width: i32) -> Spans {
224  spans
225    .into_iter()
226    .map(|(start, end)| (start.max(0), end.min(width)))
227    .filter(|(start, end)| start < end)
228    .collect()
229}
230
231/// The columns where `keep` holds for whether they are in `a` and in `b`.
232fn combine(a: &[(i32, i32)], b: &[(i32, i32)], keep: fn(bool, bool) -> bool) -> Spans {
233  let mut edges: Vec<i32> = a
234    .iter()
235    .chain(b)
236    .flat_map(|&(start, end)| [start, end])
237    .collect();
238  edges.sort_unstable();
239  edges.dedup();
240  let inside =
241    |spans: &[(i32, i32)], x: i32| spans.iter().any(|&(start, end)| start <= x && x < end);
242  let mut out = Spans::new();
243  for pair in edges.windows(2) {
244    let (start, end) = (pair[0], pair[1]);
245    if !keep(inside(a, start), inside(b, start)) {
246      continue;
247    }
248    match out.last_mut() {
249      Some(last) if last.1 == start => last.1 = end,
250      _ => out.push((start, end)),
251    }
252  }
253  out
254}