Merge pull request #274

This commit is contained in:
gamingwithhomie
2026-12-06 04:19:48 +05:30

View File

@ -9,7 +9,8 @@
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::sync::{Condvar, Mutex};
use std::thread::ThreadId;
use std::time::Duration;
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
@ -21,11 +22,95 @@ use crate::{HleModule, hle_export};
type Routine = extern "system" fn(quiesced: u8, context: *mut c_void);
/// Registration id, routine and context of each suspend routine.
static ROUTINES: Mutex<Vec<(usize, Routine, usize)>> = Mutex::new(Vec::new());
// Port of VIctory's constrained-before-quiesced delivery. A desktop host
// does not deliver the constrained notification on a title window close.
type Registration = (usize, Routine, usize);
struct Subscribers {
entries: Vec<Registration>,
running: Vec<(usize, ThreadId)>,
}
struct Notifications {
subscribers: Mutex<Subscribers>,
done: Condvar,
}
impl Notifications {
const fn new() -> Self {
Self { subscribers: Mutex::new(Subscribers { entries: Vec::new(), running: Vec::new() }), done: Condvar::new() }
}
fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> {
ROUTINES.lock().unwrap_or_else(|e| e.into_inner())
fn register(&self, routine: Option<Routine>, context: *mut c_void, out: *mut usize) -> u32 {
let Some(routine) = routine else { return ERROR_INVALID_PARAMETER };
if out.is_null() { return ERROR_INVALID_PARAMETER; }
static NEXT: AtomicUsize = AtomicUsize::new(1);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let mut state = self.subscribers.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: the title provides room for its token; publish it before the callback can run.
unsafe { out.write(id) };
state.entries.push((id, routine, context as usize));
0
}
fn unregister(&self, id: usize) {
let me = std::thread::current().id();
let mut state = self.subscribers.lock().unwrap_or_else(|e| e.into_inner());
state.entries.retain(|entry| entry.0 != id);
while state.running.iter().any(|t| t.0 == id && t.1 != me) {
state = self.done.wait(state).unwrap_or_else(|e| e.into_inner());
}
}
fn notify(&self) {
let ids: Vec<_> = self.subscribers.lock().unwrap_or_else(|e| e.into_inner()).entries.iter().map(|e| e.0).collect();
let me = std::thread::current().id();
for id in ids {
let mut state = self.subscribers.lock().unwrap_or_else(|e| e.into_inner());
let Some((_, routine, context)) = state.entries.iter().find(|e| e.0 == id).copied() else { continue };
state.running.push((id, me));
drop(state);
routine(1, context as *mut c_void);
let mut state = self.subscribers.lock().unwrap_or_else(|e| e.into_inner());
if let Some(i) = state.running.iter().rposition(|v| *v == (id, me)) { state.running.swap_remove(i); }
drop(state);
self.done.notify_all();
}
}
}
static CONSTRAINED: Notifications = Notifications::new();
static ROUTINES: Notifications = Notifications::new();
fn constrain_then_suspend(constrained: &Notifications, suspend: &Notifications) {
constrained.notify();
suspend.notify();
}
#[cfg(test)]
mod suspend_tests {
use super::*;
#[test]
fn constrain_precedes_quiesce_and_can_cancel_a_later_callback() {
struct State { suspend: Notifications, cancel: usize, calls: Mutex<Vec<u8>> }
extern "system" fn prepare(flag: u8, ctx: *mut c_void) {
// SAFETY: these callbacks run on this test's thread while the state lives.
let s = unsafe { &*ctx.cast::<State>() };
s.calls.lock().unwrap().push(flag);
s.suspend.unregister(s.cancel);
}
extern "system" fn save(flag: u8, ctx: *mut c_void) {
// SAFETY: same caller-owned test context as `prepare`.
unsafe { &*ctx.cast::<State>() }.calls.lock().unwrap().push(1 + flag);
}
let mut s = State { suspend: Notifications::new(), cancel: 0, calls: Default::default() };
let ctx = std::ptr::from_mut(&mut s).cast();
let constrained = Notifications::new();
let mut id = 0;
assert_eq!(constrained.register(Some(prepare), ctx, &mut id), 0);
assert_eq!(s.suspend.register(Some(save), ctx, &mut s.cancel), 0);
assert_eq!(s.suspend.register(Some(save), ctx, &mut id), 0);
constrain_then_suspend(&constrained, &s.suspend);
assert_eq!(*s.calls.lock().unwrap(), [1, 2]);
}
}
/// How long the console lets suspend routines run before it ends the title.
@ -38,22 +123,21 @@ pub extern "system" fn RegisterAppStateChangeNotification(
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);
routines().push((id, routine, context as usize));
// SAFETY: checked non-null; the title passes room for its registration.
unsafe { registration.write(id) };
0
ROUTINES.register(routine, context, registration)
}
pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) {
routines().retain(|&(id, ..)| id != registration);
ROUTINES.unregister(registration);
}
pub extern "system" fn RegisterAppConstrainedChangeNotification(
routine: Option<Routine>, context: *mut c_void, registration: *mut usize,
) -> u32 {
CONSTRAINED.register(routine, context, registration)
}
pub extern "system" fn UnregisterAppConstrainedChangeNotification(registration: usize) {
CONSTRAINED.unregister(registration);
}
/// The window procedure a title window had before ours.
@ -240,8 +324,7 @@ pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) {
if ENDING.swap(true, Ordering::SeqCst) {
return;
}
let suspend = routines().clone();
tracing::info!(routines = suspend.len(), "title: suspending ({why})");
tracing::info!("title: constraining then suspending ({why})");
// Whoever comes first (the routines or the deadline) runs `then`; the
// other waits for it, so the process never ends halfway through.
let then = std::sync::Arc::new(Mutex::new(Some(then)));
@ -259,9 +342,7 @@ pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) {
std::thread::spawn(move || {
larp_tracy::thread_name("larp: title suspend routines");
super::placement::title_thread();
for (_, routine, context) in suspend {
routine(1, context as *mut c_void);
}
constrain_then_suspend(&CONSTRAINED, &ROUTINES);
finish("suspended");
});
std::thread::spawn(move || {
@ -343,6 +424,8 @@ pub(crate) fn module() -> HleModule {
exports: vec![
hle_export!(RegisterAppStateChangeNotification),
hle_export!(UnregisterAppStateChangeNotification),
hle_export!(RegisterAppConstrainedChangeNotification),
hle_export!(UnregisterAppConstrainedChangeNotification),
hle_export!(CreateWindowExW),
hle_export!(CreateWindowExA),
],