rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Panes and their layout: where each one goes, splitting, closing, zooming.

use super::*;

impl App {
    /// Everything below the title bar, which the panes share.
    pub(super) fn full_area(&self, st: &State) -> Rect {
        let size = st.window.inner_size();
        let g = (self.config.gap * st.scale).round();
        let top = titlebar_height(st.scale);
        Rect::new(g, top, size.width as f32 - 2.0 * g, size.height as f32 - top - g)
    }

    pub(super) fn grid_for(&self, st: &State, r: &Rect, claude: bool) -> GridSize {
        let pad = (self.config.padding * st.scale).round();
        // Claude panes give up a strip at the bottom for the usage bar.
        let bar = if claude { render::claude_bar_height(st.glyphs.cell_h, st.scale) } else { 0.0 };
        GridSize {
            cols: (((r.w - 2.0 * pad) / st.glyphs.cell_w).floor() as usize).max(2),
            rows: (((r.h - 2.0 * pad - bar) / st.glyphs.cell_h).floor() as usize).max(1),
        }
    }

    pub(super) fn target_rects(&self, st: &State) -> Vec<(PaneId, Rect)> {
        if let Some(id) = st.zoomed.filter(|id| st.panes.iter().any(|p| p.id == *id)) {
            return vec![(id, self.full_area(st))];
        }
        let mut rects = Vec::new();
        st.layout.layout(self.full_area(st), (self.config.gap * st.scale).round(), &mut rects);
        rects
    }

    /// Recompute pane targets from the layout tree. `snap` skips the animation
    /// (window resizes); `immediate` resizes the shell now instead of debouncing,
    /// so text reflows once, before the panes start moving.
    pub(super) fn relayout(&mut self, snap: bool, immediate: bool) {
        let Some(st) = self.state.take() else { return };
        let mut st = st;
        let rects = self.target_rects(&st);
        let cell = (st.glyphs.cell_w, st.glyphs.cell_h);
        let now = Instant::now();
        let d = self.dur(LAYOUT_SECS);
        // Panes with no place in the layout (tucked away by a zoom) fade out and stop taking
        // clicks; their shells keep running at their old size.
        let shown: Vec<PaneId> = rects.iter().map(|(id, _)| *id).collect();
        for p in st.panes.iter_mut() {
            if shown.contains(&p.id) {
                p.opacity_anim.set(1.0, d, now);
            } else {
                p.opacity_anim.set(0.0, d, now);
                p.target = Rect::default();
            }
        }
        for (id, r) in rects {
            let claude = st.panes.iter().any(|p| p.id == id && p.claude);
            let grid = self.grid_for(&st, &r, claude);
            if let Some(p) = st.panes.iter_mut().find(|p| p.id == id) {
                p.target = r;
                if snap {
                    p.rect_anim.snap(r);
                    p.rect = r;
                } else {
                    p.rect_anim.set(r, d, now);
                }
                p.request_grid(grid, cell, immediate);
            }
        }
        st.window.request_redraw();
        self.state = Some(st);
    }

    pub(super) fn spawn_pane(
        &self,
        st: &mut State,
        id: PaneId,
        target: Rect,
        start: Rect,
        cwd: Option<PathBuf>,
    ) -> bool {
        let grid = self.grid_for(st, &target, false);
        let cell = (st.glyphs.cell_w, st.glyphs.cell_h);
        let mut env = self.shell_env.clone();
        if id == 1 && self.install_hint {
            env.push(("RUSTIMAL_HINT".into(), "1".into()));
        }
        match Pane::spawn(
            id,
            self.proxy.clone(),
            self.config.shell_program(),
            &env,
            cwd,
            self.config.scrollback,
            grid,
            cell,
            start,
        ) {
            Ok(mut p) => {
                p.target = target;
                p.opacity_anim.set(1.0, self.dur(FADE_IN_SECS), Instant::now());
                st.panes.push(p);
                true
            }
            Err(e) => {
                log::error!("failed to spawn shell: {e}");
                false
            }
        }
    }

    /// Show the focused pane full size, or bring the other panes back.
    pub(super) fn toggle_zoom(&mut self) {
        let Some(st) = self.state.as_mut() else { return };
        if st.zoomed.is_some() {
            st.zoomed = None;
        } else if st.panes.len() > 1 {
            st.zoomed = Some(st.focused);
        } else {
            return;
        }
        let message =
            if st.zoomed.is_some() { "Pane zoomed (Ctrl+Shift+Z to bring the others back)" } else { "Layout restored" };
        self.relayout(false, false);
        self.toast(message);
    }

