rustimal 0.5.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The current environment variables, read from the registry.
//!
//! Programs started from the Start menu inherit Explorer's environment, which
//! is frozen at login. Installers that don't broadcast their PATH change
//! (Claude Code, npm, pnpm, scoop, ...) would be missing from every shell
//! until the next sign-in. Like Windows Terminal, each new shell gets the
//! variables as the registry has them now, and open shells are told when PATH
//! changes (see `watch`).

use std::collections::HashMap;

const HKEY_CURRENT_USER: isize = 0x8000_0001u32 as i32 as isize;
const HKEY_LOCAL_MACHINE: isize = 0x8000_0002u32 as i32 as isize;
const KEY_READ: u32 = 0x20019;
const REG_SZ: u32 = 1;
const REG_EXPAND_SZ: u32 = 2;
const ERROR_MORE_DATA: i32 = 234;

#[link(name = "advapi32")]
unsafe extern "system" {
    fn RegOpenKeyExW(key: isize, subkey: *const u16, options: u32, sam: u32, result: *mut isize) -> i32;
    #[allow(clippy::too_many_arguments)]
    fn RegEnumValueW(
        key: isize,
        index: u32,
        name: *mut u16,
        name_len: *mut u32,
        reserved: *mut u32,
        kind: *mut u32,
        data: *mut u8,
        data_len: *mut u32,
    ) -> i32;
    fn RegCloseKey(key: isize) -> i32;
    fn RegNotifyChangeKeyValue(key: isize, subtree: i32, filter: u32, event: isize, asynchronous: i32) -> i32;
}

const SYSTEM_ENV: &str = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
const USER_ENV: &str = "Environment";
const REG_NOTIFY_CHANGE_LAST_SET: u32 = 4;

/// (name, value, needs %VAR% expansion) for every string value under a key.
fn read(root: isize, path: &str) -> Vec<(String, String, bool)> {
    let wide: Vec<u16> = path.encode_utf16().chain([0]).collect();
    let mut key = 0;
    // SAFETY: valid null-terminated path and out pointer.
    if unsafe { RegOpenKeyExW(root, wide.as_ptr(), 0, KEY_READ, &mut key) } != 0 {
        return Vec::new();
    }
    let mut out = Vec::new();
    let mut name = vec![0u16; 16384];
    let mut data = vec![0u8; 8192];
    let mut index = 0;
    loop {
        let mut name_len = name.len() as u32;
        let mut data_len = data.len() as u32;
        let mut kind = 0;
        // SAFETY: buffers and their lengths match.
        let status = unsafe {
            RegEnumValueW(
                key,
                index,
                name.as_mut_ptr(),
                &mut name_len,
                std::ptr::null_mut(),
                &mut kind,
                data.as_mut_ptr(),
                &mut data_len,
            )
        };
        if status == ERROR_MORE_DATA {
            data.resize(data_len as usize + 2, 0);
            continue;
        }
        if status != 0 {
            break;
        }
        index += 1;
        if kind != REG_SZ && kind != REG_EXPAND_SZ {
            continue;
        }
        let units: Vec<u16> =
            data[..data_len as usize].as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes([b[0], b[1]])).collect();
        let value = String::from_utf16_lossy(&units).trim_end_matches('\0').to_string();
        out.push((String::from_utf16_lossy(&name[..name_len as usize]), value, kind == REG_EXPAND_SZ));
    }
    // SAFETY: `key` was opened above.
    unsafe { RegCloseKey(key) };
    out
}

/// Replace %NAME% with values from `vars` (case-insensitive), then the process environment.
fn expand(s: &str, vars: &HashMap<String, (String, String)>) -> String {
    let mut out = String::new();
    let mut rest = s;
    while let Some(start) = rest.find('%') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        let Some(end) = after.find('%') else {
            out.push_str(&rest[start..]);
            return out;
        };
        let name = &after[..end];
        match vars.get(&name.to_ascii_lowercase()).map(|(_, v)| v.clone()).or_else(|| std::env::var(name).ok()) {
            Some(v) if !name.is_empty() => out.push_str(&v),
            _ => out.push_str(&rest[start..start + end + 2]),
        }
        rest = &after[end + 1..];
    }
    out.push_str(rest);
    out
}

