#![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] #![allow(clippy::too_many_arguments)] use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex, MutexGuard}; use std::thread::ThreadId; use std::time::Duration; use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM}; use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, ScreenToClient}; use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessId, TerminateProcess}; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetCapture, ReleaseCapture, SetCapture}; use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU}; use windows_sys::core::{PCSTR, PCWSTR, w}; use crate::hle::{HleModule}; use crate::hle_export; type Routine = extern "system" fn(flag: u8, context: *mut c_void); type Registration = (usize, Routine, usize); struct NotificationState { entries: Vec, running: Vec<(usize, ThreadId)>, } struct Notifications { state: Mutex, done: Condvar, } impl Notifications { const fn new() -> Self { Self { state: Mutex::new(NotificationState { entries: Vec::new(), running: Vec::new(), }), done: Condvar::new(), } } fn lock(&self) -> MutexGuard<'_, NotificationState> { self.state.lock().unwrap_or_else(|e| e.into_inner()) } fn len(&self) -> usize { self.lock().entries.len() } fn register( &self, routine: Option, context: *mut c_void, registration: *mut usize, ) -> u32 { let Some(routine) = routine else { return ERROR_INVALID_PARAMETER; }; if registration.is_null() { return ERROR_INVALID_PARAMETER; } static NEXT: AtomicUsize = AtomicUsize::new(1); let id = NEXT.fetch_add(1, Ordering::Relaxed); let mut state = self.lock(); unsafe { registration.write(id) }; state.entries.push((id, routine, context as usize)); 0 } fn unregister(&self, registration: usize) { let me = std::thread::current().id(); let mut state = self.lock(); state.entries.retain(|&(id, ..)| id != registration); while state .running .iter() .any(|&(id, thread)| id == registration && thread != me) { state = self.done.wait(state).unwrap_or_else(|e| e.into_inner()); } } fn notify(&self, flag: u8) { let ids: Vec = self.lock().entries.iter().map(|&(id, ..)| id).collect(); let me = std::thread::current().id(); for id in ids { let target = { let mut state = self.lock(); let found = state .entries .iter() .find(|&&(entry_id, ..)| entry_id == id) .map(|&(_, routine, context)| (routine, context)); if found.is_some() { state.running.push((id, me)); } found }; let Some((routine, context)) = target else { continue; }; let _active = Active { notifications: self, id, thread: me, }; routine(flag, context as *mut c_void); } } } struct Active<'a> { notifications: &'a Notifications, id: usize, thread: ThreadId, } impl Drop for Active<'_> { fn drop(&mut self) { let mut state = self.notifications.lock(); if let Some(pos) = state .running .iter() .rposition(|&(id, thread)| id == self.id && thread == self.thread) { state.running.swap_remove(pos); } drop(state); self.notifications.done.notify_all(); } } static ROUTINES: Notifications = Notifications::new(); static CONSTRAINED: Notifications = Notifications::new(); const SUSPEND_DEADLINE: Duration = Duration::from_secs(1); const ERROR_INVALID_PARAMETER: u32 = 87; pub extern "system" fn RegisterAppStateChangeNotification( routine: Option, context: *mut c_void, registration: *mut usize, ) -> u32 { ROUTINES.register(routine, context, registration) } pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) { ROUTINES.unregister(registration); } pub extern "system" fn RegisterAppConstrainedChangeNotification( routine: Option, context: *mut c_void, registration: *mut usize, ) -> u32 { CONSTRAINED.register(routine, context, registration) } pub extern "system" fn UnregisterAppConstrainedChangeNotification(registration: usize) { CONSTRAINED.unregister(registration); } const TITLE_PROC: PCWSTR = w!("eonacat-xs.wndproc"); const BACKDROP_PROP: PCWSTR = w!("eonacat-xs.backdrop"); pub(super) fn enabled(name: &str) -> bool { std::env::var_os(name).is_some_and(|v| v == "1" || (name == "EONACAT_XS_FULLSCREEN" && v == "stretch")) } fn ensure_dpi_aware() { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { if std::env::var_os("EONACAT_XS_DPI_AWARE").is_some_and(|v| v == "0") { return; } use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; const PER_MONITOR_AWARE_V2: isize = -4; unsafe { let user32 = GetModuleHandleW(w!("user32.dll")); if !user32.is_null() && let Some(proc) = GetProcAddress(user32, c"SetProcessDpiAwarenessContext".as_ptr().cast()) { let set_dpi: unsafe extern "system" fn(isize) -> i32 = std::mem::transmute(proc); let ok = set_dpi(PER_MONITOR_AWARE_V2); tracing::info!(ok = ok != 0, "per-monitor v2 DPI awareness requested"); } } }); } fn fullscreen_box( screen_w: i32, screen_h: i32, content_w: i32, content_h: i32, stretch: bool, ) -> (i32, i32, i32, i32) { if stretch || content_w <= 0 || content_h <= 0 || screen_w <= 0 || screen_h <= 0 { return (0, 0, screen_w, screen_h); } let scale = f64::min( f64::from(screen_w) / f64::from(content_w), f64::from(screen_h) / f64::from(content_h), ); let w = ((f64::from(content_w) * scale).round() as i32).clamp(1, screen_w); let h = ((f64::from(content_h) * scale).round() as i32).clamp(1, screen_h); ((screen_w - w) / 2, (screen_h - h) / 2, w, h) } fn spawn_backdrop(hwnd: HWND, screen_w: i32, screen_h: i32) { use windows_sys::Win32::Graphics::Gdi::{BLACK_BRUSH, GetStockObject}; use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; static CLASS: std::sync::Once = std::sync::Once::new(); const CLASS_NAME: PCWSTR = w!("eonacat-xsBackdrop"); unsafe { CLASS.call_once(|| { let wc = wm::WNDCLASSEXW { cbSize: size_of::() as u32, style: 0, lpfnWndProc: Some(wm::DefWindowProcW), cbClsExtra: 0, cbWndExtra: 0, hInstance: GetModuleHandleW(std::ptr::null()), hIcon: std::ptr::null_mut(), hCursor: std::ptr::null_mut(), hbrBackground: GetStockObject(BLACK_BRUSH), lpszMenuName: std::ptr::null(), lpszClassName: CLASS_NAME, hIconSm: std::ptr::null_mut(), }; let _ = wm::RegisterClassExW(&wc); }); let backdrop = wm::CreateWindowExW( wm::WS_EX_TOOLWINDOW | wm::WS_EX_NOACTIVATE, CLASS_NAME, w!(""), wm::WS_POPUP | wm::WS_DISABLED, 0, 0, screen_w, screen_h, std::ptr::null_mut(), std::ptr::null_mut(), GetModuleHandleW(std::ptr::null()), std::ptr::null(), ); if !backdrop.is_null() { wm::SetPropW(hwnd, BACKDROP_PROP, backdrop); wm::SetWindowPos( backdrop, hwnd, 0, 0, screen_w, screen_h, wm::SWP_NOACTIVATE | wm::SWP_SHOWWINDOW, ); } } } fn fullscreen(hwnd: HWND, orig_w: i32, orig_h: i32) { if !enabled("EONACAT_XS_FULLSCREEN") { return; } ensure_dpi_aware(); let stretch = std::env::var_os("EONACAT_XS_FULLSCREEN").is_some_and(|v| v == "stretch"); unsafe { let (cw, ch) = if orig_w > 0 && orig_h > 0 { (orig_w, orig_h) } else { let mut client = RECT::default(); if wm::GetClientRect(hwnd, &mut client) != 0 { (client.right - client.left, client.bottom - client.top) } else { (0, 0) } }; let (sw, sh) = std::env::var("EONACAT_XS_FULLSCREEN_RES") .ok() .as_deref() .and_then(parse_window_limit) .unwrap_or_else(|| (wm::GetSystemMetrics(wm::SM_CXSCREEN), wm::GetSystemMetrics(wm::SM_CYSCREEN))); let (x, y, width, height) = fullscreen_box(sw, sh, cw, ch, stretch); enter_borderless(hwnd, RECT { left: x, top: y, right: x + width, bottom: y + height }); let bars = std::env::var_os("EONACAT_XS_FULLSCREEN_BARS").is_none_or(|v| v != "0"); if bars && cw >= 320 && ch >= 200 && (width < sw || height < sh) { spawn_backdrop(hwnd, sw, sh); } tracing::info!( screen = ?(sw, sh), content = ?(cw, ch), placed = ?(x, y, width, height), stretch, "borderless fullscreen applied" ); } } fn borderless_style(style: u32, ex: u32) -> (u32, u32) { ( (style & !wm::WS_OVERLAPPEDWINDOW) | wm::WS_POPUP, ex & !(wm::WS_EX_CLIENTEDGE | wm::WS_EX_WINDOWEDGE | wm::WS_EX_DLGMODALFRAME | wm::WS_EX_STATICEDGE), ) } struct Windowed { window: usize, style: u32, ex: u32, rect: RECT, } static WINDOWED: Mutex> = Mutex::new(None); unsafe fn enter_borderless(hwnd: HWND, area: RECT) { unsafe { let style = wm::GetWindowLongW(hwnd, wm::GWL_STYLE) as u32; let ex = wm::GetWindowLongW(hwnd, wm::GWL_EXSTYLE) as u32; let mut rect = RECT::default(); wm::GetWindowRect(hwnd, &mut rect); *WINDOWED.lock().unwrap_or_else(|e| e.into_inner()) = Some(Windowed { window: hwnd as usize, style, ex, rect }); let (style, ex) = borderless_style(style, ex); wm::SetWindowLongW(hwnd, wm::GWL_STYLE, style as i32); wm::SetWindowLongW(hwnd, wm::GWL_EXSTYLE, ex as i32); wm::SetWindowPos(hwnd, std::ptr::null_mut(), area.left, area.top, area.right - area.left, area.bottom - area.top, wm::SWP_FRAMECHANGED | wm::SWP_NOZORDER | wm::SWP_NOACTIVATE); } } fn toggle_fullscreen(hwnd: HWND) { use windows_sys::Win32::Graphics::Gdi as gdi; unsafe { let saved = { let mut windowed = WINDOWED.lock().unwrap_or_else(|e| e.into_inner()); if windowed.as_ref().is_some_and(|w| w.window == hwnd as usize) { windowed.take() } else { None } }; if let Some(saved) = saved { let backdrop = wm::RemovePropW(hwnd, BACKDROP_PROP); if !backdrop.is_null() { wm::DestroyWindow(backdrop); } wm::SetWindowLongW(hwnd, wm::GWL_STYLE, saved.style as i32); wm::SetWindowLongW(hwnd, wm::GWL_EXSTYLE, saved.ex as i32); let r = saved.rect; wm::SetWindowPos(hwnd, std::ptr::null_mut(), r.left, r.top, r.right - r.left, r.bottom - r.top, wm::SWP_FRAMECHANGED | wm::SWP_NOZORDER | wm::SWP_NOACTIVATE); return; } let mut info: gdi::MONITORINFO = std::mem::zeroed(); info.cbSize = std::mem::size_of::() as u32; let monitor = gdi::MonitorFromWindow(hwnd, gdi::MONITOR_DEFAULTTONEAREST); if monitor.is_null() || gdi::GetMonitorInfoW(monitor, &mut info) == 0 { return; } enter_borderless(hwnd, info.rcMonitor); } } fn is_alt_enter(message: u32, wparam: WPARAM, lparam: LPARAM) -> bool { use windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_RETURN; let alt = lparam & (1 << 29) != 0; match message { wm::WM_SYSKEYDOWN | wm::WM_SYSKEYUP => alt && wparam == VK_RETURN as usize, wm::WM_SYSCHAR => alt && wparam == 0x0d, _ => false, } } fn english_input() { use windows_sys::Win32::UI::Input::KeyboardAndMouse as kb; if !enabled("EONACAT_XS_IME_ENGLISH") { return; } unsafe { static ENGLISH: std::sync::OnceLock = std::sync::OnceLock::new(); let layout = *ENGLISH.get_or_init(|| { let mut layouts = vec![std::ptr::null_mut(); kb::GetKeyboardLayoutList(0, std::ptr::null_mut()).max(0) as usize]; let count = kb::GetKeyboardLayoutList(layouts.len() as i32, layouts.as_mut_ptr()).max(0) as usize; let found = layouts.iter().take(count).find(|&&h| h as usize & 0xffff_ffff == 0x0409_0409).copied(); if found.is_none() { tracing::warn!("en-US keyboard layout unavailable; keeping current input language"); } found.unwrap_or(std::ptr::null_mut()) as usize }); if layout != 0 { kb::ActivateKeyboardLayout(layout as kb::HKL, 0); } } } #[derive(Default)] struct MouseCapture { window: usize, center: (i32, i32), reference: Option<(i32, i32)>, hidden: i32, } static MOUSE_CAPTURE: std::sync::LazyLock> = std::sync::LazyLock::new(|| Mutex::new(MouseCapture::default())); fn mouse_capture_setting_enabled(value: Option<&str>) -> bool { value != Some("0") } fn mouse_capture_enabled() -> bool { mouse_capture_setting_enabled( std::env::var("EONACAT_XS_MOUSE_CAPTURE").ok().as_deref(), ) } fn mouse_input_enabled() -> bool { use super::gameinput::{Controls, controls}; matches!(controls(), Controls::Auto | Controls::Keyboard) } static MOUSE_DRAGGING: AtomicBool = AtomicBool::new(false); pub(crate) fn mouse_dragging() -> bool { MOUSE_DRAGGING.load(Ordering::Relaxed) } fn is_current_process_tree(pid: u32) -> bool { use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; use windows_sys::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS, }; static PROCESS_TREE: std::sync::OnceLock> = std::sync::OnceLock::new(); let descendants = PROCESS_TREE.get_or_init(|| { let current = unsafe { GetCurrentProcessId() }; let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; if snapshot == INVALID_HANDLE_VALUE { return vec![current]; } let mut parents = Vec::new(); let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() }; entry.dwSize = std::mem::size_of::() as u32; let mut more = unsafe { Process32FirstW(snapshot, &mut entry) } != 0; while more { parents.push((entry.th32ProcessID, entry.th32ParentProcessID)); more = unsafe { Process32NextW(snapshot, &mut entry) } != 0; } unsafe { CloseHandle(snapshot); } let mut descendants = vec![current]; let mut index = 0; while index < descendants.len() { let parent = descendants[index]; for &(child, owner) in &parents { if owner == parent && !descendants.contains(&child) { descendants.push(child); } } index += 1; } descendants }); descendants.contains(&pid) } fn game_window_has_focus(hwnd: HWND) -> bool { if hwnd.is_null() { return false; } unsafe { let foreground = wm::GetForegroundWindow(); if foreground.is_null() { return false; } let mut foreground_pid = 0; wm::GetWindowThreadProcessId(foreground, &mut foreground_pid); is_current_process_tree(foreground_pid) || foreground == hwnd || wm::IsChild(foreground, hwnd) != 0 || wm::IsChild(hwnd, foreground) != 0 } } fn capture_mouse(hwnd: HWND, active: bool) { if !mouse_capture_enabled() || offscreen() { return; } let mut state = MOUSE_CAPTURE.lock().unwrap_or_else(|e| e.into_inner()); unsafe { if active && !wm::GetParent(hwnd).is_null() { return; } let active = active && !MOUSE_DRAGGING.load(Ordering::Relaxed) && game_window_has_focus(hwnd) && wm::IsIconic(hwnd) == 0; if !active { if state.window == hwnd as usize { wm::ClipCursor(std::ptr::null()); for _ in 0..state.hidden { wm::ShowCursor(1); } *state = MouseCapture::default(); } return; } if state.window != 0 && state.window != hwnd as usize { return; } let (mut area, mut origin) = (RECT::default(), POINT::default()); if wm::GetClientRect(hwnd, &mut area) == 0 || ClientToScreen(hwnd, &mut origin) == 0 || area.right <= 0 || area.bottom <= 0 { return; } let center = (origin.x + area.right / 2, origin.y + area.bottom / 2); area.left += origin.x; area.right += origin.x; area.top += origin.y; area.bottom += origin.y; if wm::ClipCursor(&area) == 0 { return; } if state.window == 0 { state.hidden = 1 + (wm::ShowCursor(0) + 1).max(0); for _ in 1..state.hidden { wm::ShowCursor(0); } } if state.center != center { state.reference = None; } state.window = hwnd as usize; state.center = center; } } pub(super) fn captured_mouse_delta(menu_open: bool) -> Option<(i64, i64)> { if super::gameinput::native_mouse_enabled() || !mouse_capture_enabled() || !mouse_input_enabled() { return None; } let mut state = MOUSE_CAPTURE.lock().unwrap_or_else(|e| e.into_inner()); unsafe { if state.window == 0 || MOUSE_DRAGGING.load(Ordering::Relaxed) || !game_window_has_focus(state.window as HWND) { return None; } if menu_open { state.reference = None; return Some((0, 0)); } let mut point = POINT::default(); if wm::GetCursorPos(&mut point) == 0 { state.reference = None; return None; } let point = (point.x, point.y); let warp = std::env::var_os("EONACAT_XS_MOUSE_WARP").is_some_and(|v| v == "1"); let warped = (warp && wm::SetCursorPos(state.center.0, state.center.1) != 0) .then_some(state.center); Some(mouse_motion(&mut state.reference, point, warped)) } } fn mouse_motion(reference: &mut Option<(i32, i32)>, point: (i32, i32), warped: Option<(i32, i32)>) -> (i64, i64) { let delta = reference.map_or((0, 0), |(x, y)| (i64::from(point.0) - i64::from(x), i64::from(point.1) - i64::from(y))); *reference = Some(warped.unwrap_or(point)); delta } pub extern "system" fn CreateWindowExW( ex_style: u32, class: PCWSTR, name: PCWSTR, style: u32, x: i32, y: i32, width: i32, height: i32, parent: HWND, menu: HMENU, instance: HINSTANCE, param: *const c_void, ) -> HWND { let (orig_w, orig_h) = (width, height); let (x, y, width, height) = fit(parent, x, y, width, height); let (ex_style, x, y) = offscreen_at_creation(parent, ex_style, x, y); let hwnd = unsafe { wm::CreateWindowExW( ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, ) }; hook(hwnd, orig_w, orig_h); hwnd } pub extern "system" fn CreateWindowExA( ex_style: u32, class: PCSTR, name: PCSTR, style: u32, x: i32, y: i32, width: i32, height: i32, parent: HWND, menu: HMENU, instance: HINSTANCE, param: *const c_void, ) -> HWND { let (orig_w, orig_h) = (width, height); let (x, y, width, height) = fit(parent, x, y, width, height); let (ex_style, x, y) = offscreen_at_creation(parent, ex_style, x, y); let hwnd = unsafe { wm::CreateWindowExA( ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, ) }; hook(hwnd, orig_w, orig_h); hwnd } fn offscreen() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("EONACAT_XS_WINDOW_OFFSCREEN").is_some_and(|v| v == "1")) } const OFFSCREEN: i32 = -32000; fn offscreen_at_creation(parent: HWND, ex_style: u32, x: i32, y: i32) -> (u32, i32, i32) { if !offscreen() || !parent.is_null() { return (ex_style, x, y); } tracing::info!("the title's window is kept off the screen (EONACAT_XS_WINDOW_OFFSCREEN=1)"); (ex_style | wm::WS_EX_TOOLWINDOW | wm::WS_EX_NOACTIVATE, OFFSCREEN, OFFSCREEN) } fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) { if parent.is_null() && width >= 320 && height >= 200 { ensure_dpi_aware(); } let mut area = RECT::default(); let known = unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) }; let limit = window_limit(); let fitted = fit_with_limit(&area, width, height, limit); if !parent.is_null() || known == 0 { return (x, y, width, height); } if fitted == (width, height) { if x == 0 && y == 0 && width >= 320 && height >= 200 { let left = area.left + (area.right - area.left - width) / 2; let top = area.top + (area.bottom - area.top - height) / 2; return (left, top, width, height); } return (x, y, width, height); } tracing::info!(width, height, to = ?fitted, ?limit, "title window fitted to the screen"); let (w, h) = fitted; let left = area.left + (area.right - area.left - w) / 2; let top = area.top + (area.bottom - area.top - h) / 2; (left, top, w, h) } fn parse_window_limit(value: &str) -> Option<(i32, i32)> { let (width, height) = value.trim().split_once(['x', 'X'])?; let (width, height) = (width.trim().parse().ok()?, height.trim().parse().ok()?); (width > 0 && height > 0).then_some((width, height)) } fn window_limit() -> Option<(i32, i32)> { static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); *LIMIT.get_or_init(|| { let value = std::env::var_os("EONACAT_XS_WINDOW_MAX")?; let parsed = value.to_str().and_then(parse_window_limit); if parsed.is_none() { tracing::warn!( ?value, "ignoring invalid EONACAT_XS_WINDOW_MAX; expected positive WIDTHxHEIGHT" ); } parsed }) } fn fit_with_limit( area: &RECT, width: i32, height: i32, limit: Option<(i32, i32)>, ) -> (i32, i32) { let Some((max_width, max_height)) = limit else { return fit_into(area, width, height); }; let bounded = RECT { left: 0, top: 0, right: (area.right - area.left).min(max_width), bottom: (area.bottom - area.top).min(max_height), }; fit_into(&bounded, width, height) } fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { let (aw, ah) = (area.right - area.left, area.bottom - area.top); if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) { return (width, height); } let scale = f64::min( f64::from(aw) / f64::from(width), f64::from(ah) / f64::from(height), ); ( (f64::from(width) * scale) as i32, (f64::from(height) * scale) as i32, ) } fn hook(hwnd: HWND, orig_w: i32, orig_h: i32) { if hwnd.is_null() { return; } unsafe { let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC); wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void); wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize); if wm::GetParent(hwnd).is_null() && !offscreen() { fullscreen(hwnd, orig_w, orig_h); english_input(); super::icon::start(hwnd); super::theme::apply(hwnd); capture_mouse(hwnd, true); } } super::gameinput::register_raw_mouse(hwnd); } fn client_xy(lparam: LPARAM) -> (i32, i32) { let bits = lparam as usize; let x = ((bits & 0xffff) as u16) as i16; let y = (((bits >> 16) & 0xffff) as u16) as i16; (i32::from(x), i32::from(y)) } fn client_size(hwnd: HWND) -> Option<(i32, i32)> { if hwnd.is_null() { return None; } let mut rect = RECT::default(); if unsafe { wm::GetClientRect(hwnd, &mut rect) } == 0 { return None; } let w = rect.right - rect.left; let h = rect.bottom - rect.top; (w > 0 && h > 0).then_some((w, h)) } fn wheel_client_xy(hwnd: HWND) -> Option<(i32, i32)> { if hwnd.is_null() { return None; } let mut pt = POINT::default(); unsafe { if wm::GetCursorPos(&mut pt) == 0 || ScreenToClient(hwnd, &mut pt) == 0 { return None; } } Some((pt.x, pt.y)) } fn release_drag_capture(hwnd: HWND) { if hwnd.is_null() { return; } unsafe { if GetCapture() == hwnd { let _ = ReleaseCapture(); } } } extern "system" fn window_proc( hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM, ) -> LRESULT { let foreground = unsafe { wm::GetForegroundWindow() }; let mut foreground_pid = 0; if !foreground.is_null() { unsafe { wm::GetWindowThreadProcessId(foreground, &mut foreground_pid); } } let focused_window = !foreground.is_null() && (is_current_process_tree(foreground_pid) || unsafe { foreground == hwnd || wm::IsChild(foreground, hwnd) != 0 || wm::IsChild(hwnd, foreground) != 0 }); if message == wm::WM_SETCURSOR && (lparam as u16) == wm::HTCLIENT as u16 && enabled("EONACAT_XS_MOUSE_CAPTURE") && focused_window { let menu = eonacat_xsbox_gpu::SETTINGS_MENU_OPEN.load(std::sync::atomic::Ordering::Relaxed); unsafe { wm::SetCursor(if menu { wm::LoadCursorW(std::ptr::null_mut(), wm::IDC_ARROW) } else { std::ptr::null_mut() }) }; return 1; } if message == wm::WM_SETFOCUS { english_input(); } if message == wm::WM_SETICON && !super::icon::is_ours(lparam) { tracing::debug!(big = wparam == wm::ICON_BIG as usize, "icon: the title set its own"); } if message == wm::WM_SETTINGCHANGE && unsafe { wm::GetParent(hwnd) }.is_null() { super::theme::apply_for_setting(hwnd, lparam); } if message == wm::WM_MOUSEWHEEL { super::gameinput::mnk::wheel_scroll(hwnd, ((wparam >> 16) as u16 as i16).into()); } let top_level = message == wm::WM_CLOSE && unsafe { wm::GetParent(hwnd) }.is_null(); if let Some(why) = close_request(message, wparam, top_level) { super::gameinput::on_window_unfocused(hwnd); end_title(why, Box::new(|| {})); return 0; } if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { return 0; } let _ = super::gameinput::mnk::note_button(message, wparam); let f1_open = eonacat_xsbox_gpu::SETTINGS_MENU_OPEN.load(Ordering::Relaxed); match message { wm::WM_SETCURSOR => { if super::gameinput::native_mouse_enabled() && (lparam & 0xffff) == wm::HTCLIENT as isize { unsafe { if super::gameinput::mouse_captured() { wm::SetCursor(std::ptr::null_mut()); } else if !f1_open && super::gameinput::is_map_dragging() { wm::SetCursor(wm::LoadCursorW(std::ptr::null_mut(), wm::IDC_SIZEALL)); } else { wm::SetCursor(wm::LoadCursorW(std::ptr::null_mut(), wm::IDC_ARROW)); } } return 1; } } wm::WM_INPUT => { if super::gameinput::mouse_captured() { super::gameinput::on_raw_input(hwnd, lparam); return 0; } } wm::WM_KILLFOCUS => { MOUSE_DRAGGING.store(false, Ordering::Relaxed); super::gameinput::mnk::forget_buttons(); release_drag_capture(hwnd); capture_mouse(hwnd, false); super::gameinput::on_window_unfocused(std::ptr::null_mut()); } wm::WM_NCDESTROY => { MOUSE_DRAGGING.store(false, Ordering::Relaxed); super::gameinput::mnk::forget_buttons(); release_drag_capture(hwnd); capture_mouse(hwnd, false); super::gameinput::on_window_unfocused(hwnd); } wm::WM_ENTERSIZEMOVE | wm::WM_NCLBUTTONDOWN => { MOUSE_DRAGGING.store(true, Ordering::Relaxed); capture_mouse(hwnd, false); } wm::WM_EXITSIZEMOVE => { if MOUSE_DRAGGING.swap(false, Ordering::Relaxed) { capture_mouse(hwnd, true); } } wm::WM_MOUSEMOVE if !f1_open => { let (x, y) = client_xy(lparam); super::gameinput::on_ui_mouse_move(hwnd, x, y, client_size(hwnd)); } wm::WM_LBUTTONDOWN => { MOUSE_DRAGGING.store(false, Ordering::Relaxed); capture_mouse(hwnd, true); if !f1_open { let (x, y) = client_xy(lparam); let size = client_size(hwnd); if super::gameinput::on_client_lbutton_down(hwnd, x, y, size) { return 0; } if crate::hle::mousehook::is_map_active() && super::gameinput::menu_mouse_enabled() { unsafe { SetCapture(hwnd) }; } } } wm::WM_LBUTTONUP => { super::gameinput::on_lbutton_up(hwnd); if !super::gameinput::is_ui_map_button_held() { release_drag_capture(hwnd); } } wm::WM_RBUTTONDOWN if !f1_open => { let (x, y) = client_xy(lparam); super::gameinput::on_ui_rbutton_down(hwnd, x, y, client_size(hwnd)); } wm::WM_RBUTTONUP => { super::gameinput::on_rbutton_up(); } wm::WM_MBUTTONDOWN if !f1_open => { let (x, y) = client_xy(lparam); super::gameinput::on_ui_mbutton_down(hwnd, x, y, client_size(hwnd)); if crate::hle::mousehook::is_map_active() && super::gameinput::menu_mouse_enabled() { unsafe { SetCapture(hwnd) }; } } wm::WM_MBUTTONUP => { super::gameinput::on_mbutton_up(hwnd); if !super::gameinput::is_ui_map_button_held() { release_drag_capture(hwnd); } } wm::WM_XBUTTONDOWN if !f1_open => { let button = ((wparam >> 16) & 0xffff) as u16; super::gameinput::on_ui_xbutton_down(button); } wm::WM_XBUTTONUP => { let button = ((wparam >> 16) & 0xffff) as u16; super::gameinput::on_ui_xbutton_up(button); } wm::WM_MOUSEWHEEL => { let delta = ((wparam >> 16) as u16) as i16; if f1_open { eonacat_xsbox_gpu::push_settings_menu_wheel(delta); return 0; } else if super::gameinput::mouse_captured() { super::gameinput::on_mouse_wheel(delta); return 0; } else if crate::hle::mousehook::is_menu_or_paused() && super::gameinput::menu_mouse_enabled() { if let Some((x, y)) = wheel_client_xy(hwnd) { super::gameinput::refresh_ui_cursor(x, y, client_size(hwnd)); } super::gameinput::on_ui_mouse_wheel(delta); return 0; } } wm::WM_KEYDOWN if (lparam & (1 << 30)) == 0 && !f1_open => match wparam as u32 { 0x77 if super::gameinput::native_mouse_enabled() => { crate::hle::mousehook::toggle_vehicle_auto_center(); return 0; } 0x74 => { crate::hle::console_window::show(); return 0; } 0x78 => { super::gameinput::toggle_user_mouse_capture(hwnd); return 0; } 0xDB if super::gameinput::native_mouse_enabled() => { super::gameinput::adjust_mouse_sensitivity(1.0 / 1.15); return 0; } 0xDD if super::gameinput::native_mouse_enabled() => { super::gameinput::adjust_mouse_sensitivity(1.15); return 0; } _ => {} }, wm::WM_ACTIVATE => { let active = wparam & 0xffff != wm::WA_INACTIVE as usize; if !active { MOUSE_DRAGGING.store(false, Ordering::Relaxed); } capture_mouse(hwnd, active); if active { unsafe { let backdrop = wm::GetPropW(hwnd, BACKDROP_PROP); if !backdrop.is_null() { wm::SetWindowPos( backdrop, hwnd, 0, 0, 0, 0, wm::SWP_NOMOVE | wm::SWP_NOSIZE | wm::SWP_NOACTIVATE, ); } } } } wm::WM_ACTIVATEAPP if wparam == 0 => { release_drag_capture(hwnd); super::gameinput::on_window_unfocused(std::ptr::null_mut()); } wm::WM_SETFOCUS => capture_mouse(hwnd, true), wm::WM_MOVE | wm::WM_SIZE => { if !MOUSE_DRAGGING.load(Ordering::Relaxed) { capture_mouse(hwnd, true); } super::gameinput::refresh_cursor_clip(hwnd); } _ => {} } if is_alt_enter(message, wparam, lparam) { if message == wm::WM_SYSKEYDOWN && lparam & (1 << 30) == 0 && unsafe { wm::GetParent(hwnd) }.is_null() { toggle_fullscreen(hwnd); } return 0; } if message == wm::WM_WINDOWPOSCHANGING && lparam != 0 && offscreen() && unsafe { wm::GetParent(hwnd) }.is_null() { let pos = unsafe { &mut *(lparam as *mut wm::WINDOWPOS) }; pos.x = OFFSCREEN; pos.y = OFFSCREEN; pos.flags = (pos.flags & !wm::SWP_NOMOVE) | wm::SWP_NOACTIVATE; } if super::gameinput::pads_only() && keys_or_mouse(message) { return unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) }; } unsafe { let title = wm::GetPropW(hwnd, TITLE_PROC); if message == wm::WM_NCDESTROY { let backdrop = wm::RemovePropW(hwnd, BACKDROP_PROP); if !backdrop.is_null() { wm::DestroyWindow(backdrop); } wm::RemovePropW(hwnd, TITLE_PROC); } let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title); wm::CallWindowProcW(title, hwnd, message, wparam, lparam) } } fn close_request(message: u32, wparam: WPARAM, top_level: bool) -> Option<&'static str> { match message { wm::WM_SYSCOMMAND if wparam & 0xFFF0 == wm::SC_CLOSE as usize => Some("window closed"), wm::WM_CLOSE if top_level => Some("window closed (WM_CLOSE)"), _ => None, } } pub(crate) fn end_title(why: &'static str, then: Box) { static ENDING: AtomicBool = AtomicBool::new(false); if ENDING.swap(true, Ordering::SeqCst) { return; } tracing::info!( constrained = CONSTRAINED.len(), routines = ROUTINES.len(), "{why}: suspending the title" ); eonacat_xsbox_gpu::log_defrag_counters(); let then = std::sync::Arc::new(Mutex::new(Some(then))); let finish = move |how: &str| { let mut then = then.lock().unwrap_or_else(|e| e.into_inner()); tracing::info!("{how}; ending the title"); if let Some(then) = then.take() { then(); } end(); }; let late = finish.clone(); std::thread::spawn(move || { constrain_then_suspend(&CONSTRAINED, &ROUTINES); finish("title suspended"); }); std::thread::spawn(move || { std::thread::sleep(SUSPEND_DEADLINE); late("title did not finish suspending in time"); }); } fn constrain_then_suspend(constrain: &Notifications, suspend: &Notifications) { constrain.notify(1); suspend.notify(1); } const RELAUNCHED_FROM: &str = "EONACAT_XS_RELAUNCHED_FROM"; pub(crate) fn relaunch(args: Vec) { use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE}; let mut me: HANDLE = std::ptr::null_mut(); let duplicated = unsafe { DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &mut me, 0, 1, DUPLICATE_SAME_ACCESS, ) } != 0; let spawned = std::env::current_exe().and_then(|exe| { let mut command = std::process::Command::new(exe); command.args(&args); if duplicated { command.env(RELAUNCHED_FROM, (me as usize).to_string()); } command.spawn() }); match spawned { Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"), Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"), } } pub fn wait_for_previous() { use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; use windows_sys::Win32::System::Threading::WaitForSingleObject; let Some(handle) = std::env::var(RELAUNCHED_FROM) .ok() .and_then(|h| h.parse::().ok()) else { return; }; unsafe { std::env::remove_var(RELAUNCHED_FROM) }; let handle = handle as HANDLE; unsafe { WaitForSingleObject(handle, 30_000); CloseHandle(handle); } } fn end() { crate::hle::modules::gameinput::stop_rumble(); #[cfg(windows)] eonacat_xsbox_gpu::pipeline::save_pipeline_cache(); unsafe { TerminateProcess(GetCurrentProcess(), 0) }; } pub(crate) fn module() -> HleModule { HleModule { name: "lifecycle", dlls: &[ "api-ms-win-core-psm-appnotify-*", "ext-ms-win-rtcore-ntuser-window-*", ], exports: vec![ hle_export!(RegisterAppStateChangeNotification), hle_export!(UnregisterAppStateChangeNotification), hle_export!(RegisterAppConstrainedChangeNotification), hle_export!(UnregisterAppConstrainedChangeNotification), hle_export!(CreateWindowExW), hle_export!(CreateWindowExA), ], } } #[cfg(windows)] fn keys_or_mouse(message: u32) -> bool { message == 0x00FF || (0x0100..=0x0109).contains(&message) || (0x0200..=0x020E).contains(&message) } #[cfg(test)] mod mouse_capture_tests { use super::mouse_capture_setting_enabled; #[test] fn mouse_capture_is_enabled_when_unset() { assert!(mouse_capture_setting_enabled(None)); } #[test] fn mouse_capture_can_be_explicitly_disabled() { assert!(!mouse_capture_setting_enabled(Some("0"))); } #[test] fn mouse_capture_accepts_explicit_enable() { assert!(mouse_capture_setting_enabled(Some("1"))); } }