rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Saved window layouts: the split tree, and each pane's folder and start command.
//!
//! A layout is a small JSON file in `%APPDATA%\rustimal\layouts`, so it can be edited by hand:
//!
//! ```json
//! { "root": { "split": "right", "ratio": 0.5,
//!             "a": { "cwd": "C:\\work\\frontend", "run": "npm run dev" },
//!             "b": { "split": "down",
//!                    "a": { "cwd": "C:\\work\\backend", "run": "cargo watch -x run" },
//!                    "b": { "cwd": "C:\\work", "run": "claude" } } } }
//! ```
//!
//! A pane is `{ "cwd": ..., "run": ... }` (both optional); a split puts `a` and `b` side by side
//! (`"right"`) or on top of each other (`"down"`). The last session is kept the same way, in
//! the state folder, so windows can reopen as they were.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::layout::{Axis, Node, PaneId};

/// More panes than this in one window is not useful, and a typo shouldn't start a hundred shells.
pub const MAX_PANES: usize = 12;

fn half() -> f32 {
    0.5
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Spec {
    Split {
        /// `right` puts `a` and `b` side by side, `down` stacks them.
        split: String,
        #[serde(default = "half")]
        ratio: f32,
        a: Box<Spec>,
        b: Box<Spec>,
    },
    Pane {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cwd: Option<String>,
        /// Typed into the shell once it is ready.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        run: Option<String>,
    },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Layout {
    pub root: Spec,
}

/// A pane to start for a layout.
#[derive(Clone, Debug, PartialEq)]
pub struct Leaf {
    pub id: PaneId,
    pub cwd: Option<PathBuf>,
    pub run: Option<String>,
}

impl Spec {
    fn count(&self) -> usize {
        match self {
            Spec::Pane { .. } => 1,
            Spec::Split { a, b, .. } => a.count() + b.count(),
        }
    }

    fn build(&self, next: &mut PaneId, leaves: &mut Vec<Leaf>) -> Node {
        match self {
            Spec::Pane { cwd, run } => {
                let id = *next;
                *next += 1;
                let run = run.as_ref().map(|r| r.trim().to_string()).filter(|r| !r.is_empty());
                leaves.push(Leaf { id, cwd: cwd.as_ref().filter(|c| !c.is_empty()).map(PathBuf::from), run });
                Node::Leaf(id)
            }
            Spec::Split { split, ratio, a, b } => {
                let axis = if matches!(split.to_lowercase().as_str(), "down" | "vertical" | "stacked") {
                    Axis::Vertical
                } else {
                    Axis::Horizontal
                };
                let ratio = if ratio.is_finite() { ratio.clamp(0.1, 0.9) } else { 0.5 };
                let a = Box::new(a.build(next, leaves));
                let b = Box::new(b.build(next, leaves));
                Node::Split { axis, ratio, a, b }
            }
        }
    }

    fn from_node(node: &Node, cwd: &dyn Fn(PaneId) -> Option<String>) -> Spec {
        match node {
            Node::Leaf(id) => Spec::Pane { cwd: cwd(*id), run: None },
            Node::Split { axis, ratio, a, b } => Spec::Split {
                split: if *axis == Axis::Horizontal { "right" } else { "down" }.to_string(),
                ratio: *ratio,
                a: Box::new(Spec::from_node(a, cwd)),
                b: Box::new(Spec::from_node(b, cwd)),
            },
        }
    }
}

impl Layout {
    pub fn panes(&self) -> usize {
        self.root.count()
    }

    /// The layout of a window: its split tree and the folder of each pane.
    pub fn from_node(node: &Node, cwd: &dyn Fn(PaneId) -> Option<String>) -> Layout {
        Layout { root: Spec::from_node(node, cwd) }
    }

    /// The split tree for this layout, with new pane ids counting up from `first_id`, and the
    /// panes to start.
    pub fn build(&self, first_id: PaneId) -> Result<(Node, Vec<Leaf>), String> {
        let n = self.panes();
        if n > MAX_PANES {
            return Err(format!("a layout can have at most {MAX_PANES} panes, this one has {n}"));
        }
        let mut next = first_id;
        let mut leaves = Vec::new();
        let node = self.root.build(&mut next, &mut leaves);
        Ok((node, leaves))
    }
}

/// A name that is safe as a file name: letters, digits, spaces, `-` and `_`.
pub fn sanitize(name: &str) -> Option<String> {
    let cleaned: String = name
        .trim()
        .chars()
        .map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_') { c } else { '-' })
        .take(60)
        .collect();
    let cleaned = cleaned.trim().to_string();
    (!cleaned.is_empty()).then_some(cleaned)
}

fn config_folder() -> Option<PathBuf> {
    crate::config::config_path().and_then(|p| p.parent().map(Path::to_path_buf))
}

pub fn dir() -> Option<PathBuf> {
    config_folder().map(|d| d.join("layouts"))
}

fn session_file() -> Option<PathBuf> {
    crate::config::state_dir().map(|d| d.join("session.json"))
}

fn write(path: &Path, layout: &Layout) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let text = serde_json::to_string_pretty(layout).map_err(|e| e.to_string())?;
    std::fs::write(path, text).map_err(|e| format!("could not write {}: {e}", path.display()))
}

fn read(path: &Path) -> Result<Layout, String> {
    let text = std::fs::read_to_string(path).map_err(|e| format!("could not read {}: {e}", path.display()))?;
    serde_json::from_str(&text).map_err(|e| format!("{} is not a valid layout: {e}", path.display()))
}

pub fn save(name: &str, layout: &Layout) -> Result<String, String> {
    let name = sanitize(name).ok_or("give the layout a name")?;
    let path = dir().ok_or("no config folder")?.join(format!("{name}.json"));
    write(&path, layout)?;
    Ok(name)
}

pub fn load(name: &str) -> Result<Layout, String> {
    let path = dir().ok_or("no config folder")?.join(format!("{}.json", sanitize(name).ok_or("no such layout")?));
    read(&path)
}

pub fn save_session(layout: &Layout) {
    if let Some(path) = session_file()
        && let Err(e) = write(&path, layout)
    {
        log::warn!("could not save the session: {e}");
    }
}

pub fn load_session() -> Option<Layout> {
    session_file().filter(|p| p.exists()).and_then(|p| read(&p).ok())
}

fn names_in(dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = std::fs::read_dir(dir)
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|e| {
            let path = e.path();
            (path.extension().is_some_and(|x| x == "json")).then(|| path.file_stem()?.to_str().map(str::to_string))?
        })
        .collect();
    names.sort_by_key(|n| n.to_lowercase());
    names
}

