//! Terminal geometry and splitting primitives. //! //! This module defines points, sizes, rectangles, layout constraints, and the //! fixed/min/fill length model used by containers. It is deliberately numeric //! and widget-agnostic so layout helpers can be tested without rendering. use std::array; use std::marker::PhantomData; use crate::Size; pub mod coord { //! Coordinate system markers. /// Terminal screen coordinates. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Screen; /// Widget-local coordinates. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Local; } /// A point in a coordinate system. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Point { /// Column coordinate. pub x: usize, /// Row coordinate. pub y: usize, /// Dimensional unit. unit: PhantomData U>, } impl Clone for Point { fn clone(&self) -> Self { *self } } impl Copy for Point {} impl Point { /// Creates a point. pub const fn new(x: usize, y: usize) -> Self { Self { x, y, unit: PhantomData, } } } /// A rectangular terminal region. #[derive(Debug, PartialEq, Eq, Hash)] pub struct Rect { /// Left column. pub x: usize, /// Top row. pub y: usize, /// Width in terminal cells. pub cols: usize, /// Height in terminal cells. pub rows: usize, /// Dimensional unit. unit: PhantomData U>, } impl Clone for Rect { fn clone(&self) -> Self { *self } } impl Copy for Rect {} impl Default for Rect { fn default() -> Self { Self::ZERO } } impl Rect { /// Empty rectangle at the origin. pub const ZERO: Self = Self::new(0, 0, 0, 0); /// Creates a rectangle. pub const fn new(x: usize, y: usize, cols: usize, rows: usize) -> Self { Self { x, y, cols, rows, unit: PhantomData, } } /// Creates a rectangle at the origin. pub const fn from_size(size: Size) -> Self { Self::new(0, 0, size.cols, size.rows) } /// Returns the rectangle size. pub const fn size(self) -> Size { Size::new(self.cols, self.rows) } /// Returns the right edge. pub const fn right(self) -> usize { self.x + self.cols } /// Returns the bottom edge. pub const fn bottom(self) -> usize { self.y + self.rows } /// Returns whether this rectangle is empty. pub const fn is_empty(self) -> bool { self.cols == 0 || self.rows == 0 } /// Returns whether the point is inside this rectangle. pub const fn contains(self, point: Point) -> bool { point.x >= self.x && point.x < self.right() && point.y >= self.y && point.y < self.bottom() } /// Returns this rectangle inset by `margin` cells. pub const fn inner(self, margin: usize) -> Self { let inset = margin * 2; if self.cols <= inset || self.rows <= inset { Self::new(self.x + margin, self.y + margin, 0, 0) } else { Self::new( self.x + margin, self.y + margin, self.cols - inset, self.rows - inset, ) } } /// Splits this rectangle into top rows and the remaining rows. pub const fn split_top(self, rows: usize) -> (Self, Self) { let rows = if rows > self.rows { self.rows } else { rows }; ( Self::new(self.x, self.y, self.cols, rows), Self::new(self.x, self.y + rows, self.cols, self.rows - rows), ) } /// Splits this rectangle into remaining rows and bottom rows. pub const fn split_bottom(self, rows: usize) -> (Self, Self) { let rows = if rows > self.rows { self.rows } else { rows }; ( Self::new(self.x, self.y, self.cols, self.rows - rows), Self::new(self.x, self.bottom() - rows, self.cols, rows), ) } /// Returns the intersection of two rectangles. pub fn intersection(self, other: Self) -> Self { let x = self.x.max(other.x); let y = self.y.max(other.y); let right = self.right().min(other.right()); let bottom = self.bottom().min(other.bottom()); Self::new(x, y, right.saturating_sub(x), bottom.saturating_sub(y)) } } /// Layout direction. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Direction { /// Split left-to-right. Horizontal, /// Split top-to-bottom. Vertical, } /// Length allocated by a split layout. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Length { /// A fixed number of terminal cells. Fixed(usize), /// A minimum number of cells plus a share of remaining space. Min(usize), /// Weighted share of remaining space. Fill(u16), } /// Deterministic split layout. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Layout { /// Split direction. direction: Direction, /// Child lengths. lengths: Vec, } impl Layout { /// Creates a layout with a direction. pub fn new(direction: Direction) -> Self { Self { direction, lengths: Vec::new(), } } /// Adds a child length. pub fn child(mut self, length: Length) -> Self { self.lengths.push(length); self } /// Splits an area into child rectangles. pub fn split(&self, area: Rect) -> Vec> { split(area, self.direction, &self.lengths) } /// Splits an area into a fixed-size array of child rectangles. pub fn areas(&self, area: Rect) -> [Rect; N] { areas(area, self.direction, self.lengths.as_slice()) } } /// Splits an area into rectangles. pub fn split(area: Rect, direction: Direction, lengths: &[Length]) -> Vec> { if lengths.is_empty() { return Vec::new(); } let total = match direction { Direction::Horizontal => area.cols, Direction::Vertical => area.rows, }; let widths = allocate(total, lengths); let mut cursor = match direction { Direction::Horizontal => area.x, Direction::Vertical => area.y, }; widths .into_iter() .map(|amount| { let rect = match direction { Direction::Horizontal => Rect::new(cursor, area.y, amount, area.rows), Direction::Vertical => Rect::new(area.x, cursor, area.cols, amount), }; cursor += amount; rect }) .collect() } /// Splits an area into a fixed-size array of rectangles. pub fn areas( area: Rect, direction: Direction, lengths: &[Length], ) -> [Rect; N] { let chunks = split(area, direction, lengths); array::from_fn(|index| chunks.get(index).copied().unwrap_or(Rect::ZERO)) } /// Allocates a one-dimensional split. fn allocate(total: usize, lengths: &[Length]) -> Vec { let base = lengths .iter() .map(|length| match *length { Length::Fixed(n) | Length::Min(n) => n, Length::Fill(_) => 0, }) .sum::(); let fill = lengths .iter() .map(|length| match *length { Length::Fill(weight) => weight.max(1) as usize, _ => 0, }) .sum::(); let remaining = total.saturating_sub(base); let mut used = 0usize; lengths .iter() .enumerate() .map(|(i, length)| { let mut amount = match *length { Length::Fixed(n) | Length::Min(n) => n, Length::Fill(weight) if fill > 0 => remaining * weight.max(1) as usize / fill, Length::Fill(_) => 0, }; if i == lengths.len() - 1 { amount = total.saturating_sub(used); } amount = amount.min(total.saturating_sub(used)); used += amount; amount }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn rect_inner_insets_edges() { let rect: Rect = Rect::new(2, 3, 10, 8); assert_eq!(rect.inner(1), Rect::new(3, 4, 8, 6)); assert!(rect.contains(Point::new(2, 3))); assert!(!rect.contains(Point::new(12, 3))); } #[test] fn rect_split_top_clamps_to_available_rows() { let rect: Rect = Rect::new(2, 3, 10, 8); assert_eq!( rect.split_top(3), (Rect::new(2, 3, 10, 3), Rect::new(2, 6, 10, 5)) ); assert_eq!( rect.split_top(10), (Rect::new(2, 3, 10, 8), Rect::new(2, 11, 10, 0)) ); } #[test] fn rect_split_bottom_clamps_to_available_rows() { let rect: Rect = Rect::new(2, 3, 10, 8); assert_eq!( rect.split_bottom(3), (Rect::new(2, 3, 10, 5), Rect::new(2, 8, 10, 3)) ); assert_eq!( rect.split_bottom(10), (Rect::new(2, 3, 10, 0), Rect::new(2, 3, 10, 8)) ); } #[test] fn horizontal_split_distributes_fill() { let area: Rect = Rect::new(0, 0, 10, 3); let layout = Layout::new(Direction::Horizontal) .child(Length::Fixed(2)) .child(Length::Fill(1)) .child(Length::Fill(1)); assert_eq!( layout.split(area), vec![ Rect::new(0, 0, 2, 3), Rect::new(2, 0, 4, 3), Rect::new(6, 0, 4, 3), ] ); } #[test] fn vertical_split_uses_minimums_and_weighted_fill() { let area: Rect = Rect::new(1, 2, 5, 10); let layout = Layout::new(Direction::Vertical) .child(Length::Min(2)) .child(Length::Fill(1)) .child(Length::Fill(2)); assert_eq!( layout.split(area), vec![ Rect::new(1, 2, 5, 2), Rect::new(1, 4, 5, 2), Rect::new(1, 6, 5, 6), ] ); } #[test] fn split_clamps_when_fixed_lengths_exceed_available_space() { let area: Rect = Rect::new(0, 0, 3, 1); let layout = Layout::new(Direction::Horizontal) .child(Length::Fixed(2)) .child(Length::Fixed(2)) .child(Length::Fill(1)); assert_eq!( layout.split(area), vec![ Rect::new(0, 0, 2, 1), Rect::new(2, 0, 1, 1), Rect::new(3, 0, 0, 1), ] ); } #[test] fn empty_split_returns_no_rectangles() { let area: Rect = Rect::new(0, 0, 3, 1); assert!(split(area, Direction::Horizontal, &[]).is_empty()); } #[test] fn areas_returns_fixed_array_and_zero_fills_missing_chunks() { let area: Rect = Rect::new(0, 0, 5, 1); let [left, right, missing] = areas( area, Direction::Horizontal, &[Length::Fixed(2), Length::Fill(1)], ); assert_eq!(left, Rect::new(0, 0, 2, 1)); assert_eq!(right, Rect::new(2, 0, 3, 1)); assert_eq!(missing, Rect::ZERO); } }