rustimal 0.2.4

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Command line: `--install`, `--uninstall`, `--version` and `--help`.
//!
//! `cargo install rustimal` only puts the exe in `~/.cargo/bin`. `rustimal --install`
//! adds what makes it feel installed: a Start menu entry, "Open in rustimal" in
//! Explorer's right-click menu, and Win+R. That's the job of `install.ps1`, which is
//! embedded here so it works from a crates.io install, with no repo checkout.

use std::process::Command;

const INSTALL_SCRIPT: &str = include_str!("../install.ps1");

const HELP: &str = "\
rustimal - a GPU-rendered terminal for Windows

USAGE:
    rustimal [DIRECTORY]       open a window, starting in DIRECTORY
    rustimal --install         add Start menu, Explorer right-click and Win+R entries
    rustimal --install --desktop
                               ... and a desktop shortcut
    rustimal --uninstall       remove those entries (the exe and your config stay)
    rustimal --version
    rustimal --help
";

#[link(name = "kernel32")]
unsafe extern "system" {
    fn AttachConsole(pid: u32) -> i32;
    fn GetStdHandle(which: u32) -> isize;
    fn SetStdHandle(which: u32, handle: isize) -> i32;
}

const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
const STD_ERROR_HANDLE: u32 = -12i32 as u32;

/// The release build is a windowed program, so it starts without console output.
/// When run from a terminal, connect to that terminal so messages show up.
fn attach_console() {
    use std::os::windows::io::IntoRawHandle;
    // SAFETY: plain kernel32 calls; the handles passed to SetStdHandle stay open on purpose.
    unsafe {
        if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
            return; // no parent console (or we already have one, as in debug builds)
        }
        for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
            let h = GetStdHandle(which);
            if (h == 0 || h == -1)
                && let Ok(f) = std::fs::OpenOptions::new().write(true).open("CONOUT$")
            {
                SetStdHandle(which, f.into_raw_handle() as isize);
            }
        }
    }
}

/// Handle a command line option. Returns the exit code, or `None` if `arg` isn't one
/// (it's then the starting directory).
pub fn run(arg: &str) -> Option<i32> {
    let rest = || std::env::args().skip(2).collect::<Vec<_>>();
    match arg {
        "--version" | "-V" => {
            attach_console();
            println!("rustimal {}", env!("CARGO_PKG_VERSION"));
            Some(0)
        }
        "--help" | "-h" | "/?" => {
            attach_console();
            print!("{HELP}");
            Some(0)
        }
        "--install" => {
            attach_console();
            Some(setup(false, &rest()))
        }
        "--uninstall" => {
            attach_console();
            Some(setup(true, &rest()))
        }
        _ => None,
    }
}

fn setup(uninstall: bool, extra: &[String]) -> i32 {
    let mut args = vec!["-NoProfile".to_string(), "-ExecutionPolicy".into(), "Bypass".into(), "-File".into()];
    let script = std::env::temp_dir().join(format!("rustimal-setup-{}.ps1", std::process::id()));
    if let Err(e) = std::fs::write(&script, INSTALL_SCRIPT) {
        eprintln!("could not write {}: {e}", script.display());
        return 1;
    }
    args.push(script.to_string_lossy().into_owned());
    match std::env::current_exe() {
        Ok(exe) => {
            args.push("-ExePath".into());
            args.push(exe.to_string_lossy().into_owned());
        }
        Err(e) => {
            eprintln!("could not find the rustimal executable: {e}");
            let _ = std::fs::remove_file(&script);
            return 1;
        }
    }
    if uninstall {
        args.push("-Uninstall".into());
    }
    for a in extra {
        match a.to_ascii_lowercase().as_str() {
            "--desktop" if !uninstall => args.push("-Desktop".into()),
            other => {
                eprintln!("unknown option: {other}\n\n{HELP}");
                let _ = std::fs::remove_file(&script);
                return 2;
            }
        }
    }
    let status = Command::new("powershell.exe").args(&args).status();
    let _ = std::fs::remove_file(&script);
    match status {
        Ok(s) if s.success() => 0,
        Ok(s) => s.code().unwrap_or(1),
        Err(e) => {
            eprintln!("could not run powershell.exe: {e}");
            1
        }
    }
}