diff --git a/gpui/src/app.rs b/gpui/src/app.rs index 53988b7b..968712c0 100644 --- a/gpui/src/app.rs +++ b/gpui/src/app.rs @@ -144,6 +144,8 @@ pub struct AppView { sidebar_collapsed: bool, settings: Settings, games: Vec, + /// True while the Games page's manual rescan runs off the UI thread. + games_scanning: bool, devices: Devices, /// Linux `/dev/hidraw*` mouse nodes blocked by permissions (always empty off Linux). hid_blocked: Vec, @@ -304,6 +306,7 @@ impl AppView { sidebar_collapsed: false, settings, games, + games_scanning: false, devices: Devices::default(), hid_blocked: Vec::new(), udev_fix: UdevFix::Idle, @@ -511,6 +514,7 @@ impl Default for AppView { sidebar_collapsed: false, settings: Settings::default(), games: Vec::new(), + games_scanning: false, devices: Devices::default(), hid_blocked: Vec::new(), udev_fix: UdevFix::Idle, diff --git a/gpui/src/app/games_page.rs b/gpui/src/app/games_page.rs index 6e1dd672..84215813 100644 --- a/gpui/src/app/games_page.rs +++ b/gpui/src/app/games_page.rs @@ -22,6 +22,42 @@ fn badge(text: &'static str, accent: Hsla, cx: &App) -> Div { } impl AppView { + /// Re-read the launcher manifests right now. The scan is blocking, so it + /// runs on the background executor; back on the UI thread only the + /// `installed` flags are applied, leaving running games, profiles and the + /// periodic watchers untouched. One scan at a time, like device rescan. + pub(super) fn rescan_games(&mut self, cx: &mut Context) { + if self.games_scanning { + return; + } + crate::logging::log("[games] manual rescan requested"); + self.games_scanning = true; + cx.notify(); + let catalog = self.games.clone(); + cx.spawn(async move |view, cx| { + let updates = cx + .background_executor() + .spawn(async move { crate::game_watcher::scan_installed(&catalog) }) + .await; + let _ = view.update(cx, |this, cx| { + this.games_scanning = false; + let changed = updates.iter().filter(|update| update.installed.is_some()).count(); + this.apply_game_updates(&updates, cx); + let message = if changed == 0 { + "Games rescanned — no changes found".to_string() + } else { + format!( + "Games rescanned — {} {} updated", + changed, + if changed == 1 { "game" } else { "games" } + ) + }; + this.show_toast(message, false, cx); + }); + }) + .detach(); + } + /// Games page: a header with live counts, then the installed/running /// games and the rest of the catalog as grids of poster cards. Cached art /// falls back to a name-initial tile until prefetch completes. @@ -49,12 +85,28 @@ impl AppView { .gap_6() .overflow_y_scrollbar() .child( - div() - .flex() - .flex_col() - .gap_1() - .child(div().text_xl().font_weight(FontWeight::SEMIBOLD).text_color(fg).child("Games")) - .child(div().text_sm().text_color(muted).child(subtitle)), + h_flex() + .justify_between() + .items_center() + .gap_4() + .child( + div() + .flex() + .flex_col() + .gap_1() + .child(div().text_xl().font_weight(FontWeight::SEMIBOLD).text_color(fg).child("Games")) + .child(div().text_sm().text_color(muted).child(subtitle)), + ) + .child( + Button::new("rescan-games") + .compact() + .icon(IconName::RefreshCw) + .label(if self.games_scanning { "Scanning…" } else { "Rescan" }) + .loading(self.games_scanning) + .disabled(self.games_scanning) + .tooltip("Look for newly installed games again") + .on_click(cx.listener(|this, _, _, cx| this.rescan_games(cx))), + ), ) .child(self.render_game_section(cx, "Installed & running", "Pick a game or app to give it its own mouse profile.", &installed, false)) .child(self.render_game_section(cx, "More games", "Not found on this PC. Profiles you set up still apply once they are installed.", &rest, true)) diff --git a/gpui/src/game_watcher.rs b/gpui/src/game_watcher.rs index 992562bd..dd424950 100644 --- a/gpui/src/game_watcher.rs +++ b/gpui/src/game_watcher.rs @@ -69,20 +69,24 @@ impl GameWatcher { .await; loop { let started = Instant::now(); - let (updated, changes) = cx + let (updated, scanned) = cx .background_executor() .spawn(async move { - let changes = tracker.poll(); - (tracker, changes) + let scanned = tracker.poll(); + (tracker, scanned) }) .await; tracker = updated; - if changes.is_empty() { + // Reconcile against the view's *current* state, not a private + // delta baseline: a manual rescan may have changed installed + // flags since this tracker last looked. Unchanged values are + // no-ops in `apply_game_updates`, so this only corrects drift. + if scanned.is_empty() { if view.upgrade().is_none() { break; } } else if view - .update(cx, |view, cx| view.apply_game_updates(&changes, cx)) + .update(cx, |view, cx| view.apply_game_updates(&scanned, cx)) .is_err() { break; @@ -130,6 +134,30 @@ pub(crate) fn apply_updates(catalog: &mut [Game], updates: &[GameUpdate]) -> boo changed } +/// One-off install scan for the Games page's Rescan button. Blocking (reads +/// launcher manifests and the registry), so callers must run it off the UI +/// thread. The returned updates carry only `installed`, leaving the running +/// state to the two-second process tracker. +pub(crate) fn scan_installed(catalog: &[Game]) -> Vec { + let mut scanned = catalog.to_vec(); + games::mark_installed(&mut scanned); + install_updates(catalog, &scanned) +} + +fn install_updates(previous: &[Game], scanned: &[Game]) -> Vec { + previous + .iter() + .zip(scanned) + .filter_map(|(before, after)| { + (before.installed != after.installed).then(|| GameUpdate { + id: before.id.clone(), + installed: Some(after.installed), + running: None, + }) + }) + .collect() +} + struct RunningTracker { system: System, matches: ProcessMatches, @@ -284,33 +312,30 @@ fn executable_basename(name: &str) -> &str { struct InstallationTracker { catalog: Vec, - installed: Vec, } impl InstallationTracker { fn new(catalog: Vec) -> Self { - let installed = catalog.iter().map(|game| game.installed).collect(); - Self { catalog, installed } + Self { catalog } } fn poll(&mut self) -> Vec { games::mark_installed(&mut self.catalog); - self.updates() + self.state_updates() } - fn updates(&mut self) -> Vec { - let mut changes = Vec::new(); - for (game, previous) in self.catalog.iter().zip(&mut self.installed) { - if game.installed != *previous { - changes.push(GameUpdate { - id: game.id.clone(), - installed: Some(game.installed), - running: None, - }); - *previous = game.installed; - } - } - changes + /// Every game's current installed state, not just transitions. The view + /// applies this against its own flags, so a manual rescan cannot leave a + /// stale value that this tracker's private baseline would never correct. + fn state_updates(&self) -> Vec { + self.catalog + .iter() + .map(|game| GameUpdate { + id: game.id.clone(), + installed: Some(game.installed), + running: None, + }) + .collect() } } @@ -455,19 +480,41 @@ mod tests { } #[test] - fn installation_lifecycle_does_not_reset_concurrent_running_state() { + fn periodic_install_state_reconciles_manual_changes_and_preserves_running() { let mut tracker = InstallationTracker::new(vec![game("cs2", "cs2.exe")]); let mut catalog = vec![game("cs2", "cs2.exe")]; catalog[0].running = true; - assert!(tracker.updates().is_empty()); - tracker.catalog[0].installed = true; - assert!(apply_updates(&mut catalog, &tracker.updates())); - assert!(catalog[0].installed && catalog[0].running); - assert!(tracker.updates().is_empty()); + // Unchanged values are reported too, but applying them is a no-op. + assert_eq!(tracker.state_updates().len(), 1); + assert!(!apply_updates(&mut catalog, &tracker.state_updates())); + + // A manual rescan marks it installed; it is then uninstalled before + // the periodic scan runs. The next poll must still clear the UI flag. + catalog[0].installed = true; tracker.catalog[0].installed = false; - assert!(apply_updates(&mut catalog, &tracker.updates())); + assert!(apply_updates(&mut catalog, &tracker.state_updates())); assert!(!catalog[0].installed && catalog[0].running); - assert!(tracker.updates().is_empty()); + assert!(!apply_updates(&mut catalog, &tracker.state_updates())); + } + + #[test] + fn manual_install_scan_reports_only_installed_changes() { + let mut before = vec![game("cs2", "cs2.exe"), game("valorant", "VALORANT.exe")]; + before[0].running = true; + let mut after = before.clone(); + after[0].installed = true; + let updates = install_updates(&before, &after); + assert_eq!( + updates, + vec![GameUpdate { + id: "cs2".into(), + installed: Some(true), + running: None, + }] + ); + assert!(apply_updates(&mut before, &updates)); + assert!(before[0].installed && before[0].running, "running state survives"); + assert!(!apply_updates(&mut before, &updates), "no duplicate change"); } #[test] diff --git a/gpui/src/games/install_scan.rs b/gpui/src/games/install_scan.rs index fc8257b2..1c7ad068 100644 --- a/gpui/src/games/install_scan.rs +++ b/gpui/src/games/install_scan.rs @@ -93,6 +93,10 @@ struct Installed { steam: HashSet, epic: HashSet, riot: HashSet<&'static str>, + /// Catalog ids found in the OS's installed-programs list. A last resort + /// for launchers with no manifest of their own (EA's Apex, Battle.net's + /// Overwatch, and so on). + programs: HashSet, } pub(super) fn mark_installed(games: &mut [Game]) { @@ -104,6 +108,7 @@ fn mark_with_roots(games: &mut [Game], roots: &Roots) { scan_steam(&roots.steam, &mut installed.steam); scan_epic(&roots.epic, &mut installed.epic); scan_riot(roots, &mut installed.riot); + scan_installed_programs(games, &mut installed.programs); for game in games { game.installed = game .steam_app_id @@ -115,10 +120,144 @@ fn mark_with_roots(games: &mut [Game], roots: &Roots) { || game .riot_id .as_deref() - .is_some_and(|id| installed.riot.contains(id)); + .is_some_and(|id| installed.riot.contains(id)) + || installed.programs.contains(&game.id); } } +/// Non-Windows platforms have no central uninstall registry; launcher +/// manifests above cover the games we know about there. +#[cfg(not(target_os = "windows"))] +fn scan_installed_programs(_games: &[Game], _ids: &mut HashSet) {} + +/// Windows records every installed game under Uninstall, including EA and +/// Battle.net titles that publish no manifest we recognise. Only an exact +/// catalog name with a real executable on disk counts: stale entries and +/// similarly named tools never make a game look installed. +#[cfg(target_os = "windows")] +fn scan_installed_programs(games: &[Game], ids: &mut HashSet) { + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ}; + use winreg::RegKey; + + for (root, path) in [ + ( + HKEY_LOCAL_MACHINE, + r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", + ), + ( + HKEY_LOCAL_MACHINE, + r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", + ), + ( + HKEY_CURRENT_USER, + r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", + ), + ] { + let Ok(key) = RegKey::predef(root).open_subkey_with_flags(path, KEY_READ) else { + continue; + }; + for name in key.enum_keys().flatten() { + let Ok(entry) = key.open_subkey(&name) else { continue }; + let location = entry + .get_value::("InstallLocation") + .ok() + .map(PathBuf::from); + // `DisplayIcon` may point at a .ico resource; that is not evidence + // the game is installed. Only an executable counts, otherwise look + // in InstallLocation (also covers Store entries with no icon). + let icon = entry + .get_value::("DisplayIcon") + .ok() + .map(|value| icon_file(&value).to_path_buf()) + .filter(|path| path.is_file() && is_executable(path)); + if let Some(id) = installed_program(games, icon.as_deref(), location.as_deref()) { + ids.insert(id.to_string()); + } + } + } +} + +/// Pure part of the uninstall scan, kept separate so it can be tested +/// without touching the real registry. The display name is irrelevant: a +/// catalog executable must exist, either as the icon target itself or in the +/// install directory. No executable match means not installed. +fn installed_program<'a>( + games: &'a [Game], + icon: Option<&Path>, + install_dir: Option<&Path>, +) -> Option<&'a str> { + let key = icon + .filter(|path| path.is_file() && is_executable(path)) + .map(executable_key); + games + .iter() + .find(|game| { + key.as_deref().is_some_and(|key| { + game.executables.iter().any(|candidate| executable_key(candidate) == key) + }) || install_dir.is_some_and(|dir| has_catalog_executable(game, dir)) + }) + .map(|game| game.id.as_str()) +} + +fn is_executable(path: &Path) -> bool { + path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("exe")) +} + +/// The display name may differ from the catalog's, so also check the install +/// directory for one of the executables the catalog knows. +fn has_catalog_executable(game: &Game, dir: &Path) -> bool { + std::fs::read_dir(dir).ok().is_some_and(|entries| { + entries.flatten().any(|entry| { + let path = entry.path(); + path.is_file() + && is_executable(&path) + && game + .executables + .iter() + .any(|candidate| executable_key(candidate) == executable_key(&path)) + }) + }) +} + +/// `DisplayIcon` is often `"C:\...\game.exe"` or `"...\game.exe",0`. +/// Only a trailing numeric resource index is decoration; a comma inside the +/// path (`Apex, Legends`) is part of the file name. +fn icon_file(value: &str) -> &Path { + let value = value.trim(); + let path = if let Some(rest) = value.strip_prefix('"') { + rest.split_once('"').map_or(rest, |(path, _)| path) + } else { + let end = value + .rfind(',') + .filter(|&comma| { + let index = value[comma + 1..].trim(); + !index.is_empty() && index.chars().all(|ch| ch.is_ascii_digit()) + }) + .unwrap_or(value.len()); + &value[..end] + }; + Path::new(path.trim()) +} + +/// Compare executables without the launcher's build suffixes: EA's +/// `r5apex_dx12.exe` and Steam's `r5apex.exe` are the same game. +fn executable_key(value: impl AsRef) -> String { + let stem = value + .as_ref() + .file_stem() + .unwrap_or_default() + .to_string_lossy() + .to_ascii_lowercase(); + let mut key: String = stem.chars().filter(|ch| ch.is_ascii_alphanumeric()).collect(); + for suffix in ["win64shipping", "win32shipping", "dx12", "dx11", "win64", "shipping", "retail", "x64"] { + if let Some(bare) = key.strip_suffix(suffix) { + key = bare.to_string(); + break; + } + } + key +} + fn unique_existing_dirs>(paths: impl IntoIterator) -> Vec { let mut paths: Vec<_> = paths .into_iter() diff --git a/gpui/src/games/install_scan/tests.rs b/gpui/src/games/install_scan/tests.rs index be6d1c69..9447c717 100644 --- a/gpui/src/games/install_scan/tests.rs +++ b/gpui/src/games/install_scan/tests.rs @@ -90,6 +90,59 @@ fn quoted_path(path: &Path) -> String { .replace('"', "\\\"") } +#[test] +fn icon_file_keeps_commas_in_paths_and_strips_only_resource_indexes() { + let cases = [ + (r"C:\Games\Apex, Legends\r5apex.exe,0", r"C:\Games\Apex, Legends\r5apex.exe"), + (r#" "C:\Games\Apex, Legends\r5apex.exe",0 "#, r"C:\Games\Apex, Legends\r5apex.exe"), + (r"C:\Games\Apex, Legends\r5apex.exe", r"C:\Games\Apex, Legends\r5apex.exe"), + (r"C:\Games\game.exe, 12", r"C:\Games\game.exe"), + ]; + for (value, expected) in cases { + assert_eq!(icon_file(value).to_string_lossy(), expected, "{value}"); + } +} + +#[test] +fn installed_programs_need_executable_evidence() { + let dir = std::env::temp_dir().join(format!("openmouse-uninstall-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let exe = dir.join("r5apex.exe"); + let dx12 = dir.join("r5apex_dx12.exe"); + let helper = dir.join("EADesktop.exe"); + let icon = dir.join("apex.ico"); + for path in [&exe, &dx12, &helper, &icon] { + std::fs::write(path, b"fake").unwrap(); + } + let mut games = vec![game(None, None, None)]; + games[0].name = "Apex Legends".into(); + games[0].executables = vec!["r5apex.exe".into()]; + + assert_eq!(installed_program(&games, Some(&exe), None), Some("fixture")); + assert_eq!(installed_program(&games, Some(&dx12), None), Some("fixture")); + // An icon resource on its own is not evidence, and neither is nothing. + assert_eq!(installed_program(&games, Some(&icon), None), None); + assert_eq!(installed_program(&games, None, None), None); + // A helper executable and a different display name do not hide a catalog + // executable that is present in InstallLocation. + assert_eq!(installed_program(&games, Some(&helper), Some(&dir)), Some("fixture")); + assert_eq!(installed_program(&games, None, Some(&dir)), Some("fixture")); + // Stale entry: no catalog executable anywhere. + games[0].executables = vec!["missing.exe".into()]; + assert_eq!(installed_program(&games, Some(&helper), Some(&dir)), None); + + // Paths containing commas must reach the check intact. + games[0].executables = vec!["r5apex.exe".into()]; + let comma = dir.join("Apex, Legends"); + std::fs::create_dir_all(&comma).unwrap(); + let comma_exe = comma.join("r5apex.exe"); + std::fs::write(&comma_exe, b"fake").unwrap(); + assert_eq!(installed_program(&games, Some(&comma_exe), None), Some("fixture")); + + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn steam_scans_modern_and_legacy_extra_libraries_and_deduplicates_roots() { let f = Fixture::new(); diff --git a/public/games.json b/public/games.json index fbf58d4c..ac7fc041 100644 --- a/public/games.json +++ b/public/games.json @@ -25,7 +25,7 @@ "id": "apex-legends", "name": "Apex Legends", "steamAppId": 1172470, - "executables": ["r5apex.exe", "r5apex"] + "executables": ["r5apex.exe", "r5apex_dx12.exe", "r5apex"] }, { "id": "overwatch-2",