From 985bca766f4ebbc3a4b9fde15386199001f9bf9f Mon Sep 17 00:00:00 2001 From: AliceWood <36452359+AliceWood@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:46:45 +0300 Subject: [PATCH 1/2] hle: read Windows caption and high contrast settings --- README.md | 6 + crates/xtp-hle/Cargo.toml | 5 +- crates/xtp-hle/src/modules/speech.rs | 42 +-- crates/xtp-hle/src/modules/speech/captions.rs | 257 ++++++++++++++++++ 4 files changed, 287 insertions(+), 23 deletions(-) create mode 100644 crates/xtp-hle/src/modules/speech/captions.rs diff --git a/README.md b/README.md index ecf32d8d..a966550f 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,12 @@ The window caption shows the framerate. Saves, settings and `crashes.log` are kept under the data folder (default `%LOCALAPPDATA%\xtp\data`), derived data under the cache folder. +Titles can read Windows caption colors, opacity, font, text size and high +contrast mode. Captions initially follow Windows ShowSounds. A title can +turn them on or off for its own session. Without preferences, captions are +off, with white text on black, a transparent window, default font and edge, +and 100% text size. High contrast defaults to off. + Input: XInput pads; Xbox One and Series pads get their trigger motors too (through Windows.Gaming.Input). The keyboard and mouse play as a pad while the title's window has focus: a pad of their own while no pad is connected, diff --git a/crates/xtp-hle/Cargo.toml b/crates/xtp-hle/Cargo.toml index d8bd2275..2aa777f1 100644 --- a/crates/xtp-hle/Cargo.toml +++ b/crates/xtp-hle/Cargo.toml @@ -34,9 +34,8 @@ windows-sys = { workspace = true, features = [ "Win32_UI_Input_XboxController", "Win32_UI_WindowsAndMessaging", ] } -# Pads' trigger motors (`modules::gameinput::triggers`); diagnostics builds -# add what recording our own audio needs (`modules::audio::capture`). -windows = { workspace = true, features = ["Gaming_Input"] } +# Host gamepads and accessibility settings. Diagnostics adds audio capture. +windows = { workspace = true, features = ["Gaming_Input", "Media_ClosedCaptioning", "UI_ViewManagement"] } # `#[implement]` names it. windows-core = { workspace = true, optional = true } diff --git a/crates/xtp-hle/src/modules/speech.rs b/crates/xtp-hle/src/modules/speech.rs index 15e8eca8..4f2a117b 100644 --- a/crates/xtp-hle/src/modules/speech.rs +++ b/crates/xtp-hle/src/modules/speech.rs @@ -1,4 +1,4 @@ -//! Accessibility: speech synthesis for the title's narration. No voice is +//! Accessibility: caption preferences, high contrast and speech synthesis. No voice is //! installed here, and every stream is valid WAVE audio of no length, so //! narration is silent. // shortcut: silent speech. The host's engine (SAPI through COM, or WinRT @@ -7,6 +7,8 @@ // title then plays the empty stream and goes on. #![allow(clippy::not_unsafe_ptr_arg_deref)] +mod captions; + use std::ffi::{c_char, c_void}; use super::xgameruntime::{ @@ -99,25 +101,25 @@ static VTABLE: Methods<22> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), - missing::<3> as *const (), // 0x18 closed captions - missing::<4> as *const (), // 0x20 - missing::<5> as *const (), // 0x28 high contrast - missing::<6> as *const (), // 0x30 speech to text - missing::<7> as *const (), // 0x38 - enumerate_voices as *const (), // 0x40 - create as *const (), // 0x48 - close as *const (), // 0x50 - set_default_voice as *const (), // 0x58 - set_custom_voice as *const (), // 0x60 - create_stream as *const (), // 0x68 from text - close as *const (), // 0x70 a stream - stream_size as *const (), // 0x78 - stream_data as *const (), // 0x80 - missing::<17> as *const (), // 0x88 speech to text - missing::<18> as *const (), // 0x90 - missing::<19> as *const (), // 0x98 - missing::<20> as *const (), // 0xa0 - create_stream as *const (), // 0xa8 from SSML + captions::properties as *const (), // 0x18 + captions::set_enabled as *const (), // 0x20 + captions::high_contrast as *const (), // 0x28 + missing::<6> as *const (), // 0x30 speech to text + missing::<7> as *const (), // 0x38 + enumerate_voices as *const (), // 0x40 + create as *const (), // 0x48 + close as *const (), // 0x50 + set_default_voice as *const (), // 0x58 + set_custom_voice as *const (), // 0x60 + create_stream as *const (), // 0x68 from text + close as *const (), // 0x70 a stream + stream_size as *const (), // 0x78 + stream_data as *const (), // 0x80 + missing::<17> as *const (), // 0x88 speech to text + missing::<18> as *const (), // 0x90 + missing::<19> as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + create_stream as *const (), // 0xa8 from SSML ]); #[cfg(test)] diff --git a/crates/xtp-hle/src/modules/speech/captions.rs b/crates/xtp-hle/src/modules/speech/captions.rs new file mode 100644 index 00000000..4c7e888a --- /dev/null +++ b/crates/xtp-hle/src/modules/speech/captions.rs @@ -0,0 +1,257 @@ +use std::sync::atomic::{AtomicU8, Ordering}; + +use super::{HRESULT, S_OK, This, put}; + +// Read ShowSounds until the title makes a choice of its own. +const FOLLOW_WINDOWS: u8 = 2; +static ENABLED: AtomicU8 = AtomicU8::new(FOLLOW_WINDOWS); + +#[repr(C)] +pub(super) struct Properties { + background: [u8; 4], + text: [u8; 4], + window: [u8; 4], + edge: u32, + style: u32, + scale: f32, + enabled: u8, + reserved: [u8; 3], +} + +impl Default for Properties { + fn default() -> Self { + Self { + background: [255, 0, 0, 0], + text: [255; 4], + window: [0; 4], + edge: 0, + style: 0, + scale: 1.0, + enabled: 0, + reserved: [0; 3], + } + } +} + +impl Properties { + fn write(mut self, out: *mut Self, enabled: u8) -> HRESULT { + if enabled != FOLLOW_WINDOWS { + self.enabled = enabled; + } + put(out, self) + } +} + +pub(super) extern "system" fn properties(_: This, out: *mut Properties) -> HRESULT { + let settings = Properties::default(); + #[cfg(windows)] + let settings = host::captions(settings); + settings.write(out, ENABLED.load(Ordering::Relaxed)) +} + +pub(super) extern "system" fn set_enabled(_: This, enabled: u8) -> HRESULT { + ENABLED.store(u8::from(enabled != 0), Ordering::Relaxed); + S_OK +} + +pub(super) extern "system" fn high_contrast(_: This, out: *mut u32) -> HRESULT { + #[cfg(windows)] + let mode = host::contrast(); + #[cfg(not(windows))] + let mode = 0; + put(out, mode) +} + +#[cfg(windows)] +mod host { + use super::Properties; + use windows::Media::ClosedCaptioning::{ + ClosedCaptionColor as Color, ClosedCaptionOpacity as Opacity, + ClosedCaptionProperties as Captions, ClosedCaptionSize as Size, + }; + use windows::UI::ViewManagement::{AccessibilitySettings, UIElementType, UISettings}; + use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_SHOWSOUNDS}; + + // The caption ABI stores alpha first. Windows lets the user override the + // color and opacity independently, including setting just one of them. + fn argb( + color: Color, + computed: impl FnOnce() -> windows::core::Result, + opacity: Opacity, + fallback: [u8; 4], + ) -> [u8; 4] { + let [alpha, r, g, b] = fallback; + let [r, g, b] = if color != Color::Default + && let Ok(c) = computed() + { + [c.R, c.G, c.B] + } else { + [r, g, b] + }; + let alpha = match opacity { + Opacity::OneHundredPercent => 255, + Opacity::SeventyFivePercent => 191, + Opacity::TwentyFivePercent => 64, + Opacity::ZeroPercent => 0, + _ => alpha, + }; + [alpha, r, g, b] + } + + fn font_scale(size: Size) -> f32 { + match size { + Size::FiftyPercent => 0.5, + Size::OneHundredFiftyPercent => 1.5, + Size::TwoHundredPercent => 2.0, + _ => 1.0, + } + } + + pub(super) fn captions(defaults: Properties) -> Properties { + // The Windows and title enums use the same values for font styles and edges. + let style = Captions::FontStyle().unwrap_or_default().0; + let edge = Captions::FontEffect().unwrap_or_default().0; + Properties { + background: argb( + Captions::BackgroundColor().unwrap_or_default(), + Captions::ComputedBackgroundColor, + Captions::BackgroundOpacity().unwrap_or_default(), + defaults.background, + ), + text: argb( + Captions::FontColor().unwrap_or_default(), + Captions::ComputedFontColor, + Captions::FontOpacity().unwrap_or_default(), + defaults.text, + ), + window: argb( + Captions::RegionColor().unwrap_or_default(), + Captions::ComputedRegionColor, + Captions::RegionOpacity().unwrap_or_default(), + defaults.window, + ), + style: if (0..=7).contains(&style) { + style as u32 + } else { + defaults.style + }, + edge: if (0..=5).contains(&edge) { + edge as u32 + } else { + defaults.edge + }, + scale: font_scale(Captions::FontSize().unwrap_or_default()), + // SAFETY: GetSystemMetrics takes only the identifier of the requested metric. + enabled: u8::from(unsafe { GetSystemMetrics(SM_SHOWSOUNDS) } != 0), + ..defaults + } + } + + pub(super) fn contrast() -> u32 { + if !AccessibilitySettings::new() + .and_then(|s| s.HighContrast()) + .unwrap_or(false) + { + return 0; + } + let background = UISettings::new().and_then(|s| s.UIElementColor(UIElementType::Window)); + match background { + Ok(c) => contrast_for_background(c.R, c.G, c.B), + Err(_) => 3, // Active, but the palette is unknown. + } + } + + fn contrast_for_background(r: u8, g: u8, b: u8) -> u32 { + // Windows UI's perceived brightness weights green most heavily. + let brightness = 5 * u32::from(g) + 2 * u32::from(r) + u32::from(b); + if brightness >= 8 * 128 { 2 } else { 1 } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn independent_color_opacity_and_size_preferences() { + let defaults = Properties::default(); + let computed = || { + Ok(windows::UI::Color { + A: 255, + R: 23, + G: 45, + B: 67, + }) + }; + assert_eq!( + argb(Color::Cyan, computed, Opacity::Default, defaults.background), + [255, 23, 45, 67] + ); + assert_eq!( + argb( + Color::Default, + computed, + Opacity::TwentyFivePercent, + defaults.text + ), + [64, 255, 255, 255] + ); + assert_eq!( + argb(Color::Red, computed, Opacity::ZeroPercent, defaults.window), + [0, 23, 45, 67] + ); + assert_eq!( + [ + Size::FiftyPercent, + Size::Default, + Size::OneHundredFiftyPercent, + Size::TwoHundredPercent + ] + .map(font_scale), + [0.5, 1.0, 1.5, 2.0] + ); + } + + #[test] + fn distinguishes_dark_and_light_contrast_palettes() { + assert_eq!(contrast_for_background(15, 20, 60), 1); + assert_eq!(contrast_for_background(255, 241, 211), 2); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::{speech::OBJECT, xasync::E_INVALIDARG, xgameruntime::method}; + + #[test] + fn missing_preferences_initialize_the_entire_output() { + assert_eq!(size_of::(), 28); + let mut words = [0xa5a5_a5a5_u32; 7]; + assert_eq!( + Properties::default().write(words.as_mut_ptr().cast(), FOLLOW_WINDOWS), + S_OK + ); + assert_eq!(words, [255, u32::MAX, 0, 0, 0, 1.0_f32.to_bits(), 0]); + } + + #[test] + fn title_can_enable_and_disable_captions_through_the_provider() { + let get = method:: HRESULT>(&OBJECT, 0x18); + let set = method:: HRESULT>(&OBJECT, 0x20); + let contrast = method:: HRESULT>(&OBJECT, 0x28); + assert_eq!(get(&OBJECT, std::ptr::null_mut()), E_INVALIDARG); + assert_eq!(contrast(&OBJECT, std::ptr::null_mut()), E_INVALIDARG); + let previous = ENABLED.load(Ordering::Relaxed); + for choice in [1, 0] { + let mut result = Properties::default(); + assert_eq!(set(&OBJECT, choice), S_OK); + assert_eq!(get(&OBJECT, &mut result), S_OK); + assert_eq!(result.enabled, choice); + } + ENABLED.store(previous, Ordering::Relaxed); + let mut mode = u32::MAX; + assert_eq!(contrast(&OBJECT, &mut mode), S_OK); + assert!(mode <= 3); + } +} From bd8e20aa577895c89c111a625c9e9e8a01854f45 Mon Sep 17 00:00:00 2001 From: AliceWood <36452359+AliceWood@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:20:25 +0300 Subject: [PATCH 2/2] hle: cache Windows accessibility settings between polls --- README.md | 12 +++-- crates/xtp-hle/Cargo.toml | 3 +- crates/xtp-hle/src/modules/speech.rs | 8 +-- crates/xtp-hle/src/modules/speech/captions.rs | 50 +++++++++++++++++-- docs/analysis/hle.md | 8 +-- 5 files changed, 63 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index a966550f..bac071b6 100644 --- a/README.md +++ b/README.md @@ -74,10 +74,14 @@ are kept under the data folder (default `%LOCALAPPDATA%\xtp\data`), derived data under the cache folder. Titles can read Windows caption colors, opacity, font, text size and high -contrast mode. Captions initially follow Windows ShowSounds. A title can -turn them on or off for its own session. Without preferences, captions are -off, with white text on black, a transparent window, default font and edge, -and 100% text size. High contrast defaults to off. +contrast mode. Captions initially follow Windows ShowSounds, under Control +Panel > Ease of Access > Ease of Access Center > Use text or visual +alternatives for sounds. A title can turn captions on or off immediately +for its own session. XTP refreshes each host setting on demand at most +once per second. Without preferences, captions are off, with white text on +black, a transparent window, default font and edge, and 100% text size. +High contrast defaults to off. An active theme reports light or dark based +on its window background, or `Other` if Windows cannot supply that color. Input: XInput pads; Xbox One and Series pads get their trigger motors too (through Windows.Gaming.Input). The keyboard and mouse play as a pad while diff --git a/crates/xtp-hle/Cargo.toml b/crates/xtp-hle/Cargo.toml index 2aa777f1..328758dd 100644 --- a/crates/xtp-hle/Cargo.toml +++ b/crates/xtp-hle/Cargo.toml @@ -34,7 +34,8 @@ windows-sys = { workspace = true, features = [ "Win32_UI_Input_XboxController", "Win32_UI_WindowsAndMessaging", ] } -# Host gamepads and accessibility settings. Diagnostics adds audio capture. +# Trigger motors (`modules::gameinput::triggers`) and Windows accessibility +# settings (`modules::speech::captions`). Diagnostics adds `modules::audio::capture`. windows = { workspace = true, features = ["Gaming_Input", "Media_ClosedCaptioning", "UI_ViewManagement"] } # `#[implement]` names it. windows-core = { workspace = true, optional = true } diff --git a/crates/xtp-hle/src/modules/speech.rs b/crates/xtp-hle/src/modules/speech.rs index 4f2a117b..89b8a63c 100644 --- a/crates/xtp-hle/src/modules/speech.rs +++ b/crates/xtp-hle/src/modules/speech.rs @@ -1,5 +1,5 @@ -//! Accessibility: caption preferences, high contrast and speech synthesis. No voice is -//! installed here, and every stream is valid WAVE audio of no length, so +//! Accessibility covers caption preferences, high contrast and speech synthesis. +//! No voice is installed here. Each stream is a valid, empty WAVE file, so //! narration is silent. // shortcut: silent speech. The host's engine (SAPI through COM, or WinRT // speech synthesis) needs COM bindings this crate has only in diagnostics @@ -101,9 +101,9 @@ static VTABLE: Methods<22> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), - captions::properties as *const (), // 0x18 + captions::properties as *const (), // 0x18 closed captions captions::set_enabled as *const (), // 0x20 - captions::high_contrast as *const (), // 0x28 + captions::high_contrast as *const (), // 0x28 high contrast missing::<6> as *const (), // 0x30 speech to text missing::<7> as *const (), // 0x38 enumerate_voices as *const (), // 0x40 diff --git a/crates/xtp-hle/src/modules/speech/captions.rs b/crates/xtp-hle/src/modules/speech/captions.rs index 4c7e888a..343f716e 100644 --- a/crates/xtp-hle/src/modules/speech/captions.rs +++ b/crates/xtp-hle/src/modules/speech/captions.rs @@ -1,3 +1,5 @@ +//! Windows caption preferences, the title's enabled override, and high-contrast mode. + use std::sync::atomic::{AtomicU8, Ordering}; use super::{HRESULT, S_OK, This, put}; @@ -7,6 +9,7 @@ const FOLLOW_WINDOWS: u8 = 2; static ENABLED: AtomicU8 = AtomicU8::new(FOLLOW_WINDOWS); #[repr(C)] +#[derive(Clone, Copy)] pub(super) struct Properties { background: [u8; 4], text: [u8; 4], @@ -43,9 +46,10 @@ impl Properties { } pub(super) extern "system" fn properties(_: This, out: *mut Properties) -> HRESULT { - let settings = Properties::default(); #[cfg(windows)] - let settings = host::captions(settings); + let settings = host::captions(); + #[cfg(not(windows))] + let settings = Properties::default(); settings.write(out, ENABLED.load(Ordering::Relaxed)) } @@ -65,6 +69,8 @@ pub(super) extern "system" fn high_contrast(_: This, out: *mut u32) -> HRESULT { #[cfg(windows)] mod host { use super::Properties; + use std::sync::{Mutex, PoisonError}; + use std::time::{Duration, Instant}; use windows::Media::ClosedCaptioning::{ ClosedCaptionColor as Color, ClosedCaptionOpacity as Opacity, ClosedCaptionProperties as Captions, ClosedCaptionSize as Size, @@ -72,6 +78,20 @@ mod host { use windows::UI::ViewManagement::{AccessibilitySettings, UIElementType, UISettings}; use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_SHOWSOUNDS}; + const REFRESH: Duration = Duration::from_secs(1); + + fn cached(cache: &Mutex>, read: impl FnOnce() -> T) -> T { + let mut entry = cache.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((at, value)) = *entry + && at.elapsed() < REFRESH + { + return value; + } + let value = read(); + *entry = Some((Instant::now(), value)); + value + } + // The caption ABI stores alpha first. Windows lets the user override the // color and opacity independently, including setting just one of them. fn argb( @@ -107,7 +127,13 @@ mod host { } } - pub(super) fn captions(defaults: Properties) -> Properties { + pub(super) fn captions() -> Properties { + static CAPTIONS: Mutex> = Mutex::new(None); + cached(&CAPTIONS, read_captions) + } + + fn read_captions() -> Properties { + let defaults = Properties::default(); // The Windows and title enums use the same values for font styles and edges. let style = Captions::FontStyle().unwrap_or_default().0; let edge = Captions::FontEffect().unwrap_or_default().0; @@ -148,6 +174,11 @@ mod host { } pub(super) fn contrast() -> u32 { + static CONTRAST: Mutex> = Mutex::new(None); + cached(&CONTRAST, read_contrast) + } + + fn read_contrast() -> u32 { if !AccessibilitySettings::new() .and_then(|s| s.HighContrast()) .unwrap_or(false) @@ -171,6 +202,15 @@ mod host { mod tests { use super::*; + #[test] + fn repeated_polls_reuse_the_value_until_refresh() { + let mut cache = Mutex::new(None); + assert_eq!(cached(&cache, || 1), 1); + assert_eq!(cached(&cache, || panic!("unexpected refresh")), 1); + *cache.get_mut().unwrap() = Some((Instant::now() - REFRESH, 1)); + assert_eq!(cached(&cache, || 2), 2); + } + #[test] fn independent_color_opacity_and_size_preferences() { let defaults = Properties::default(); @@ -243,11 +283,11 @@ mod tests { assert_eq!(get(&OBJECT, std::ptr::null_mut()), E_INVALIDARG); assert_eq!(contrast(&OBJECT, std::ptr::null_mut()), E_INVALIDARG); let previous = ENABLED.load(Ordering::Relaxed); - for choice in [1, 0] { + for (choice, expected) in [(0, 0), (2, 1), (0, 0), (0xff, 1), (1, 1), (0, 0)] { let mut result = Properties::default(); assert_eq!(set(&OBJECT, choice), S_OK); assert_eq!(get(&OBJECT, &mut result), S_OK); - assert_eq!(result.enabled, choice); + assert_eq!(result.enabled, expected); } ENABLED.store(previous, Ordering::Relaxed); let mut mode = u32::MAX; diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index e4117790..791bfb8c 100644 --- a/docs/analysis/hle.md +++ b/docs/analysis/hle.md @@ -175,7 +175,7 @@ Legend: ✔ implemented and tested, ◐ partial, ✘ missing, — not needed. | XGameUi: profile card, text entry (host dialog) | ✔ | → PC runtime | 1 / — | Keep XTP | | XGameUi message and error dialogs | ✘ | → PC runtime | — / — | **New work** (R5) | | Speech synthesis | ◐ valid empty WAVE | → PC runtime | 1 / — | **New work** (R6) | -| Closed captions, high contrast | ✘ slots 0x18/0x28 | ✔ `accessibility.rs` | — / 3 | **Rewrite after xcl** (R7) | +| 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) | | Relaunch (`XLaunchNewGame`), restart on crash | ◐ relaunch untested live | ✔ both | 4 (lifecycle) / — | Verify (R10) | | HDR, URIs, deferrals, screenshots | ✔ | ◐ | 1 / — | Keep XTP | @@ -385,10 +385,10 @@ shows the title calls them. with the recorded arguments, and only once. - **Depends on:** — -### R7. Closed captions and high contrast — S +### R7. Closed captions and high contrast — S (done) - **Goal:** answer the accessibility slots from the host: Windows closed-caption settings (enabled, colours, size) and high-contrast mode. -- **Files:** `crates/xtp-hle/src/modules/speech.rs`. +- **Files:** `crates/xtp-hle/src/modules/speech.rs` and `speech/captions.rs`. - **xcl ref:** `hle/xgameruntime/accessibility.rs` `XClosedCaptionGetProperties`, `XClosedCaptionSetEnabled`, `XHighContrastGetMode` (structure filled, defaults). - **Acceptance:** unit test: the structure is fully written with documented @@ -512,7 +512,7 @@ shows the title calls them. | 9 | I2 mouse as right stick | M | I1 | | 10 | R5 message/error dialogs | M | (R1) | | 11 | R10 relaunch, restart on crash | S | — | -| 12 | R7 closed captions, high contrast | S | — | +| 12 | R7 closed captions, high contrast (done) | S | — | | 13 | R6 speech synthesis | M | — | | 14 | I3 trigger rumble | M | — | | 15 | K1 commit measurement | S | — |