/// System variables, overridden by user variables; PATH is system PATH followed by user PATH.
pub fn fresh() -> Vec<(String, String)> {
    let system = read(HKEY_LOCAL_MACHINE, SYSTEM_ENV);
    let user = read(HKEY_CURRENT_USER, USER_ENV);
    if system.is_empty() && user.is_empty() {
        return Vec::new();
    }
    // Plain values first, so expandable ones can refer to them.
    let mut vars: HashMap<String, (String, String)> = HashMap::new();
    for pass in [false, true] {
        for (name, value, expandable) in system.iter().chain(&user) {
            if *expandable != pass || name.eq_ignore_ascii_case("path") {
                continue;
            }
            let value = if *expandable { expand(value, &vars) } else { value.clone() };
            vars.insert(name.to_ascii_lowercase(), (name.clone(), value));
        }
    }
    let path_of = |list: &[(String, String, bool)]| {
        list.iter().find(|(n, _, _)| n.eq_ignore_ascii_case("path")).map(|(_, v, _)| expand(v, &vars))
    };
    let path: Vec<String> =
        [path_of(&system), path_of(&user)].into_iter().flatten().filter(|p| !p.is_empty()).collect();
    let mut out: Vec<(String, String)> = vars.into_values().collect();
    if !path.is_empty() {
        out.push(("Path".into(), path.join(";")));
    }
    out
}

/// Windows PATH as the registry has it now.
pub fn path() -> Option<String> {
    fresh().into_iter().find(|(k, _)| k.eq_ignore_ascii_case("path")).map(|(_, v)| v)
}

/// Keep `file` holding the current Windows PATH, rewriting it whenever the
/// environment changes in the registry. The shell integration reads it at each
/// prompt, so open shells pick up newly installed tools without a restart.
pub fn watch(file: std::path::PathBuf) {
    let file = std::sync::Arc::new(file);
    write_path(&file);
    for (root, subkey) in [(HKEY_CURRENT_USER, USER_ENV), (HKEY_LOCAL_MACHINE, SYSTEM_ENV)] {
        let file = file.clone();
        let spawned = std::thread::Builder::new().name("env-watch".into()).spawn(move || {
            let wide: Vec<u16> = subkey.encode_utf16().chain([0]).collect();
            let mut key = 0;
            // SAFETY: valid null-terminated path and out pointer.
            if unsafe { RegOpenKeyExW(root, wide.as_ptr(), 0, KEY_READ, &mut key) } != 0 {
                return;
            }
            loop {
                // SAFETY: `key` is open; blocks until a value under it changes.
                if unsafe { RegNotifyChangeKeyValue(key, 0, REG_NOTIFY_CHANGE_LAST_SET, 0, 0) } != 0 {
                    break;
                }
                // Installers often write several values in a row; let them finish.
                std::thread::sleep(std::time::Duration::from_millis(300));
                write_path(&file);
            }
            // SAFETY: opened above.
            unsafe { RegCloseKey(key) };
        });
        if let Err(e) = spawned {
            log::warn!("could not watch the environment: {e}");
        }
    }
}

fn write_path(file: &std::path::Path) {
    let Some(path) = path() else { return };
    if std::fs::read_to_string(file).is_ok_and(|old| old.trim_end() == path) {
        return;
    }
    // Write then rename, so a shell never reads half a line.
    let tmp = file.with_extension(format!("{}.tmp", std::process::id()));
    if std::fs::write(&tmp, format!("{path}\n")).is_ok() && std::fs::rename(&tmp, file).is_err() {
        let _ = std::fs::remove_file(&tmp);
    }
}