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