| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263 |
- //! Process-wide state the implementations need.
- use std::path::{Path, PathBuf};
- use std::sync::Mutex;
- use std::sync::atomic::{AtomicUsize, Ordering};
- static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0);
- /// Records where the title's main image is mapped. The title expects
- /// `GetModuleHandle(NULL)` and friends to return this, not our own exe.
- pub fn set_main_image(base: usize) {
- MAIN_IMAGE_BASE.store(base, Ordering::Release);
- crate::image_watch::start(base);
- }
- pub fn main_image() -> Option<usize> {
- match MAIN_IMAGE_BASE.load(Ordering::Acquire) {
- 0 => None,
- base => Some(base),
- }
- }
- /// Original file of each title image we mapped, by base address.
- static IMAGE_PATHS: Mutex<Vec<(usize, PathBuf)>> = Mutex::new(Vec::new());
- /// Records the file a title image was mapped from: the title asks for its
- /// own path (`GetModuleFileName`) to find its data, and must not get our
- /// cache copy.
- pub fn set_image_path(base: usize, path: &Path) {
- let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
- let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
- paths.retain(|(b, _)| *b != base);
- paths.push((base, path));
- }
- /// Forgets a title image that was unmapped again.
- pub fn forget_image(base: usize) {
- let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
- paths.retain(|(b, _)| *b != base);
- }
- pub fn image_path(base: usize) -> Option<PathBuf> {
- let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
- paths
- .iter()
- .find(|(b, _)| *b == base)
- .map(|(_, p)| p.clone())
- }
- /// The title image whose original file is called `file` (any case).
- pub fn image_named(file: &str) -> Option<usize> {
- let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
- paths
- .iter()
- .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file)))
- .map(|(b, _)| *b)
- }
- static TITLE_ARGS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
- /// The arguments the title's `main` gets (those after `--`). Set once, before
- /// the title starts; later calls are ignored.
- pub fn set_title_args(args: Vec<String>) {
- let _ = TITLE_ARGS.set(args);
- }
- pub fn title_args() -> &'static [String] {
- TITLE_ARGS.get().map_or(&[], Vec::as_slice)
- }
- /// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its
- /// base; `Ok(None)` if `file` is not one of the title's DLLs.
- pub type TitleDllLoader = Box<dyn Fn(&str) -> Result<Option<usize>, String> + Send + Sync>;
- static TITLE_DLL_LOADER: std::sync::OnceLock<TitleDllLoader> = std::sync::OnceLock::new();
- /// Set once, by whoever mapped the title (it knows the folders and the
- /// resolver); later calls are ignored.
- pub fn set_title_dll_loader(loader: TitleDllLoader) {
- let _ = TITLE_DLL_LOADER.set(loader);
- }
- pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> {
- TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file))
- }
- /// What the title's manifest (`MicrosoftGame.config` beside its executable)
- /// says about it, and where its persistent local storage lives.
- #[derive(Debug, Clone, Default, PartialEq, Eq)]
- pub struct Title {
- pub id: u32,
- /// The store's product id (empty if the manifest has none).
- pub store_id: String,
- /// Persistent local storage: our folder for it and the title's quota.
- /// Game saves live beside it ([`Title::saves`]).
- pub storage: PathBuf,
- pub storage_bytes: u64,
- }
- impl Title {
- /// Id, store id and storage quota from the manifest (zero or empty
- /// where it has none); the storage folder is left for the caller.
- pub fn from_manifest(text: &str) -> Title {
- let elements = elements(text);
- let get = |path: &str| {
- elements
- .iter()
- .find(|(p, _)| p == path)
- .map(|(_, text)| text.as_str())
- };
- let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
- let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok());
- Title {
- id: id.unwrap_or(0),
- store_id: get("Game/StoreId").unwrap_or_default().to_owned(),
- storage: PathBuf::new(),
- storage_bytes: storage_mb.unwrap_or(0) << 20,
- }
- }
- /// Where game saves live: next to persistent local storage, under the
- /// data directory, never the cache.
- pub fn saves(&self) -> PathBuf {
- self.storage.with_file_name("saves")
- }
- }
- /// Each element of an XML text as its path from the root (`Game/TitleId`)
- /// and its trimmed text up to the first child, the predefined entities
- /// decoded; comments, CDATA sections, declarations and attributes are
- /// skipped.
- fn elements(text: &str) -> Vec<(String, String)> {
- let mut out = Vec::new();
- let mut path: Vec<&str> = Vec::new();
- let mut rest = text;
- while let Some(open) = rest.find('<') {
- rest = &rest[open..];
- let end = if rest.starts_with("<!--") {
- rest.find("-->").map(|e| e + 3)
- } else if rest.starts_with("<![CDATA[") {
- rest.find("]]>").map(|e| e + 3)
- } else {
- tag_end(rest)
- };
- let Some(end) = end else { break };
- let tag = &rest[1..end - 1];
- rest = &rest[end..];
- if tag.starts_with(['!', '?']) {
- continue;
- }
- if let Some(name) = tag.strip_prefix('/') {
- if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
- path.truncate(at);
- }
- continue;
- }
- let closed = tag.ends_with('/');
- let name = tag
- .trim_end_matches('/')
- .split_whitespace()
- .next()
- .unwrap_or("");
- path.push(name);
- let body = rest[..rest.find('<').unwrap_or(rest.len())].trim();
- let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")]
- .iter()
- .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c));
- out.push((path.join("/"), body));
- if closed {
- path.pop();
- }
- }
- out
- }
- /// Where the tag that starts `text` ends, past its `>`; a `>` in a quoted
- /// attribute value is part of the value (XML allows it there unescaped).
- fn tag_end(text: &str) -> Option<usize> {
- let mut quote = None;
- for (at, c) in text.char_indices() {
- match (quote, c) {
- (None, '"' | '\'') => quote = Some(c),
- (Some(open), _) if c == open => quote = None,
- (None, '>') => return Some(at + 1),
- _ => {}
- }
- }
- None
- }
- static TITLE: Mutex<Option<Title>> = Mutex::new(None);
- pub fn set_title(title: Title) {
- *TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title);
- }
- /// The running title; the default (id 0, no storage) until set.
- pub fn title() -> Title {
- TITLE
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .clone()
- .unwrap_or_default()
- }
- /// Gives the process the console's millisecond timers. Titles pace
- /// themselves with short waits (the title's audio mixer sleeps
- /// about 4 ms per 5.3 ms block) and cannot tune the timer on the console;
- /// a desktop process waits in 15.6 ms ticks unless it asks for finer ones,
- /// and Windows 11 drops that request while the window is hidden unless the
- /// process opts out. Process-wide, for the whole run.
- #[cfg(windows)]
- pub fn use_console_timers() {
- use windows_sys::Win32::Media::timeBeginPeriod;
- use windows_sys::Win32::System::Threading::{
- GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION,
- PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
- ProcessPowerThrottling, SetProcessInformation,
- };
- let keep = PROCESS_POWER_THROTTLING_STATE {
- Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
- ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION,
- StateMask: 0,
- };
- // SAFETY: plain process settings; `keep` outlives the call.
- unsafe {
- SetProcessInformation(
- GetCurrentProcess(),
- ProcessPowerThrottling,
- (&raw const keep).cast(),
- size_of_val(&keep) as u32,
- );
- timeBeginPeriod(1);
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn a_quoted_angle_bracket_does_not_end_its_tag() {
- let text = "<Game><ShellVisuals DefaultDisplayName=\"A > B\" Description='x>y'/>\
- <TitleId>639AA8DD</TitleId>\
- <PersistentLocalStorage><SizeMB>64</SizeMB></PersistentLocalStorage></Game>";
- let t = Title::from_manifest(text);
- assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 64 << 20));
- }
- #[test]
- fn reads_title_id_store_id_and_storage_quota() {
- let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\
- <!-- <TitleId>00000000</TitleId> -->\
- <Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
- <![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&C</StoreId><Other><SizeMB>7</SizeMB></Other>\
- <PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\
- </PersistentLocalStorage></Game>";
- let t = Title::from_manifest(text);
- assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20));
- assert_eq!(t.store_id, "9&C");
- assert_eq!(Title::from_manifest("").storage_bytes, 0);
- }
- }
|