Window and input: fullscreen, English input method, and a mouse capture that leaves the pointer alone

Three switches, each on by default, each 0 restoring the behaviour before it: VICTORY_FULLSCREEN (borderless, VICTORY_FULLSCREEN_RES for another size), VICTORY_IME_ENGLISH (the window's input context to en-US), and VICTORY_MOUSE_CAPTURE (clip to the client area and hide the pointer, release on focus loss).

Capture also fixes a mistake in the mouse device merged as #9: it warped the pointer back to the centre after every sample, which pins the absolute position the title reads and makes the camera look frozen. Warping is now VICTORY_MOUSE_WARP, off by default; with it on the delta is taken from the centre.

Measured on an RTX 5070 Ti Laptop (12 GB): window 0,0-1920,1080 with a client area of the same size and GetClipCursor returning it. cargo build --release and --profile diag pass, cargo test -p victory-hle: 162 passed, 2 ignored.

Written with an AI assistant.
This commit is contained in:
superboynick committed 2026-11-27 12:12:12 +08:00
1 parent 9d6300fa2d
commit 4a0c8ea373
3 files changed
+211 -9

No files matched your search

+1
View File
@@ -20,6 +20,7 @@ tracing.workspace = true
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Globalization",
"Win32_Graphics_Gdi",
"Win32_Media",
"Win32_Security",
"Win32_Security_Cryptography",
+73 -8
View File
@@ -30,6 +30,7 @@ const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
/// Input kinds (bits) our devices have.
const KEYBOARD_KIND: u32 = 0x10;
const MOUSE_KIND: u32 = 0x20;
const GAMEPAD_KIND: u32 = 0x4_0000;
/// Device status of a connected device: connected, input enabled.
const STATUS_CONNECTED: u32 = 0x3;
@@ -55,7 +56,8 @@ const RIGHT_STICK: u32 = 0x2000;
const PADS: usize = 4;
const FALLBACK: usize = PADS;
const KEYBOARD: usize = PADS + 1;
const DEVICES: usize = PADS + 2;
const MOUSE: usize = PADS + 2;
const DEVICES: usize = PADS + 3;
/// Readings kept per device for next/previous lookups.
const HISTORY: usize = 256;
@@ -105,8 +107,21 @@ struct KeyState {
const _: () = assert!(size_of::<KeyState>() == 12 && size_of::<PadState>() == 28);
/// GameInput v0: cumulative motion; scroll axes are not sampled.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct MouseState {
buttons: u32,
position_x: i64,
position_y: i64,
wheel_x: i64,
wheel_y: i64,
}
const _: () = assert!(size_of::<MouseState>() == 40);
/// Host input, or a fake in tests.
trait Source: Send {
fn mouse(&mut self) -> Option<MouseState> { None }
/// The pad in host slot `slot`, `None` when the slot is empty.
fn pad(&mut self, slot: usize) -> Option<PadState>;
/// Keys held down; none while the title's window lacks focus.
@@ -210,6 +225,7 @@ struct DeviceInfo {
const _: () = assert!(std::mem::offset_of!(DeviceInfo, id) == 0x20);
fn kind(index: usize) -> u32 {
if index == MOUSE { return MOUSE_KIND; }
if index == KEYBOARD {
KEYBOARD_KIND
} else {
@@ -247,6 +263,7 @@ impl Device {
#[derive(PartialEq)]
enum Value {
Mouse(MouseState),
Pad(PadState),
Keys(Vec<KeyState>),
}
@@ -264,6 +281,7 @@ pub struct Reading {
impl Reading {
fn kind(&self) -> u32 {
match self.value {
Value::Mouse(_) => MOUSE_KIND,
Value::Pad(_) => GAMEPAD_KIND,
Value::Keys(_) => KEYBOARD_KIND,
}
@@ -430,12 +448,12 @@ impl Hub {
/// Reads the host once; device callbacks run on the calling thread.
fn poll(&self) {
let (pads, keys) = {
let (pads, keys, mouse) = {
let mut source = lock(&self.source);
let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot));
(pads, source.keys())
(pads, source.keys(), source.mouse())
};
let events = self.state().poll(&self.devices, self.one_pad, pads, keys);
let events = self.state().poll(&self.devices, self.one_pad, pads, keys, mouse);
self.deliver(events);
}
@@ -481,9 +499,11 @@ impl State {
one_pad: bool,
pads: [Option<PadState>; PADS],
keys: Vec<KeyState>,
mouse: Option<MouseState>,
) -> Vec<Event> {
let now = now();
let mut events = std::mem::take(&mut self.pending);
self.update(devices, MOUSE, mouse.map(Value::Mouse), now, &mut events);
if one_pad {
let pad = pads.into_iter().flatten().fold(fallback(&keys), merged);
self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events);
@@ -881,7 +901,8 @@ extern "system" fn find_by_id(this: This, id: *const [u8; 32], out: Out) -> HRES
}
// SAFETY: checked non-null; the title passes a device id.
let id = unsafe { &*id };
match hub(this).devices.iter().find(|d| d.info.id == *id) {
match hub(this).devices.iter().find(|d| d.info.id == *id
&& (d.index != MOUSE || hub(this).state().slots[MOUSE].connected)) {
Some(device) => {
// SAFETY: checked non-null.
unsafe { out.write((device as *const Device).cast()) };
@@ -1044,7 +1065,7 @@ extern "system" fn reading_device(this: *const Reading, out: *mut *const Device)
extern "system" fn key_count(this: *const Reading) -> u32 {
match &reading(this).value {
Value::Keys(keys) => keys.len() as u32,
Value::Pad(_) => 0,
_ => 0,
}
}
extern "system" fn key_state(this: *const Reading, count: u32, out: *mut KeyState) -> u32 {
@@ -1069,6 +1090,14 @@ extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bo
_ => false,
}
}
extern "system" fn mouse_state(this: *const Reading, out: *mut MouseState) -> bool {
if let Value::Mouse(state) = &reading(this).value && !out.is_null() {
// SAFETY: the caller supplies room for one v0 mouse state.
unsafe { out.write(*state) };
return true;
}
false
}
/// Kinds our devices do not have: no count, no state.
extern "system" fn nothing(_: *const c_void) -> usize {
0
@@ -1091,7 +1120,7 @@ static READING: Table<25> = Table([
nothing as *const (), // 0x68
key_count as *const (), // 0x70
key_state as *const (), // 0x78
nothing as *const (), // 0x80 mouse
mouse_state as *const (), // 0x80 mouse
nothing as *const (), // 0x88 touch
nothing as *const (), // 0x90
nothing as *const (), // 0x98 motion
@@ -1177,9 +1206,19 @@ mod host {
#[derive(Default)]
pub(super) struct Host {
empty_until: [Option<Instant>; PADS],
mouse: MouseState,
}
impl Source for Host {
fn mouse(&mut self) -> Option<MouseState> {
let (dx, dy) = crate::modules::lifecycle::captured_mouse_delta()?;
self.mouse.position_x += dx;
self.mouse.position_y += dy;
self.mouse.buttons = [0x01, 0x02, 0x04, 0x05, 0x06].into_iter().enumerate()
// SAFETY: virtual-key state query.
.fold(0, |bits, (i, vk)| bits | ((unsafe { GetAsyncKeyState(vk) } < 0) as u32) << i);
Some(self.mouse)
}
fn pad(&mut self, slot: usize) -> Option<PadState> {
if self.empty_until[slot].is_some_and(|until| Instant::now() < until) {
return None;
@@ -1432,6 +1471,7 @@ mod tests {
#[derive(Default)]
struct FakeHost {
mouse: Option<MouseState>,
pads: [Option<PadState>; PADS],
keys: Vec<KeyState>,
rumble: Vec<(usize, u16, u16)>,
@@ -1440,6 +1480,7 @@ mod tests {
struct Fake(Arc<Mutex<FakeHost>>);
impl Source for Fake {
fn mouse(&mut self) -> Option<MouseState> { self.0.lock().unwrap().mouse }
fn pad(&mut self, slot: usize) -> Option<PadState> {
self.0.lock().unwrap().pads[slot]
}
@@ -1580,6 +1621,30 @@ mod tests {
assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None);
}
#[test]
fn mouse_readings_connect_and_disconnect_in_both_pad_modes() {
for one_pad in [false, true] {
let (hub, host) = fake_with(one_pad);
let log = Log::default();
register(hub, MOUSE_KIND, 2, &log);
assert!(log.lock().unwrap().is_empty());
let sample = MouseState { position_x: 30, position_y: -12, buttons: 1, ..Default::default() };
host.lock().unwrap().mouse = Some(sample);
hub.poll();
let r = current(hub, MOUSE_KIND, MOUSE).unwrap();
let mut got = MouseState::default();
let get = slot::<extern "system" fn(*const Reading, *mut MouseState) -> bool, _>(r, 0x80);
assert!(get(r, &mut got));
assert_eq!(got, sample);
assert!(!get(r, std::ptr::null_mut()));
release(r);
host.lock().unwrap().mouse = None;
hub.poll();
assert_eq!(current(hub, MOUSE_KIND, MOUSE), Err(DEVICE_DISCONNECTED));
assert_eq!(*log.lock().unwrap(), [(MOUSE, STATUS_CONNECTED, 0), (MOUSE, 0, STATUS_CONNECTED)]);
}
}
#[test]
fn pads_connect_report_and_disconnect() {
let (hub, host) = fake();
@@ -1685,7 +1750,7 @@ mod tests {
assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]);
let pad = |hub: &Hub| match &hub.state().slots[FALLBACK].history.back().unwrap().value {
Value::Pad(p) => *p,
Value::Keys(_) => unreachable!(),
_ => unreachable!(),
};
host.lock().unwrap().keys = vec![key(b'D')];
hub.poll();
+137 -1
View File
@@ -13,7 +13,8 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
use windows_sys::Win32::Graphics::Gdi::ClientToScreen;
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU};
use windows_sys::core::{PCSTR, PCWSTR, w};
@@ -96,6 +97,113 @@ pub extern "system" fn UnregisterAppConstrainedChangeNotification(registration:
/// The window procedure a title window had before ours.
const TITLE_PROC: PCWSTR = w!("victory.wndproc");
pub(super) fn enabled(name: &str) -> bool {
std::env::var_os(name).is_none_or(|v| v != "0")
}
fn fullscreen(hwnd: HWND) {
if !enabled("VICTORY_FULLSCREEN") {
return;
}
// SAFETY: this thread owns the newly created top-level window.
unsafe {
let (width, height) = std::env::var("VICTORY_FULLSCREEN_RES")
.ok().as_deref().and_then(parse_window_limit)
.unwrap_or_else(|| (wm::GetSystemMetrics(wm::SM_CXSCREEN), wm::GetSystemMetrics(wm::SM_CYSCREEN)));
let style = wm::GetWindowLongW(hwnd, wm::GWL_STYLE) as u32;
let ex = wm::GetWindowLongW(hwnd, wm::GWL_EXSTYLE) as u32;
wm::SetWindowLongW(hwnd, wm::GWL_STYLE, ((style & !wm::WS_OVERLAPPEDWINDOW) | wm::WS_POPUP) as i32);
wm::SetWindowLongW(hwnd, wm::GWL_EXSTYLE, (ex & !(wm::WS_EX_CLIENTEDGE | wm::WS_EX_WINDOWEDGE | wm::WS_EX_DLGMODALFRAME | wm::WS_EX_STATICEDGE)) as i32);
wm::SetWindowPos(hwnd, std::ptr::null_mut(), 0, 0, width, height,
wm::SWP_FRAMECHANGED | wm::SWP_NOZORDER | wm::SWP_NOACTIVATE);
}
}
fn english_input() {
use windows_sys::Win32::UI::Input::KeyboardAndMouse as kb;
if !enabled("VICTORY_IME_ENGLISH") {
return;
}
// SAFETY: enumerate loaded layouts; activate only on the window's thread.
unsafe {
static ENGLISH: std::sync::OnceLock<usize> = 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<Mutex<MouseCapture>> =
std::sync::LazyLock::new(|| Mutex::new(MouseCapture::default()));
fn capture_mouse(hwnd: HWND, active: bool) {
if !enabled("VICTORY_MOUSE_CAPTURE") { return; }
let mut state = MOUSE_CAPTURE.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: runs on the window thread; local geometry, balanced cursor count.
unsafe {
if active && !wm::GetParent(hwnd).is_null() { return; }
let active = active && wm::GetForegroundWindow() == 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() -> Option<(i64, i64)> {
if !enabled("VICTORY_MOUSE_CAPTURE") { return None; }
let mut state = MOUSE_CAPTURE.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: sampling and warping serialize with capture/focus messages.
unsafe {
if state.window == 0 || wm::GetForegroundWindow() as usize != state.window { return None; }
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("VICTORY_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,
@@ -237,6 +345,11 @@ fn hook(hwnd: HWND) {
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() {
fullscreen(hwnd);
english_input();
capture_mouse(hwnd, true);
}
}
}
@@ -246,6 +359,15 @@ extern "system" fn window_proc(
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
if message == wm::WM_SETFOCUS {
english_input();
}
match message {
wm::WM_KILLFOCUS | wm::WM_NCDESTROY => capture_mouse(hwnd, false),
wm::WM_ACTIVATE => capture_mouse(hwnd, wparam & 0xffff != wm::WA_INACTIVE as usize),
wm::WM_SETFOCUS | wm::WM_MOVE | wm::WM_SIZE => capture_mouse(hwnd, true),
_ => {}
}
// A user close (close button, Alt+F4, window or taskbar menu); a
// console title never sees one, nor a WM_CLOSE from it.
if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize {
@@ -406,6 +528,19 @@ pub(crate) fn module() -> HleModule {
mod tests {
use super::*;
#[test]
fn mouse_reference_handles_focus_reset_and_warp() {
if !enabled("VICTORY_MOUSE_CAPTURE") { assert_eq!(captured_mouse_delta(), None); }
let mut reference = None;
assert_eq!(mouse_motion(&mut reference, (480, 390), None), (0, 0));
assert_eq!(mouse_motion(&mut reference, (500, 400), None), (20, 10));
reference = None; // Refocus never reports motion from another application.
assert_eq!(mouse_motion(&mut reference, (500, 400), Some((960, 540))), (0, 0));
assert_eq!(mouse_motion(&mut reference, (970, 535), Some((960, 540))), (10, -5));
assert_eq!(mouse_motion(&mut reference, (960, 540), None), (0, 0));
assert_eq!(reference, Some((960, 540))); // Failed/disabled warp uses the sample.
}
extern "system" fn noop(_: u8, _: *mut c_void) {}
#[test]
@@ -552,6 +687,7 @@ mod tests {
let mut text = [0u16; 16];
// SAFETY: our window; the buffer holds 16 characters.
unsafe {
assert_eq!(wm::GetWindowLongW(hwnd, wm::GWL_STYLE) as u32 & wm::WS_POPUP != 0, enabled("VICTORY_FULLSCREEN"));
wm::SetWindowTextW(hwnd, w!("after"));
let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16);
assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after");