crates/tui-core/src/layout.rs 11.2 KiB raw
1
//! Terminal geometry and splitting primitives.
2
//!
3
//! This module defines points, sizes, rectangles, layout constraints, and the
4
//! fixed/min/fill length model used by containers. It is deliberately numeric
5
//! and widget-agnostic so layout helpers can be tested without rendering.
6
7
use std::array;
8
use std::marker::PhantomData;
9
10
use crate::Size;
11
12
pub mod coord {
13
    //! Coordinate system markers.
14
15
    /// Terminal screen coordinates.
16
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
17
    pub struct Screen;
18
19
    /// Widget-local coordinates.
20
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
21
    pub struct Local;
22
}
23
24
/// A point in a coordinate system.
25
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
26
pub struct Point<U = coord::Screen> {
27
    /// Column coordinate.
28
    pub x: usize,
29
    /// Row coordinate.
30
    pub y: usize,
31
    /// Dimensional unit.
32
    unit: PhantomData<fn() -> U>,
33
}
34
35
impl<U> Clone for Point<U> {
36
    fn clone(&self) -> Self {
37
        *self
38
    }
39
}
40
41
impl<U> Copy for Point<U> {}
42
43
impl<U> Point<U> {
44
    /// Creates a point.
45
    pub const fn new(x: usize, y: usize) -> Self {
46
        Self {
47
            x,
48
            y,
49
            unit: PhantomData,
50
        }
51
    }
52
}
53
54
/// A rectangular terminal region.
55
#[derive(Debug, PartialEq, Eq, Hash)]
56
pub struct Rect<U = coord::Screen> {
57
    /// Left column.
58
    pub x: usize,
59
    /// Top row.
60
    pub y: usize,
61
    /// Width in terminal cells.
62
    pub cols: usize,
63
    /// Height in terminal cells.
64
    pub rows: usize,
65
    /// Dimensional unit.
66
    unit: PhantomData<fn() -> U>,
67
}
68
69
impl<U> Clone for Rect<U> {
70
    fn clone(&self) -> Self {
71
        *self
72
    }
73
}
74
75
impl<U> Copy for Rect<U> {}
76
77
impl<U> Default for Rect<U> {
78
    fn default() -> Self {
79
        Self::ZERO
80
    }
81
}
82
83
impl<U> Rect<U> {
84
    /// Empty rectangle at the origin.
85
    pub const ZERO: Self = Self::new(0, 0, 0, 0);
86
87
    /// Creates a rectangle.
88
    pub const fn new(x: usize, y: usize, cols: usize, rows: usize) -> Self {
89
        Self {
90
            x,
91
            y,
92
            cols,
93
            rows,
94
            unit: PhantomData,
95
        }
96
    }
97
98
    /// Creates a rectangle at the origin.
99
    pub const fn from_size(size: Size) -> Self {
100
        Self::new(0, 0, size.cols, size.rows)
101
    }
102
103
    /// Returns the rectangle size.
104
    pub const fn size(self) -> Size {
105
        Size::new(self.cols, self.rows)
106
    }
107
108
    /// Returns the right edge.
109
    pub const fn right(self) -> usize {
110
        self.x + self.cols
111
    }
112
113
    /// Returns the bottom edge.
114
    pub const fn bottom(self) -> usize {
115
        self.y + self.rows
116
    }
117
118
    /// Returns whether this rectangle is empty.
119
    pub const fn is_empty(self) -> bool {
120
        self.cols == 0 || self.rows == 0
121
    }
122
123
    /// Returns whether the point is inside this rectangle.
124
    pub const fn contains(self, point: Point<U>) -> bool {
125
        point.x >= self.x && point.x < self.right() && point.y >= self.y && point.y < self.bottom()
126
    }
127
128
    /// Returns this rectangle inset by `margin` cells.
129
    pub const fn inner(self, margin: usize) -> Self {
130
        let inset = margin * 2;
131
        if self.cols <= inset || self.rows <= inset {
132
            Self::new(self.x + margin, self.y + margin, 0, 0)
133
        } else {
134
            Self::new(
135
                self.x + margin,
136
                self.y + margin,
137
                self.cols - inset,
138
                self.rows - inset,
139
            )
140
        }
141
    }
142
143
    /// Splits this rectangle into top rows and the remaining rows.
144
    pub const fn split_top(self, rows: usize) -> (Self, Self) {
145
        let rows = if rows > self.rows { self.rows } else { rows };
146
        (
147
            Self::new(self.x, self.y, self.cols, rows),
148
            Self::new(self.x, self.y + rows, self.cols, self.rows - rows),
149
        )
150
    }
151
152
    /// Splits this rectangle into remaining rows and bottom rows.
153
    pub const fn split_bottom(self, rows: usize) -> (Self, Self) {
154
        let rows = if rows > self.rows { self.rows } else { rows };
155
        (
156
            Self::new(self.x, self.y, self.cols, self.rows - rows),
157
            Self::new(self.x, self.bottom() - rows, self.cols, rows),
158
        )
159
    }
160
161
    /// Returns the intersection of two rectangles.
162
    pub fn intersection(self, other: Self) -> Self {
163
        let x = self.x.max(other.x);
164
        let y = self.y.max(other.y);
165
        let right = self.right().min(other.right());
166
        let bottom = self.bottom().min(other.bottom());
167
168
        Self::new(x, y, right.saturating_sub(x), bottom.saturating_sub(y))
169
    }
170
}
171
172
/// Layout direction.
173
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174
pub enum Direction {
175
    /// Split left-to-right.
176
    Horizontal,
177
    /// Split top-to-bottom.
178
    Vertical,
179
}
180
181
/// Length allocated by a split layout.
182
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
183
pub enum Length {
184
    /// A fixed number of terminal cells.
185
    Fixed(usize),
186
    /// A minimum number of cells plus a share of remaining space.
187
    Min(usize),
188
    /// Weighted share of remaining space.
189
    Fill(u16),
190
}
191
192
/// Deterministic split layout.
193
#[derive(Debug, Clone, PartialEq, Eq)]
194
pub struct Layout {
195
    /// Split direction.
196
    direction: Direction,
197
    /// Child lengths.
198
    lengths: Vec<Length>,
199
}
200
201
impl Layout {
202
    /// Creates a layout with a direction.
203
    pub fn new(direction: Direction) -> Self {
204
        Self {
205
            direction,
206
            lengths: Vec::new(),
207
        }
208
    }
209
210
    /// Adds a child length.
211
    pub fn child(mut self, length: Length) -> Self {
212
        self.lengths.push(length);
213
        self
214
    }
215
216
    /// Splits an area into child rectangles.
217
    pub fn split<U>(&self, area: Rect<U>) -> Vec<Rect<U>> {
218
        split(area, self.direction, &self.lengths)
219
    }
220
221
    /// Splits an area into a fixed-size array of child rectangles.
222
    pub fn areas<U, const N: usize>(&self, area: Rect<U>) -> [Rect<U>; N] {
223
        areas(area, self.direction, self.lengths.as_slice())
224
    }
225
}
226
227
/// Splits an area into rectangles.
228
pub fn split<U>(area: Rect<U>, direction: Direction, lengths: &[Length]) -> Vec<Rect<U>> {
229
    if lengths.is_empty() {
230
        return Vec::new();
231
    }
232
233
    let total = match direction {
234
        Direction::Horizontal => area.cols,
235
        Direction::Vertical => area.rows,
236
    };
237
    let widths = allocate(total, lengths);
238
    let mut cursor = match direction {
239
        Direction::Horizontal => area.x,
240
        Direction::Vertical => area.y,
241
    };
242
243
    widths
244
        .into_iter()
245
        .map(|amount| {
246
            let rect = match direction {
247
                Direction::Horizontal => Rect::new(cursor, area.y, amount, area.rows),
248
                Direction::Vertical => Rect::new(area.x, cursor, area.cols, amount),
249
            };
250
            cursor += amount;
251
            rect
252
        })
253
        .collect()
254
}
255
256
/// Splits an area into a fixed-size array of rectangles.
257
pub fn areas<U, const N: usize>(
258
    area: Rect<U>,
259
    direction: Direction,
260
    lengths: &[Length],
261
) -> [Rect<U>; N] {
262
    let chunks = split(area, direction, lengths);
263
264
    array::from_fn(|index| chunks.get(index).copied().unwrap_or(Rect::ZERO))
265
}
266
267
/// Allocates a one-dimensional split.
268
fn allocate(total: usize, lengths: &[Length]) -> Vec<usize> {
269
    let base = lengths
270
        .iter()
271
        .map(|length| match *length {
272
            Length::Fixed(n) | Length::Min(n) => n,
273
            Length::Fill(_) => 0,
274
        })
275
        .sum::<usize>();
276
    let fill = lengths
277
        .iter()
278
        .map(|length| match *length {
279
            Length::Fill(weight) => weight.max(1) as usize,
280
            _ => 0,
281
        })
282
        .sum::<usize>();
283
    let remaining = total.saturating_sub(base);
284
    let mut used = 0usize;
285
286
    lengths
287
        .iter()
288
        .enumerate()
289
        .map(|(i, length)| {
290
            let mut amount = match *length {
291
                Length::Fixed(n) | Length::Min(n) => n,
292
                Length::Fill(weight) if fill > 0 => remaining * weight.max(1) as usize / fill,
293
                Length::Fill(_) => 0,
294
            };
295
            if i == lengths.len() - 1 {
296
                amount = total.saturating_sub(used);
297
            }
298
            amount = amount.min(total.saturating_sub(used));
299
            used += amount;
300
            amount
301
        })
302
        .collect()
303
}
304
305
#[cfg(test)]
306
mod tests {
307
    use super::*;
308
309
    #[test]
310
    fn rect_inner_insets_edges() {
311
        let rect: Rect = Rect::new(2, 3, 10, 8);
312
313
        assert_eq!(rect.inner(1), Rect::new(3, 4, 8, 6));
314
        assert!(rect.contains(Point::new(2, 3)));
315
        assert!(!rect.contains(Point::new(12, 3)));
316
    }
317
318
    #[test]
319
    fn rect_split_top_clamps_to_available_rows() {
320
        let rect: Rect = Rect::new(2, 3, 10, 8);
321
322
        assert_eq!(
323
            rect.split_top(3),
324
            (Rect::new(2, 3, 10, 3), Rect::new(2, 6, 10, 5))
325
        );
326
        assert_eq!(
327
            rect.split_top(10),
328
            (Rect::new(2, 3, 10, 8), Rect::new(2, 11, 10, 0))
329
        );
330
    }
331
332
    #[test]
333
    fn rect_split_bottom_clamps_to_available_rows() {
334
        let rect: Rect = Rect::new(2, 3, 10, 8);
335
336
        assert_eq!(
337
            rect.split_bottom(3),
338
            (Rect::new(2, 3, 10, 5), Rect::new(2, 8, 10, 3))
339
        );
340
        assert_eq!(
341
            rect.split_bottom(10),
342
            (Rect::new(2, 3, 10, 0), Rect::new(2, 3, 10, 8))
343
        );
344
    }
345
346
    #[test]
347
    fn horizontal_split_distributes_fill() {
348
        let area: Rect = Rect::new(0, 0, 10, 3);
349
        let layout = Layout::new(Direction::Horizontal)
350
            .child(Length::Fixed(2))
351
            .child(Length::Fill(1))
352
            .child(Length::Fill(1));
353
354
        assert_eq!(
355
            layout.split(area),
356
            vec![
357
                Rect::new(0, 0, 2, 3),
358
                Rect::new(2, 0, 4, 3),
359
                Rect::new(6, 0, 4, 3),
360
            ]
361
        );
362
    }
363
364
    #[test]
365
    fn vertical_split_uses_minimums_and_weighted_fill() {
366
        let area: Rect = Rect::new(1, 2, 5, 10);
367
        let layout = Layout::new(Direction::Vertical)
368
            .child(Length::Min(2))
369
            .child(Length::Fill(1))
370
            .child(Length::Fill(2));
371
372
        assert_eq!(
373
            layout.split(area),
374
            vec![
375
                Rect::new(1, 2, 5, 2),
376
                Rect::new(1, 4, 5, 2),
377
                Rect::new(1, 6, 5, 6),
378
            ]
379
        );
380
    }
381
382
    #[test]
383
    fn split_clamps_when_fixed_lengths_exceed_available_space() {
384
        let area: Rect = Rect::new(0, 0, 3, 1);
385
        let layout = Layout::new(Direction::Horizontal)
386
            .child(Length::Fixed(2))
387
            .child(Length::Fixed(2))
388
            .child(Length::Fill(1));
389
390
        assert_eq!(
391
            layout.split(area),
392
            vec![
393
                Rect::new(0, 0, 2, 1),
394
                Rect::new(2, 0, 1, 1),
395
                Rect::new(3, 0, 0, 1),
396
            ]
397
        );
398
    }
399
400
    #[test]
401
    fn empty_split_returns_no_rectangles() {
402
        let area: Rect = Rect::new(0, 0, 3, 1);
403
404
        assert!(split(area, Direction::Horizontal, &[]).is_empty());
405
    }
406
407
    #[test]
408
    fn areas_returns_fixed_array_and_zero_fills_missing_chunks() {
409
        let area: Rect = Rect::new(0, 0, 5, 1);
410
        let [left, right, missing] = areas(
411
            area,
412
            Direction::Horizontal,
413
            &[Length::Fixed(2), Length::Fill(1)],
414
        );
415
416
        assert_eq!(left, Rect::new(0, 0, 2, 1));
417
        assert_eq!(right, Rect::new(2, 0, 3, 1));
418
        assert_eq!(missing, Rect::ZERO);
419
    }
420
}