From 23b23a6b6667f09a944f38dffc85cbdc9cadcbaa Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Fri, 6 Nov 2026 11:32:09 -0800 Subject: [PATCH] refactor(testwin): share the command line and the commands across platforms The test window of the e2e suite is a Win32 program whose command line (--title, --class, --color, --size, --min-size, --fixed, --rename-to, --after) and standard input commands (title, color, resize, report, close, exit) are the contract every scenario port relies on. Move what knows no window system into cli.rs, with tests that run anywhere, and the Win32 window into win32.rs, so that another platform can implement the same window against the same contract. The Windows window itself is moved, not changed: it reads its options and its commands from cli.rs now, and the colour is converted to a GDI one where it is used. A fullscreen command is added to the shared set; on Windows it does what the WM_APP + 2 message does. --- crates/komorebi-testwin/Cargo.toml | 2 + crates/komorebi-testwin/src/cli.rs | 208 +++++++++++++ crates/komorebi-testwin/src/main.rs | 423 ++------------------------- crates/komorebi-testwin/src/win32.rs | 359 +++++++++++++++++++++++ 4 files changed, 590 insertions(+), 402 deletions(-) create mode 100644 crates/komorebi-testwin/src/cli.rs create mode 100644 crates/komorebi-testwin/src/win32.rs diff --git a/crates/komorebi-testwin/Cargo.toml b/crates/komorebi-testwin/Cargo.toml index c853e294..c9818792 100644 --- a/crates/komorebi-testwin/Cargo.toml +++ b/crates/komorebi-testwin/Cargo.toml @@ -7,4 +7,6 @@ publish = false [dependencies] serde_json = { workspace = true } + +[target.'cfg(windows)'.dependencies] windows = { workspace = true } diff --git a/crates/komorebi-testwin/src/cli.rs b/crates/komorebi-testwin/src/cli.rs new file mode 100644 index 00000000..02273005 --- /dev/null +++ b/crates/komorebi-testwin/src/cli.rs @@ -0,0 +1,208 @@ +//! What the test window is told, on every platform: its command line, and the lines on its standard +//! input. Nothing here knows a window system, so it is tested anywhere. + +use std::io::Write; + +/// What the window is started with. +#[derive(Debug, PartialEq)] +pub struct Options { + pub title: String, + /// The size of the window, in pixels (points on macOS). + pub size: (i32, i32), + /// The window class on Windows; no other platform has one, and ignores it. + pub class: Option, + /// `0xRRGGBB`. + pub color: Option, + pub min_size: Option<(i32, i32)>, + /// Not resizable. + pub fixed: bool, + /// A title the window gives itself, and how many seconds after it opens. + pub rename: Option<(String, f64)>, +} + +impl Default for Options { + fn default() -> Self { + Self { + title: String::from("komorebi-testwin"), + size: (400, 300), + class: None, + color: None, + min_size: None, + fixed: false, + rename: None, + } + } +} + +/// `RRGGBB`, with or without a `#`, as `0xRRGGBB`. +pub fn parse_color(s: &str) -> Option { + u32::from_str_radix(s.trim_start_matches('#'), 16) + .ok() + .filter(|rgb| *rgb <= 0xff_ffff) +} + +pub fn parse_size(s: &str) -> Option<(i32, i32)> { + let (w, h) = s.split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?)) +} + +/// The options of a command line (without the program name). What is not understood is said on +/// standard error and left out, as a window that opens is worth more to a scenario than one that +/// refuses. +pub fn parse(args: impl IntoIterator) -> Options { + let mut options = Options::default(); + let mut rename_to = None; + let mut after = 0.0; + let mut args = args.into_iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--title" => options.title = args.next().unwrap_or(options.title), + "--class" => options.class = args.next(), + "--color" => options.color = args.next().as_deref().and_then(parse_color), + "--size" => { + options.size = args + .next() + .as_deref() + .and_then(parse_size) + .unwrap_or(options.size) + } + "--min-size" => options.min_size = args.next().as_deref().and_then(parse_size), + "--fixed" => options.fixed = true, + "--rename-to" => rename_to = args.next(), + "--after" => after = args.next().and_then(|s| s.parse().ok()).unwrap_or(0.0), + other => eprintln!("komorebi-testwin: ignoring {other}"), + } + } + options.rename = rename_to.map(|title| (title, after)); + options +} + +/// One line on standard input. +#[derive(Debug, PartialEq)] +pub enum Command { + Title(String), + Color(u32), + Resize(i32, i32), + /// Fullscreen over its display, or back. + Fullscreen(bool), + Report, + Close, + Exit, + /// A line that is not a command, with what is wrong with it. + Invalid(String), + Empty, +} + +impl Command { + pub fn parse(line: &str) -> Command { + let mut words = line.split_whitespace(); + match words.next() { + None => Command::Empty, + Some("title") => Command::Title( + line.trim_start() + .strip_prefix("title") + .unwrap_or_default() + .trim() + .to_string(), + ), + Some("color") => match words.next().and_then(parse_color) { + Some(color) => Command::Color(color), + None => Command::Invalid(String::from("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()); + match (w, h) { + (Some(w), Some(h)) => Command::Resize(w, h), + _ => Command::Invalid(String::from("resize wants W H")), + } + } + Some("fullscreen") => match words.next() { + Some("on") => Command::Fullscreen(true), + Some("off") => Command::Fullscreen(false), + _ => Command::Invalid(String::from("fullscreen wants on or off")), + }, + Some("report") => Command::Report, + Some("close") => Command::Close, + Some("exit") => Command::Exit, + Some(other) => Command::Invalid(format!("unknown {other}")), + } + } +} + +/// One line of JSON on standard output, which is how a command is answered. +pub fn say(value: serde_json::Value) { + let mut out = std::io::stdout().lock(); + let _ = writeln!(out, "{value}"); + let _ = out.flush(); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(line: &str) -> Vec { + line.split(' ').map(String::from).collect() + } + + #[test] + fn the_defaults_are_a_plain_window() { + assert_eq!(parse(Vec::new()), Options::default()); + } + + #[test] + fn every_option_is_read() { + let options = parse(args( + "--title a --class C --color #ff8000 --size 640x480 --min-size 100x50 --fixed \ + --rename-to b --after 1.5", + )); + assert_eq!(options.title, "a"); + assert_eq!(options.class.as_deref(), Some("C")); + assert_eq!(options.color, Some(0xff8000)); + assert_eq!(options.size, (640, 480)); + assert_eq!(options.min_size, Some((100, 50))); + assert!(options.fixed); + assert_eq!(options.rename, Some((String::from("b"), 1.5))); + } + + #[test] + fn what_is_not_understood_is_left_out() { + let options = parse(args("--size big --color nope --nothing --title t")); + assert_eq!(options.size, (400, 300)); + assert_eq!(options.color, None); + assert_eq!(options.title, "t"); + } + + #[test] + fn a_colour_is_at_most_six_digits() { + assert_eq!(parse_color("ffffff"), Some(0xff_ffff)); + assert_eq!(parse_color("1000000"), None); + } + + #[test] + fn commands_are_read() { + assert_eq!( + Command::parse("title two words"), + Command::Title(String::from("two words")) + ); + assert_eq!(Command::parse("color 00ff00"), Command::Color(0x00ff00)); + assert_eq!(Command::parse("resize 10 20"), Command::Resize(10, 20)); + assert_eq!(Command::parse("fullscreen on"), Command::Fullscreen(true)); + assert_eq!(Command::parse("fullscreen off"), Command::Fullscreen(false)); + assert_eq!(Command::parse("report"), Command::Report); + assert_eq!(Command::parse("close"), Command::Close); + assert_eq!(Command::parse("exit"), Command::Exit); + assert_eq!(Command::parse(" "), Command::Empty); + } + + #[test] + fn a_command_that_is_wrong_says_how() { + assert!(matches!(Command::parse("resize 10"), Command::Invalid(_))); + assert!(matches!(Command::parse("color zz"), Command::Invalid(_))); + assert!(matches!(Command::parse("fullscreen"), Command::Invalid(_))); + assert_eq!( + Command::parse("jump"), + Command::Invalid(String::from("unknown jump")) + ); + } +} diff --git a/crates/komorebi-testwin/src/main.rs b/crates/komorebi-testwin/src/main.rs index 14e8193c..33085eee 100644 --- a/crates/komorebi-testwin/src/main.rs +++ b/crates/komorebi-testwin/src/main.rs @@ -1,420 +1,39 @@ //! 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. +//! It has a stable exe name, 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. The command line and the commands are the same on every platform (`cli.rs`); +//! the window is a Win32 one on Windows (`win32.rs`) and an AppKit one on macOS (`appkit.rs`). //! //! ```text //! title TEXT set the title //! color RRGGBB fill the client area with a colour //! resize W H resize the outer frame +//! fullscreen on|off take the window over its whole display, or bring it back //! 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`, `--class C` (the window class, `KomorebiTestWin` by -//! default), `--color RRGGBB`, `--size WxH`, `--min-size WxH`, `--fixed` (not -//! resizable) and `--rename-to T` with `--after SECONDS` (the window gives -//! itself that title after that long, as a program that sets it late does). +//! Options: `--title T`, `--class C` (the window class, `KomorebiTestWin` by default; macOS has +//! none and ignores it), `--color RRGGBB`, `--size WxH`, `--min-size WxH`, `--fixed` (not +//! resizable) and `--rename-to T` with `--after SECONDS` (the window gives itself that title after +//! that long, as a program that sets it late does). //! -//! The message `WM_APP + 2` takes the window fullscreen (`wparam` 1: a -//! borderless window over its monitor, as a program's own key does) or brings -//! it back (`wparam` 0). +//! On Windows the message `WM_APP + 2` also takes the window fullscreen (`wparam` 1: a borderless +//! window over its monitor, as a program's own key does) or brings it back (`wparam` 0). -#![cfg(windows)] +mod cli; +#[cfg(windows)] +mod win32; -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::GetMonitorInfoW; -use windows::Win32::Graphics::Gdi::HGDIOBJ; -use windows::Win32::Graphics::Gdi::InvalidateRect; -use windows::Win32::Graphics::Gdi::MONITOR_DEFAULTTONEAREST; -use windows::Win32::Graphics::Gdi::MONITORINFO; -use windows::Win32::Graphics::Gdi::MonitorFromWindow; -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::GWL_STYLE; -use windows::Win32::UI::WindowsAndMessaging::GetMessageW; -use windows::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW; -use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; -use windows::Win32::UI::WindowsAndMessaging::HMENU; -use windows::Win32::UI::WindowsAndMessaging::HWND_TOP; -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_FRAMECHANGED; -use windows::Win32::UI::WindowsAndMessaging::SWP_NOMOVE; -use windows::Win32::UI::WindowsAndMessaging::SWP_NOOWNERZORDER; -use windows::Win32::UI::WindowsAndMessaging::SWP_NOZORDER; -use windows::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW; -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_POPUP; -use windows::Win32::UI::WindowsAndMessaging::WS_THICKFRAME; -use windows::Win32::UI::WindowsAndMessaging::WS_VISIBLE; -use windows::core::PCWSTR; - -/// Posted to the window when a command is waiting in [`COMMANDS`]. -const WM_COMMAND_READY: u32 = WM_APP + 1; - -/// Posted to the window to take it fullscreen (`wparam` 1) or back (0). -const WM_FULLSCREEN: u32 = WM_APP + 2; - -/// The style and the rectangle of the window before it went fullscreen. -static BEFORE_FULLSCREEN: Mutex> = Mutex::new(None); - -static COMMANDS: Mutex> = Mutex::new(VecDeque::new()); -static HWND_RAW: AtomicIsize = AtomicIsize::new(0); -static COLOR: AtomicU32 = AtomicU32::new(0x0070_7070); -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() +#[cfg(windows)] +fn main() -> ::windows::core::Result<()> { + win32::run(cli::parse(std::env::args().skip(1))) } -/// `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 -} - -fn set_fullscreen(hwnd: HWND, on: bool) { - let mut before = BEFORE_FULLSCREEN.lock().unwrap(); - // SAFETY: plain Win32 calls on this process's own window, on the thread - // that owns it. - unsafe { - if on && before.is_none() { - let style = GetWindowLongPtrW(hwnd, GWL_STYLE); - let mut rect = RECT::default(); - let _ = GetWindowRect(hwnd, &mut rect); - let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); - let mut info = MONITORINFO { - cbSize: size_of::() as u32, - ..Default::default() - }; - if GetMonitorInfoW(monitor, &mut info).as_bool() { - *before = Some((style, rect)); - let area = info.rcMonitor; - SetWindowLongPtrW(hwnd, GWL_STYLE, (WS_POPUP | WS_VISIBLE).0 as isize); - let _ = SetWindowPos( - hwnd, - Some(HWND_TOP), - area.left, - area.top, - area.right - area.left, - area.bottom - area.top, - SWP_FRAMECHANGED | SWP_NOOWNERZORDER, - ); - } - } else if !on && let Some((style, rect)) = before.take() { - SetWindowLongPtrW(hwnd, GWL_STYLE, style); - let _ = SetWindowPos( - hwnd, - None, - rect.left, - rect.top, - rect.right - rect.left, - rect.bottom - rect.top, - SWP_FRAMECHANGED | SWP_NOOWNERZORDER | SWP_NOZORDER, - ); - } - } -} - -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_FULLSCREEN => { - set_fullscreen(hwnd, wparam.0 != 0); - 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 class_name = wide("KomorebiTestWin"); - let mut rename: Option<(String, f64)> = None; - let mut rename_to = None; - let mut after = 0.0; - - 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), - "--class" => { - if let Some(c) = args.next() { - class_name = wide(&c); - } - } - "--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, - "--rename-to" => rename_to = args.next(), - "--after" => after = args.next().and_then(|s| s.parse().ok()).unwrap_or(0.0), - other => eprintln!("komorebi-testwin: ignoring {other}"), - } - } - if fixed { - *FIXED.lock().unwrap() = Some(size); - } - if let Some(new) = rename_to { - rename = Some((new, after)); - } - - // 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: PCWSTR(class_name.as_ptr()), - 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), - PCWSTR(class_name.as_ptr()), - 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); - - if let Some((new, after)) = rename { - std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_secs_f64(after)); - let hwnd = HWND(HWND_RAW.load(Ordering::SeqCst) as *mut _); - let title = wide(&new); - // `title` is NUL-terminated and outlives the call. - let _ = SetWindowTextW(hwnd, PCWSTR(title.as_ptr())); - }); - } - - 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(()) +#[cfg(not(windows))] +fn main() { + eprintln!("komorebi-testwin opens a window on Windows only"); + std::process::exit(1); } diff --git a/crates/komorebi-testwin/src/win32.rs b/crates/komorebi-testwin/src/win32.rs new file mode 100644 index 00000000..14a37186 --- /dev/null +++ b/crates/komorebi-testwin/src/win32.rs @@ -0,0 +1,359 @@ +//! The test window on Windows: a Win32 window, a class of its own, and the control channel. + +use std::collections::VecDeque; +use std::io::BufRead; +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::GetMonitorInfoW; +use windows::Win32::Graphics::Gdi::HGDIOBJ; +use windows::Win32::Graphics::Gdi::InvalidateRect; +use windows::Win32::Graphics::Gdi::MONITOR_DEFAULTTONEAREST; +use windows::Win32::Graphics::Gdi::MONITORINFO; +use windows::Win32::Graphics::Gdi::MonitorFromWindow; +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::GWL_STYLE; +use windows::Win32::UI::WindowsAndMessaging::GetMessageW; +use windows::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW; +use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; +use windows::Win32::UI::WindowsAndMessaging::HMENU; +use windows::Win32::UI::WindowsAndMessaging::HWND_TOP; +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_FRAMECHANGED; +use windows::Win32::UI::WindowsAndMessaging::SWP_NOMOVE; +use windows::Win32::UI::WindowsAndMessaging::SWP_NOOWNERZORDER; +use windows::Win32::UI::WindowsAndMessaging::SWP_NOZORDER; +use windows::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW; +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_POPUP; +use windows::Win32::UI::WindowsAndMessaging::WS_THICKFRAME; +use windows::Win32::UI::WindowsAndMessaging::WS_VISIBLE; +use windows::core::PCWSTR; + +use crate::cli; +use crate::cli::Command; +use crate::cli::say; + +/// Posted to the window when a command is waiting in [`COMMANDS`]. +const WM_COMMAND_READY: u32 = WM_APP + 1; + +/// Posted to the window to take it fullscreen (`wparam` 1) or back (0). +const WM_FULLSCREEN: u32 = WM_APP + 2; + +/// The style and the rectangle of the window before it went fullscreen. +static BEFORE_FULLSCREEN: Mutex> = Mutex::new(None); + +static COMMANDS: Mutex> = Mutex::new(VecDeque::new()); +static HWND_RAW: AtomicIsize = AtomicIsize::new(0); +static COLOR: AtomicU32 = AtomicU32::new(0x0070_7070); +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() +} + +/// `0xRRGGBB` as a GDI colour, which is `0x00BBGGRR`. +fn gdi_color(rgb: u32) -> u32 { + let (r, g, b) = ((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff); + r | (g << 8) | (b << 16) +} + +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 { + match Command::parse(line) { + Command::Title(title) => { + 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})); + } + Command::Color(rgb) => { + COLOR.store(gdi_color(rgb), Ordering::SeqCst); + // SAFETY: `hwnd` is this process's own window. + let _ = unsafe { InvalidateRect(Some(hwnd), None, true) }; + say(serde_json::json!({"ok": true})); + } + Command::Resize(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})); + } + Command::Fullscreen(on) => { + set_fullscreen(hwnd, on); + say(serde_json::json!({"ok": true})); + } + Command::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"})), + }, + Command::Close => { + // SAFETY: `hwnd` is this process's own window. + let _ = unsafe { PostMessageW(Some(hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)) }; + } + Command::Exit => return false, + Command::Invalid(why) => say(serde_json::json!({"error": why})), + Command::Empty => {} + } + true +} + +fn set_fullscreen(hwnd: HWND, on: bool) { + let mut before = BEFORE_FULLSCREEN.lock().unwrap(); + // SAFETY: plain Win32 calls on this process's own window, on the thread + // that owns it. + unsafe { + if on && before.is_none() { + let style = GetWindowLongPtrW(hwnd, GWL_STYLE); + let mut rect = RECT::default(); + let _ = GetWindowRect(hwnd, &mut rect); + let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + let mut info = MONITORINFO { + cbSize: size_of::() as u32, + ..Default::default() + }; + if GetMonitorInfoW(monitor, &mut info).as_bool() { + *before = Some((style, rect)); + let area = info.rcMonitor; + SetWindowLongPtrW(hwnd, GWL_STYLE, (WS_POPUP | WS_VISIBLE).0 as isize); + let _ = SetWindowPos( + hwnd, + Some(HWND_TOP), + area.left, + area.top, + area.right - area.left, + area.bottom - area.top, + SWP_FRAMECHANGED | SWP_NOOWNERZORDER, + ); + } + } else if !on && let Some((style, rect)) = before.take() { + SetWindowLongPtrW(hwnd, GWL_STYLE, style); + let _ = SetWindowPos( + hwnd, + None, + rect.left, + rect.top, + rect.right - rect.left, + rect.bottom - rect.top, + SWP_FRAMECHANGED | SWP_NOOWNERZORDER | SWP_NOZORDER, + ); + } + } +} + +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_FULLSCREEN => { + set_fullscreen(hwnd, wparam.0 != 0); + 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) }, + } +} + +pub fn run(options: cli::Options) -> windows::core::Result<()> { + let cli::Options { + title, + size, + class, + color, + min_size, + fixed, + rename, + } = options; + let class_name = wide(class.as_deref().unwrap_or("KomorebiTestWin")); + if let Some(rgb) = color { + COLOR.store(gdi_color(rgb), Ordering::SeqCst); + } + *MIN_SIZE.lock().unwrap() = min_size; + 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: PCWSTR(class_name.as_ptr()), + 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), + PCWSTR(class_name.as_ptr()), + 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); + + if let Some((new, after)) = rename { + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs_f64(after)); + let hwnd = HWND(HWND_RAW.load(Ordering::SeqCst) as *mut _); + let title = wide(&new); + // `title` is NUL-terminated and outlives the call. + let _ = SetWindowTextW(hwnd, PCWSTR(title.as_ptr())); + }); + } + + 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(()) +}