diff --git a/README.md b/README.md index 593340af..75334a3a 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ What each part does today and what it still needs: | Subsystem | Today | Needs | |-----------|-------|-------| | Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | -| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog, text and SSML narration with installed Windows voices | Narration returns an empty WAVE for blank text or when Windows cannot produce audio. The dialog and relaunch are untested live | +| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry, message and error dialogs, text and SSML narration with installed Windows voices | Narration returns an empty WAVE for blank text or when Windows cannot produce audio. The dialogs and relaunch are untested live | | Network | Offline by design: the title cannot reach the network | – | | Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | | Input | XInput pads with trigger rumble, keyboard, keyboard and mouse as a pad (keys by place, mouse as the right stick) | Trigger rumble and the mouse are untested in play | @@ -186,6 +186,7 @@ cargo build --profile diag -p xtp --features diagnostics # target\diag\xtp.exe | `XTP_QUEUE_WAIT=0` | every build: a queue told to wait for a fence no signal has reached yet runs what it is given next at once, as before queues held it (to compare frame times); such waits are still counted on the `queue waits for fences so far` line | | `XTP_RT_STANDIN=1` | every build: the title's ray-tracing programs that do not translate yet (traced sun and local-light shadows, probe and irradiance-cache gathers, screen probes, reflections, particle collision) have their dropped dispatches' outputs cleared to "every ray missed" (shadow traces' textures lit; others as `XTP_RT_STANDIN_FILL=[.]=lit\|zero\|keep\|f:\|u:;…` says); `ab[:[:]]` alternates off and on within one run; every build logs what each dropped trace would have written (`rt:` lines; docs/analysis/rt-standin.md) | | `XTP_FRAMES_IN_FLIGHT=ab[:[:]]` | every build: one frame in flight off (phase A) and on (phase B) in turn within one run, phases of 20 s by default, the first 3 s of each not measured; each frame-rate line is tagged with its phase and `cargo xtask play` ends with the median per phase (docs/dev/START_HERE.md, "A/B a switch"); `1` on, `0` or unset off | +| `XTP_DIALOGS=auto` | every build: auto-dismisses `XGameUi` message and error dialogs without opening a window (message dialogs return `cancel_button`, error dialogs complete with `S_OK`; enabled automatically under `--autopilot`; does not affect text entry) | Every build appends crashes and host GPU failures to `crashes.log` in the title's data folder. The loader also prints the first 16 title C++ throws diff --git a/apps/xtp/src/run.rs b/apps/xtp/src/run.rs index 0401238d..c3a094ca 100644 --- a/apps/xtp/src/run.rs +++ b/apps/xtp/src/run.rs @@ -266,6 +266,7 @@ pub fn run( late.load(file, show).map_err(|e| format!("{e:#}")) })); if let Some(script) = autopilot { + xtp_hle::modules::xgameui::set_auto_dismiss(true); let size = image.info().size_of_image as usize; xtp_hle::modules::autopilot::start(&script, &hash, image.base(), size) .map_err(anyhow::Error::msg)?; diff --git a/crates/xtp-hle/src/modules/xgameui.rs b/crates/xtp-hle/src/modules/xgameui.rs index 90da66c9..137004c3 100644 --- a/crates/xtp-hle/src/modules/xgameui.rs +++ b/crates/xtp-hle/src/modules/xgameui.rs @@ -1,11 +1,17 @@ //! System dialogs a title opens (XGameUi). A profile card has nothing to -//! show and closes at once. Text entry opens a small host dialog (title, -//! description, default text, the length limit) on a thread of its own and -//! completes the call with what the user typed, or as cancelled (`E_ABORT`) -//! when the dialog is dismissed or cannot open. +//! show and closes at once. Text entry opens a small host dialog on a thread +//! of its own and completes with what the user typed, or `E_ABORT` on +//! Cancel/Esc or when it cannot open. Message and error dialogs likewise run +//! on a worker thread: Esc and the close box on a message dialog complete with +//! `S_OK` and `cancel_button`, while `E_ABORT` is returned when no window can +//! be opened. When `XTP_DIALOGS=auto` (or [`set_auto_dismiss`] in +//! unattended/autopilot runs) is enabled, message dialogs complete immediately +//! with `cancel_button` (`S_OK`) and error dialogs complete immediately with +//! `S_OK` without opening a window (text entry is unaffected). #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::{c_char, c_void}; +use std::sync::atomic::{AtomicBool, Ordering}; use super::xasync::{self, AsyncBlock, E_ABORT}; use super::xgameruntime::{ @@ -30,11 +36,189 @@ pub const IID_2026: Guid = Guid::new( pub static OBJECT: Object = Object::new("game ui", &VTABLE); pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; +/// Environment variable that auto-dismisses message and error dialogs when set +/// to `auto` (does not affect text entry). +pub const DIALOGS_ENV: &str = "XTP_DIALOGS"; + +/// `E_INVALIDARG` (`0x80070057`). +const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; + +/// `XGameUiMessageDialogButton` values in `XGameUI.h`. +pub const BUTTON_FIRST: u32 = 0; +pub const BUTTON_SECOND: u32 = 1; +pub const BUTTON_THIRD: u32 = 2; + +static AUTO_DISMISS: AtomicBool = AtomicBool::new(false); + +/// Enable or disable unattended auto-dismissal of message and error dialogs +/// (used by `--autopilot` runs so modal dialogs never stall the session). +pub fn set_auto_dismiss(enabled: bool) { + AUTO_DISMISS.store(enabled, Ordering::Relaxed); +} + +fn auto_dismiss_enabled() -> bool { + AUTO_DISMISS.load(Ordering::Relaxed) + || std::env::var(DIALOGS_ENV).is_ok_and(|v| v.trim().eq_ignore_ascii_case("auto")) +} + type This = *const Object; +static MESSAGE: u8 = 0; static PROFILE: u8 = 0; +static ERROR_DIALOG: u8 = 0; static TEXT: u8 = 0; +/// Request passed to the host message-dialog backend. +/// +/// Each entry in `buttons` carries its original `XGameUiMessageDialogButton` +/// enum value (`0`, `1`, or `2`) paired with its label so gaps (e.g. a null +/// second button) never shift the reported button index. +#[derive(Debug, Clone, PartialEq, Eq)] +struct MessageDialogRequest { + title: String, + content: String, + buttons: Vec<(u32, String)>, + default_button: u32, + cancel_button: u32, +} + +fn escape_mnemonic(label: &str) -> String { + label.replace('&', "&&") +} + +extern "system" fn message_dialog_async( + _: This, + block: *mut AsyncBlock, + title: *const c_char, + content: *const c_char, + first_button: *const c_char, + second_button: *const c_char, + third_button: *const c_char, + default_button: u32, + cancel_button: u32, +) -> HRESULT { + let title = text(title).unwrap_or_default(); + let content = text(content).unwrap_or_default(); + let mut buttons = Vec::new(); + for (idx, label) in [ + (BUTTON_FIRST, first_button), + (BUTTON_SECOND, second_button), + (BUTTON_THIRD, third_button), + ] { + if let Some(s) = text(label).filter(|s| !s.is_empty()) { + buttons.push((idx, s)); + } + } + if buttons.is_empty() { + buttons.push((BUTTON_FIRST, "OK".to_owned())); + } + if auto_dismiss_enabled() { + tracing::warn!( + title, + content, + cancel_button, + "message dialog: auto-dismissing with cancel_button" + ); + return xasync::pending_with(block, (&raw const MESSAGE).cast(), move || { + Ok(cancel_button.to_le_bytes().to_vec()) + }); + } + tracing::info!( + title, + content, + buttons = buttons.len(), + default_button, + cancel_button, + "message dialog" + ); + let req = MessageDialogRequest { + title, + content, + buttons, + default_button, + cancel_button, + }; + xasync::pending_with( + block, + (&raw const MESSAGE).cast(), + move || match show_message_dialog(&req) { + Some(button) => { + tracing::info!(button, "message dialog: button chosen"); + Ok(button.to_le_bytes().to_vec()) + } + None => { + tracing::info!("message dialog: could not open"); + Err(E_ABORT) + } + }, + ) +} + +extern "system" fn message_dialog_result( + _: This, + block: *mut AsyncBlock, + result_button: *mut u32, +) -> HRESULT { + if result_button.is_null() { + return E_INVALIDARG; + } + let mut raw = [0u8; 4]; + let mut written = 0usize; + let hr = xasync::XAsyncGetResult( + block, + (&raw const MESSAGE).cast(), + raw.len(), + raw.as_mut_ptr().cast(), + &mut written, + ); + if hr < 0 { + return hr; + } + put(result_button, u32::from_le_bytes(raw)) +} + +extern "system" fn error_dialog_async( + _: This, + block: *mut AsyncBlock, + error_code: HRESULT, + context: *const c_char, +) -> HRESULT { + let context = text(context).unwrap_or_default(); + if auto_dismiss_enabled() { + tracing::warn!( + error_code = format_args!("{error_code:#010x}"), + context, + "error dialog: auto-dismissing" + ); + return xasync::finished(block, (&raw const ERROR_DIALOG).cast(), S_OK); + } + tracing::warn!( + error_code = format_args!("{error_code:#010x}"), + context, + "error dialog" + ); + xasync::pending_with(block, (&raw const ERROR_DIALOG).cast(), move || { + if show_error_dialog(error_code, &context) { + tracing::info!("error dialog: dismissed"); + Ok(Vec::new()) + } else { + tracing::info!("error dialog: could not open"); + Err(E_ABORT) + } + }) +} + +extern "system" fn error_dialog_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult( + block, + (&raw const ERROR_DIALOG).cast(), + 0, + none, + none.cast(), + ) +} + extern "system" fn profile_card_async( _: This, block: *mut AsyncBlock, @@ -124,6 +308,44 @@ fn ask(title: &str, _: &str, default: &str, _: u32) -> Option { title.starts_with("Type").then(|| format!("{default}typed")) } +/// Shows a modal host message dialog; returns the chosen button enum value or +/// `None` if no window can be shown. +#[cfg(not(test))] +fn show_message_dialog(req: &MessageDialogRequest) -> Option { + dialog::message(req) +} + +/// Shows a modal host error dialog; returns `true` when dismissed by the user, +/// or `false` if no window could be shown. +#[cfg(not(test))] +fn show_error_dialog(error_code: HRESULT, context: &str) -> bool { + dialog::error(error_code, context) +} + +#[cfg(test)] +type MessageDialogHook = Box Option + Send + Sync>; + +#[cfg(test)] +type ErrorDialogHook = Box bool + Send + Sync>; + +#[cfg(test)] +static MESSAGE_HOOK: std::sync::Mutex> = std::sync::Mutex::new(None); + +#[cfg(test)] +static ERROR_HOOK: std::sync::Mutex> = std::sync::Mutex::new(None); + +#[cfg(test)] +fn show_message_dialog(req: &MessageDialogRequest) -> Option { + let guard = MESSAGE_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + guard.as_ref().and_then(|f| f(req)) +} + +#[cfg(test)] +fn show_error_dialog(error_code: HRESULT, context: &str) -> bool { + let guard = ERROR_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + guard.as_ref().is_some_and(|f| f(error_code, context)) +} + mod dialog { use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; @@ -131,10 +353,212 @@ mod dialog { use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE}; const EDIT: i32 = 100; + pub(super) const BTN_BASE: i32 = 200; + // Static control style: do not interpret '&' as a mnemonic prefix. + const SS_NOPREFIX: u32 = 0x0080; // Edit control messages (the controls headers). const EM_SETSEL: u32 = 0xb1; const EM_LIMITTEXT: u32 = 0xc5; + /// Pick the control ID that should receive initial focus: `default_button` + /// if present among `button_ids`, otherwise the first visible button. + pub(super) fn focus_button_id(button_ids: &[u32], default_button: u32) -> i32 { + let target = if button_ids.contains(&default_button) { + default_button + } else { + button_ids.first().copied().unwrap_or(0) + }; + BTN_BASE + target as i32 + } + + /// Map a `WM_COMMAND` control ID to the chosen `XGameUiMessageDialogButton` + /// enum value (`IDCANCEL` -> `cancel_button`, `BTN_BASE + v` -> `v` if visible). + pub(super) fn command_to_button( + id: i32, + button_ids: &[u32], + cancel_button: u32, + ) -> Option { + if id == wm::IDCANCEL { + return Some(cancel_button); + } + if id >= BTN_BASE { + let value = (id - BTN_BASE) as u32; + if button_ids.contains(&value) { + return Some(value); + } + } + None + } + + struct MessageState { + chosen: Option, + button_ids: Vec, + default_button: u32, + cancel_button: u32, + } + + /// Shows a modal message dialog with up to three buttons from an in-memory + /// template. Esc and the close box report `req.cancel_button`. Returns + /// `None` only if the host dialog could not be created. + #[allow(dead_code)] // unused in test builds + pub(super) fn message(req: &super::MessageDialogRequest) -> Option { + let mut t: Vec = Vec::new(); + fn dword(t: &mut Vec, v: u32) { + t.extend([v as u16, (v >> 16) as u16]); + } + fn text(t: &mut Vec, s: &str) { + t.extend(s.encode_utf16().filter(|&c| c != 0)); + t.push(0); + } + let btn_count = req.buttons.len().min(3) as u16; + let width: u16 = 280; + let height: u16 = 104; + let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU; + let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32; + dword(&mut t, style | flags); + dword(&mut t, wm::WS_EX_TOPMOST); + t.extend([1 + btn_count, 0, 0, width, height, 0, 0]); + text(&mut t, &req.title); + let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| { + if t.len() % 2 == 1 { + t.push(0); + } + dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style); + dword(&mut t, 0); + t.extend(rect); + t.extend([id, 0xffff, class]); + text(&mut t, caption); + t.push(0); + }; + let (button_cls, label_cls) = (0x80, 0x82); + item( + SS_NOPREFIX, + [8, 8, width - 16, 66], + 0xffff, + label_cls, + &req.content, + ); + let btn_w: u16 = 72; + let gap: u16 = 6; + let total_w = btn_count * btn_w + btn_count.saturating_sub(1) * gap; + let start_x = width.saturating_sub(8 + total_w); + for (pos, &(btn_value, ref label)) in req.buttons.iter().take(3).enumerate() { + let is_default = btn_value == req.default_button; + let btn_style = wm::WS_TABSTOP + | if is_default { + wm::BS_DEFPUSHBUTTON as u32 + } else { + wm::BS_PUSHBUTTON as u32 + }; + let x = start_x + (pos as u16) * (btn_w + gap); + let caption = super::escape_mnemonic(label); + item( + btn_style, + [x, height - 22, btn_w, 14], + (BTN_BASE + btn_value as i32) as u16, + button_cls, + &caption, + ); + } + let template: Vec = t + .chunks(2) + .map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16) + .collect(); + let mut state = MessageState { + chosen: None, + button_ids: req.buttons.iter().take(3).map(|&(id, _)| id).collect(), + default_button: req.default_button, + cancel_button: req.cancel_button, + }; + // SAFETY: `template` is a valid in-memory dialog template and `state` + // outlives the synchronous `DialogBoxIndirectParamW` call. + let rc = unsafe { + wm::DialogBoxIndirectParamW( + GetModuleHandleW(std::ptr::null()), + template.as_ptr().cast::(), + std::ptr::null_mut(), + Some(message_proc), + (&raw mut state) as LPARAM, + ) + }; + if rc <= 0 { + return None; + } + state.chosen + } + + extern "system" fn message_proc( + dialog: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> isize { + // SAFETY: `dialog` belongs to `message` above; `GWLP_USERDATA` holds + // the `&mut MessageState` stored during `WM_INITDIALOG`. + unsafe { + match message { + wm::WM_INITDIALOG => { + wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam); + let state = &*(lparam as *const MessageState); + let btn = wm::GetDlgItem( + dialog, + focus_button_id(&state.button_ids, state.default_button), + ); + if !btn.is_null() { + SetFocus(btn); + 0 // focus explicitly set on the default button + } else { + 1 + } + } + wm::WM_COMMAND => { + let state = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) + as *mut MessageState); + let id = (wparam & 0xffff) as i32; + if let Some(choice) = + command_to_button(id, &state.button_ids, state.cancel_button) + { + state.chosen = Some(choice); + wm::EndDialog(dialog, 1); + return 1; + } + 0 + } + wm::WM_CLOSE => { + let state = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) + as *mut MessageState); + state.chosen = Some(state.cancel_button); + wm::EndDialog(dialog, 1); + 1 + } + _ => 0, + } + } + } + + /// Shows a modal host error dialog with `MessageBoxW`. Returns `false` if + /// no window could be shown (`MessageBoxW` returns 0). + #[allow(dead_code)] // unused in test builds + pub(super) fn error(error_code: super::HRESULT, context: &str) -> bool { + let title: Vec = "Error\0".encode_utf16().collect(); + let body = if context.is_empty() { + format!("Error {error_code:#010x}") + } else { + format!("{context}\n\nError {error_code:#010x}") + }; + let wide_body: Vec = body.encode_utf16().chain(Some(0)).collect(); + // SAFETY: both strings are NUL-terminated UTF-16 slices. + let rc = unsafe { + wm::MessageBoxW( + std::ptr::null_mut(), + wide_body.as_ptr(), + title.as_ptr(), + wm::MB_OK | wm::MB_ICONERROR | wm::MB_TOPMOST, + ) + }; + rc != 0 + } + /// The dialog's state, behind its user data while it runs. struct Entry { max: u32, @@ -255,30 +679,35 @@ static VTABLE: Methods<20> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), - missing::<3> as *const (), // 0x18 message dialog - missing::<4> as *const (), // 0x20 - missing::<5> as *const (), // 0x28 send invite - missing::<6> as *const (), // 0x30 - profile_card_async as *const (), // 0x38 - profile_card_result as *const (), // 0x40 - missing::<9> as *const (), // 0x48 achievements - missing::<10> as *const (), // 0x50 - missing::<11> as *const (), // 0x58 player picker - missing::<12> as *const (), // 0x60 - missing::<13> as *const (), // 0x68 - missing::<14> as *const (), // 0x70 error dialog - missing::<15> as *const (), // 0x78 - missing::<16> as *const (), // 0x80 notification position - text_entry_async as *const (), // 0x88 - text_entry_size as *const (), // 0x90 - text_entry_result as *const (), // 0x98 + message_dialog_async as *const (), // 0x18 message dialog + message_dialog_result as *const (), // 0x20 + missing::<5> as *const (), // 0x28 send invite + missing::<6> as *const (), // 0x30 + profile_card_async as *const (), // 0x38 + profile_card_result as *const (), // 0x40 + missing::<9> as *const (), // 0x48 achievements + missing::<10> as *const (), // 0x50 + missing::<11> as *const (), // 0x58 player picker + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 + error_dialog_async as *const (), // 0x70 error dialog + error_dialog_result as *const (), // 0x78 + missing::<16> as *const (), // 0x80 notification position + text_entry_async as *const (), // 0x88 + text_entry_size as *const (), // 0x90 + text_entry_result as *const (), // 0x98 ]); #[cfg(test)] mod tests { + use std::sync::{Arc, Mutex}; + use super::*; use crate::modules::xgameruntime::method; + /// Serialize tests that mutate process-wide dialog hooks / auto-dismiss. + static TEST_LOCK: Mutex<()> = Mutex::new(()); + fn block() -> AsyncBlock { AsyncBlock { queue: std::ptr::null(), @@ -344,4 +773,247 @@ mod tests { assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7)); assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}"); } + + #[test] + fn message_dialog_buttons_gaps_default_cancel_and_auto_dismiss() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + set_auto_dismiss(false); + + let this: This = &OBJECT; + type ShowMsg = extern "system" fn( + This, + *mut AsyncBlock, + *const c_char, + *const c_char, + *const c_char, + *const c_char, + *const c_char, + u32, + u32, + ) -> HRESULT; + type MsgResult = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + let show = method::(&OBJECT, 0x18); + let result = method::(&OBJECT, 0x20); + + // 1. Fake dialog answers button 2 (BUTTON_SECOND) and records the request + // without asserting on the worker thread. + let recorded = Arc::new(Mutex::new(None::)); + let rec = recorded.clone(); + *MESSAGE_HOOK.lock().unwrap() = Some(Box::new(move |req| { + *rec.lock().unwrap() = Some(req.clone()); + Some(BUTTON_SECOND) + })); + let mut b = block(); + assert_eq!( + show( + this, + &mut b, + c"Confirm".as_ptr(), + c"Proceed?".as_ptr(), + c"Yes".as_ptr(), + c"No".as_ptr(), + std::ptr::null(), + BUTTON_SECOND, + BUTTON_SECOND, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(result(this, &mut b, std::ptr::null_mut()), E_INVALIDARG); + let mut chosen = u32::MAX; + assert_eq!(result(this, &mut b, &mut chosen), S_OK); + assert_eq!(chosen, BUTTON_SECOND); + let req = recorded.lock().unwrap().take().expect("hook ran"); + assert_eq!(req.title, "Confirm"); + assert_eq!(req.default_button, BUTTON_SECOND); + assert_eq!(req.cancel_button, BUTTON_SECOND); + assert_eq!( + req.buttons, + vec![ + (BUTTON_FIRST, "Yes".to_owned()), + (BUTTON_SECOND, "No".to_owned()), + ] + ); + + // 2. Labels with a gap (null second button): third button keeps BUTTON_THIRD. + let rec = recorded.clone(); + *MESSAGE_HOOK.lock().unwrap() = Some(Box::new(move |req| { + *rec.lock().unwrap() = Some(req.clone()); + Some(BUTTON_THIRD) + })); + let mut b = block(); + assert_eq!( + show( + this, + &mut b, + c"Gap".as_ptr(), + c"Save & Quit".as_ptr(), + c"Save".as_ptr(), + std::ptr::null(), + c"Quit".as_ptr(), + BUTTON_THIRD, + BUTTON_FIRST, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(result(this, &mut b, &mut chosen), S_OK); + assert_eq!(chosen, BUTTON_THIRD); + let req = recorded.lock().unwrap().take().expect("hook ran"); + assert_eq!( + req.buttons, + vec![ + (BUTTON_FIRST, "Save".to_owned()), + (BUTTON_THIRD, "Quit".to_owned()), + ] + ); + assert_eq!(req.default_button, BUTTON_THIRD); + assert_eq!(req.cancel_button, BUTTON_FIRST); + + // 3. Esc / cancel returns req.cancel_button with S_OK. + *MESSAGE_HOOK.lock().unwrap() = Some(Box::new(|req| Some(req.cancel_button))); + let mut b = block(); + assert_eq!( + show( + this, + &mut b, + c"Esc".as_ptr(), + c"Close?".as_ptr(), + c"Stay".as_ptr(), + c"Leave".as_ptr(), + c"Cancel".as_ptr(), + BUTTON_FIRST, + BUTTON_THIRD, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(result(this, &mut b, &mut chosen), S_OK); + assert_eq!(chosen, BUTTON_THIRD); + + // 4. Unattended auto-dismiss answers with cancel_button without calling the hook. + *MESSAGE_HOOK.lock().unwrap() = None; + set_auto_dismiss(true); + let mut b = block(); + assert_eq!( + show( + this, + &mut b, + c"Auto".as_ptr(), + c"Unattended".as_ptr(), + c"OK".as_ptr(), + c"Cancel".as_ptr(), + std::ptr::null(), + BUTTON_FIRST, + BUTTON_SECOND, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(result(this, &mut b, &mut chosen), S_OK); + assert_eq!(chosen, BUTTON_SECOND); + set_auto_dismiss(false); + + // 5. No window / cannot open: completes with E_ABORT. + let mut b = block(); + assert_eq!( + show( + this, + &mut b, + c"Headless".as_ptr(), + c"No window".as_ptr(), + c"OK".as_ptr(), + std::ptr::null(), + std::ptr::null(), + BUTTON_FIRST, + BUTTON_FIRST, + ), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); + assert_eq!(result(this, &mut b, &mut chosen), E_ABORT); + assert_eq!(escape_mnemonic("Save & Exit"), "Save && Exit"); + } + + #[test] + fn error_dialog_completes_auto_dismisses_or_cancels_without_window() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + set_auto_dismiss(false); + + let this: This = &OBJECT; + type ShowErr = extern "system" fn(This, *mut AsyncBlock, HRESULT, *const c_char) -> HRESULT; + type ErrResult = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + let show = method::(&OBJECT, 0x70); + let result = method::(&OBJECT, 0x78); + + let recorded = Arc::new(Mutex::new(None::<(HRESULT, String)>)); + let rec = recorded.clone(); + *ERROR_HOOK.lock().unwrap() = Some(Box::new(move |code, ctx| { + *rec.lock().unwrap() = Some((code, ctx.to_owned())); + true + })); + let mut b = block(); + assert_eq!( + show(this, &mut b, E_ABORT, c"network offline".as_ptr()), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(result(this, &mut b), S_OK); + assert_eq!( + recorded.lock().unwrap().take(), + Some((E_ABORT, "network offline".to_owned())) + ); + + // Unattended auto-dismiss completes immediately with S_OK. + *ERROR_HOOK.lock().unwrap() = None; + set_auto_dismiss(true); + let mut b = block(); + assert_eq!(show(this, &mut b, E_ABORT, std::ptr::null()), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(result(this, &mut b), S_OK); + set_auto_dismiss(false); + + // No window / cannot open: completes as cancelled (E_ABORT). + let mut b = block(); + assert_eq!(show(this, &mut b, E_ABORT, std::ptr::null()), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); + assert_eq!(result(this, &mut b), E_ABORT); + } + + #[test] + fn message_proc_helpers_map_focus_esc_and_gapped_buttons() { + let gapped = [BUTTON_FIRST, BUTTON_THIRD]; + // Default button present -> focused directly. + assert_eq!( + dialog::focus_button_id(&gapped, BUTTON_THIRD), + dialog::BTN_BASE + BUTTON_THIRD as i32 + ); + // Missing default button -> falls back to first visible button. + assert_eq!( + dialog::focus_button_id(&gapped, BUTTON_SECOND), + dialog::BTN_BASE + BUTTON_FIRST as i32 + ); + // Esc (IDCANCEL = 2) -> cancel_button. + assert_eq!( + dialog::command_to_button(2, &gapped, BUTTON_THIRD), + Some(BUTTON_THIRD) + ); + // Visible gapped button keeps its enum value; absent button ignored. + assert_eq!( + dialog::command_to_button( + dialog::BTN_BASE + BUTTON_THIRD as i32, + &gapped, + BUTTON_FIRST + ), + Some(BUTTON_THIRD) + ); + assert_eq!( + dialog::command_to_button( + dialog::BTN_BASE + BUTTON_SECOND as i32, + &gapped, + BUTTON_FIRST + ), + None + ); + } } diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index 5c0dba53..fb983d42 100644 --- a/docs/analysis/hle.md +++ b/docs/analysis/hle.md @@ -173,7 +173,7 @@ Legend: ✔ implemented and tested, ◐ partial, ✘ missing, — not needed. | XStore: own licence active, add-ons none, store calls fail as offline | ✔ | ✘ refused class | 1 / — | **Keep XTP** (better) | | XNetworking: stack up, reaches nothing | ✔ | ✔ real hints, CryptoAPI certificate checks | 1 / 7 | Keep XTP (offline by design) | | XGameUi: profile card, text entry (host dialog) | ✔ | → PC runtime | 1 / — | Keep XTP | -| XGameUi message and error dialogs | ✘ | → PC runtime | — / — | **New work** (R5) | +| XGameUi message and error dialogs | ✔ host dialogs (`XTP_DIALOGS=auto`) | → PC runtime | 3 / — | Done (R5) | | Speech synthesis | ✔ Windows voices, text and SSML to 48 kHz PCM | → PC runtime | 4 / — | Done (R6) | | Closed captions, high contrast | ✔ Windows settings and title override | ✔ `accessibility.rs` | 5 / 3 | Done (R7) | | XError callback and options | ✘ class absent | ✔ | — / — | After xcl, if the title asks (R9) | @@ -358,7 +358,7 @@ shows the title calls them. presses, focus loss resets everything. - **Depends on:** I1. -### R5. Message and error dialogs — M +### R5. Message and error dialogs — M (done) - **Goal:** `XGameUiShowMessageDialogAsync`/`Result` and `XGameUiShowErrorDialogAsync`/`Result` as host task dialogs on a thread of their own (like text entry), returning the chosen button; cancel → the @@ -509,7 +509,7 @@ shows the title calls them. | 7 | R3 waiters, XThread | S | (R1) | | 8 | A1 Opus check | S | — | | 9 | I2 mouse as right stick | M | I1 | -| 10 | R5 message/error dialogs | M | (R1) | +| 10 | R5 message/error dialogs (done) | M | (R1) | | 11 | R10 relaunch, restart on crash | S | — | | 12 | R7 closed captions, high contrast (done) | S | — | | 13 | R6 speech synthesis (done) | M | — |