From eee24dad36c9c6a206bfe5ab42d9ecd7a359cadc Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 19:33:26 -0700 Subject: [PATCH] feat(e2e): add the guest agent and the test window for the Windows guest komorebi-e2e-agent runs in the interactive session of the guest and answers the host over a forwarded TCP port: exec, spawn, os_windows (DWM frame, cloak and focus), displays, window verbs and file transfer. komorebi-testwin is a plain Win32 window with a stable exe name and class and a control channel on stdin. Both cross-build from Linux and pass clippy; neither has run in a guest yet. --- Cargo.lock | 17 ++ Cargo.toml | 2 + e2e/guest/agent/Cargo.toml | 11 ++ e2e/guest/agent/src/main.rs | 282 +++++++++++++++++++++++++++++ e2e/guest/testwin/Cargo.toml | 10 ++ e2e/guest/testwin/src/main.rs | 328 ++++++++++++++++++++++++++++++++++ 6 files changed, 650 insertions(+) create mode 100644 e2e/guest/agent/Cargo.toml create mode 100644 e2e/guest/agent/src/main.rs create mode 100644 e2e/guest/testwin/Cargo.toml create mode 100644 e2e/guest/testwin/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index f53e00a9..9f1ff5f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3427,6 +3427,15 @@ dependencies = [ "uds_windows", ] +[[package]] +name = "komorebi-e2e-agent" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json_lenient", + "windows 0.62.2", +] + [[package]] name = "komorebi-gui" version = "0.1.42" @@ -3471,6 +3480,14 @@ dependencies = [ "whkd-parser", ] +[[package]] +name = "komorebi-testwin" +version = "0.1.0" +dependencies = [ + "serde_json_lenient", + "windows 0.62.2", +] + [[package]] name = "komorebi-themes" version = "0.1.42" diff --git a/Cargo.toml b/Cargo.toml index 0baed429..8b68f258 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,8 @@ members = [ "komorebi-bar", "komorebi-themes", "komorebi-shortcuts", + "e2e/guest/agent", + "e2e/guest/testwin", ] [workspace.dependencies] diff --git a/e2e/guest/agent/Cargo.toml b/e2e/guest/agent/Cargo.toml new file mode 100644 index 00000000..17fb92d7 --- /dev/null +++ b/e2e/guest/agent/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "komorebi-e2e-agent" +version = "0.1.0" +edition = "2024" +description = "Runs in the interactive session of an e2e guest and answers the host" +publish = false + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +windows = { workspace = true } diff --git a/e2e/guest/agent/src/main.rs b/e2e/guest/agent/src/main.rs new file mode 100644 index 00000000..04031196 --- /dev/null +++ b/e2e/guest/agent/src/main.rs @@ -0,0 +1,282 @@ +//! The guest half of the e2e suite on Windows. +//! +//! It must run inside the interactive session (a Run entry of the autologon +//! user), because session 0 has no usable desktop. The host talks to it over +//! a TCP port that QEMU forwards from the host's loopback. One request is one +//! line of JSON, `{"id": 1, "verb": "...", ...}`, answered by one line, +//! `{"id": 1, "ok": ...}` or `{"id": 1, "error": "..."}`. +//! +//! `put_file` and `get_file` move bytes after the JSON line, as the `size` +//! raw bytes that the request or the answer announces, so that a daemon of +//! tens of megabytes is not wrapped in JSON. +//! +//! The agent injects no input: keys, pointer and screenshots come from the +//! host (QMP), which also works at the lock screen. + +#![cfg(windows)] + +use std::io::BufRead; +use std::io::BufReader; +use std::io::Read; +use std::io::Write; +use std::net::TcpListener; +use std::net::TcpStream; +use std::process::Command; + +use serde::Deserialize; +use serde_json::Value; +use serde_json::json; +use windows::Win32::Foundation::HWND; +use windows::Win32::Foundation::LPARAM; +use windows::Win32::Foundation::RECT; +use windows::Win32::Foundation::WPARAM; +use windows::Win32::Graphics::Dwm::DWMWA_CLOAKED; +use windows::Win32::Graphics::Dwm::DWMWA_EXTENDED_FRAME_BOUNDS; +use windows::Win32::Graphics::Dwm::DwmGetWindowAttribute; +use windows::Win32::Graphics::Gdi::EnumDisplayMonitors; +use windows::Win32::Graphics::Gdi::GetMonitorInfoW; +use windows::Win32::Graphics::Gdi::HDC; +use windows::Win32::Graphics::Gdi::HMONITOR; +use windows::Win32::Graphics::Gdi::MONITORINFO; +use windows::Win32::UI::WindowsAndMessaging::EnumWindows; +use windows::Win32::UI::WindowsAndMessaging::GetClassNameW; +use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow; +use windows::Win32::UI::WindowsAndMessaging::GetWindowTextW; +use windows::Win32::UI::WindowsAndMessaging::IsIconic; +use windows::Win32::UI::WindowsAndMessaging::IsWindowVisible; +use windows::Win32::UI::WindowsAndMessaging::PostMessageW; +use windows::Win32::UI::WindowsAndMessaging::SW_MINIMIZE; +use windows::Win32::UI::WindowsAndMessaging::SW_RESTORE; +use windows::Win32::UI::WindowsAndMessaging::SetForegroundWindow; +use windows::Win32::UI::WindowsAndMessaging::ShowWindow; +use windows::Win32::UI::WindowsAndMessaging::WM_CLOSE; +use windows::core::BOOL; + +const DEFAULT_PORT: u16 = 7878; + +#[derive(Deserialize)] +struct Request { + id: Value, + verb: String, + #[serde(default)] + args: Vec, + #[serde(default)] + path: String, + #[serde(default)] + size: u64, + #[serde(default)] + hwnd: isize, +} + +fn rect_json(r: &RECT) -> Value { + // the shape komorebi itself prints: right and bottom are width and height + json!({ + "left": r.left, "top": r.top, + "right": r.right - r.left, "bottom": r.bottom - r.top, + }) +} + +fn hwnd_of(raw: isize) -> HWND { + HWND(raw as *mut _) +} + +/// One top-level window as the operating system describes it. +fn describe(hwnd: HWND) -> Option { + let mut title = [0u16; 512]; + // SAFETY: the buffer is valid for the length it is given. + let n = unsafe { GetWindowTextW(hwnd, &mut title) }; + if n <= 0 { + return None; + } + let mut class = [0u16; 256]; + // SAFETY: as above. + let c = unsafe { GetClassNameW(hwnd, &mut class) }; + + let mut frame = RECT::default(); + // SAFETY: `frame` is a RECT and its size is passed. + let _ = unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + (&mut frame as *mut RECT).cast(), + std::mem::size_of::() as u32, + ) + }; + let mut cloaked = 0u32; + // SAFETY: `cloaked` is a u32 and its size is passed. + let _ = unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_CLOAKED, + (&mut cloaked as *mut u32).cast(), + std::mem::size_of::() as u32, + ) + }; + + // SAFETY: plain queries on a window handle. + let (visible, minimized, focused) = unsafe { + ( + IsWindowVisible(hwnd).as_bool(), + IsIconic(hwnd).as_bool(), + GetForegroundWindow() == hwnd, + ) + }; + Some(json!({ + "hwnd": hwnd.0 as isize, + "title": String::from_utf16_lossy(&title[..n as usize]), + "class": String::from_utf16_lossy(&class[..c.max(0) as usize]), + "frame": rect_json(&frame), + "visible": visible, + "minimized": minimized, + "cloaked": cloaked != 0, + "focused": focused, + })) +} + +fn os_windows() -> Vec { + unsafe extern "system" fn each(hwnd: HWND, out: LPARAM) -> BOOL { + // SAFETY: `out` is the `Vec` passed below, alive for the whole call. + let out = unsafe { &mut *(out.0 as *mut Vec) }; + out.extend(describe(hwnd)); + BOOL(1) + } + let mut out = Vec::new(); + // SAFETY: the callback only touches the `Vec` passed as the parameter. + let _ = unsafe { EnumWindows(Some(each), LPARAM(&mut out as *mut _ as isize)) }; + out +} + +fn displays() -> Vec { + unsafe extern "system" fn each(monitor: HMONITOR, _: HDC, _: *mut RECT, out: LPARAM) -> BOOL { + // SAFETY: `out` is the `Vec` passed below, alive for the whole call. + let out = unsafe { &mut *(out.0 as *mut Vec) }; + let mut info = MONITORINFO { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }; + // SAFETY: `info` has its size set, as the call requires. + if unsafe { GetMonitorInfoW(monitor, &mut info) }.as_bool() { + out.push(json!({ + "monitor": rect_json(&info.rcMonitor), + "work_area": rect_json(&info.rcWork), + "primary": info.dwFlags & 1 != 0, + })); + } + BOOL(1) + } + let mut out = Vec::new(); + // SAFETY: the callback only touches the `Vec` passed as the parameter. + let _ = + unsafe { EnumDisplayMonitors(None, None, Some(each), LPARAM(&mut out as *mut _ as isize)) }; + out +} + +fn answer(stream: &mut TcpStream, id: &Value, result: Result) { + let line = match result { + Ok(ok) => json!({"id": id, "ok": ok}), + Err(error) => json!({"id": id, "error": error}), + }; + let _ = writeln!(stream, "{line}"); +} + +fn exec(args: &[String]) -> Result { + let (program, rest) = args.split_first().ok_or("exec wants a program")?; + let out = Command::new(program) + .args(rest) + .output() + .map_err(|e| format!("{program}: {e}"))?; + Ok(json!({ + "status": out.status.code(), + "stdout": String::from_utf8_lossy(&out.stdout), + "stderr": String::from_utf8_lossy(&out.stderr), + })) +} + +/// Starts a program that keeps running, in this session, and returns at once. +fn spawn(args: &[String]) -> Result { + let (program, rest) = args.split_first().ok_or("spawn wants a program")?; + let child = Command::new(program) + .args(rest) + .spawn() + .map_err(|e| format!("{program}: {e}"))?; + Ok(json!({"pid": child.id()})) +} + +fn serve(stream: TcpStream) -> std::io::Result<()> { + let mut writer = stream.try_clone()?; + let mut reader = BufReader::new(stream); + let mut line = String::new(); + loop { + line.clear(); + if reader.read_line(&mut line)? == 0 { + return Ok(()); + } + let req: Request = match serde_json::from_str(&line) { + Ok(req) => req, + Err(e) => { + answer(&mut writer, &Value::Null, Err(format!("bad request: {e}"))); + continue; + } + }; + let hwnd = hwnd_of(req.hwnd); + let result = match req.verb.as_str() { + "ping" => Ok(json!("pong")), + "exec" => exec(&req.args), + "spawn" => spawn(&req.args), + "os_windows" => Ok(Value::Array(os_windows())), + "displays" => Ok(Value::Array(displays())), + "activate" => { + // SAFETY: plain calls on a window handle given by the host. + unsafe { + let _ = ShowWindow(hwnd, SW_RESTORE); + Ok(json!(SetForegroundWindow(hwnd).as_bool())) + } + } + "minimize" => { + // SAFETY: as above. + Ok(json!(unsafe { ShowWindow(hwnd, SW_MINIMIZE) }.as_bool())) + } + "close" => { + // SAFETY: as above. + unsafe { PostMessageW(Some(hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)) } + .map(|()| json!(true)) + .map_err(|e| e.to_string()) + } + "put_file" => { + let mut bytes = vec![0u8; req.size as usize]; + reader.read_exact(&mut bytes)?; + std::fs::write(&req.path, bytes) + .map(|()| json!(req.size)) + .map_err(|e| format!("{}: {e}", req.path)) + } + "get_file" => match std::fs::read(&req.path) { + Ok(bytes) => { + answer(&mut writer, &req.id, Ok(json!({"size": bytes.len()}))); + writer.write_all(&bytes)?; + continue; + } + Err(e) => Err(format!("{}: {e}", req.path)), + }, + other => Err(format!("unknown verb {other}")), + }; + answer(&mut writer, &req.id, result); + } +} + +fn main() -> std::io::Result<()> { + let port = std::env::var("KOMOREBI_E2E_AGENT_PORT") + .ok() + .and_then(|p| p.parse().ok()) + .unwrap_or(DEFAULT_PORT); + // QEMU's user-mode network forwards the host port to the guest's own + // address, so loopback would not see it. The guest is on a private + // network of its own and has its firewall off (see `setup.ps1`). + let listener = TcpListener::bind(("0.0.0.0", port))?; + for stream in listener.incoming() { + let stream = stream?; + std::thread::spawn(move || { + let _ = serve(stream); + }); + } + Ok(()) +} diff --git a/e2e/guest/testwin/Cargo.toml b/e2e/guest/testwin/Cargo.toml new file mode 100644 index 00000000..64586ee2 --- /dev/null +++ b/e2e/guest/testwin/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "komorebi-testwin" +version = "0.1.0" +edition = "2024" +description = "A plain window for the e2e suite to tile, with a control channel" +publish = false + +[dependencies] +serde_json = { workspace = true } +windows = { workspace = true } diff --git a/e2e/guest/testwin/src/main.rs b/e2e/guest/testwin/src/main.rs new file mode 100644 index 00000000..e95dc48f --- /dev/null +++ b/e2e/guest/testwin/src/main.rs @@ -0,0 +1,328 @@ +//! A window for the e2e scenarios to tile. +//! +//! It has a stable exe name and window class, so that rules can match it, and +//! a control channel on stdin so that a scenario can change it while it runs. +//! Every command is one line; every answer is one line of JSON on stdout. +//! +//! ```text +//! title TEXT set the title +//! color RRGGBB fill the client area with a colour +//! resize W H resize the outer frame +//! report print the title and the visible frame +//! close close the window, as the close button would +//! exit leave without closing the window first +//! ``` +//! +//! Options: `--title T`, `--color RRGGBB`, `--size WxH`, `--min-size WxH` and +//! `--fixed` (not resizable). + +#![cfg(windows)] + +use std::collections::VecDeque; +use std::io::BufRead; +use std::io::Write; +use std::mem::size_of; +use std::sync::Mutex; +use std::sync::atomic::AtomicIsize; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +use windows::Win32::Foundation::COLORREF; +use windows::Win32::Foundation::HWND; +use windows::Win32::Foundation::LPARAM; +use windows::Win32::Foundation::LRESULT; +use windows::Win32::Foundation::RECT; +use windows::Win32::Foundation::WPARAM; +use windows::Win32::Graphics::Dwm::DWMWA_EXTENDED_FRAME_BOUNDS; +use windows::Win32::Graphics::Dwm::DwmGetWindowAttribute; +use windows::Win32::Graphics::Gdi::BeginPaint; +use windows::Win32::Graphics::Gdi::CreateSolidBrush; +use windows::Win32::Graphics::Gdi::DeleteObject; +use windows::Win32::Graphics::Gdi::EndPaint; +use windows::Win32::Graphics::Gdi::FillRect; +use windows::Win32::Graphics::Gdi::HGDIOBJ; +use windows::Win32::Graphics::Gdi::InvalidateRect; +use windows::Win32::Graphics::Gdi::PAINTSTRUCT; +use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::UI::WindowsAndMessaging::CW_USEDEFAULT; +use windows::Win32::UI::WindowsAndMessaging::CreateWindowExW; +use windows::Win32::UI::WindowsAndMessaging::DefWindowProcW; +use windows::Win32::UI::WindowsAndMessaging::DestroyWindow; +use windows::Win32::UI::WindowsAndMessaging::DispatchMessageW; +use windows::Win32::UI::WindowsAndMessaging::GetMessageW; +use windows::Win32::UI::WindowsAndMessaging::HMENU; +use windows::Win32::UI::WindowsAndMessaging::IDC_ARROW; +use windows::Win32::UI::WindowsAndMessaging::LoadCursorW; +use windows::Win32::UI::WindowsAndMessaging::MINMAXINFO; +use windows::Win32::UI::WindowsAndMessaging::MSG; +use windows::Win32::UI::WindowsAndMessaging::PostMessageW; +use windows::Win32::UI::WindowsAndMessaging::PostQuitMessage; +use windows::Win32::UI::WindowsAndMessaging::RegisterClassW; +use windows::Win32::UI::WindowsAndMessaging::SW_SHOW; +use windows::Win32::UI::WindowsAndMessaging::SWP_NOMOVE; +use windows::Win32::UI::WindowsAndMessaging::SWP_NOZORDER; +use windows::Win32::UI::WindowsAndMessaging::SetWindowPos; +use windows::Win32::UI::WindowsAndMessaging::SetWindowTextW; +use windows::Win32::UI::WindowsAndMessaging::ShowWindow; +use windows::Win32::UI::WindowsAndMessaging::TranslateMessage; +use windows::Win32::UI::WindowsAndMessaging::WINDOW_EX_STYLE; +use windows::Win32::UI::WindowsAndMessaging::WM_APP; +use windows::Win32::UI::WindowsAndMessaging::WM_CLOSE; +use windows::Win32::UI::WindowsAndMessaging::WM_DESTROY; +use windows::Win32::UI::WindowsAndMessaging::WM_ERASEBKGND; +use windows::Win32::UI::WindowsAndMessaging::WM_GETMINMAXINFO; +use windows::Win32::UI::WindowsAndMessaging::WM_PAINT; +use windows::Win32::UI::WindowsAndMessaging::WNDCLASSW; +use windows::Win32::UI::WindowsAndMessaging::WS_MAXIMIZEBOX; +use windows::Win32::UI::WindowsAndMessaging::WS_OVERLAPPEDWINDOW; +use windows::Win32::UI::WindowsAndMessaging::WS_THICKFRAME; +use windows::core::PCWSTR; +use windows::core::w; + +/// The window class rules can match on. +const CLASS: windows::core::PCWSTR = w!("KomorebiTestWin"); + +/// Posted to the window when a command is waiting in [`COMMANDS`]. +const WM_COMMAND_READY: u32 = WM_APP + 1; + +static COMMANDS: Mutex> = Mutex::new(VecDeque::new()); +static HWND_RAW: AtomicIsize = AtomicIsize::new(0); +static COLOR: AtomicU32 = AtomicU32::new(0x0080_5030); +static MIN_SIZE: Mutex> = Mutex::new(None); +static FIXED: Mutex> = Mutex::new(None); + +fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() +} + +/// `RRGGBB` as a GDI colour, which is `0x00BBGGRR`. +fn parse_color(s: &str) -> Option { + let rgb = u32::from_str_radix(s.trim_start_matches('#'), 16).ok()?; + let (r, g, b) = ((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff); + Some(r | (g << 8) | (b << 16)) +} + +fn parse_size(s: &str) -> Option<(i32, i32)> { + let (w, h) = s.split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?)) +} + +fn say(value: serde_json::Value) { + let mut out = std::io::stdout().lock(); + let _ = writeln!(out, "{value}"); + let _ = out.flush(); +} + +fn frame(hwnd: HWND) -> Option { + let mut rect = RECT::default(); + // SAFETY: `rect` is a RECT and the size passed is the size of a RECT. + unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + (&mut rect as *mut RECT).cast(), + size_of::() as u32, + ) + } + .ok()?; + Some(rect) +} + +fn title_of(hwnd: HWND) -> String { + use windows::Win32::UI::WindowsAndMessaging::GetWindowTextW; + let mut buf = [0u16; 512]; + // SAFETY: the buffer is valid for the length it is given. + let n = unsafe { GetWindowTextW(hwnd, &mut buf) }; + String::from_utf16_lossy(&buf[..n.max(0) as usize]) +} + +fn run_command(hwnd: HWND, line: &str) -> bool { + let mut words = line.split_whitespace(); + match words.next() { + Some("title") => { + let title = line.trim_start().strip_prefix("title").unwrap().trim(); + let title = wide(title); + // SAFETY: `title` is NUL-terminated and outlives the call. + let _ = unsafe { SetWindowTextW(hwnd, PCWSTR(title.as_ptr())) }; + say(serde_json::json!({"ok": true})); + } + Some("color") => match words.next().and_then(parse_color) { + Some(c) => { + COLOR.store(c, Ordering::SeqCst); + // SAFETY: `hwnd` is this process's own window. + let _ = unsafe { InvalidateRect(Some(hwnd), None, true) }; + say(serde_json::json!({"ok": true})); + } + None => say(serde_json::json!({"error": "color wants RRGGBB"})), + }, + Some("resize") => { + let w = words.next().and_then(|s| s.parse::().ok()); + let h = words.next().and_then(|s| s.parse::().ok()); + if let (Some(w), Some(h)) = (w, h) { + // SAFETY: `hwnd` is this process's own window. + let _ = unsafe { SetWindowPos(hwnd, None, 0, 0, w, h, SWP_NOMOVE | SWP_NOZORDER) }; + say(serde_json::json!({"ok": true})); + } else { + say(serde_json::json!({"error": "resize wants W H"})); + } + } + Some("report") => match frame(hwnd) { + Some(r) => say(serde_json::json!({ + "hwnd": hwnd.0 as isize, + "title": title_of(hwnd), + "frame": { + "left": r.left, "top": r.top, + "right": r.right - r.left, "bottom": r.bottom - r.top, + }, + })), + None => say(serde_json::json!({"error": "no frame"})), + }, + Some("close") => { + // SAFETY: `hwnd` is this process's own window. + let _ = unsafe { PostMessageW(Some(hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)) }; + } + Some("exit") => return false, + Some(other) => say(serde_json::json!({"error": format!("unknown {other}")})), + None => {} + } + true +} + +extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + match msg { + WM_COMMAND_READY => { + loop { + let Some(line) = COMMANDS.lock().unwrap().pop_front() else { + break; + }; + if !run_command(hwnd, &line) { + // SAFETY: plain Win32 call on the thread that owns the loop. + unsafe { PostQuitMessage(0) }; + break; + } + } + LRESULT(0) + } + WM_ERASEBKGND => LRESULT(1), + WM_PAINT => { + let mut ps = PAINTSTRUCT::default(); + // SAFETY: the usual paint sequence, on the window's own thread. + unsafe { + let hdc = BeginPaint(hwnd, &mut ps); + let brush = CreateSolidBrush(COLORREF(COLOR.load(Ordering::SeqCst))); + FillRect(hdc, &ps.rcPaint, brush); + let _ = DeleteObject(HGDIOBJ(brush.0)); + let _ = EndPaint(hwnd, &ps); + } + LRESULT(0) + } + WM_GETMINMAXINFO => { + // SAFETY: for this message `lparam` points at a MINMAXINFO. + let info = unsafe { &mut *(lparam.0 as *mut MINMAXINFO) }; + if let Some((w, h)) = *MIN_SIZE.lock().unwrap() { + info.ptMinTrackSize.x = w; + info.ptMinTrackSize.y = h; + } + if let Some((w, h)) = *FIXED.lock().unwrap() { + info.ptMinTrackSize.x = w; + info.ptMinTrackSize.y = h; + info.ptMaxTrackSize.x = w; + info.ptMaxTrackSize.y = h; + } + LRESULT(0) + } + WM_CLOSE => { + // SAFETY: `hwnd` is this process's own window. + let _ = unsafe { DestroyWindow(hwnd) }; + LRESULT(0) + } + WM_DESTROY => { + // SAFETY: plain Win32 call on the thread that owns the loop. + unsafe { PostQuitMessage(0) }; + LRESULT(0) + } + // SAFETY: forwards the arguments the system gave us, unchanged. + _ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }, + } +} + +fn main() -> windows::core::Result<()> { + let mut title = String::from("komorebi-testwin"); + let mut size = (400, 300); + let mut fixed = false; + + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "--title" => title = args.next().unwrap_or(title), + "--color" => { + if let Some(c) = args.next().as_deref().and_then(parse_color) { + COLOR.store(c, Ordering::SeqCst); + } + } + "--size" => size = args.next().as_deref().and_then(parse_size).unwrap_or(size), + "--min-size" => { + *MIN_SIZE.lock().unwrap() = args.next().as_deref().and_then(parse_size); + } + "--fixed" => fixed = true, + other => eprintln!("komorebi-testwin: ignoring {other}"), + } + } + if fixed { + *FIXED.lock().unwrap() = Some(size); + } + + // SAFETY: plain Win32 setup on the main thread, which then runs the loop. + unsafe { + let instance = GetModuleHandleW(None)?; + let class = WNDCLASSW { + lpfnWndProc: Some(wndproc), + hInstance: instance.into(), + lpszClassName: CLASS, + hCursor: LoadCursorW(None, IDC_ARROW)?, + ..Default::default() + }; + RegisterClassW(&class); + + let mut style = WS_OVERLAPPEDWINDOW; + if fixed { + style &= !(WS_THICKFRAME | WS_MAXIMIZEBOX); + } + let title = wide(&title); + let hwnd = CreateWindowExW( + WINDOW_EX_STYLE(0), + CLASS, + PCWSTR(title.as_ptr()), + style, + CW_USEDEFAULT, + CW_USEDEFAULT, + size.0, + size.1, + None::, + None::, + Some(instance.into()), + None, + )?; + HWND_RAW.store(hwnd.0 as isize, Ordering::SeqCst); + let _ = ShowWindow(hwnd, SW_SHOW); + + std::thread::spawn(move || { + let hwnd = HWND(HWND_RAW.load(Ordering::SeqCst) as *mut _); + for line in std::io::stdin().lock().lines() { + let Ok(line) = line else { break }; + COMMANDS.lock().unwrap().push_back(line); + let _ = PostMessageW(Some(hwnd), WM_COMMAND_READY, WPARAM(0), LPARAM(0)); + } + // stdin closed: the scenario is gone, so go too + COMMANDS.lock().unwrap().push_back(String::from("exit")); + let _ = PostMessageW(Some(hwnd), WM_COMMAND_READY, WPARAM(0), LPARAM(0)); + }); + + let mut msg = MSG::default(); + while GetMessageW(&mut msg, None, 0, 0).as_bool() { + let _ = TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + Ok(()) +}