rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Other programs' windows inside a pane: a browser, a Tauri or Electron app, anything with a
//! window. It is the testing environment: run the program in a pane's shell, and its window
//! is moved into rustimal and laid over the pane, as a web view is (see `app::host`).
//!
//! Nothing here knows which program it is. A window is found by whose it is: the shell's
//! own processes and their children, so `npm run tauri dev` is found by the app it starts,
//! several steps down. It is then made a child window of rustimal's (`SetParent`).
//!
//! What can't be done this way: apps of the Microsoft Store (their window belongs to
//! `ApplicationFrameHost`), and programs running as administrator while rustimal doesn't.
//! Those keep their own window.
//!
//! A program inside a pane gets every key; rustimal hears none. So while one has the
//! keyboard, rustimal's pane shortcuts are taken from it and handed back, as the script in a
//! web view does (see [`Keys`]).

use std::collections::{BTreeMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use winit::event_loop::EventLoopProxy;

use crate::platform::win32::{
    CloseHandle, GetCurrentThreadId, GetMessageW, GetWindowLongPtrW, Hwnd, IsChild, Msg, PostThreadMessageW,
    RegisterHotKey, SetWindowLongPtrW, SetWindowPos, UnregisterHotKey,
};
use crate::terminal::events::UserEvent;

mod keys;
mod watch;
mod window;

pub use keys::Keys;
use watch::*;
pub use watch::{Found, Watch};
use window::*;
pub use window::{Mode, Window};

#[repr(C)]
struct Rect {
    left: i32,
    top: i32,
    right: i32,
    bottom: i32,
}

type EnumProc = unsafe extern "system" fn(Hwnd, isize) -> i32;
type HookProc = unsafe extern "system" fn(i32, usize, isize) -> isize;

#[link(name = "user32")]
unsafe extern "system" {
    fn EnumWindows(callback: EnumProc, param: isize) -> i32;
    fn IsWindow(hwnd: Hwnd) -> i32;
    fn IsWindowVisible(hwnd: Hwnd) -> i32;
    fn IsZoomed(hwnd: Hwnd) -> i32;
    fn GetWindow(hwnd: Hwnd, command: u32) -> Hwnd;
    fn GetAncestor(hwnd: Hwnd, flags: u32) -> Hwnd;
    fn GetParent(hwnd: Hwnd) -> Hwnd;
    fn ClientToScreen(hwnd: Hwnd, point: *mut [i32; 2]) -> i32;
    fn SetForegroundWindow(hwnd: Hwnd) -> i32;
    fn MapWindowPoints(from: Hwnd, to: Hwnd, points: *mut i32, count: u32) -> i32;
    fn SetWindowRgn(hwnd: Hwnd, region: isize, redraw: i32) -> i32;
    fn RedrawWindow(hwnd: Hwnd, update: *const Rect, region: isize, flags: u32) -> i32;
    fn GetWindowThreadProcessId(hwnd: Hwnd, process: *mut u32) -> u32;
    fn GetWindowRect(hwnd: Hwnd, rect: *mut Rect) -> i32;
    fn SetParent(child: Hwnd, parent: Hwnd) -> Hwnd;
    fn ShowWindow(hwnd: Hwnd, command: i32) -> i32;
    fn PostMessageW(hwnd: Hwnd, message: u32, wparam: usize, lparam: isize) -> i32;
    fn SetFocus(hwnd: Hwnd) -> Hwnd;
    fn GetFocus() -> Hwnd;
    fn GetCursorPos(point: *mut [i32; 2]) -> i32;
    fn SetWindowsHookExW(kind: i32, callback: HookProc, module: isize, thread: u32) -> isize;
    fn CallNextHookEx(hook: isize, code: i32, wparam: usize, lparam: isize) -> isize;
}

#[link(name = "gdi32")]
unsafe extern "system" {
    fn CreateRectRgn(left: i32, top: i32, right: i32, bottom: i32) -> isize;
}

#[link(name = "kernel32")]
unsafe extern "system" {
    fn CreateToolhelp32Snapshot(flags: u32, process: u32) -> isize;
    fn Process32FirstW(snapshot: isize, entry: *mut ProcessEntry) -> i32;
    fn Process32NextW(snapshot: isize, entry: *mut ProcessEntry) -> i32;
}

unsafe extern "system" fn collect(hwnd: Hwnd, list: isize) -> i32 {
    // SAFETY: `list` is the vector `top_level_windows` passes, alive for the whole call.
    let list = unsafe { &mut *(list as *mut Vec<Hwnd>) };
    list.push(hwnd);
    1
}

// ---- Shortcuts while a hosted program has the keyboard ---------------------------------
//
// A program in a pane is given every key, so rustimal's pane shortcuts (split, move
// between panes, close) are asked of Windows instead: while a program has the keyboard,
// those chords are registered as hot keys, and Windows reports them to a thread of our own
// instead of to the program. (A keyboard hook does this too, but Windows drops one for good
// whenever it is slow to answer, which starting a shell for a new pane is enough to cause.)

#[cfg(test)]
mod tests {
    use std::process::Command;

    use super::keys::key_name;
    use super::*;

    #[test]
    fn keys_are_named_as_the_config_names_them() {
        assert_eq!(key_name(0x54).as_deref(), Some("t"));
        assert_eq!(key_name(0x31).as_deref(), Some("1"));
        assert_eq!(key_name(0x25).as_deref(), Some("left"));
        assert_eq!(key_name(0x70).as_deref(), Some("f1"));
        assert_eq!(key_name(0x7B).as_deref(), Some("f12"));
        assert_eq!(key_name(0xBB).as_deref(), Some("="));
        assert_eq!(key_name(0x10), None, "a modifier alone is no chord");
        // Everything named here must be something the config can bind.
        for vk in 0..=0xFFu32 {
            if let Some(name) = key_name(vk) {
                assert!(crate::config::keys::Chord::parse(&name).is_some(), "{vk:#x} -> {name}");
            }
        }
    }

    #[test]
    fn the_process_list_has_this_process_and_its_parent() {
        let all = processes();
        let me = std::process::id();
        let entry = all.iter().find(|&&(id, _)| id == me).expect("this process is listed");
        assert!(entry.1 != 0);
    }

    /// Starts a real program and finds its window by whose it is.
    #[test]
    #[ignore = "opens a window"]
    fn a_programs_window_is_found_by_whose_it_is() {
        let mut child = Command::new("notepad.exe").spawn().expect("notepad");
        let mut watch = Watch::new(std::process::id());
        let began = Instant::now();
        let found = loop {
            match watch.poll() {
                Found::Window(w) => break Some(w),
                Found::Over => break None,
                Found::Waiting if began.elapsed() > Duration::from_secs(20) => break None,
                Found::Waiting => std::thread::sleep(Duration::from_millis(200)),
            }
        };
        let _ = child.kill();
        let hwnd = found.expect("notepad's window");
        assert_ne!(process_of(hwnd), 0);
    }
}