rustom 0.1.0

A library for building rich, stateful terminal user interfaces and dashboards.
Documentation
//! Layout primitives for splitting a screen area into smaller regions.

/// A rectangular region of the terminal grid, in cell coordinates.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rect {
    pub x: u16,
    pub y: u16,
    pub width: u16,
    pub height: u16,
}

impl Rect {
    pub const fn new(x: u16, y: u16, width: u16, height: u16) -> Rect {
        Rect { x, y, width, height }
    }

    pub const fn area(self) -> u32 {
        self.width as u32 * self.height as u32
    }

    pub const fn left(self) -> u16 {
        self.x
    }

    pub const fn right(self) -> u16 {
        self.x.saturating_add(self.width)
    }

    pub const fn top(self) -> u16 {
        self.y
    }

    pub const fn bottom(self) -> u16 {
        self.y.saturating_add(self.height)
    }

    /// Returns a new rect shrunk on every side by `margin`.
    pub fn inner(self, margin: u16) -> Rect {
        let doubled = margin.saturating_mul(2);
        if self.width < doubled || self.height < doubled {
            Rect::new(self.x, self.y, 0, 0)
        } else {
            Rect {
                x: self.x + margin,
                y: self.y + margin,
                width: self.width - doubled,
                height: self.height - doubled,
            }
        }
    }

    pub fn intersection(self, other: Rect) -> Rect {
        let x1 = self.x.max(other.x);
        let y1 = self.y.max(other.y);
        let x2 = self.right().min(other.right());
        let y2 = self.bottom().min(other.bottom());
        Rect {
            x: x1,
            y: y1,
            width: x2.saturating_sub(x1),
            height: y2.saturating_sub(y1),
        }
    }

    pub fn contains(self, x: u16, y: u16) -> bool {
        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
    }
}

/// The axis along which a `Layout` distributes space.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
    #[default]
    Vertical,
    Horizontal,
}

/// A sizing rule for one segment of a `Layout` split.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Constraint {
    /// A fixed number of cells.
    Length(u16),
    /// A percentage of the available space (0-100).
    Percentage(u16),
    /// A fraction expressed as a ratio, e.g. `Ratio(1, 3)` for one third.
    Ratio(u32, u32),
    /// At least this many cells; grows to absorb leftover space.
    Min(u16),
    /// At most this many cells.
    Max(u16),
    /// Splits leftover space proportionally among all `Fill` segments.
    Fill(u16),
}

/// Splits a `Rect` into a sequence of smaller rects according to a list of
/// constraints, along either the horizontal or vertical axis.
///
/// This uses a two pass greedy solver rather than a full linear constraint
/// solver: first every fixed sized constraint (`Length`, `Percentage`,
/// `Ratio`, `Max`) claims its space, then any remaining space is divided
/// among `Min` and `Fill` segments in proportion to their weights.
#[derive(Debug, Default, Clone)]
pub struct Layout {
    direction: Direction,
    margin: u16,
    constraints: Vec<Constraint>,
    spacing: u16,
}

impl Layout {
    pub fn default() -> Layout {
        Layout {
            direction: Direction::Vertical,
            margin: 0,
            constraints: Vec::new(),
            spacing: 0,
        }
    }

    pub fn direction(mut self, direction: Direction) -> Layout {
        self.direction = direction;
        self
    }

    pub fn margin(mut self, margin: u16) -> Layout {
        self.margin = margin;
        self
    }

    pub fn spacing(mut self, spacing: u16) -> Layout {
        self.spacing = spacing;
        self
    }

    pub fn constraints<I>(mut self, constraints: I) -> Layout
    where
        I: IntoIterator<Item = Constraint>,
    {
        self.constraints = constraints.into_iter().collect();
        self
    }

