tvision_rs/view/geometry.rs
1//! `Point` and `Rect` (documented on `Rect`).
2
3use std::ops::{Add, AddAssign, Sub, SubAssign};
4
5/// A screen coordinate pair `(x, y)`.
6///
7/// Use `Point` wherever you need a column/row position: view origins, cursor
8/// positions, mouse hit coordinates, or scroll offsets. Both fields are `i32`
9/// because view origins go negative when a view is scrolled offscreen, and
10/// translation deltas are frequently negative. Conversion to an unsigned buffer
11/// index happens only at the screen boundary.
12///
13/// `Point` supports all four arithmetic operators (`+`, `-`, `+=`, `-=`) so
14/// you can translate positions and compute offsets without converting to tuples:
15///
16/// ```
17/// # use tvision_rs::Point;
18/// let origin = Point::new(5, 3);
19/// let offset = Point::new(-2, 1);
20/// assert_eq!(origin + offset, Point::new(3, 4));
21/// ```
22///
23/// `Default` returns `Point::new(0, 0)`.
24///
25/// # Turbo Vision heritage
26/// Ports `TPoint` from `objects.h`. Field names are lowercase (`x`, `y`)
27/// following Rust conventions; the original used uppercase `X`/`Y`.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub struct Point {
30 /// Screen column (horizontal position).
31 ///
32 /// Zero is the leftmost column. Negative values occur when a view's origin
33 /// is scrolled to the left of the visible area. Write this field directly
34 /// when constructing geometry; use `Point::new` to set both axes at once.
35 pub x: i32,
36 /// Screen row (vertical position).
37 ///
38 /// Zero is the topmost row. Negative values occur when a view's origin is
39 /// scrolled above the visible area. Write this field directly when
40 /// constructing geometry; use `Point::new` to set both axes at once.
41 pub y: i32,
42}
43
44impl Point {
45 /// Construct a point from a column `x` and row `y`.
46 ///
47 /// This is a `const fn`, so it can be used in `const` and `static`
48 /// contexts. For the zero point, `Default::default()` (or
49 /// `Point::default()`) is equivalent and more expressive.
50 ///
51 /// ```
52 /// # use tvision_rs::Point;
53 /// const ORIGIN: Point = Point::new(0, 0);
54 /// assert_eq!(ORIGIN, Point::default());
55 /// ```
56 pub const fn new(x: i32, y: i32) -> Self {
57 Point { x, y }
58 }
59}
60
61impl Add for Point {
62 type Output = Point;
63 /// Returns a new `Point` with both axes summed.
64 ///
65 /// Use this to apply an offset to a position without mutating the original:
66 /// `child_origin + scroll_offset`.
67 fn add(self, rhs: Point) -> Point {
68 Point::new(self.x + rhs.x, self.y + rhs.y)
69 }
70}
71
72impl Sub for Point {
73 type Output = Point;
74 /// Returns a new `Point` with both axes subtracted.
75 ///
76 /// Use this to compute the offset between two positions:
77 /// `mouse_pos - view_origin` gives the hit position in view-local
78 /// coordinates.
79 fn sub(self, rhs: Point) -> Point {
80 Point::new(self.x - rhs.x, self.y - rhs.y)
81 }
82}
83
84impl AddAssign for Point {
85 /// Shifts this point in place by adding `rhs`.
86 ///
87 /// Use this to accumulate translation steps without allocating a new
88 /// `Point`: `cursor += delta`.
89 fn add_assign(&mut self, rhs: Point) {
90 self.x += rhs.x;
91 self.y += rhs.y;
92 }
93}
94
95impl SubAssign for Point {
96 /// Shifts this point in place by subtracting `rhs`.
97 ///
98 /// Use this to undo a previously applied offset in place:
99 /// `cursor -= delta`.
100 fn sub_assign(&mut self, rhs: Point) {
101 self.x -= rhs.x;
102 self.y -= rhs.y;
103 }
104}
105
106/// A rectangle defined by its top-left corner `a` (inclusive) and bottom-right
107/// corner `b` (exclusive).
108///
109/// Geometry primitives: [`Point`] and [`Rect`].
110///
111/// Coordinates are `i32`. Signed is required: view origins go negative when
112/// scrolled offscreen, and the translate/inflate operations take negative deltas.
113/// Conversion to the unsigned buffer index space happens at the screen boundary.
114///
115/// ### Keyword-collision renames
116/// Two [`Rect`] methods would collide with Rust keywords, so they use raw
117/// identifiers: `Rect::r#move` (translate) and `Rect::r#union` (bounding box).
118/// Call sites read `rect.r#move(1, 2)` / `rect.r#union(&other)`.
119///
120/// The half-open convention (`[a, b)`) means `b` is one cell past the last
121/// occupied column/row — the same model used by Rust ranges and ratatui.
122/// The width is `b.x - a.x`; the height is `b.y - a.y`.
123///
124/// The mutating methods take `&mut self` and return `&mut Self`, so they chain
125/// and operate in place:
126///
127/// ```
128/// # use tvision_rs::{Point, Rect};
129/// let mut r = Rect::new(0, 0, 10, 10);
130/// r.grow(-1, -1).r#move(1, 1);
131/// assert_eq!(r, Rect::new(2, 2, 10, 10));
132/// ```
133///
134/// # Turbo Vision heritage
135///
136/// Ports `TPoint`/`TRect` (`objects.h`). The mutating methods return `&mut Self`
137/// to mirror the original `TRect&` chaining idiom.
138///
139/// Ports `TRect` from `objects.h`. The two raw-identifier methods
140/// `r#move` and `r#union` use raw identifiers
141/// to avoid collisions with the Rust keywords `move` and `union`.
142#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
143pub struct Rect {
144 /// Top-left corner of the rectangle (inclusive).
145 ///
146 /// `a` is the first cell that belongs to the rectangle. Both `a.x` and
147 /// `a.y` are included in [`contains`](Rect::contains) tests. You may read
148 /// or write this field directly; if you set `a > b` the rectangle becomes
149 /// empty (see [`is_empty`](Rect::is_empty)) but is otherwise valid.
150 pub a: Point,
151 /// Bottom-right corner of the rectangle (exclusive).
152 ///
153 /// `b` is one cell past the last occupied column (`b.x`) and the last
154 /// occupied row (`b.y`). The rectangle width is `b.x - a.x`; height is
155 /// `b.y - a.y`. You may read or write this field directly.
156 pub b: Point,
157}
158
159impl Rect {
160 /// Construct a rectangle from the four corner coordinates `(ax, ay)`–`(bx, by)`.
161 ///
162 /// Prefer this constructor when you have individual `x`/`y` values at hand.
163 /// Use [`from_points`](Rect::from_points) when you already hold [`Point`]
164 /// values. The convention is `a = (ax, ay)` (top-left, inclusive) and
165 /// `b = (bx, by)` (bottom-right, exclusive).
166 pub const fn new(ax: i32, ay: i32, bx: i32, by: i32) -> Self {
167 Rect {
168 a: Point::new(ax, ay),
169 b: Point::new(bx, by),
170 }
171 }
172
173 /// Construct a rectangle from two [`Point`] corners.
174 ///
175 /// Equivalent to [`new`](Rect::new) but more ergonomic when you already
176 /// hold [`Point`] values. `p1` becomes [`a`](Rect::a) (top-left, inclusive)
177 /// and `p2` becomes [`b`](Rect::b) (bottom-right, exclusive); no sorting is
178 /// applied, so passing them in the wrong order yields an empty rectangle.
179 pub const fn from_points(p1: Point, p2: Point) -> Self {
180 Rect { a: p1, b: p2 }
181 }
182
183 /// Translate the rectangle by `(dx, dy)`, shifting both corners equally.
184 ///
185 /// Use this to reposition a rectangle without changing its size. Negative
186 /// deltas move it left/up; positive deltas move it right/down. Because `move`
187 /// is a Rust keyword, call this method as `rect.r#move(dx, dy)`.
188 pub fn r#move(&mut self, dx: i32, dy: i32) -> &mut Self {
189 self.a.x += dx;
190 self.a.y += dy;
191 self.b.x += dx;
192 self.b.y += dy;
193 self
194 }
195
196 /// Inflate the rectangle symmetrically by `(dx, dy)`.
197 ///
198 /// Expands each edge outward: `a` moves left/up by `(dx, dy)` and `b` moves
199 /// right/down by the same amount, so the total width grows by `2*dx` and
200 /// height by `2*dy`. Pass negative values to deflate (shrink) the rectangle;
201 /// deflating past zero produces an empty (inverted) rectangle.
202 pub fn grow(&mut self, dx: i32, dy: i32) -> &mut Self {
203 self.a.x -= dx;
204 self.a.y -= dy;
205 self.b.x += dx;
206 self.b.y += dy;
207 self
208 }
209
210 /// Clip the rectangle to the intersection with `r`.
211 ///
212 /// Replaces `self` with the largest rectangle that fits inside both `self`
213 /// and `r`. If the two rectangles do not overlap, the result is empty
214 /// (`is_empty()` returns `true`). Use this to constrain a child view's
215 /// bounds to its parent's visible area.
216 pub fn intersect(&mut self, r: &Rect) -> &mut Self {
217 self.a.x = self.a.x.max(r.a.x);
218 self.a.y = self.a.y.max(r.a.y);
219 self.b.x = self.b.x.min(r.b.x);
220 self.b.y = self.b.y.min(r.b.y);
221 self
222 }
223
224 /// Expand the rectangle to the bounding box of `self` and `r`.
225 ///
226 /// Replaces `self` with the smallest rectangle that contains both `self`
227 /// and `r`. Use this to compute a dirty region that covers multiple views.
228 /// Because `union` is a Rust keyword, call this method as
229 /// `rect.r#union(&other)`.
230 pub fn r#union(&mut self, r: &Rect) -> &mut Self {
231 self.a.x = self.a.x.min(r.a.x);
232 self.a.y = self.a.y.min(r.a.y);
233 self.b.x = self.b.x.max(r.b.x);
234 self.b.y = self.b.y.max(r.b.y);
235 self
236 }
237
238 /// Returns `true` if `p` lies inside the rectangle.
239 ///
240 /// Uses half-open semantics matching the `[a, b)` convention: the
241 /// left/top edges are **included** (`p.x >= a.x`, `p.y >= a.y`) but the
242 /// right/bottom edges are **excluded** (`p.x < b.x`, `p.y < b.y`).
243 /// This is the correct test for hit-testing a character-cell grid, where
244 /// a point exactly on the right or bottom edge belongs to the *next* cell.
245 pub fn contains(&self, p: Point) -> bool {
246 p.x >= self.a.x && p.x < self.b.x && p.y >= self.a.y && p.y < self.b.y
247 }
248
249 /// Returns `true` if the rectangle has zero or negative area.
250 ///
251 /// This is the case when `a.x >= b.x` or `a.y >= b.y` — either the
252 /// width or height is zero. An inverted rectangle (where `b < a`, e.g.
253 /// produced by deflating past zero with [`grow`](Rect::grow)) is also
254 /// considered empty.
255 pub fn is_empty(&self) -> bool {
256 self.a.x >= self.b.x || self.a.y >= self.b.y
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
265 fn point_arithmetic() {
266 let p = Point::new(3, 4) + Point::new(1, 2);
267 assert_eq!(p, Point::new(4, 6));
268 assert_eq!(Point::new(3, 4) - Point::new(1, 2), Point::new(2, 2));
269
270 let mut q = Point::new(10, 10);
271 q += Point::new(5, -5);
272 assert_eq!(q, Point::new(15, 5));
273 q -= Point::new(5, 5);
274 assert_eq!(q, Point::new(10, 0));
275 }
276
277 #[test]
278 fn rect_constructors_equivalent() {
279 let a = Rect::new(1, 2, 3, 4);
280 let b = Rect::from_points(Point::new(1, 2), Point::new(3, 4));
281 assert_eq!(a, b);
282 assert_eq!(Rect::default(), Rect::new(0, 0, 0, 0));
283 }
284
285 #[test]
286 fn rect_move_and_grow() {
287 let mut r = Rect::new(0, 0, 10, 10);
288 r.r#move(2, 3);
289 assert_eq!(r, Rect::new(2, 3, 12, 13));
290
291 r.grow(1, 1);
292 assert_eq!(r, Rect::new(1, 2, 13, 14));
293
294 // negative grow shrinks
295 r.grow(-1, -1);
296 assert_eq!(r, Rect::new(2, 3, 12, 13));
297
298 // chaining returns &mut Self
299 let mut c = Rect::new(0, 0, 4, 4);
300 c.r#move(1, 1).grow(1, 1);
301 assert_eq!(c, Rect::new(0, 0, 6, 6));
302 }
303
304 #[test]
305 fn rect_intersect_and_union() {
306 let mut r = Rect::new(0, 0, 10, 10);
307 r.intersect(&Rect::new(5, 5, 20, 8));
308 assert_eq!(r, Rect::new(5, 5, 10, 8));
309
310 let mut u = Rect::new(0, 0, 4, 4);
311 u.r#union(&Rect::new(2, 2, 10, 6));
312 assert_eq!(u, Rect::new(0, 0, 10, 6));
313 }
314
315 #[test]
316 fn rect_contains_is_half_open() {
317 let r = Rect::new(0, 0, 10, 5);
318 // inside
319 assert!(r.contains(Point::new(0, 0)));
320 assert!(r.contains(Point::new(9, 4)));
321 // right/bottom edges are EXCLUDED (classic off-by-one trap)
322 assert!(!r.contains(Point::new(10, 0)));
323 assert!(!r.contains(Point::new(0, 5)));
324 assert!(!r.contains(Point::new(10, 5)));
325 // left/top edges are INCLUDED
326 assert!(r.contains(Point::new(0, 4)));
327 }
328
329 #[test]
330 fn rect_is_empty() {
331 assert!(Rect::new(0, 0, 0, 0).is_empty());
332 assert!(Rect::new(5, 0, 5, 10).is_empty()); // zero width
333 assert!(Rect::new(0, 5, 10, 5).is_empty()); // zero height
334 assert!(Rect::new(3, 4, 2, 1).is_empty()); // inverted
335 assert!(!Rect::new(0, 0, 1, 1).is_empty());
336 }
337}