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

@@ -338,14 +338,19 @@ elsewhere it never sees a game). It never looks at the game's screen.
most 100 names, no folders. Read when the services start. most 100 names, no folders. Read when the services start.
- The foreground program is a game, in this order: in `notGames`: no; in `games`: yes - The foreground program is a game, in this order: in `notGames`: no; in `games`: yes
(`registered`); a browser (also the bot's Chrome), video player, the desktop, Discord, a (`registered`); a browser (also the bot's Chrome), video player, the desktop, Discord, a
launcher's own window or this app: no; under a launcher's game folder (`\steamapps\common\`, launcher's own window or this app: no; under a launcher's game folder (the folder after
`\epic games\`, `\riot games\`, `\battle.net\`): yes (`launcher`, with the launcher's name); `steamapps\common`, `Epic Games` or `Riot Games`) or inside a Battle.net game's install folder:
yes (`launcher`, with the launcher's name). Battle.net installs anywhere, so its games come from
the machine's uninstall entries (64- and 32-bit), read when the watch starts: entries removed by
its "Blizzard Uninstaller" or published by Blizzard Entertainment, with an install folder, not
Battle.net itself. Paths are compared part by part (folder names, ASCII case ignored), never cut by
byte positions, so any letters in a path are fine;
Windows reports a full-screen Direct3D program (`fullscreen`): yes; its window covers one monitor Windows reports a full-screen Direct3D program (`fullscreen`): yes; its window covers one monitor
completely, has no title bar or sizing border, and its process uses at least 10% of the GPU's 3D completely, has no title bar or sizing border, and its process uses at least 10% of the GPU's 3D
engine (`borderless`, the M0 check's rule): yes. engine (`borderless`, the M0 check's rule): yes.
- Once seen, game mode stays until that game's process ends, also while another window is in - Once seen, game mode stays until that game's process ends, also while another window is in
front; with `detect` off it is off. The name is the game's folder under the launcher folder, else front; with `detect` off it is off. The name is the game's folder under the launcher folder, else
the program's name without ".exe". The `game` log tab gets "game mode on: name (reason)" and the program's name without ".exe" (a Battle.net game: its uninstall entry's name). The `game` log tab gets "game mode on: name (reason)" and
"game mode off". "game mode off".
## LLM (`app/src/strata.rs`) ## LLM (`app/src/strata.rs`)
@@ -540,10 +545,12 @@ settings folder and the next install giving one working device, the monitor off
while the bot browser runs and off after, one Chrome window there filling the work area and holding while the bot browser runs and off after, one Chrome window there filling the work area and holding
the bot's tab, the focus staying in the program the user types into, no taskbar button, no Chrome the bot's tab, the focus staying in the program the user types into, no taskbar button, no Chrome
left after the stop, and the uninstall leaving no device, driver package, registry key or settings left after the stop, and the uninstall leaving no device, driver package, registry key or settings
folder. Game detection (`tests/game_watch.rs`): a program started from a Steam game folder turns folder. Game detection (`tests/game_watch.rs`): a program started from a Steam game folder (also under
game mode on with the folder's name and off once it ends. On every system: game detection's rules a path with non-ASCII letters) or from a Battle.net game's install folder (a test uninstall entry)
turns game mode on with its name and off once it ends. On every system: game detection's rules
(a borderless game, a maximised program, a browser's full-screen video, exclusive full screen, (a borderless game, a maximised program, a browser's full-screen video, exclusive full screen,
launcher folders and their own windows, the person's lists first, staying on until the game ends, launcher folders and their own windows, Battle.net games by install folder and their uninstall
entries, non-ASCII paths, the person's lists first, staying on until the game ends,
detection off) and its settings. A removal forgets the driver only when no device is left and the package detection off) and its settings. A removal forgets the driver only when no device is left and the package
is gone or was not in the store; a failed install forgets it only under the same rule (and never is gone or was not in the store; a failed install forgets it only under the same rule (and never
when it was ours before), reporting both reasons otherwise; a leftover offers removal; driver tasks refused while the services start, and a start (and a when it was ours before), reporting both reasons otherwise; a leftover offers removal; driver tasks refused while the services start, and a start (and a

View File

@@ -27,14 +27,59 @@ const NOT_GAMES: &[&str] = &[
"leagueclientuxrender.exe", "battle.net.exe", "agent.exe", "leagueclientuxrender.exe", "battle.net.exe", "agent.exe",
]; ];
/// Launcher game folders: a program under one counts as a game whatever its window looks like. /// Launcher game folders, as the path parts before the game's own folder: a program under one
const LAUNCHERS: &[(&str, &str)] = &[ /// counts as a game whatever its window looks like. Battle.net installs anywhere, so its games come
("\\steamapps\\common\\", "Steam"), /// from their install folders (`InstalledGame`).
("\\epic games\\", "Epic"), const LAUNCHERS: &[(&[&str], &str)] = &[
("\\riot games\\", "Riot"), (&["steamapps", "common"], "Steam"),
("\\battle.net\\", "Battle.net"), (&["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. /// The foreground window as Windows reports it.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct Foreground { pub struct Foreground {
@@ -54,6 +99,8 @@ pub struct Snapshot {
pub foreground: Option<Foreground>, pub foreground: Option<Foreground>,
/// Windows says a full-screen Direct3D program runs (exclusive full screen). /// Windows says a full-screen Direct3D program runs (exclusive full screen).
pub d3d_fullscreen: bool, pub d3d_fullscreen: bool,
/// Games installed outside a launcher's game folder (Battle.net).
pub installed: Vec<InstalledGame>,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[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`. /// 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); let name = file_name(&fg.path);
if listed(&name, &s.not_games) { if listed(&name, &s.not_games) {
return None; return None;
@@ -94,8 +141,7 @@ pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings) -> Opti
if NOT_GAMES.contains(&name.as_str()) { if NOT_GAMES.contains(&name.as_str()) {
return None; return None;
} }
let path = fg.path.to_lowercase().replace('/', "\\"); if let Some((launcher, _)) = launcher_game(&fg.path, installed) {
if let Some((_, launcher)) = LAUNCHERS.iter().find(|(dir, _)| path.contains(dir)) {
return Some(Reason::Launcher(launcher)); return Some(Reason::Launcher(launcher));
} }
if d3d_fullscreen { 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) (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 /// A game's name for the dashboard: its name from the launcher (the folder under a launcher's game
/// name without ".exe". /// folder, or an installed game's name), else the program's name without ".exe".
pub fn display_name(path: &str) -> String { pub fn game_name(path: &str, installed: &[InstalledGame]) -> String {
let lower = path.to_lowercase().replace('/', "\\"); if let Some((_, name)) = launcher_game(path, installed) {
for (dir, _) in LAUNCHERS { return name;
if let Some(i) = lower.find(dir) { }
let rest = &path[i + dir.len()..]; let name = parts(path).last().copied().unwrap_or(path);
if let Some(folder) = rest.split(['\\', '/']).next().filter(|f| !f.is_empty()) { match name.len().checked_sub(4) {
return folder.to_owned(); 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 /// 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; return None;
} }
let next = snap.foreground.as_ref().and_then(|fg| { 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 { if next == self.current {
return None; return None;
@@ -228,7 +272,11 @@ mod probe {
#[cfg(windows)] #[cfg(windows)]
mod probe { 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::Foundation::{CloseHandle, HWND, RECT, WAIT_TIMEOUT};
use windows_sys::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST}; use windows_sys::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST};
use windows_sys::Win32::System::Performance::*; use windows_sys::Win32::System::Performance::*;
@@ -243,6 +291,7 @@ mod probe {
pub struct Probe { pub struct Probe {
query: PDH_HQUERY, query: PDH_HQUERY,
counter: PDH_HCOUNTER, counter: PDH_HCOUNTER,
installed: Vec<InstalledGame>,
} }
impl Probe { impl Probe {
@@ -258,7 +307,7 @@ mod probe {
PdhCollectQueryData(query); PdhCollectQueryData(query);
} }
} }
Self { query, counter } Self { query, counter, installed: battle_net_games() }
} }
/// 3D engine use of process `pid` in percent, summed over its engines. /// 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)| { let foreground = foreground().map(|(pid, path, covers_monitor, no_frame)| {
Foreground { pid, path, covers_monitor, no_frame, gpu_3d: self.gpu_3d(pid) } 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 { impl Drop for Probe {
fn drop(&mut self) { fn drop(&mut self) {
if !self.query.is_null() { 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() { fn a_borderless_game_is_a_game_and_a_maximised_program_or_video_is_not() {
let s = settings(); let s = settings();
// A borderless game outside any launcher folder (the M0 check: covers, no frame, GPU >= 10%). // 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. // 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. // 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. // 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. // 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] #[test]
fn launcher_folders_make_a_game_whatever_the_window_and_name_it_by_its_folder() { fn launcher_folders_make_a_game_whatever_the_window_and_name_it_by_its_folder() {
let s = settings(); let s = settings();
let valorant = r"C:\Riot Games\VALORANT\live\ShooterGame\Binaries\Win64\VALORANT-Win64-Shipping.exe"; 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!(classify(&fg(valorant, false, false, 0.0), false, &s, &[]), Some(Reason::Launcher("Riot")));
assert_eq!(display_name(valorant), "VALORANT"); assert_eq!(game_name(valorant, &[]), "VALORANT");
let steam = r"D:\SteamLibrary\steamapps\common\Stardew Valley\Stardew Valley.exe"; 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!(classify(&fg(steam, false, false, 0.0), false, &s, &[]), Some(Reason::Launcher("Steam")));
assert_eq!(display_name(steam), "Stardew Valley"); assert_eq!(game_name(steam, &[]), "Stardew Valley");
// The launchers' own windows are not games. // 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!(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!(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] #[test]
@@ -419,18 +549,18 @@ mod tests {
let mut s = settings(); let mut s = settings();
s.games = vec!["MyGame".into()]; s.games = vec!["MyGame".into()];
s.not_games = vec!["Hades.exe".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:\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:\Games\Hades\Hades.exe", true, true, 90.0), true, &s, &[]), None, "not a game, whatever it does");
s.games = vec!["chrome".into()]; 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] #[test]
fn game_mode_stays_until_the_game_ends_and_detection_off_turns_it_off() { fn game_mode_stays_until_the_game_ends_and_detection_off_turns_it_off() {
let mut s = settings(); let mut s = settings();
let mut g = GameState::default(); 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 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 }; 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"); let on = g.update(&game, &s, |_| true).expect("changed").expect("a game");
assert_eq!((on.name.as_str(), on.reason.clone()), ("Hades", Reason::Borderless)); assert_eq!((on.name.as_str(), on.reason.clone()), ("Hades", Reason::Borderless));
// Alt+Tab to the desktop: still on while the game runs. // Alt+Tab to the desktop: still on while the game runs.

View File

@@ -1,6 +1,8 @@
//! Game detection on Windows (admin.spec.md, "Game detection"): a program started from a launcher's //! Game detection on Windows (admin.spec.md, "Game detection"): a program started from a launcher's
//! game folder turns game mode on with the folder's name, and off once it ends. Runs only with //! game folder turns game mode on with the folder's name, and off once it ends. Runs only with
//! `JARVIS_TEST_GAME_EXE=<a windowed program under ...\steamapps\common\<Game>\>`; elsewhere it skips. //! `JARVIS_TEST_GAME_EXE=<a windowed program under ...\steamapps\common\<Game>\>`; elsewhere it skips.
//! For a game installed elsewhere (Battle.net) also set `JARVIS_TEST_GAME_LAUNCHER=Battle.net` and
//! `JARVIS_TEST_GAME_NAME=<its uninstall entry's name>`.
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@@ -31,7 +33,9 @@ fn a_launcher_game_turns_game_mode_on_until_it_ends() {
let on = wait_for(&w, |v| !v.is_null(), 15); let on = wait_for(&w, |v| !v.is_null(), 15);
eprintln!("on after {:?}: {on}", t0.elapsed()); eprintln!("on after {:?}: {on}", t0.elapsed());
let folder = std::path::Path::new(&exe).parent().unwrap().file_name().unwrap().to_string_lossy().into_owned(); let folder = std::path::Path::new(&exe).parent().unwrap().file_name().unwrap().to_string_lossy().into_owned();
assert_eq!(on, serde_json::json!({"name": folder, "reason": {"kind": "launcher", "launcher": "Steam"}})); let name = std::env::var("JARVIS_TEST_GAME_NAME").unwrap_or(folder);
let launcher = std::env::var("JARVIS_TEST_GAME_LAUNCHER").unwrap_or("Steam".into());
assert_eq!(on, serde_json::json!({"name": name, "reason": {"kind": "launcher", "launcher": launcher}}));
game.kill().unwrap(); game.kill().unwrap();
let _ = game.wait(); let _ = game.wait();
let t1 = Instant::now(); let t1 = Instant::now();

View File

@@ -12,7 +12,7 @@
|---|---| |---|---|
| 독점 전체화면 | Windows가 알려 주는 "전체화면 D3D 앱 실행 중" 상태로 감지합니다. | | 독점 전체화면 | Windows가 알려 주는 "전체화면 D3D 앱 실행 중" 상태로 감지합니다. |
| 테두리 없는 창 모드 (borderless) | 앞에 있는 창이 아래 세 조건을 모두 만족하면 게임으로 봅니다. 셋 다 맞아야 하므로 일반 프로그램을 최대화한 것과 구분됩니다. (1) 모니터 한 장을 빈틈없이 덮습니다. (2) 제목 표시줄·테두리가 없습니다. (3) 그 프로세스가 GPU 3D 엔진을 일정 수준 이상 씁니다. | | 테두리 없는 창 모드 (borderless) | 앞에 있는 창이 아래 세 조건을 모두 만족하면 게임으로 봅니다. 셋 다 맞아야 하므로 일반 프로그램을 최대화한 것과 구분됩니다. (1) 모니터 한 장을 빈틈없이 덮습니다. (2) 제목 표시줄·테두리가 없습니다. (3) 그 프로세스가 GPU 3D 엔진을 일정 수준 이상 씁니다. |
| 게임 폴더·목록 | Steam, Epic, Riot, Battle.net 게임 폴더에서 실행된 프로그램과 GUI에서 직접 등록한 게임은 창 모양과 상관없이 게임으로 봅니다. | | 게임 폴더·목록 | Steam, Epic, Riot, Battle.net 게임 폴더에서 실행된 프로그램과 GUI에서 직접 등록한 게임은 창 모양과 상관없이 게임으로 봅니다. Battle.net 게임은 아무 폴더에나 설치되므로 Windows에 등록된 설치 정보(프로그램 제거 목록)에서 설치 폴더를 찾습니다. |
| 게임이 아닌 것 | 브라우저 전체화면 영상, 동영상 플레이어, 바탕화면, 디스코드, 봇용 크롬은 제외합니다. 잘못 잡히는 프로그램은 "게임 아님" 목록에 넣습니다. | | 게임이 아닌 것 | 브라우저 전체화면 영상, 동영상 플레이어, 바탕화면, 디스코드, 봇용 크롬은 제외합니다. 잘못 잡히는 프로그램은 "게임 아님" 목록에 넣습니다. |
한 번 게임으로 감지되면 게임 프로세스가 끝날 때까지 게임 모드를 유지합니다. Alt+Tab으로 다른 창을 봐도 마찬가지입니다. 게임이 뒤에 있어도 VRAM은 계속 쓰기 때문입니다. 대시보드에는 "게임 모드: 켜짐 (게임 이름, 감지 이유)"를 표시합니다. 한 번 게임으로 감지되면 게임 프로세스가 끝날 때까지 게임 모드를 유지합니다. Alt+Tab으로 다른 창을 봐도 마찬가지입니다. 게임이 뒤에 있어도 VRAM은 계속 쓰기 때문입니다. 대시보드에는 "게임 모드: 켜짐 (게임 이름, 감지 이유)"를 표시합니다.

File diff suppressed because one or more lines are too long