    pub(super) fn split(&mut self, dir: Dir) {
        let Some(mut st) = self.state.take() else { return };
        st.zoomed = None;
        let id = st.next_id;
        st.next_id += 1;
        let cwd = st.panes.iter().find(|p| p.id == st.focused).and_then(|p| p.cwd.clone()).or(self.start_dir.clone());
        if st.layout.split(st.focused, dir, id) {
            let rects = self.target_rects(&st);
            let target = rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).unwrap_or_default();
            // Grow in from the edge of the pane being split.
            let start = match dir {
                Dir::Right => Rect::new(target.right(), target.y, 0.0, target.h),
                Dir::Left => Rect::new(target.x, target.y, 0.0, target.h),
                Dir::Down => Rect::new(target.x, target.bottom(), target.w, 0.0),
                Dir::Up => Rect::new(target.x, target.y, target.w, 0.0),
            };
            if self.spawn_pane(&mut st, id, target, start, cwd) {
                let prev = st.focused;
                st.focused = id;
                notify_focus(&st, prev);
            } else {
                st.layout.remove(id);
            }
        }
        self.state = Some(st);
        self.relayout(false, true);
        self.autosave_session();
    }

    pub(super) fn close_pane(&mut self, event_loop: &ActiveEventLoop, id: PaneId) {
        let Some(mut st) = self.state.take() else { return };
        let Some(idx) = st.panes.iter().position(|p| p.id == id) else {
            self.state = Some(st);
            return;
        };
        let mut pane = st.panes.remove(idx);
        st.web.remove(id);
        if st.picker.as_ref().is_some_and(|p| p.pane == id) {
            st.picker = None;
        }
        st.layout.remove(id);
        if st.zoomed == Some(id) || st.panes.len() < 2 {
            st.zoomed = None;
        }
        if st.panes.is_empty() {
            event_loop.exit();
            self.state = Some(st);
            return;
        }
        pane.shutdown();
        // Fade out in place while the neighbours slide over it.
        let r = pane.rect;
        pane.opacity_anim.set(0.0, self.dur(FADE_OUT_SECS), Instant::now());
        if self.config.animation_speed > 0.0 {
            st.closing.push(pane);
        }
        if st.focused == id {
            // Focus whichever pane takes over the closed pane's center.
            let rects = self.target_rects(&st);
            let (cx, cy) = (r.x + r.w / 2.0, r.y + r.h / 2.0);
            st.focused = rects
                .iter()
                .find(|(_, rect)| rect.contains(cx, cy))
                .map(|(i, _)| *i)
                .unwrap_or_else(|| st.layout.first_leaf());
            notify_focus(&st, id);
        }
        self.state = Some(st);
        self.relayout(false, true);
        self.autosave_session();
    }

    pub(super) fn pane_at(&self, x: f32, y: f32) -> Option<PaneId> {
        let st = self.state.as_ref()?;
        st.panes.iter().find(|p| p.target.contains(x, y)).map(|p| p.id)
    }

    /// Map a pixel position to a grid point inside a pane.
    pub(super) fn grid_point(&self, id: PaneId, x: f32, y: f32) -> Option<(Point, Side, usize, usize)> {
        let st = self.state.as_ref()?;
        let p = st.panes.iter().find(|p| p.id == id)?;
        let pad = (self.config.padding * st.scale).round();
        let (ox, oy) = ((p.rect.x + pad).round(), (p.rect.y + pad).round());
        let (cw, ch) = (st.glyphs.cell_w, st.glyphs.cell_h);
        let fx = ((x - ox) / cw).max(0.0);
        let col = (fx.floor() as usize).min(p.grid.cols - 1);
        let row = ((((y - oy) / ch).max(0.0)).floor() as usize).min(p.grid.rows - 1);
        let side = if fx.fract() > 0.5 { Side::Right } else { Side::Left };
        let offset = p.term.lock().grid().display_offset() as i32;
        Some((Point::new(Line(row as i32 - offset), Column(col)), side, col, row))
    }

    pub(super) fn set_font_size(&mut self, pt: f32) {
        let Some(st) = self.state.as_mut() else { return };
        st.font_pt = pt.clamp(6.0, 40.0);
        let px = (st.font_pt * 96.0 / 72.0 * st.scale).round();
        st.glyphs.set_size(px);
        self.relayout(true, true);
    }
}