rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Finding the window a command opens: the processes below the shell, and the windows
//! they own.

use super::*;

/// A window smaller than this is a splash screen or a helper, not the program's window.
pub(super) const MIN_SIZE: (i32, i32) = (200, 150);

/// How long a window is waited for, as long as the command it is looked for in goes on.
pub(super) const GIVE_UP: Duration = Duration::from_secs(600);

/// A command whose processes are all gone has finished, even if it never showed a window.
pub(super) const FINISHED_AFTER: Duration = Duration::from_secs(3);

/// Without a single process to be seen, nothing was started.
pub(super) const NOTHING_STARTED: Duration = Duration::from_secs(20);

#[repr(C)]
pub(super) struct ProcessEntry {
    pub(super) size: u32,
    pub(super) usage: u32,
    pub(super) id: u32,
    pub(super) heap: usize,
    pub(super) module: u32,
    pub(super) threads: u32,
    pub(super) parent: u32,
    pub(super) priority: i32,
    pub(super) flags: u32,
    pub(super) exe: [u16; 260],
}

/// Every process now running, as `(id, parent id)`.
pub(super) fn processes() -> Vec<(u32, u32)> {
    const SNAPSHOT_PROCESSES: u32 = 2;
    const INVALID: isize = -1;
    let mut all = Vec::new();
    // SAFETY: the snapshot is closed below; the entry is the structure these take, with
    // its size set.
    unsafe {
        let snapshot = CreateToolhelp32Snapshot(SNAPSHOT_PROCESSES, 0);
        if snapshot == INVALID || snapshot == 0 {
            return all;
        }
        let mut entry = ProcessEntry {
            size: size_of::<ProcessEntry>() as u32,
            usage: 0,
            id: 0,
            heap: 0,
            module: 0,
            threads: 0,
            parent: 0,
            priority: 0,
            flags: 0,
            exe: [0; 260],
        };
        let mut more = Process32FirstW(snapshot, &mut entry) != 0;
        while more {
            all.push((entry.id, entry.parent));
            more = Process32NextW(snapshot, &mut entry) != 0;
        }
        CloseHandle(snapshot);
    }
    all
}

pub(super) fn process_of(hwnd: Hwnd) -> u32 {
    let mut id = 0u32;
    // SAFETY: `id` is where the process id goes.
    unsafe { GetWindowThreadProcessId(hwnd, &mut id) };
    id
}

pub(super) fn rect_of(hwnd: Hwnd) -> Option<Rect> {
    let mut rect = Rect { left: 0, top: 0, right: 0, bottom: 0 };
    // SAFETY: `rect` is the structure this fills.
    (unsafe { GetWindowRect(hwnd, &mut rect) } != 0).then_some(rect)
}

/// Windows of the desktop that a person would call an app's: visible, with no owner, and
/// not a tool window.
pub(super) fn top_level_windows() -> Vec<Hwnd> {
    let mut list: Vec<Hwnd> = Vec::new();
    // SAFETY: the callback only uses the vector, which outlives the call.
    unsafe { EnumWindows(collect, &mut list as *mut Vec<Hwnd> as isize) };
    list.retain(|&w| {
        // SAFETY: only reads about a window handle that may be stale by now.
        unsafe {
            IsWindowVisible(w) != 0
                && GetWindow(w, GW_OWNER) == 0
                && GetWindowLongPtrW(w, GWL_EXSTYLE) & (WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE) == 0
        }
    });
    list
}

/// Looks, for a command a pane's shell runs, for the window it opens.
pub struct Watch {
    root: u32,
    /// The shell's descendants seen so far. Kept after they end, so that one that starts
    /// another and quits (a browser's launcher) doesn't lose the chain.
    tree: HashSet<u32>,
    before: HashSet<Hwnd>,
    started: Instant,
    seen_any: bool,
    empty_since: Option<Instant>,
}

pub enum Found {
    Window(Hwnd),
    Waiting,
    /// The command ended, or never began.
    Over,
}

impl Watch {
    /// Look for windows opened from now on by `root`'s children.
    pub fn new(root: u32) -> Self {
        Self {
            root,
            tree: HashSet::new(),
            before: top_level_windows().into_iter().collect(),
            started: Instant::now(),
            seen_any: false,
            empty_since: None,
        }
    }

    pub fn poll(&mut self) -> Found {
        let all = processes();
        let alive: HashSet<u32> = all.iter().map(|&(id, _)| id).collect();
        // A process id may be reused; one whose parent is not alive is not ours anyway,
        // unless we saw its parent, which `tree` remembers.
        self.tree.insert(self.root);
        loop {
            let before = self.tree.len();
            for &(id, parent) in &all {
                if self.tree.contains(&parent) && id != std::process::id() {
                    self.tree.insert(id);
                }
            }
            if self.tree.len() == before {
                break;
            }
        }
        let running = self.tree.iter().filter(|&&id| id != self.root && alive.contains(&id)).count();
        if running > 0 {
            self.seen_any = true;
            self.empty_since = None;
        }
        for window in top_level_windows() {
            let owner = process_of(window);
            // Never rustimal's own window, nor the shell's.
            if self.before.contains(&window) || !self.tree.contains(&owner) || owner == std::process::id() {
                continue;
            }
            let Some(r) = rect_of(window) else { continue };
            if r.right - r.left >= MIN_SIZE.0 && r.bottom - r.top >= MIN_SIZE.1 {
                return Found::Window(window);
            }
        }
        let over = if running == 0 {
            let since = *self.empty_since.get_or_insert_with(Instant::now);
            let patience = if self.seen_any { FINISHED_AFTER } else { NOTHING_STARTED };
            since.elapsed() >= patience
        } else {
            false
        };
        if over || self.started.elapsed() >= GIVE_UP { Found::Over } else { Found::Waiting }
    }
}