fix(app): game detection finds Battle.net games where they are installed and takes any letters in a path

- Battle.net installs anywhere: its games come from the machine's uninstall entries (removed by
  its Blizzard Uninstaller or published by Blizzard Entertainment, with an install folder, not
  Battle.net itself), read when the watch starts; a program inside one is a game named after
  the entry
- launcher folders are matched part by part with ASCII case ignored; the name was cut by byte
  positions of a lower-cased copy, which panicked the detection thread on a path such as
  D:\İ\steamapps\common\하데스\game.exe
- checked on the win-ci VM: a Steam game under a non-ASCII path and a Battle.net game (test
  uninstall entry) turn game mode on with their names and off when they end

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 09:32:53 +09:00
parent c9101e0d6a
commit 7e83b09dd5
5 changed files with 192 additions and 51 deletions

View File

@@ -27,14 +27,59 @@ const NOT_GAMES: &[&str] = &[
"leagueclientuxrender.exe", "battle.net.exe", "agent.exe",
];
/// Launcher game folders: a program under one counts as a game whatever its window looks like.
const LAUNCHERS: &[(&str, &str)] = &[
("\\steamapps\\common\\", "Steam"),
("\\epic games\\", "Epic"),
("\\riot games\\", "Riot"),
("\\battle.net\\", "Battle.net"),
/// Launcher game folders, as the path parts before the game's own folder: a program under one
/// counts as a game whatever its window looks like. Battle.net installs anywhere, so its games come
/// from their install folders (`InstalledGame`).
const LAUNCHERS: &[(&[&str], &str)] = &[
(&["steamapps", "common"], "Steam"),
(&["epic games"], "Epic"),
(&["riot games"], "Riot"),
];
/// A game a launcher installed somewhere of its own choosing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstalledGame {
pub dir: String,
pub name: String,
pub launcher: &'static str,
}
/// A Battle.net game from its Windows uninstall entry: Battle.net writes one per game, removed by
/// its "Blizzard Uninstaller" (also for other publishers' games); Blizzard's own entries count too.
/// Battle.net itself and entries without a folder are not games.
pub fn battle_net_game(name: &str, publisher: &str, uninstall: &str, dir: &str) -> Option<InstalledGame> {
let by_battle_net = uninstall.to_ascii_lowercase().contains("blizzard uninstaller")
|| publisher.trim().eq_ignore_ascii_case("blizzard entertainment");
let dir = dir.trim().trim_end_matches(['\\', '/']);
(by_battle_net && !name.trim().eq_ignore_ascii_case("battle.net") && !dir.is_empty())
.then(|| InstalledGame { dir: dir.to_owned(), name: name.trim().to_owned(), launcher: "Battle.net" })
}
/// A path's parts (folders and file name), whichever slash it uses.
fn parts(path: &str) -> Vec<&str> {
path.split(['\\', '/']).filter(|p| !p.is_empty()).collect()
}
/// The launcher and game name of a program under a launcher's game folder or an installed game's
/// folder. Parts are compared without case (ASCII), never cut by byte positions.
fn launcher_game(path: &str, installed: &[InstalledGame]) -> Option<(&'static str, String)> {
let p = parts(path);
let same = |a: &[&str], b: &[&str]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.eq_ignore_ascii_case(y));
for g in installed {
let d = parts(&g.dir);
if p.len() > d.len() && same(&p[..d.len()], &d) {
return Some((g.launcher, g.name.clone()));
}
}
for (marker, launcher) in LAUNCHERS {
// The game's folder follows the marker, and the program is inside it.
if let Some(i) = (0..p.len().saturating_sub(marker.len() + 1)).find(|&i| same(&p[i..i + marker.len()], marker)) {
return Some((launcher, p[i + marker.len()].to_owned()));
}
}
None
}
/// The foreground window as Windows reports it.
#[derive(Debug, Clone, PartialEq)]
pub struct Foreground {
@@ -54,6 +99,8 @@ pub struct Snapshot {
pub foreground: Option<Foreground>,
/// Windows says a full-screen Direct3D program runs (exclusive full screen).
pub d3d_fullscreen: bool,
/// Games installed outside a launcher's game folder (Battle.net).
pub installed: Vec<InstalledGame>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -83,7 +130,7 @@ fn listed(name: &str, list: &[String]) -> bool {
}
/// Why the foreground program is a game, or `None`.
pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings) -> Option<Reason> {
pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings, installed: &[InstalledGame]) -> Option<Reason> {
let name = file_name(&fg.path);
if listed(&name, &s.not_games) {
return None;
@@ -94,8 +141,7 @@ pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings) -> Opti
if NOT_GAMES.contains(&name.as_str()) {
return None;
}
let path = fg.path.to_lowercase().replace('/', "\\");
if let Some((_, launcher)) = LAUNCHERS.iter().find(|(dir, _)| path.contains(dir)) {
if let Some((launcher, _)) = launcher_game(&fg.path, installed) {
return Some(Reason::Launcher(launcher));
}
if d3d_fullscreen {
@@ -104,20 +150,17 @@ pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings) -> Opti
(fg.covers_monitor && fg.no_frame && fg.gpu_3d >= MIN_GPU_3D).then_some(Reason::Borderless)
}
/// A game's name for the dashboard: its folder under a launcher's game folder, else the program's
/// name without ".exe".
pub fn display_name(path: &str) -> String {
let lower = path.to_lowercase().replace('/', "\\");
for (dir, _) in LAUNCHERS {
if let Some(i) = lower.find(dir) {
let rest = &path[i + dir.len()..];
if let Some(folder) = rest.split(['\\', '/']).next().filter(|f| !f.is_empty()) {
return folder.to_owned();
}
}
/// A game's name for the dashboard: its name from the launcher (the folder under a launcher's game
/// folder, or an installed game's name), else the program's name without ".exe".
pub fn game_name(path: &str, installed: &[InstalledGame]) -> String {
if let Some((_, name)) = launcher_game(path, installed) {
return name;
}
let name = parts(path).last().copied().unwrap_or(path);
match name.len().checked_sub(4) {
Some(i) if name.is_char_boundary(i) && name[i..].eq_ignore_ascii_case(".exe") => name[..i].to_owned(),
_ => name.to_owned(),
}
let name = path.rsplit(['\\', '/']).next().unwrap_or(path);
name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name).to_owned()
}
/// The game mode: once a game is seen it stays until its process ends, also while another window
@@ -138,7 +181,8 @@ impl GameState {
return None;
}
let next = snap.foreground.as_ref().and_then(|fg| {
classify(fg, snap.d3d_fullscreen, s).map(|reason| Detected { pid: fg.pid, name: display_name(&fg.path), reason })
classify(fg, snap.d3d_fullscreen, s, &snap.installed)
.map(|reason| Detected { pid: fg.pid, name: game_name(&fg.path, &snap.installed), reason })
});
if next == self.current {
return None;
@@ -228,7 +272,11 @@ mod probe {
#[cfg(windows)]
mod probe {
use super::{Foreground, Snapshot};
use super::{battle_net_game, Foreground, InstalledGame, Snapshot};
use windows_sys::Win32::System::Registry::{
RegCloseKey, RegEnumKeyExW, RegGetValueW, RegOpenKeyExW, HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY,
KEY_WOW64_64KEY, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ,
};
use windows_sys::Win32::Foundation::{CloseHandle, HWND, RECT, WAIT_TIMEOUT};
use windows_sys::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST};
use windows_sys::Win32::System::Performance::*;
@@ -243,6 +291,7 @@ mod probe {
pub struct Probe {
query: PDH_HQUERY,
counter: PDH_HCOUNTER,
installed: Vec<InstalledGame>,
}
impl Probe {
@@ -258,7 +307,7 @@ mod probe {
PdhCollectQueryData(query);
}
}
Self { query, counter }
Self { query, counter, installed: battle_net_games() }
}
/// 3D engine use of process `pid` in percent, summed over its engines.
@@ -297,10 +346,62 @@ mod probe {
let foreground = foreground().map(|(pid, path, covers_monitor, no_frame)| {
Foreground { pid, path, covers_monitor, no_frame, gpu_3d: self.gpu_3d(pid) }
});
Snapshot { foreground, d3d_fullscreen }
Snapshot { foreground, d3d_fullscreen, installed: self.installed.clone() }
}
}
/// Battle.net's games from the machine's uninstall entries (64- and 32-bit views), read once
/// when the watch starts.
fn battle_net_games() -> Vec<InstalledGame> {
const KEY: &str = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
let key: Vec<u16> = KEY.encode_utf16().chain(Some(0)).collect();
let mut out: Vec<InstalledGame> = vec![];
for view in [KEY_WOW64_64KEY, KEY_WOW64_32KEY] {
let mut h: HKEY = std::ptr::null_mut();
// SAFETY: opening a key for reading into a local handle, closed below.
if unsafe { RegOpenKeyExW(HKEY_LOCAL_MACHINE, key.as_ptr(), 0, KEY_READ | view, &mut h) } != 0 {
continue;
}
for i in 0.. {
let mut name = [0u16; 256];
let mut len = name.len() as u32;
// SAFETY: `name` holds `len` characters; the loop ends at the first index past the list.
let r = unsafe {
RegEnumKeyExW(h, i, name.as_mut_ptr(), &mut len, std::ptr::null(), std::ptr::null_mut(), std::ptr::null_mut(),
std::ptr::null_mut())
};
if r != 0 {
break;
}
let sub = &name[..=len as usize];
let value = |v: &str| -> String {
let v: Vec<u16> = v.encode_utf16().chain(Some(0)).collect();
let mut buf = [0u16; 1024];
let mut size = (buf.len() * 2) as u32;
// SAFETY: valid NUL-terminated names; `buf` holds `size` bytes.
let ok = unsafe {
RegGetValueW(h, sub.as_ptr(), v.as_ptr(), RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ, std::ptr::null_mut(),
buf.as_mut_ptr().cast(), &mut size)
} == 0;
if !ok {
return String::new();
}
let n = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
String::from_utf16_lossy(&buf[..n])
};
if let Some(g) = battle_net_game(&value("DisplayName"), &value("Publisher"), &value("UninstallString"),
&value("InstallLocation")) {
if !out.contains(&g) {
out.push(g);
}
}
}
// SAFETY: the key opened above.
unsafe { RegCloseKey(h) };
}
out
}
impl Drop for Probe {
fn drop(&mut self) {
if !self.query.is_null() {
@@ -389,29 +490,58 @@ mod tests {
fn a_borderless_game_is_a_game_and_a_maximised_program_or_video_is_not() {
let s = settings();
// A borderless game outside any launcher folder (the M0 check: covers, no frame, GPU >= 10%).
assert_eq!(classify(&fg(r"D:\Games\Hades\Hades.exe", true, true, 45.0), false, &s), Some(Reason::Borderless));
assert_eq!(classify(&fg(r"D:\Games\Hades\Hades.exe", true, true, 45.0), false, &s, &[]), Some(Reason::Borderless));
// Too little 3D work: a borderless tool, not a game.
assert_eq!(classify(&fg(r"D:\Tools\kiosk.exe", true, true, 3.0), false, &s), None);
assert_eq!(classify(&fg(r"D:\Tools\kiosk.exe", true, true, 3.0), false, &s, &[]), None);
// A maximised program has a title bar.
assert_eq!(classify(&fg(r"C:\Windows\notepad.exe", true, false, 0.0), false, &s), None);
assert_eq!(classify(&fg(r"C:\Windows\notepad.exe", true, false, 0.0), false, &s, &[]), None);
// A browser's full-screen video, even with the GPU busy.
assert_eq!(classify(&fg(r"C:\Program Files\Google\Chrome\Application\chrome.exe", true, true, 60.0), false, &s), None);
assert_eq!(classify(&fg(r"C:\Program Files\Google\Chrome\Application\chrome.exe", true, true, 60.0), false, &s, &[]), None);
// Exclusive full screen.
assert_eq!(classify(&fg(r"D:\Games\Old\old.exe", true, true, 0.0), true, &s), Some(Reason::Fullscreen));
assert_eq!(classify(&fg(r"D:\Games\Old\old.exe", true, true, 0.0), true, &s, &[]), Some(Reason::Fullscreen));
}
#[test]
fn launcher_folders_make_a_game_whatever_the_window_and_name_it_by_its_folder() {
let s = settings();
let valorant = r"C:\Riot Games\VALORANT\live\ShooterGame\Binaries\Win64\VALORANT-Win64-Shipping.exe";
assert_eq!(classify(&fg(valorant, false, false, 0.0), false, &s), Some(Reason::Launcher("Riot")));
assert_eq!(display_name(valorant), "VALORANT");
assert_eq!(classify(&fg(valorant, false, false, 0.0), false, &s, &[]), Some(Reason::Launcher("Riot")));
assert_eq!(game_name(valorant, &[]), "VALORANT");
let steam = r"D:\SteamLibrary\steamapps\common\Stardew Valley\Stardew Valley.exe";
assert_eq!(classify(&fg(steam, false, false, 0.0), false, &s), Some(Reason::Launcher("Steam")));
assert_eq!(display_name(steam), "Stardew Valley");
assert_eq!(classify(&fg(steam, false, false, 0.0), false, &s, &[]), Some(Reason::Launcher("Steam")));
assert_eq!(game_name(steam, &[]), "Stardew Valley");
// The launchers' own windows are not games.
assert_eq!(classify(&fg(r"C:\Riot Games\Riot Client\RiotClientServices.exe", true, true, 20.0), false, &s), None);
assert_eq!(display_name(r"D:\Games\Hades\Hades.exe"), "Hades");
assert_eq!(classify(&fg(r"C:\Riot Games\Riot Client\RiotClientServices.exe", true, true, 20.0), false, &s, &[]), None);
assert_eq!(game_name(r"D:\Games\Hades\Hades.exe", &[]), "Hades");
}
#[test]
fn any_letters_in_a_path_are_fine() {
// Lower-casing "İ" changes its length: matching must not cut the path by those positions.
let path = "D:\\İ\\steamapps\\common\\하데스\\game.exe";
assert_eq!(classify(&fg(path, false, false, 0.0), false, &settings(), &[]), Some(Reason::Launcher("Steam")));
assert_eq!(game_name(path, &[]), "하데스");
assert_eq!(game_name("D:\\İ\\게임.exe", &[]), "게임");
}
#[test]
fn battle_net_games_are_found_where_they_are_installed() {
let wow = InstalledGame { dir: r"D:\Games\World of Warcraft".into(), name: "World of Warcraft".into(), launcher: "Battle.net" };
let installed = [wow];
let exe = r"D:\Games\world of warcraft\_retail_\Wow.exe";
// A plain window: the install folder alone makes it a game.
assert_eq!(classify(&fg(exe, false, false, 0.0), false, &settings(), &installed), Some(Reason::Launcher("Battle.net")));
assert_eq!(game_name(exe, &installed), "World of Warcraft");
// A folder that only starts with the same letters is not inside it.
assert_eq!(classify(&fg(r"D:\Games\World of Warcraft Tools\x.exe", false, false, 0.0), false, &settings(), &installed), None);
// The uninstall entries Battle.net writes: its games (Blizzard's, or any it uninstalls), not itself.
let entry = |name: &str, publisher: &str, uninstall: &str, dir: &str| battle_net_game(name, publisher, uninstall, dir);
assert_eq!(entry("World of Warcraft", "Blizzard Entertainment", r#""C:\ProgramData\Battle.net\Agent\Blizzard Uninstaller.exe" --lang=koKR --uid=wow"#, r"D:\Games\World of Warcraft"),
Some(InstalledGame { dir: r"D:\Games\World of Warcraft".into(), name: "World of Warcraft".into(), launcher: "Battle.net" }));
assert!(entry("Call of Duty", "Activision", r#""C:\ProgramData\Battle.net\Agent\Blizzard Uninstaller.exe" --uid=fore"#, r"C:\Games\Call of Duty").is_some());
assert_eq!(entry("Battle.net", "Blizzard Entertainment", r"C:\Battle.net\Uninstall.exe", r"C:\Program Files (x86)\Battle.net"), None);
assert_eq!(entry("Notepad++", "Notepad++ Team", r"C:\npp\uninstall.exe", r"C:\npp"), None);
assert_eq!(entry("World of Warcraft", "Blizzard Entertainment", "x", ""), None, "no folder, nothing to match");
}
#[test]
@@ -419,18 +549,18 @@ mod tests {
let mut s = settings();
s.games = vec!["MyGame".into()];
s.not_games = vec!["Hades.exe".into()];
assert_eq!(classify(&fg(r"D:\x\mygame.exe", false, false, 0.0), false, &s), Some(Reason::Registered));
assert_eq!(classify(&fg(r"D:\Games\Hades\Hades.exe", true, true, 90.0), true, &s), None, "not a game, whatever it does");
assert_eq!(classify(&fg(r"D:\x\mygame.exe", false, false, 0.0), false, &s, &[]), Some(Reason::Registered));
assert_eq!(classify(&fg(r"D:\Games\Hades\Hades.exe", true, true, 90.0), true, &s, &[]), None, "not a game, whatever it does");
s.games = vec!["chrome".into()];
assert_eq!(classify(&fg(r"C:\c\chrome.exe", false, false, 0.0), false, &s), Some(Reason::Registered));
assert_eq!(classify(&fg(r"C:\c\chrome.exe", false, false, 0.0), false, &s, &[]), Some(Reason::Registered));
}
#[test]
fn game_mode_stays_until_the_game_ends_and_detection_off_turns_it_off() {
let mut s = settings();
let mut g = GameState::default();
let game = Snapshot { foreground: Some(fg(r"D:\Games\Hades\Hades.exe", true, true, 50.0)), d3d_fullscreen: false };
let desk = Snapshot { foreground: Some(fg(r"C:\Windows\explorer.exe", true, true, 0.0)), d3d_fullscreen: false };
let game = Snapshot { foreground: Some(fg(r"D:\Games\Hades\Hades.exe", true, true, 50.0)), d3d_fullscreen: false, installed: vec![] };
let desk = Snapshot { foreground: Some(fg(r"C:\Windows\explorer.exe", true, true, 0.0)), d3d_fullscreen: false, installed: vec![] };
let on = g.update(&game, &s, |_| true).expect("changed").expect("a game");
assert_eq!((on.name.as_str(), on.reason.clone()), ("Hades", Reason::Borderless));
// Alt+Tab to the desktop: still on while the game runs.