/// Names of the saved layouts, sorted.
pub fn saved_names() -> Vec<String> {
    dir().map(|d| names_in(&d)).unwrap_or_default()
}

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

    const SAMPLE: &str = r#"{ "root": { "split": "right", "ratio": 0.4,
        "a": { "cwd": "C:\\work\\frontend", "run": "npm run dev" },
        "b": { "split": "down",
               "a": { "cwd": "C:\\work\\backend", "run": "cargo watch" },
               "b": { } } } }"#;

    #[test]
    fn a_layout_builds_a_tree_and_its_panes() {
        let layout: Layout = serde_json::from_str(SAMPLE).unwrap();
        assert_eq!(layout.panes(), 3);
        let (node, leaves) = layout.build(10).unwrap();
        let ids: Vec<_> = leaves.iter().map(|l| l.id).collect();
        assert_eq!(ids, vec![10, 11, 12]);
        assert_eq!(leaves[0].cwd.as_deref(), Some(Path::new("C:\\work\\frontend")));
        assert_eq!(leaves[0].run.as_deref(), Some("npm run dev"));
        assert_eq!((leaves[2].cwd.clone(), leaves[2].run.clone()), (None, None));
        let Node::Split { axis, ratio, a, b } = node else { panic!("root is a split") };
        assert_eq!((axis, ratio), (Axis::Horizontal, 0.4));
        assert!(matches!(*a, Node::Leaf(10)));
        assert!(matches!(*b, Node::Split { axis: Axis::Vertical, ratio, .. } if ratio == 0.5));
    }

    #[test]
    fn a_layout_round_trips_through_the_tree() {
        let layout: Layout = serde_json::from_str(SAMPLE).unwrap();
        let (node, _) = layout.build(1).unwrap();
        let back = Layout::from_node(&node, &|id| Some(format!("folder{id}")));
        assert_eq!(back.panes(), 3);
        let text = serde_json::to_string(&back).unwrap();
        let again: Layout = serde_json::from_str(&text).unwrap();
        assert_eq!(again, back);
        let Spec::Split { split, ratio, .. } = &back.root else { panic!() };
        assert_eq!((split.as_str(), *ratio), ("right", 0.4));
    }

    #[test]
    fn bad_layouts_are_refused_or_cleaned() {
        // Too many panes.
        let mut spec = Spec::Pane { cwd: None, run: None };
        for _ in 0..MAX_PANES {
            spec = Spec::Split { split: "right".into(), ratio: 0.5, a: Box::new(spec), b: Box::new(Spec::Pane { cwd: None, run: None }) };
        }
        assert!(Layout { root: spec }.build(1).is_err());
        // A silly ratio is pulled into range; blank commands are dropped.
        let layout: Layout = serde_json::from_str(
            r#"{"root":{"split":"down","ratio":7.0,"a":{"run":"  "},"b":{"cwd":""}}}"#,
        )
        .unwrap();
        let (node, leaves) = layout.build(1).unwrap();
        assert!(matches!(node, Node::Split { axis: Axis::Vertical, ratio, .. } if ratio == 0.9));
        assert!(leaves.iter().all(|l| l.run.is_none() && l.cwd.is_none()));
        // Not a layout at all.
        assert!(serde_json::from_str::<Layout>("{\"nope\": 1}").is_err());
    }

    #[test]
    fn names_are_safe_file_names() {
        assert_eq!(sanitize("  work setup "), Some("work setup".into()));
        assert_eq!(sanitize("a/b\\c:d"), Some("a-b-c-d".into()));
        assert_eq!(sanitize("..\\evil"), Some("---evil".into()));
        assert_eq!(sanitize("   "), None);
        assert_eq!(sanitize(&"x".repeat(100)).unwrap().len(), 60);
    }

    #[test]
    fn saved_layouts_are_listed_by_name() {
        let dir = std::env::temp_dir().join(format!("rustimal-layouts-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let layout: Layout = serde_json::from_str(SAMPLE).unwrap();
        write(&dir.join("Work.json"), &layout).unwrap();
        write(&dir.join("alpha.json"), &layout).unwrap();
        std::fs::write(dir.join("notes.txt"), "x").unwrap();
        assert_eq!(names_in(&dir), vec!["alpha".to_string(), "Work".to_string()]);
        assert_eq!(read(&dir.join("Work.json")).unwrap(), layout);
        std::fs::write(dir.join("broken.json"), "{").unwrap();
        assert!(read(&dir.join("broken.json")).is_err());
        let _ = std::fs::remove_dir_all(&dir);
    }
}