xgame.rs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. //! The title's own id (from its manifest), which runtime areas exist, and
  2. //! game invites and events. Offline no invite arrives and events go
  3. //! nowhere.
  4. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  5. use std::ffi::{CStr, c_char, c_void};
  6. use super::xgameruntime::{
  7. Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token,
  8. };
  9. use crate::runtime;
  10. /// Title id and launching another title.
  11. pub const TITLE_PROVIDER: Guid = Guid::new(
  12. 0x973a_344e,
  13. 0x24bf,
  14. 0x4d0f,
  15. [0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29],
  16. );
  17. /// As Minecraft (2022) asks for it.
  18. pub const TITLE_IID: Guid = Guid::new(
  19. 0x2549_f142,
  20. 0x6419,
  21. 0x4a06,
  22. [0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34],
  23. );
  24. /// Feature checks; the interface id is the provider's, as for the next two.
  25. pub const FEATURES: Guid = Guid::new(
  26. 0x8836_fe87,
  27. 0xedb9,
  28. 0x4fe3,
  29. [0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40],
  30. );
  31. pub const INVITES: Guid = Guid::new(
  32. 0x0651_aae2,
  33. 0x4012,
  34. 0x4077,
  35. [0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c],
  36. );
  37. pub const EVENTS: Guid = Guid::new(
  38. 0xbbfb_dcc7,
  39. 0xbfe7,
  40. 0x409b,
  41. [0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d],
  42. );
  43. pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE);
  44. pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE);
  45. pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE);
  46. pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE);
  47. pub const INTERFACES: &[Interface] = &[
  48. (TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT),
  49. (FEATURES, FEATURES, &FEATURES_OBJECT),
  50. (INVITES, INVITES, &INVITES_OBJECT),
  51. (EVENTS, EVENTS, &EVENTS_OBJECT),
  52. ];
  53. type This = *const Object;
  54. extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT {
  55. put(out, runtime::title().id)
  56. }
  57. /// As documented: the title ends (suspended first, as on any end) and the
  58. /// game starts again in a new process; this never returns.
  59. /// The title relaunches itself (its own path from `GetModuleFileNameA`) with
  60. /// arguments from its configuration. The new `victory run` gets the same
  61. /// options, the new executable, and the title's arguments after `--`
  62. /// (the title reads the whole command line).
  63. extern "system" fn launch_new_game(
  64. _: This,
  65. exe: *const c_char,
  66. args: *const c_char,
  67. _user: *const c_void,
  68. ) {
  69. let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default());
  70. tracing::info!(exe, args, "XLaunchNewGame");
  71. let current = runtime::main_image()
  72. .and_then(runtime::image_path)
  73. .unwrap_or_default();
  74. let ours: Vec<_> = std::env::args_os().skip(1).collect();
  75. let command = relaunch_args(ours, current.as_os_str(), &exe, &args);
  76. #[cfg(windows)]
  77. {
  78. super::lifecycle::end_title(
  79. "XLaunchNewGame",
  80. Box::new(move || super::lifecycle::relaunch(command)),
  81. );
  82. loop {
  83. std::thread::park();
  84. }
  85. }
  86. #[cfg(not(windows))]
  87. let _ = command;
  88. }
  89. /// Our own arguments for the relaunch: the title's executable replaced by
  90. /// `exe`, earlier title arguments dropped, `args` after `--`.
  91. fn relaunch_args(
  92. ours: Vec<std::ffi::OsString>,
  93. current: &std::ffi::OsStr,
  94. exe: &str,
  95. args: &str,
  96. ) -> Vec<std::ffi::OsString> {
  97. let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect();
  98. // `runtime` makes the image path absolute when it maps the title, so a
  99. // relative launch argument is not textually equal to it. Normalise the
  100. // same way before matching, or a relaunch would run the old executable.
  101. if !exe.is_empty()
  102. && let Some(slot) = out.iter_mut().find(|a| {
  103. a.as_os_str() == current
  104. || std::path::absolute(a).is_ok_and(|p| p.as_os_str() == current)
  105. })
  106. {
  107. *slot = exe.into();
  108. }
  109. if !args.trim().is_empty() {
  110. out.push("--".into());
  111. out.extend(split_args(args).into_iter().map(Into::into));
  112. }
  113. out
  114. }
  115. /// Splits the title's command-line tail into arguments, keeping double-quoted
  116. /// strings together (including empty ones). Windows command lines quote only
  117. /// with `"`: an apostrophe is ordinary text, as in `O'Brien`.
  118. fn split_args(args: &str) -> Vec<String> {
  119. let mut out = Vec::new();
  120. let mut current = String::new();
  121. let mut quoted = false;
  122. let mut started = false;
  123. for c in args.chars() {
  124. match c {
  125. '"' => {
  126. quoted = !quoted;
  127. started = true;
  128. }
  129. c if !quoted && c.is_whitespace() => {
  130. if started {
  131. out.push(std::mem::take(&mut current));
  132. started = false;
  133. }
  134. }
  135. c => {
  136. current.push(c);
  137. started = true;
  138. }
  139. }
  140. }
  141. if started {
  142. out.push(current);
  143. }
  144. out
  145. }
  146. /// Runtime areas by number, in the public feature list's order, that we
  147. /// serve: accessibility (0), app capture (1), async calls and providers
  148. /// (2, 3), display (4), game (5), invites (6), game saves (7), game UI (8),
  149. /// launcher (9), networking (10), packages (11), persistent local storage
  150. /// (12), speech synthesis (13), store (14), system (15), task queues (16),
  151. /// users (18), error reports (19), game events (20). Not threads (17) or
  152. /// game streaming (21).
  153. const AVAILABLE: [u32; 20] = [
  154. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20,
  155. ];
  156. extern "system" fn is_feature_available(_: This, feature: u32) -> bool {
  157. AVAILABLE.contains(&feature)
  158. }
  159. /// Nothing raises these events offline, so the callback never runs.
  160. extern "system" fn register(
  161. _: This,
  162. _queue: *const c_void,
  163. _context: *mut c_void,
  164. _callback: *const c_void,
  165. out: *mut u64,
  166. ) -> HRESULT {
  167. put(out, token())
  168. }
  169. extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
  170. true
  171. }
  172. /// Accepted and dropped; the name goes to the debug log.
  173. extern "system" fn write_event(
  174. _: This,
  175. _user: *const c_void,
  176. _service_config: *const c_char,
  177. _session: *const c_char,
  178. name: *const c_char,
  179. _dimensions: *const c_char,
  180. _measurements: *const c_char,
  181. ) -> HRESULT {
  182. if !name.is_null() {
  183. // SAFETY: a non-null name is a NUL-terminated string.
  184. let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
  185. tracing::debug!(%name, "game event dropped");
  186. }
  187. S_OK
  188. }
  189. static TITLE_VTABLE: Methods<5> = Methods([
  190. missing::<0> as *const (),
  191. add_ref as *const (),
  192. add_ref as *const (),
  193. title_id as *const (), // 0x18
  194. launch_new_game as *const (), // 0x20
  195. ]);
  196. static FEATURES_VTABLE: Methods<4> = Methods([
  197. missing::<0> as *const (),
  198. add_ref as *const (),
  199. add_ref as *const (),
  200. is_feature_available as *const (), // 0x18
  201. ]);
  202. static INVITES_VTABLE: Methods<5> = Methods([
  203. missing::<0> as *const (),
  204. add_ref as *const (),
  205. add_ref as *const (),
  206. register as *const (), // 0x18
  207. unregister as *const (), // 0x20
  208. ]);
  209. static EVENTS_VTABLE: Methods<4> = Methods([
  210. missing::<0> as *const (),
  211. add_ref as *const (),
  212. add_ref as *const (),
  213. write_event as *const (), // 0x18
  214. ]);
  215. #[cfg(test)]
  216. mod tests {
  217. use super::*;
  218. use crate::modules::xgameruntime::method;
  219. #[test]
  220. fn a_relaunch_keeps_our_options() {
  221. let ours: Vec<std::ffi::OsString> =
  222. ["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"]
  223. .map(Into::into)
  224. .into();
  225. let current = std::ffi::OsStr::new("G:/game.exe");
  226. let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y ");
  227. let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"];
  228. assert_eq!(again[..6], expected.map(std::ffi::OsString::from));
  229. assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from));
  230. let other = relaunch_args(ours, current, "G:/other.exe", "");
  231. assert_eq!(other.len(), 5);
  232. assert_eq!(other[1], "G:/other.exe");
  233. }
  234. #[test]
  235. fn a_relaunch_replaces_a_relative_startup_executable() {
  236. // `runtime::set_image_path` makes this absolute before the launch.
  237. let current = std::path::absolute("game.exe").unwrap();
  238. let ours: Vec<std::ffi::OsString> =
  239. ["run", "game.exe", "--execute", "--console", "series-s", "--", "-old"]
  240. .map(Into::into)
  241. .into();
  242. let again = relaunch_args(
  243. ours,
  244. current.as_os_str(),
  245. "other.exe",
  246. r#"--config="C:\Program Files\game" "" -name=O'Brien -y"#,
  247. );
  248. let expected: Vec<std::ffi::OsString> = [
  249. "run",
  250. "other.exe",
  251. "--execute",
  252. "--console",
  253. "series-s",
  254. "--",
  255. r"--config=C:\Program Files\game",
  256. "",
  257. "-name=O'Brien",
  258. "-y",
  259. ]
  260. .map(Into::into)
  261. .into();
  262. assert_eq!(again, expected, "the requested exe and quoted args survive");
  263. }
  264. #[test]
  265. fn served_areas_are_available_others_not() {
  266. type Check = extern "system" fn(This, u32) -> bool;
  267. let check = method::<Check>(&FEATURES_OBJECT, 0x18);
  268. assert!(check(&FEATURES_OBJECT, 18), "users");
  269. assert!(!check(&FEATURES_OBJECT, 21), "game streaming");
  270. type Register = extern "system" fn(
  271. This,
  272. *const c_void,
  273. *mut c_void,
  274. *const c_void,
  275. *mut u64,
  276. ) -> HRESULT;
  277. type Unregister = extern "system" fn(This, u64, bool) -> bool;
  278. let null = std::ptr::null();
  279. let mut token = 0;
  280. let register = method::<Register>(&INVITES_OBJECT, 0x18);
  281. assert_eq!(
  282. register(&INVITES_OBJECT, null, null as _, null, &mut token),
  283. S_OK
  284. );
  285. assert_ne!(token, 0);
  286. assert!(method::<Unregister>(&INVITES_OBJECT, 0x20)(
  287. &INVITES_OBJECT,
  288. token,
  289. true
  290. ));
  291. }
  292. }