//! Game detection (`docs/v2/pc-features.md`, "게임 감지 기준"; admin.spec.md, "Game detection"): //! whether a game runs, from the foreground window, Windows' full-screen state and where the //! program lives. It drives the performance stages (M7). Nothing here looks at the game's screen. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use serde::Serialize; use crate::settings::GameSettings; /// How often the foreground is looked at. const EVERY: Duration = Duration::from_secs(2); /// A borderless window counts as a game when its process uses at least this much of the GPU's 3D /// engine (the M0 `games` check's threshold). const MIN_GPU_3D: f64 = 10.0; /// Programs that are never games: browsers (also the bot's Chrome), video players, the desktop, /// Discord, launchers' own windows and this app. const NOT_GAMES: &[&str] = &[ "chrome.exe", "msedge.exe", "firefox.exe", "opera.exe", "brave.exe", "whale.exe", "vivaldi.exe", "msedgewebview2.exe", "vlc.exe", "potplayer.exe", "potplayermini.exe", "potplayermini64.exe", "mpc-hc.exe", "mpc-hc64.exe", "mpc-be64.exe", "wmplayer.exe", "video.ui.exe", "explorer.exe", "discord.exe", "jarvis.exe", "steam.exe", "steamwebhelper.exe", "epicgameslauncher.exe", "epicwebhelper.exe", "riotclientservices.exe", "riot client.exe", "riotclientux.exe", "riotclientuxrender.exe", "leagueclient.exe", "leagueclientux.exe", "leagueclientuxrender.exe", "battle.net.exe", "agent.exe", ]; /// 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, unless that folder is one of the launcher's /// own (its client, shared runtimes, or a non-game app such as Wallpaper Engine, which runs all /// the time). Battle.net installs anywhere, so its games come from their install folders /// (`InstalledGame`). const LAUNCHERS: &[(&[&str], &str, &[&str])] = &[ (&["steamapps", "common"], "Steam", &["steamworks shared", "wallpaper_engine"]), (&["epic games"], "Epic", &["launcher", "epic online services"]), (&["riot games"], "Riot", &["riot client"]), ]; /// 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 { 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, own) 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)) { let folder = p[i + marker.len()]; return (!own.iter().any(|o| folder.eq_ignore_ascii_case(o))).then(|| (*launcher, folder.to_owned())); } } None } /// The foreground window as Windows reports it. #[derive(Debug, Clone, PartialEq)] pub struct Foreground { pub pid: u32, /// The program's full path. pub path: String, /// The window covers one monitor completely. pub covers_monitor: bool, /// No title bar and no sizing border. pub no_frame: bool, /// The process's use of the GPU's 3D engine, in percent. pub gpu_3d: f64, } #[derive(Debug, Clone, Default, PartialEq)] pub struct Snapshot { pub foreground: Option, /// 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, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(tag = "kind", content = "launcher", rename_all = "camelCase")] pub enum Reason { Fullscreen, Borderless, Launcher(&'static str), Registered, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Detected { #[serde(skip)] pub pid: u32, pub name: String, pub reason: Reason, } pub(crate) fn file_name(path: &str) -> String { path.rsplit(['\\', '/']).next().unwrap_or(path).to_lowercase() } /// Whether `name` (a program's file name, lower case) is in `list`; list entries may leave out ".exe". pub(crate) fn listed(name: &str, list: &[String]) -> bool { list.iter().map(|e| e.trim().to_lowercase()).any(|e| e == name || format!("{e}.exe") == name) } /// Why the foreground program is a game, or `None`. pub fn classify(fg: &Foreground, d3d_fullscreen: bool, s: &GameSettings, installed: &[InstalledGame]) -> Option { let name = file_name(&fg.path); if listed(&name, &s.not_games) { return None; } if listed(&name, &s.games) { return Some(Reason::Registered); } if NOT_GAMES.contains(&name.as_str()) { return None; } if let Some((launcher, _)) = launcher_game(&fg.path, installed) { return Some(Reason::Launcher(launcher)); } if d3d_fullscreen { return Some(Reason::Fullscreen); } (fg.covers_monitor && fg.no_frame && fg.gpu_3d >= MIN_GPU_3D).then_some(Reason::Borderless) } /// The first of these programs (full paths) that is a game by what it is: the person's list or a /// launcher's game folder. Used once as the services start, for games behind other windows (how a /// window looks is not known there, so those rules do not apply). pub fn game_running_among(paths: &[String], s: &GameSettings, installed: &[InstalledGame]) -> Option { paths.iter().find(|p| { let fg = Foreground { pid: 0, path: (*p).clone(), covers_monitor: false, no_frame: false, gpu_3d: 0.0 }; classify(&fg, false, s, installed).is_some() }).cloned() } /// 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(), } } /// The game mode: once a game is seen it stays until its process ends, also while another window /// is in front (the game still holds its video memory). #[derive(Default)] pub struct GameState { current: Option, } impl GameState { /// Look at `snap`; `alive(pid)` says whether a process still runs. Returns the new state when /// it changed. pub fn update(&mut self, snap: &Snapshot, s: &GameSettings, alive: impl Fn(u32) -> bool) -> Option> { if !s.detect { return self.current.take().map(|_| None); } if self.current.as_ref().is_some_and(|d| alive(d.pid)) { return None; } let next = snap.foreground.as_ref().and_then(|fg| { 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; } self.current = next.clone(); Some(next) } pub fn current(&self) -> Option<&Detected> { self.current.as_ref() } } /// Watches for games every two seconds while the services run (Windows only; elsewhere it never /// sees one). pub struct GameWatch { state: Arc>, /// A game process ran (in front or behind other windows) when the watch started. background: bool, stop: Arc, thread: Mutex>>, } impl GameWatch { /// Start watching; the first look happens before this returns, so a game already running is /// known at once (`on`). pub fn start(settings: GameSettings) -> Self { let (state, stop) = (Arc::new(Mutex::new(GameState::default())), Arc::new(AtomicBool::new(false))); let mut background = false; if cfg!(windows) && settings.detect { let snap = probe::Probe::new().snapshot(); state.lock().unwrap().update(&snap, &settings, probe::alive); if let Some(path) = game_running_among(&probe::process_paths(), &settings, &snap.installed) { // Which program, so a wrong one can be put on the "not games" list. crate::info_log!("game", "a game runs as the services start: {}", file_name(&path)); background = true; } } let thread = (cfg!(windows) && settings.detect).then(|| { let (state, stop) = (state.clone(), stop.clone()); std::thread::spawn(move || { let mut probe = probe::Probe::new(); while !stop.load(Ordering::SeqCst) { let snap = probe.snapshot(); let changed = state.lock().unwrap().update(&snap, &settings, probe::alive); match changed { Some(Some(d)) => { crate::info_log!("game", "game mode on: {} ({:?})", d.name, d.reason); } Some(None) => { crate::info_log!("game", "game mode off"); } None => {} } // Short sleeps, so a stop does not wait for the whole interval. for _ in 0..(EVERY.as_millis() / 100) { if stop.load(Ordering::SeqCst) { break; } std::thread::sleep(Duration::from_millis(100)); } } }) }); Self { state, background, stop, thread: Mutex::new(thread) } } /// Whether a game process ran when the watch started, also one behind other windows (found by /// what the program is: the person's list or a launcher's game folder). pub fn in_background_at_start(&self) -> bool { self.background } /// Whether game mode is on. pub fn on(&self) -> bool { self.state.lock().unwrap().current().is_some() } /// The game's name while game mode is on (PC control's anti-cheat sentence). pub fn name(&self) -> Option { self.state.lock().unwrap().current().map(|d| d.name.clone()) } /// The game for the dashboard: `{name, reason}` or null. pub fn view(&self) -> serde_json::Value { serde_json::json!(self.state.lock().unwrap().current()) } pub fn stop(&self) { self.stop.store(true, Ordering::SeqCst); if let Some(t) = self.thread.lock().unwrap().take() { let _ = t.join(); } } } impl Drop for GameWatch { /// A start that fails part way drops the watch: its thread ends too. fn drop(&mut self) { self.stop(); } } #[cfg(not(windows))] mod probe { use super::Snapshot; pub struct Probe; impl Probe { pub(super) fn new() -> Self { Probe } pub fn snapshot(&mut self) -> Snapshot { Snapshot::default() } } pub fn alive(_pid: u32) -> bool { false } pub fn process_paths() -> Vec { vec![] } } #[cfg(windows)] pub(crate) mod probe { 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::*; use windows_sys::Win32::System::Threading::{ OpenProcess, QueryFullProcessImageNameW, WaitForSingleObject, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, }; use windows_sys::Win32::UI::Shell::{SHQueryUserNotificationState, QUNS_RUNNING_D3D_FULL_SCREEN}; use windows_sys::Win32::UI::WindowsAndMessaging::*; /// The GPU 3D engine counters (PDH), kept open: the rate needs two samples. pub struct Probe { query: PDH_HQUERY, counter: PDH_HCOUNTER, installed: Vec, } impl Probe { pub(super) fn new() -> Self { let mut query: PDH_HQUERY = std::ptr::null_mut(); let mut counter: PDH_HCOUNTER = std::ptr::null_mut(); let path: Vec = "\\GPU Engine(*engtype_3D)\\Utilization Percentage".encode_utf16().chain(Some(0)).collect(); // SAFETY: plain PDH calls with out pointers to locals; a failure leaves zeros, which // `gpu_3d` treats as "no counters". unsafe { if PdhOpenQueryW(std::ptr::null(), 0, &mut query) == 0 { PdhAddEnglishCounterW(query, path.as_ptr(), 0, &mut counter); PdhCollectQueryData(query); } } Self { query, counter, installed: battle_net_games() } } /// 3D engine use of process `pid` in percent, summed over its engines. fn gpu_3d(&mut self, pid: u32) -> f64 { if self.query.is_null() || self.counter.is_null() { return 0.0; } let (mut size, mut count) = (0u32, 0u32); // SAFETY: the documented two-call pattern: the first call asks for the buffer size, // the second fills a buffer of that many bytes, aligned for the items. unsafe { if PdhCollectQueryData(self.query) != 0 { return 0.0; } PdhGetFormattedCounterArrayW(self.counter, PDH_FMT_DOUBLE, &mut size, &mut count, std::ptr::null_mut()); if size == 0 { return 0.0; } let mut buf = vec![0u64; (size as usize).div_ceil(8)]; let items = buf.as_mut_ptr() as *mut PDH_FMT_COUNTERVALUE_ITEM_W; if PdhGetFormattedCounterArrayW(self.counter, PDH_FMT_DOUBLE, &mut size, &mut count, items) != 0 { return 0.0; } let prefix = format!("pid_{pid}_"); (0..count as usize).map(|i| &*items.add(i)) .filter(|it| wide_str(it.szName).starts_with(&prefix)) .map(|it| it.FmtValue.Anonymous.doubleValue) .sum() } } pub fn snapshot(&mut self) -> Snapshot { // SAFETY: plain query. let mut state = 0; let d3d_fullscreen = unsafe { SHQueryUserNotificationState(&mut state) } == 0 && state == QUNS_RUNNING_D3D_FULL_SCREEN; 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, 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 { const KEY: &str = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; let key: Vec = KEY.encode_utf16().chain(Some(0)).collect(); let mut out: Vec = 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 = 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() { // SAFETY: the query this probe opened. unsafe { PdhCloseQuery(self.query) }; } } } unsafe fn wide_str(p: *const u16) -> String { if p.is_null() { return String::new(); } let mut n = 0; // SAFETY: PDH gives NUL-terminated names that live as long as the buffer. while unsafe { *p.add(n) } != 0 { n += 1; } String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(p, n) }) } /// The foreground window's process, program path, whether it covers its monitor and whether /// it has no title bar or sizing border. fn foreground() -> Option<(u32, String, bool, bool)> { // SAFETY: plain window queries on the foreground window; buffers are sized as passed and // the process handle is closed. unsafe { let hwnd: HWND = GetForegroundWindow(); if hwnd.is_null() { return None; } let mut pid = 0; GetWindowThreadProcessId(hwnd, &mut pid); let path = image_path(pid)?; let mut r: RECT = std::mem::zeroed(); GetWindowRect(hwnd, &mut r); let mut mi = MONITORINFO { cbSize: std::mem::size_of::() as u32, ..Default::default() }; GetMonitorInfoW(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mut mi); let m = mi.rcMonitor; let covers = r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom; let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; let no_frame = style & WS_CAPTION != WS_CAPTION && style & WS_THICKFRAME == 0; Some((pid, path, covers, no_frame)) } } /// Process `pid`'s program path. pub(crate) fn image_path(pid: u32) -> Option { // SAFETY: a query-only handle, closed at once; the buffer is sized as passed. unsafe { let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); if h.is_null() { return None; } let mut buf = [0u16; 1024]; let mut len = buf.len() as u32; let ok = QueryFullProcessImageNameW(h, PROCESS_NAME_WIN32, buf.as_mut_ptr(), &mut len) != 0; CloseHandle(h); ok.then(|| String::from_utf16_lossy(&buf[..len as usize])) } } /// Every running program's path this user may read. pub fn process_paths() -> Vec { use windows_sys::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS, }; let mut out = vec![]; // SAFETY: a process snapshot walked with a sized entry, then closed. unsafe { let snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if snap == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE { return out; } let mut e: PROCESSENTRY32W = std::mem::zeroed(); e.dwSize = std::mem::size_of::() as u32; let mut more = Process32FirstW(snap, &mut e) != 0; while more { if let Some(p) = image_path(e.th32ProcessID) { out.push(p); } more = Process32NextW(snap, &mut e) != 0; } CloseHandle(snap); } out } /// Whether process `pid` still runs. pub fn alive(pid: u32) -> bool { // SAFETY: a handle only to wait on, closed at once. unsafe { let h = OpenProcess(PROCESS_SYNCHRONIZE, 0, pid); if h.is_null() { return false; } let running = WaitForSingleObject(h, 0) == WAIT_TIMEOUT; CloseHandle(h); running } } } #[cfg(test)] mod tests { use super::*; fn settings() -> GameSettings { GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false } } fn fg(path: &str, covers: bool, no_frame: bool, gpu: f64) -> Foreground { Foreground { pid: 7, path: path.into(), covers_monitor: covers, no_frame, gpu_3d: gpu } } #[test] 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)); // 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); // A maximised program has a title bar. 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); // Exclusive full screen. 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!(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!(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!(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] fn a_game_running_in_the_background_is_found_by_its_program() { let s = settings(); let wow = InstalledGame { dir: r"D:\Games\World of Warcraft".into(), name: "World of Warcraft".into(), launcher: "Battle.net" }; // Behind other windows: only what the program is (where it lives, or the person's list). assert_eq!(game_running_among(&[r"C:\Windows\explorer.exe".into(), r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()], &s, &[]), Some(r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()), "the program found, for the log"); assert!(game_running_among(&[r"D:\Games\World of Warcraft\_retail_\Wow.exe".into()], &s, &[wow]).is_some()); assert!(game_running_among(&[r"C:\Windows\explorer.exe".into(), r"C:\Riot Games\Riot Client\RiotClientServices.exe".into(), r"C:\Program Files\Google\Chrome\Application\chrome.exe".into()], &s, &[]).is_none(), "launchers and browsers are not games"); let mut mine = settings(); mine.games = vec!["mygame".into()]; assert!(game_running_among(&[r"D:\x\MyGame.exe".into()], &mine, &[]).is_some()); mine.not_games = vec!["VALORANT.exe".into()]; assert!(game_running_among(&[r"C:\Riot Games\VALORANT\live\VALORANT.exe".into()], &mine, &[]).is_none()); } #[test] fn programs_in_a_launchers_own_folders_are_not_games() { let s = settings(); // Always running on the game PC (2026-11-17): Wallpaper Engine is a Steam app, and the Riot // client's crash handler sits in the client's folder. for p in [r"C:\Program Files (x86)\Steam\steamapps\common\wallpaper_engine\wallpaper64.exe", r"C:\Program Files (x86)\Steam\steamapps\common\Steamworks Shared\_CommonRedist\vcredist\x.exe", r"C:\Riot Games\Riot Client\RiotClientCrashHandler.exe", r"C:\Program Files\Epic Games\Launcher\Portal\Binaries\Win64\EpicGamesLauncher.exe", r"C:\Program Files (x86)\Epic Games\Epic Online Services\service\EpicOnlineServices.exe"] { assert_eq!(classify(&fg(p, false, false, 0.0), false, &s, &[]), None, "{p}"); } assert_eq!(game_running_among(&[r"C:\Riot Games\Riot Client\RiotClientCrashHandler.exe".into(), r"C:\Program Files (x86)\Steam\steamapps\common\wallpaper_engine\wallpaper64.exe".into()], &s, &[]), None); // The games beside them still are. assert_eq!(classify(&fg(r"C:\Program Files\Epic Games\Fortnite\FortniteClient.exe", false, false, 0.0), false, &s, &[]), Some(Reason::Launcher("Epic"))); } #[test] fn the_persons_lists_come_first() { 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"); s.games = vec!["chrome".into()]; 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, 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. assert_eq!(g.update(&desk, &s, |_| true), None); assert!(g.current().is_some()); // The game ended: off. assert_eq!(g.update(&desk, &s, |_| false), Some(None)); assert_eq!(g.update(&desk, &s, |_| false), None, "no change, no event"); // Detection off: nothing, and a game on turns off. g.update(&game, &s, |_| true); s.detect = false; assert_eq!(g.update(&game, &s, |_| true), Some(None)); assert_eq!(g.update(&game, &s, |_| true), None); } #[test] fn the_dashboard_gets_the_name_and_the_reason() { let d = Detected { pid: 1, name: "VALORANT".into(), reason: Reason::Launcher("Riot") }; assert_eq!(serde_json::to_value(&d).unwrap(), serde_json::json!({"name": "VALORANT", "reason": {"kind": "launcher", "launcher": "Riot"}})); assert_eq!(serde_json::to_value(Reason::Borderless).unwrap(), serde_json::json!({"kind": "borderless"})); } }