    pub fn split(&self, area: Rect) -> Vec<Rect> {
        let area = area.inner(self.margin);
        let axis_len = match self.direction {
            Direction::Horizontal => area.width,
            Direction::Vertical => area.height,
        };

        let n = self.constraints.len();
        if n == 0 {
            return Vec::new();
        }

        let total_spacing = self.spacing.saturating_mul(n.saturating_sub(1) as u16);
        let usable = axis_len.saturating_sub(total_spacing);

        let mut sizes = vec![0u16; n];
        let mut flexible: Vec<usize> = Vec::new();
        let mut flexible_weight: Vec<u32> = Vec::new();
        let mut claimed: u32 = 0;

        // Pass 1: resolve every constraint that has an absolute size up
        // front (Length, Percentage, Ratio, Max). Min and Fill are deferred
        // to pass 2 since they depend on leftover space.
        for (i, c) in self.constraints.iter().enumerate() {
            match *c {
                Constraint::Length(n) => {
                    sizes[i] = n.min(usable);
                    claimed += sizes[i] as u32;
                }
                Constraint::Percentage(p) => {
                    let s = (usable as u32 * p as u32 / 100) as u16;
                    sizes[i] = s;
                    claimed += s as u32;
                }
                Constraint::Ratio(num, den) => {
                    let s = if den == 0 {
                        0
                    } else {
                        (usable as u32 * num / den) as u16
                    };
                    sizes[i] = s;
                    claimed += s as u32;
                }
                Constraint::Max(m) => {
                    sizes[i] = m;
                    claimed += m as u32;
                }
                Constraint::Min(_) => {
                    flexible.push(i);
                    flexible_weight.push(1);
                }
                Constraint::Fill(w) => {
                    flexible.push(i);
                    flexible_weight.push(w.max(1) as u32);
                }
            }
        }

        // Pass 2: divide whatever space is left among Min/Fill segments,
        // weighted by their Fill weight (Min segments get weight 1).
        let leftover = (usable as u32).saturating_sub(claimed);
        let total_weight: u32 = flexible_weight.iter().sum();
        if !flexible.is_empty() && total_weight > 0 {
            let mut distributed = 0u32;
            for (idx, &pos) in flexible.iter().enumerate() {
                let share = if idx == flexible.len() - 1 {
                    leftover - distributed
                } else {
                    leftover * flexible_weight[idx] / total_weight
                };
                distributed += share;
                let min_floor = if let Constraint::Min(m) = self.constraints[pos] {
                    m as u32
                } else {
                    0
                };
                sizes[pos] = share.max(min_floor).min(u16::MAX as u32) as u16;
            }
        }

        // Lay the resolved sizes out sequentially along the chosen axis.
        let mut result = Vec::with_capacity(n);
        let mut cursor = match self.direction {
            Direction::Horizontal => area.x,
            Direction::Vertical => area.y,
        };
        for size in sizes {
            let rect = match self.direction {
                Direction::Horizontal => Rect::new(cursor, area.y, size, area.height),
                Direction::Vertical => Rect::new(area.x, cursor, area.width, size),
            };
            result.push(rect);
            cursor = cursor.saturating_add(size).saturating_add(self.spacing);
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn splits_fixed_lengths() {
        let area = Rect::new(0, 0, 10, 10);
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Length(7)])
            .split(area);
        assert_eq!(chunks[0], Rect::new(0, 0, 10, 3));
        assert_eq!(chunks[1], Rect::new(0, 3, 10, 7));
    }

    #[test]
    fn fill_absorbs_leftover_space() {
        let area = Rect::new(0, 0, 100, 1);
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(20), Constraint::Fill(1), Constraint::Fill(1)])
            .split(area);
        assert_eq!(chunks[0].width, 20);
        assert_eq!(chunks[1].width + chunks[2].width, 80);
        assert_eq!(chunks[1].width, chunks[2].width);
    }

    #[test]
    fn percentage_split() {
        let area = Rect::new(0, 0, 100, 1);
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
            .split(area);
        assert_eq!(chunks[0].width, 30);
        assert_eq!(chunks[1].width, 70);
    }

    #[test]
    fn min_respects_floor() {
        let area = Rect::new(0, 0, 20, 1);
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(15), Constraint::Min(10)])
            .split(area);
        // Even though only 5 cells are left, Min(10) still claims its floor.
        assert_eq!(chunks[1].width, 10);
    }

    #[test]
    fn inner_applies_margin() {
        let area = Rect::new(0, 0, 10, 10);
        assert_eq!(area.inner(1), Rect::new(1, 1, 8, 8));
    }
}