rustimal 0.5.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Binary split tree describing how panes tile the window.

pub type PaneId = u64;

#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Rect {
    pub x: f32,
    pub y: f32,
    pub w: f32,
    pub h: f32,
}

impl Rect {
    pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
        Self { x, y, w, h }
    }
    pub fn right(&self) -> f32 {
        self.x + self.w
    }
    pub fn bottom(&self) -> f32 {
        self.y + self.h
    }
    pub fn contains(&self, x: f32, y: f32) -> bool {
        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
    }
    pub fn inset(&self, d: f32) -> Rect {
        Rect::new(self.x + d, self.y + d, (self.w - 2.0 * d).max(0.0), (self.h - 2.0 * d).max(0.0))
    }
    pub fn lerp(&self, to: &Rect, t: f32) -> Rect {
        let l = |a: f32, b: f32| a + (b - a) * t;
        Rect::new(l(self.x, to.x), l(self.y, to.y), l(self.w, to.w), l(self.h, to.h))
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Dir {
    Left,
    Right,
    Up,
    Down,
}

impl Dir {
    fn axis(self) -> Axis {
        match self {
            Dir::Left | Dir::Right => Axis::Horizontal,
            Dir::Up | Dir::Down => Axis::Vertical,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Axis {
    /// Children side by side.
    Horizontal,
    /// Children stacked.
    Vertical,
}

#[derive(Debug)]
pub enum Node {
    Leaf(PaneId),
    Split { axis: Axis, ratio: f32, a: Box<Node>, b: Box<Node> },
}

impl Node {
    /// Split `target`, placing `new` on the `dir` side of it.
    pub fn split(&mut self, target: PaneId, dir: Dir, new: PaneId) -> bool {
        match self {
            Node::Leaf(id) if *id == target => {
                let old = Box::new(Node::Leaf(target));
                let new = Box::new(Node::Leaf(new));
                let (a, b) = match dir {
                    Dir::Right | Dir::Down => (old, new),
                    Dir::Left | Dir::Up => (new, old),
                };
                *self = Node::Split { axis: dir.axis(), ratio: 0.5, a, b };
                true
            }
            Node::Leaf(_) => false,
            Node::Split { a, b, .. } => a.split(target, dir, new) || b.split(target, dir, new),
        }
    }

    /// Remove a leaf, letting its sibling take its space.
    pub fn remove(&mut self, target: PaneId) -> bool {
        let Node::Split { a, b, .. } = self else { return false };
        let a_hit = matches!(**a, Node::Leaf(id) if id == target);
        let b_hit = matches!(**b, Node::Leaf(id) if id == target);
        if a_hit || b_hit {
            let old = std::mem::replace(self, Node::Leaf(0));
            if let Node::Split { a, b, .. } = old {
                *self = if a_hit { *b } else { *a };
            }
            return true;
        }
        a.remove(target) || b.remove(target)
    }

    /// Move the nearest divider along `dir`'s axis in the direction of `dir`.
    pub fn resize(&mut self, target: PaneId, dir: Dir, step: f32) -> bool {
        self.resize_inner(target, dir, step) == Resize::Done
    }

    fn resize_inner(&mut self, target: PaneId, dir: Dir, step: f32) -> Resize {
        match self {
            Node::Leaf(id) => {
                if *id == target {
                    Resize::Found
                } else {
                    Resize::NotFound
                }
            }
            Node::Split { axis, ratio, a, b } => {
                let mut r = a.resize_inner(target, dir, step);
                if r == Resize::NotFound {
                    r = b.resize_inner(target, dir, step);
                }
                if r == Resize::Found && *axis == dir.axis() {
                    let delta = if matches!(dir, Dir::Right | Dir::Down) { step } else { -step };
                    *ratio = (*ratio + delta).clamp(0.1, 0.9);
                    return Resize::Done;
                }
                r
            }
        }
    }

    pub fn layout(&self, area: Rect, gap: f32, out: &mut Vec<(PaneId, Rect)>) {
        match self {
            Node::Leaf(id) => out.push((*id, area)),
            Node::Split { axis, ratio, a, b } => {
                let (ra, rb) = match axis {
                    Axis::Horizontal => {
                        let avail = (area.w - gap).max(0.0);
                        let wa = (avail * ratio).round();
                        (
                            Rect::new(area.x, area.y, wa, area.h),
                            Rect::new(area.x + wa + gap, area.y, avail - wa, area.h),
                        )
                    }
                    Axis::Vertical => {
                        let avail = (area.h - gap).max(0.0);
                        let ha = (avail * ratio).round();
                        (
                            Rect::new(area.x, area.y, area.w, ha),
                            Rect::new(area.x, area.y + ha + gap, area.w, avail - ha),
                        )
                    }
                };
                a.layout(ra, gap, out);
                b.layout(rb, gap, out);
            }
        }
    }

    pub fn first_leaf(&self) -> PaneId {
        match self {
            Node::Leaf(id) => *id,
            Node::Split { a, .. } => a.first_leaf(),
        }
    }
}

#[derive(PartialEq, Eq)]
enum Resize {
    NotFound,
    Found,
    Done,
}

/// Find the pane adjacent to `from` in direction `dir`.
pub fn neighbor(rects: &[(PaneId, Rect)], from: PaneId, dir: Dir) -> Option<PaneId> {
    let (_, f) = rects.iter().find(|(id, _)| *id == from)?;
    let eps = 1.0;
    let overlap = |a0: f32, a1: f32, b0: f32, b1: f32| (a1.min(b1) - a0.max(b0)).max(0.0);
    rects
        .iter()
        .filter(|(id, _)| *id != from)
        .filter_map(|(id, r)| {
            let (dist, ov) = match dir {
                Dir::Right if r.x >= f.right() - eps => (r.x - f.right(), overlap(f.y, f.bottom(), r.y, r.bottom())),
                Dir::Left if r.right() <= f.x + eps => (f.x - r.right(), overlap(f.y, f.bottom(), r.y, r.bottom())),
                Dir::Down if r.y >= f.bottom() - eps => (r.y - f.bottom(), overlap(f.x, f.right(), r.x, r.right())),
                Dir::Up if r.bottom() <= f.y + eps => (f.y - r.bottom(), overlap(f.x, f.right(), r.x, r.right())),
                _ => return None,
            };
            (ov > 0.0).then_some((*id, dist, ov))
        })
        .min_by(|a, b| a.1.total_cmp(&b.1).then(b.2.total_cmp(&a.2)))
        .map(|(id, _, _)| id)
}