From f76a7ad293f67e6b06c8c250d92c7c59e58f5a02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABtan=20Dezeiraud?= Date: Fri, 16 Oct 2026 18:16:55 +0200 Subject: [PATCH 1/2] feat: Center window in the launch monitor --- common/src/lib.rs | 1 + common/src/win32.rs | 37 +---- common/src/window_placement.rs | 141 ++++++++++++++++++ common/src/window_placement/tests.rs | 210 +++++++++++++++++++++++++++ installer/src/main.rs | 1 + installer/src/ui/winui.rs | 2 + installer/src/ui/winui/minimal.rs | 1 + installer/src/ui/winui/wizard.rs | 1 + uninstaller/Cargo.toml | 4 + uninstaller/src/main.rs | 44 +++++- uninstaller/src/relaunch.rs | 154 +++++++++++++++++--- uninstaller/src/stages/uninstall.rs | 1 + uninstaller/src/ui/winui.rs | 1 + winui_support/src/window.rs | 33 ++++- winui_support/src/window/tests.rs | 72 +++++++++ 15 files changed, 641 insertions(+), 62 deletions(-) create mode 100644 common/src/window_placement.rs create mode 100644 common/src/window_placement/tests.rs create mode 100644 winui_support/src/window/tests.rs diff --git a/common/src/lib.rs b/common/src/lib.rs index bbc6d8a..60ade20 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -15,6 +15,7 @@ pub mod registry; pub mod shortcuts; pub mod utils; pub mod win32; +pub mod window_placement; /// Progress callback shared by the installer and uninstaller UI/worker paths. pub type ProgressFn = std::sync::Arc; diff --git a/common/src/win32.rs b/common/src/win32.rs index dbf3ff4..4d18a47 100644 --- a/common/src/win32.rs +++ b/common/src/win32.rs @@ -8,6 +8,7 @@ //! controls and again on `WM_DPICHANGED`. use crate::utils::wide; +use crate::window_placement::center; use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, RECT, WPARAM}; use windows::Win32::Graphics::Gdi::{ CLEARTYPE_QUALITY, CLIP_DEFAULT_PRECIS, CreateFontW, DEFAULT_CHARSET, DEFAULT_PITCH, @@ -20,12 +21,11 @@ use windows::Win32::UI::Controls::{ use windows::Win32::UI::HiDpi::{AdjustWindowRectExForDpi, GetDpiForWindow}; use windows::Win32::UI::Shell::ExtractIconW; use windows::Win32::UI::WindowsAndMessaging::{ - CW_USEDEFAULT, CreateWindowExW, DispatchMessageW, GetDlgItem, GetMessageW, GetSystemMetrics, - GetWindowRect, GetWindowTextLengthW, GetWindowTextW, HICON, HMENU, IDC_ARROW, LoadCursorW, MSG, - MoveWindow, PostMessageW, RegisterClassExW, SM_CXSCREEN, SM_CYSCREEN, SWP_NOACTIVATE, - SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, SendMessageW, SetWindowPos, SetWindowTextW, - TranslateMessage, WINDOW_EX_STYLE, WINDOW_STYLE, WM_SETFONT, WM_SETICON, WNDCLASSEXW, WNDPROC, - WS_CHILD, WS_TABSTOP, + CW_USEDEFAULT, CreateWindowExW, DispatchMessageW, GetDlgItem, GetMessageW, + GetWindowTextLengthW, GetWindowTextW, HICON, HMENU, IDC_ARROW, LoadCursorW, MSG, MoveWindow, + PostMessageW, RegisterClassExW, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, SendMessageW, + SetWindowPos, SetWindowTextW, TranslateMessage, WINDOW_EX_STYLE, WINDOW_STYLE, WM_SETFONT, + WM_SETICON, WNDCLASSEXW, WNDPROC, WS_CHILD, WS_TABSTOP, }; use windows::core::PCWSTR; @@ -113,6 +113,8 @@ pub unsafe fn create_main_window( /// `client_w` × `client_h` in 96-dpi units, and center it. Returns that DPI. pub fn fit_to_monitor(hwnd: HWND, client_w: i32, client_h: i32, style: WINDOW_STYLE) -> i32 { unsafe { + // Move to the launch monitor before querying its DPI. + center(hwnd); let dpi = dpi_for(hwnd); let (w, h) = window_size_for_client( scale(client_w, dpi), @@ -301,29 +303,6 @@ fn window_size_for_client( (r.right - r.left, r.bottom - r.top) } -/// Center a top-level window on the primary monitor. -fn center(hwnd: HWND) { - let mut rect = RECT::default(); - unsafe { - let _ = GetWindowRect(hwnd, &mut rect); - }; - let w = rect.right - rect.left; - let h = rect.bottom - rect.top; - let sw = unsafe { GetSystemMetrics(SM_CXSCREEN) }; - let sh = unsafe { GetSystemMetrics(SM_CYSCREEN) }; - unsafe { - let _ = SetWindowPos( - hwnd, - None, - (sw - w) / 2, - (sh - h) / 2, - 0, - 0, - SWP_NOSIZE | SWP_NOZORDER, - ); - } -} - /// Set the font of a child control by dialog id. pub fn set_font(parent: HWND, id: usize, font: HFONT) { unsafe { diff --git a/common/src/window_placement.rs b/common/src/window_placement.rs new file mode 100644 index 0000000..eb7c3cc --- /dev/null +++ b/common/src/window_placement.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Gaëtan Dezeiraud, Louis Pinaud + +//! Initial placement shared by the installer, uninstaller and both UI backends. + +use std::{fmt, str::FromStr, sync::OnceLock}; +use windows::Win32::Foundation::{HWND, POINT, RECT}; +use windows::Win32::Graphics::Gdi::{ + GetMonitorInfoW, MONITOR_DEFAULTTOPRIMARY, MONITORINFO, MonitorFromPoint, MonitorFromWindow, +}; +use windows::Win32::UI::WindowsAndMessaging::{ + GetCursorPos, GetForegroundWindow, GetWindowRect, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, + SetWindowPos, +}; + +static LAUNCH_MONITOR: OnceLock = OnceLock::new(); + +/// A point inside the launch monitor, transferable across process boundaries. +/// Monitor handles cannot be used as persistent launch coordinates. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct LaunchMonitor { + x: i32, + y: i32, +} + +impl LaunchMonitor { + /// Capture before opening UI or doing work that may change the foreground. + pub fn capture() -> Self { + unsafe { + let foreground = GetForegroundWindow(); + let monitor = if foreground.is_invalid() { + let mut point = POINT::default(); + let _ = GetCursorPos(&mut point); + MonitorFromPoint(point, MONITOR_DEFAULTTOPRIMARY) + } else { + MonitorFromWindow(foreground, MONITOR_DEFAULTTOPRIMARY) + }; + let mut info = monitor_info(); + if GetMonitorInfoW(monitor, &mut info).as_bool() { + let rc = info.rcMonitor; + Self { + x: rc.left + (rc.right - rc.left) / 2, + y: rc.top + (rc.bottom - rc.top) / 2, + } + } else { + Self::default() + } + } + } +} + +impl fmt::Display for LaunchMonitor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{},{}", self.x, self.y) + } +} + +impl FromStr for LaunchMonitor { + type Err = &'static str; + + fn from_str(value: &str) -> Result { + let (x, y) = value.split_once(',').ok_or("expected monitor point x,y")?; + Ok(Self { + x: x.parse().map_err(|_| "invalid monitor x coordinate")?, + y: y.parse().map_err(|_| "invalid monitor y coordinate")?, + }) + } +} + +pub fn capture_launch_monitor() { + remember_launch_monitor(LaunchMonitor::capture()); +} + +/// Initialize once, using the original launch point when this is a child process. +pub fn remember_launch_monitor(monitor: LaunchMonitor) { + let _ = LAUNCH_MONITOR.set(monitor); +} + +pub fn launch_monitor() -> LaunchMonitor { + LAUNCH_MONITOR.get().copied().unwrap_or_default() +} + +fn monitor_info() -> MONITORINFO { + MONITORINFO { + cbSize: size_of::() as u32, + ..Default::default() + } +} + +fn centered_origin(work: RECT, width: i32, height: i32) -> (i32, i32) { + ( + work.left + ((work.right - work.left - width) / 2).max(0), + work.top + ((work.bottom - work.top - height) / 2).max(0), + ) +} + +/// Center on the remembered monitor's work area; use primary if it disappeared. +pub fn center(hwnd: HWND) { + center_on(hwnd, launch_monitor()); +} + +fn center_on(hwnd: HWND, point: LaunchMonitor) { + unsafe { + let monitor = MonitorFromPoint( + POINT { + x: point.x, + y: point.y, + }, + MONITOR_DEFAULTTOPRIMARY, + ); + let mut info = monitor_info(); + if !GetMonitorInfoW(monitor, &mut info).as_bool() { + return; + } + // A cross-monitor move can synchronously resize for DPI. Re-read the + // final size and center again, without activating or repeatedly pinning UI. + for _ in 0..2 { + let mut rect = RECT::default(); + if GetWindowRect(hwnd, &mut rect).is_err() { + return; + } + let (x, y) = + centered_origin(info.rcWork, rect.right - rect.left, rect.bottom - rect.top); + if rect.left == x && rect.top == y { + break; + } + let _ = SetWindowPos( + hwnd, + None, + x, + y, + 0, + 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/common/src/window_placement/tests.rs b/common/src/window_placement/tests.rs new file mode 100644 index 0000000..fb278ff --- /dev/null +++ b/common/src/window_placement/tests.rs @@ -0,0 +1,210 @@ +use super::*; + +struct HiddenWindow(HWND); +impl Drop for HiddenWindow { + fn drop(&mut self) { + let _ = unsafe { windows::Win32::UI::WindowsAndMessaging::DestroyWindow(self.0) }; + } +} + +#[test] +fn centers_on_secondary_monitors_and_respects_work_area() { + for (work, size, expected) in [ + ((0, 0, 1920, 1040), (700, 540), (610, 250)), + ((1920, 0, 3840, 1040), (700, 540), (2530, 250)), + ((-1920, 0, 0, 1040), (700, 540), (-1310, 250)), + ((0, -1080, 1920, -40), (700, 540), (610, -830)), + ((48, 40, 1920, 1080), (700, 540), (634, 290)), + // Same logical window at 150% and 200% on a 4K work area. + ((1920, 0, 5760, 2100), (1050, 810), (3315, 645)), + ((1920, 0, 5760, 2080), (1400, 1080), (3140, 500)), + // Oversized windows keep their top-left controls accessible. + ((-800, 0, 0, 560), (1000, 700), (-800, 0)), + ] { + let (left, top, right, bottom) = work; + assert_eq!( + centered_origin( + RECT { + left, + top, + right, + bottom + }, + size.0, + size.1 + ), + expected, + "work={work:?}, size={size:?}", + ); + } +} + +#[test] +fn launch_coordinates_round_trip_including_negative_monitors() { + for value in ["0,0", "-960,540", "960,-540", "-960,-540"] { + assert_eq!(value.parse::().unwrap().to_string(), value); + } + for value in ["", "1", "1,2,3", "x,1", "1,y", "2147483648,0"] { + assert!(value.parse::().is_err(), "{value}"); + } +} + +#[test] +fn centers_a_real_hidden_window_without_resizing_or_activating_it() { + use windows::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, WINDOW_EX_STYLE, WS_OVERLAPPEDWINDOW, + }; + use windows::core::w; + + unsafe { + let hwnd = CreateWindowExW( + WINDOW_EX_STYLE(0), + w!("STATIC"), + w!("Installway placement test"), + WS_OVERLAPPEDWINDOW, + 0, + 0, + 700, + 540, + None, + None, + None, + None, + ) + .unwrap(); + let _window = HiddenWindow(hwnd); + let foreground = GetForegroundWindow(); + let mut before = RECT::default(); + GetWindowRect(hwnd, &mut before).unwrap(); + center_on(hwnd, LaunchMonitor::default()); + let mut after = RECT::default(); + GetWindowRect(hwnd, &mut after).unwrap(); + let mut info = monitor_info(); + assert!( + GetMonitorInfoW( + MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), + &mut info + ) + .as_bool() + ); + assert_eq!( + (after.right - after.left, after.bottom - after.top), + (before.right - before.left, before.bottom - before.top) + ); + assert_eq!( + (after.left, after.top), + centered_origin(info.rcWork, 700, 540) + ); + assert_eq!(GetForegroundWindow(), foreground); + // Moving a window later must remain possible (centering is initial only). + SetWindowPos( + hwnd, + None, + 20, + 30, + 0, + 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ) + .unwrap(); + GetWindowRect(hwnd, &mut after).unwrap(); + assert_eq!((after.left, after.top), (20, 30)); + } +} + +#[test] +fn recenters_after_a_synchronous_dpi_resize_during_the_first_move() { + use windows::Win32::Foundation::{HINSTANCE, LPARAM, LRESULT, WPARAM}; + use windows::Win32::System::LibraryLoader::GetModuleHandleW; + use windows::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DefWindowProcW, GWLP_USERDATA, GetWindowLongPtrW, RegisterClassW, + SendMessageW, SetWindowLongPtrW, WINDOW_EX_STYLE, WM_DPICHANGED, WM_WINDOWPOSCHANGED, + WNDCLASSW, WS_OVERLAPPEDWINDOW, + }; + use windows::core::{PCWSTR, w}; + + unsafe extern "system" fn proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT { + unsafe { + if msg == WM_DPICHANGED { + crate::win32::follow_dpi_change(hwnd, w, l); + return LRESULT(0); + } + if msg == WM_WINDOWPOSCHANGED && GetWindowLongPtrW(hwnd, GWLP_USERDATA) == 1 { + SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0); + let mut rect = RECT::default(); + let _ = GetWindowRect(hwnd, &mut rect); + rect.right = rect.left + 1050; + rect.bottom = rect.top + 810; + SendMessageW( + hwnd, + WM_DPICHANGED, + Some(WPARAM(144 | (144 << 16))), + Some(LPARAM(&rect as *const RECT as isize)), + ); + } + DefWindowProcW(hwnd, msg, w, l) + } + } + + unsafe { + let instance = HINSTANCE(GetModuleHandleW(PCWSTR::null()).unwrap().0); + let class = w!("InstallwayDpiPlacementTest"); + assert_ne!( + RegisterClassW(&WNDCLASSW { + lpfnWndProc: Some(proc), + hInstance: instance, + lpszClassName: class, + ..Default::default() + }), + 0 + ); + let hwnd = CreateWindowExW( + WINDOW_EX_STYLE(0), + class, + w!(""), + WS_OVERLAPPEDWINDOW, + 0, + 0, + 700, + 540, + None, + None, + Some(instance), + None, + ) + .unwrap(); + let _window = HiddenWindow(hwnd); + let mut info = monitor_info(); + assert!( + GetMonitorInfoW( + MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), + &mut info + ) + .as_bool() + ); + // Offset from the destination so the first centering move fires. + let (x, y) = centered_origin(info.rcWork, 700, 540); + SetWindowPos( + hwnd, + None, + x + 17, + y + 23, + 700, + 540, + SWP_NOZORDER | SWP_NOACTIVATE, + ) + .unwrap(); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, 1); + center_on(hwnd, LaunchMonitor::default()); + let mut rect = RECT::default(); + GetWindowRect(hwnd, &mut rect).unwrap(); + assert_eq!( + (rect.right - rect.left, rect.bottom - rect.top), + (1050, 810) + ); + assert_eq!( + (rect.left, rect.top), + centered_origin(info.rcWork, 1050, 810) + ); + } +} diff --git a/installer/src/main.rs b/installer/src/main.rs index 3b80424..b573614 100644 --- a/installer/src/main.rs +++ b/installer/src/main.rs @@ -94,6 +94,7 @@ struct Cli { } fn main() { + common::window_placement::capture_launch_monitor(); let cli = Cli::parse(); // Diagnostic / headless modes report errors as text on the parent console diff --git a/installer/src/ui/winui.rs b/installer/src/ui/winui.rs index 86e2645..35d00b7 100644 --- a/installer/src/ui/winui.rs +++ b/installer/src/ui/winui.rs @@ -58,6 +58,7 @@ pub fn run( translator: common::i18n::Translator, ui_plugins: Option, ) -> Result { + MAIN_HWND.reset(); // An existing install fixes the target folder: a patch must land there and a // reinstall must not make a second copy. So Choose is always skipped then. let skip_license = loaded.payload.skip_license; @@ -105,6 +106,7 @@ pub fn run_minimal( launch: bool, translator: common::i18n::Translator, ) -> Result { + MAIN_HWND.reset(); let title = translator.get("install.minimal_title"); seed_config(&loaded, &install_dir, launch, true, true, translator); stage_product_icon(); diff --git a/installer/src/ui/winui/minimal.rs b/installer/src/ui/winui/minimal.rs index 644ba85..43682e3 100644 --- a/installer/src/ui/winui/minimal.rs +++ b/installer/src/ui/winui/minimal.rs @@ -86,6 +86,7 @@ impl Component for Minimal { _ = context.window().request_close(); } Message::Poll => { + super::MAIN_HWND.center_once(); self.progress = self.progress_sink.get(); let signal = self.signal_sink.take(); if signal != Signal::None { diff --git a/installer/src/ui/winui/wizard.rs b/installer/src/ui/winui/wizard.rs index bfd9a0e..0af0b75 100644 --- a/installer/src/ui/winui/wizard.rs +++ b/installer/src/ui/winui/wizard.rs @@ -110,6 +110,7 @@ impl Component for WizardApp { Message::Poll => { if !self.attached && super::active_hwnd() != 0 { super::attach_window(self.feed.signal.clone()); + super::MAIN_HWND.center_once(); self.attached = true; } self.model.progress = self.feed.progress.get(); diff --git a/uninstaller/Cargo.toml b/uninstaller/Cargo.toml index 2fd4fa5..db7eb01 100644 --- a/uninstaller/Cargo.toml +++ b/uninstaller/Cargo.toml @@ -33,11 +33,15 @@ windows = { version = "0.62.2", features = [ "Win32_System_Registry", "Win32_System_LibraryLoader", "Win32_System_Threading", + "Win32_System_Com", + "Win32_System_Ole", + "Win32_System_Variant", "Win32_System_Memory", "Win32_System_Pipes", "Win32_System_IO", "Win32_Storage_FileSystem", "Win32_Security", + "Win32_UI_Shell_Common", ] } windows-reactor = { git = "https://github.com/microsoft/windows-rs.git", rev = "317646c941aa18916ffa5daeb4ffd5ffa4cd26f3" } diff --git a/uninstaller/src/main.rs b/uninstaller/src/main.rs index 44d84e9..db06946 100644 --- a/uninstaller/src/main.rs +++ b/uninstaller/src/main.rs @@ -13,6 +13,7 @@ mod worker; use anyhow::Result; use clap::{Parser, Subcommand}; +use common::window_placement::{LaunchMonitor, remember_launch_monitor}; use std::path::{Path, PathBuf}; /// Uninstaller - invoked by Windows' "Add or remove programs". @@ -37,6 +38,10 @@ struct Cli { #[arg(long)] lang: Option, + /// Internal: preserve the original monitor across Explorer/finalize relaunches. + #[arg(long, hide = true, global = true)] + launch_monitor: Option, + /// Internal: run as the elevated worker, streaming events back over the /// named pipe whose name is given here. Spawned via UAC by the main process. #[arg(long, hide = true, value_name = "PIPE")] @@ -82,7 +87,8 @@ enum Cmd { } fn main() { - if let Err(e) = run() { + let launch_monitor = LaunchMonitor::capture(); + if let Err(e) = run(launch_monitor) { #[cfg(feature = "hintway")] { analytics::error_from(&e); @@ -95,8 +101,9 @@ fn main() { analytics::shutdown(); } -fn run() -> Result<()> { +fn run(launch_monitor: LaunchMonitor) -> Result<()> { let cli = Cli::parse(); + remember_launch_monitor(cli.launch_monitor.unwrap_or(launch_monitor)); let translator = common::i18n::Translator::detect(cli.lang.as_deref()); translator.set_global(); @@ -143,3 +150,36 @@ fn run() -> Result<()> { } } } + +#[cfg(test)] +mod placement_cli_tests { + use super::*; + + #[test] + fn relaunch_argument_matches_the_cli_protocol() { + let arg = crate::relaunch::launch_monitor_arg(); + let cli = Cli::try_parse_from(["uninstall", &arg]).unwrap(); + assert_eq!( + cli.launch_monitor, + Some(common::window_placement::launch_monitor()) + ); + } + + #[test] + fn preserves_negative_launch_coordinates_for_both_uninstall_stages() { + let expected = "-960,-540".parse::().unwrap(); + let normal = Cli::try_parse_from(["uninstall", "--launch-monitor=-960,-540"]).unwrap(); + assert_eq!(normal.launch_monitor, Some(expected)); + let finalize = Cli::try_parse_from([ + "uninstall", + "finalize", + "--data-dir", + r"C:\Data\App", + "--product", + "App", + "--launch-monitor=-960,-540", + ]) + .unwrap(); + assert_eq!(finalize.launch_monitor, Some(expected)); + } +} diff --git a/uninstaller/src/relaunch.rs b/uninstaller/src/relaunch.rs index fb5ba24..fe1e349 100644 --- a/uninstaller/src/relaunch.rs +++ b/uninstaller/src/relaunch.rs @@ -1,32 +1,138 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2026 Gaëtan Dezeiraud, Louis Pinaud -//! Escape hatch out of a packaged launcher's process tree. +//! Escape a packaged launcher's process tree without losing the launch monitor. use anyhow::{Context, Result}; -use std::os::windows::process::CommandExt; -use std::process::Command; - -const DETACHED_PROCESS: u32 = 0x0000_0008; - -/// Re-launch this executable through Explorer and let the caller exit. -/// -/// Windows 11's Settings app runs `UninstallString` from inside its own package -/// (`windows.immersivecontrolpanel`), and children inherit that identity; XAML -/// then resolves against the launcher's package graph and crashes on startup. -/// `PROC_THREAD_ATTRIBUTE_DESKTOP_APP_POLICY` cannot help - the breakaway policy -/// is ignored for UWP launchers - but Explorer is a plain desktop process, so -/// what it starts on our behalf has no package identity at all. -/// -/// Explorer takes a path and passes no arguments, so this only covers the -/// argument-free interactive uninstall; every other entry point stays in-process -/// and falls back to the Win32 UI instead. +use std::os::windows::ffi::OsStrExt; +use std::path::Path; +use windows::Win32::System::Com::{ + CLSCTX_LOCAL_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, + CoUninitialize, IDispatch, IServiceProvider, +}; +use windows::Win32::System::Variant::VARIANT; +use windows::Win32::UI::Shell::{ + CSIDL_DESKTOP, IShellBrowser, IShellDispatch2, IShellFolderViewDual, IShellWindows, + SID_STopLevelBrowser, SVGIO_BACKGROUND, SWC_DESKTOP, SWFO_NEEDDISPATCH, ShellWindows, +}; +use windows::Win32::UI::WindowsAndMessaging::{SHOW_WINDOW_CMD, SW_SHOWNORMAL}; +use windows::core::{BSTR, Interface}; + +/// Ask the existing desktop Explorer to launch us outside Settings' package. +/// Unlike `explorer.exe `, desktop shell automation accepts arguments, +/// letting the child restore the original monitor even if focus has changed. pub fn via_explorer() -> Result<()> { let exe = std::env::current_exe()?; - Command::new("explorer.exe") - .arg(&exe) - .creation_flags(DETACHED_PROCESS) - .spawn() - .with_context(|| format!("relaunch {} through Explorer", exe.display()))?; - Ok(()) + execute_from_explorer(&exe, &launch_monitor_arg(), SW_SHOWNORMAL) + .with_context(|| format!("relaunch {} through Explorer", exe.display())) +} + +/// Shared by the Explorer relaunch and the detached finalize process. +pub fn launch_monitor_arg() -> String { + format!( + "--launch-monitor={}", + common::window_placement::launch_monitor() + ) +} + +fn execute_from_explorer(exe: &Path, args: &str, show: SHOW_WINDOW_CMD) -> Result<()> { + let _apartment = ComApartment::sta()?; + let shell = desktop_shell()?; + let file = BSTR::from_wide(&exe.as_os_str().encode_wide().collect::>()); + unsafe { + shell + .ShellExecute( + &file, + &VARIANT::from(args), + &VARIANT::default(), + &VARIANT::from("open"), + &VARIANT::from(show.0), + ) + .context("launch through Explorer") + } +} + +// Microsoft's desktop automation pattern: obtain Shell.Application from the +// desktop view hosted by Explorer, rather than creating a shell in our process. +// https://devblogs.microsoft.com/oldnewthing/20131118-00/?p=2643 +fn desktop_shell() -> Result { + unsafe { + let shell_windows: IShellWindows = + CoCreateInstance(&ShellWindows, None, CLSCTX_LOCAL_SERVER) + .context("connect to desktop Explorer")?; + let mut desktop_hwnd = 0; + let desktop = shell_windows + .FindWindowSW( + &VARIANT::from(CSIDL_DESKTOP as i32), + &VARIANT::default(), + SWC_DESKTOP, + &mut desktop_hwnd, + SWFO_NEEDDISPATCH, + ) + .context("find Explorer desktop")?; + let browser: IShellBrowser = desktop + .cast::()? + .QueryService(&SID_STopLevelBrowser) + .context("get desktop browser")?; + let view = browser.QueryActiveShellView().context("get desktop view")?; + // GetItemObject supports IDispatch here; query the dual interface from it. + let folder: IShellFolderViewDual = view + .GetItemObject::(SVGIO_BACKGROUND) + .context("get desktop automation")? + .cast() + .context("get desktop folder")?; + folder.Application()?.cast().context("get Explorer shell") + } +} + +/// Balance every successful CoInitializeEx, including S_FALSE and error exits. +struct ComApartment; + +impl ComApartment { + fn sta() -> windows::core::Result { + unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok()? }; + Ok(Self) + } +} + +impl Drop for ComApartment { + fn drop(&mut self) { + unsafe { CoUninitialize() }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore = "requires the interactive desktop Explorer; launches only a harmless echo probe"] + fn explorer_passes_negative_monitor_coordinates_to_child() { + let temp = tempfile::tempdir().unwrap(); + let output = temp.path().join("launch monitor.txt"); + let cmd = Path::new(&std::env::var_os("SystemRoot").unwrap()).join("System32/cmd.exe"); + let args = format!( + r#"/d /c echo --launch-monitor=-960,-540>"{}""#, + output.display() + ); + execute_from_explorer( + &cmd, + &args, + windows::Win32::UI::WindowsAndMessaging::SW_HIDE, + ) + .unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + if let Ok(text) = std::fs::read_to_string(&output) + && text.trim() == "--launch-monitor=-960,-540" + { + break; + } + assert!( + std::time::Instant::now() < deadline, + "Explorer did not pass the launch point to the probe" + ); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } } diff --git a/uninstaller/src/stages/uninstall.rs b/uninstaller/src/stages/uninstall.rs index 2326e05..253df43 100644 --- a/uninstaller/src/stages/uninstall.rs +++ b/uninstaller/src/stages/uninstall.rs @@ -320,6 +320,7 @@ pub(crate) fn spawn_finalize( .with_context(|| format!("copy finalize step to {}", dest.display()))?; Command::new(&dest) + .arg(crate::relaunch::launch_monitor_arg()) .args(finalize_args( data_dir, &data_dir_key(data_dir), diff --git a/uninstaller/src/ui/winui.rs b/uninstaller/src/ui/winui.rs index dd9cf19..8e23421 100644 --- a/uninstaller/src/ui/winui.rs +++ b/uninstaller/src/ui/winui.rs @@ -140,6 +140,7 @@ impl Component for Uninstaller { fn update(&mut self, message: Message, context: &ComponentContext) { if !self.attached && MAIN_HWND.active() != 0 { attach_window(); + MAIN_HWND.center_once(); self.attached = true; } match message { diff --git a/winui_support/src/window.rs b/winui_support/src/window.rs index f6f88d9..7ed0bd1 100644 --- a/winui_support/src/window.rs +++ b/winui_support/src/window.rs @@ -1,36 +1,55 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2026 Gaëtan Dezeiraud, Louis Pinaud -use std::sync::atomic::{AtomicIsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use windows::Win32::Foundation::{HWND, LPARAM, WPARAM}; use windows::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow; use windows::Win32::UI::WindowsAndMessaging::{PostMessageW, SW_HIDE, ShowWindow, WM_CLOSE}; -/// Cache a Reactor window handle for access from its frontend and workers. +/// Manage a Reactor window's native handle and initial placement. #[derive(Default)] -pub struct WindowHandle(AtomicIsize); +pub struct WindowHandle { + raw: AtomicIsize, + centered: AtomicBool, +} + +#[cfg(test)] +mod tests; impl WindowHandle { pub const fn new() -> Self { - Self(AtomicIsize::new(0)) + Self { + raw: AtomicIsize::new(0), + centered: AtomicBool::new(false), + } } pub fn reset(&self) { - self.0.store(0, Ordering::Relaxed); + self.raw.store(0, Ordering::Relaxed); + self.centered.store(false, Ordering::Relaxed); } pub fn active(&self) -> isize { - let cached = self.0.load(Ordering::Relaxed); + let cached = self.raw.load(Ordering::Relaxed); if cached != 0 { return cached; } let raw = unsafe { GetActiveWindow() }.0 as isize; if raw != 0 { - self.0.store(raw, Ordering::Relaxed); + self.raw.store(raw, Ordering::Relaxed); } raw } + /// Call after the first render has applied the window size. Later calls + /// leave the window where the user moved it; no active window means retry. + pub fn center_once(&self) { + let raw = self.active(); + if raw != 0 && !self.centered.swap(true, Ordering::Relaxed) { + common::window_placement::center(HWND(raw as *mut _)); + } + } + pub fn close(&self) { let raw = self.active(); if raw != 0 { diff --git a/winui_support/src/window/tests.rs b/winui_support/src/window/tests.rs new file mode 100644 index 0000000..b3ee27c --- /dev/null +++ b/winui_support/src/window/tests.rs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Gaëtan Dezeiraud, Louis Pinaud + +use super::*; +use windows::Win32::Foundation::RECT; +use windows::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DestroyWindow, GetWindowRect, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, + SetWindowPos, WINDOW_EX_STYLE, WS_OVERLAPPEDWINDOW, +}; +use windows::core::w; + +#[test] +fn initial_placement_waits_for_a_window_runs_once_and_resets_for_the_next_run() { + let handle = WindowHandle::new(); + handle.center_once(); + assert!(!handle.centered.load(Ordering::Relaxed)); + + unsafe { + let hwnd = CreateWindowExW( + WINDOW_EX_STYLE(0), + w!("STATIC"), + w!("Installway lifecycle test"), + WS_OVERLAPPEDWINDOW, + 0, + 0, + 700, + 540, + None, + None, + None, + None, + ) + .unwrap(); + struct HiddenWindow(HWND); + impl Drop for HiddenWindow { + fn drop(&mut self) { + let _ = unsafe { DestroyWindow(self.0) }; + } + } + let _window = HiddenWindow(hwnd); + handle.raw.store(hwnd.0 as isize, Ordering::Relaxed); + handle.center_once(); + let mut initial = RECT::default(); + GetWindowRect(hwnd, &mut initial).unwrap(); + + SetWindowPos( + hwnd, + None, + initial.left + 13, + initial.top + 17, + 0, + 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ) + .unwrap(); + handle.center_once(); + let mut moved = RECT::default(); + GetWindowRect(hwnd, &mut moved).unwrap(); + assert_eq!( + (moved.left, moved.top), + (initial.left + 13, initial.top + 17) + ); + + handle.reset(); + assert_eq!(handle.raw.load(Ordering::Relaxed), 0); + assert!(!handle.centered.load(Ordering::Relaxed)); + handle.raw.store(hwnd.0 as isize, Ordering::Relaxed); + handle.center_once(); + GetWindowRect(hwnd, &mut moved).unwrap(); + assert_eq!((moved.left, moved.top), (initial.left, initial.top)); + } +} From e6b140cf236cce21db6fa13cbbe91daf77f34318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABtan=20Dezeiraud?= Date: Fri, 16 Oct 2026 18:46:06 +0200 Subject: [PATCH 2/2] test: Handle Windows size limits in DPI resize test --- common/src/window_placement/tests.rs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/common/src/window_placement/tests.rs b/common/src/window_placement/tests.rs index fb278ff..e4dcbc7 100644 --- a/common/src/window_placement/tests.rs +++ b/common/src/window_placement/tests.rs @@ -114,17 +114,30 @@ fn centers_a_real_hidden_window_without_resizing_or_activating_it() { #[test] fn recenters_after_a_synchronous_dpi_resize_during_the_first_move() { + const REQUESTED_SIZE: (i32, i32) = (1050, 810); + const MAX_TRACK_SIZE: (i32, i32) = (1044, 788); + use windows::Win32::Foundation::{HINSTANCE, LPARAM, LRESULT, WPARAM}; use windows::Win32::System::LibraryLoader::GetModuleHandleW; use windows::Win32::UI::WindowsAndMessaging::{ - CreateWindowExW, DefWindowProcW, GWLP_USERDATA, GetWindowLongPtrW, RegisterClassW, - SendMessageW, SetWindowLongPtrW, WINDOW_EX_STYLE, WM_DPICHANGED, WM_WINDOWPOSCHANGED, - WNDCLASSW, WS_OVERLAPPEDWINDOW, + CreateWindowExW, DefWindowProcW, GWLP_USERDATA, GetWindowLongPtrW, MINMAXINFO, + RegisterClassW, SendMessageW, SetWindowLongPtrW, WINDOW_EX_STYLE, WM_DPICHANGED, + WM_GETMINMAXINFO, WM_WINDOWPOSCHANGED, WNDCLASSW, WS_OVERLAPPEDWINDOW, }; use windows::core::{PCWSTR, w}; unsafe extern "system" fn proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT { unsafe { + if msg == WM_GETMINMAXINFO { + let result = DefWindowProcW(hwnd, msg, w, l); + // Make the desktop's tracking limit deterministic, including on CI. + let limits = &mut *(l.0 as *mut MINMAXINFO); + limits.ptMaxTrackSize = POINT { + x: MAX_TRACK_SIZE.0, + y: MAX_TRACK_SIZE.1, + }; + return result; + } if msg == WM_DPICHANGED { crate::win32::follow_dpi_change(hwnd, w, l); return LRESULT(0); @@ -133,8 +146,8 @@ fn recenters_after_a_synchronous_dpi_resize_during_the_first_move() { SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0); let mut rect = RECT::default(); let _ = GetWindowRect(hwnd, &mut rect); - rect.right = rect.left + 1050; - rect.bottom = rect.top + 810; + rect.right = rect.left + REQUESTED_SIZE.0; + rect.bottom = rect.top + REQUESTED_SIZE.1; SendMessageW( hwnd, WM_DPICHANGED, @@ -200,11 +213,12 @@ fn recenters_after_a_synchronous_dpi_resize_during_the_first_move() { GetWindowRect(hwnd, &mut rect).unwrap(); assert_eq!( (rect.right - rect.left, rect.bottom - rect.top), - (1050, 810) + MAX_TRACK_SIZE ); + // Center the size Windows actually accepted, not the requested DPI size. assert_eq!( (rect.left, rect.top), - centered_origin(info.rcWork, 1050, 810) + centered_origin(info.rcWork, MAX_TRACK_SIZE.0, MAX_TRACK_SIZE.1) ); } }