From 43701bbadc83eafddc59a4d2ac5fa596d796fabc Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 14:32:16 +0100 Subject: [PATCH] [core] WIP: frames, detect, hotkey modules with tests; caps, docs, version 0.2.0 (fmt/clippy/wasm/android not yet run) --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 29 ++- crates/arena-core/src/detect.rs | 155 ++++++++++++++++ crates/arena-core/src/frames.rs | 119 ++++++++++++ crates/arena-core/src/hotkey.rs | 269 +++++++++++++++++++++++++++ crates/arena-core/src/lib.rs | 7 + crates/arena-core/src/limits.rs | 6 + crates/arena-core/tests/detect.rs | 293 ++++++++++++++++++++++++++++++ crates/arena-core/tests/frames.rs | 262 ++++++++++++++++++++++++++ crates/arena-core/tests/hotkey.rs | 186 +++++++++++++++++++ crates/arena-core/tests/purity.rs | 46 +++++ docs/FORMATS.md | 25 +++ 13 files changed, 1394 insertions(+), 7 deletions(-) create mode 100644 crates/arena-core/src/detect.rs create mode 100644 crates/arena-core/src/frames.rs create mode 100644 crates/arena-core/src/hotkey.rs create mode 100644 crates/arena-core/tests/detect.rs create mode 100644 crates/arena-core/tests/frames.rs create mode 100644 crates/arena-core/tests/hotkey.rs create mode 100644 crates/arena-core/tests/purity.rs diff --git a/Cargo.lock b/Cargo.lock index 90e5873..818c90f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "arena-core" -version = "0.1.1" +version = "0.2.0" dependencies = [ "proptest", "serde", diff --git a/Cargo.toml b/Cargo.toml index e1e2c3d..ced68ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.1.1" +version = "0.2.0" edition = "2024" license = "CPAL-1.0" repository = "https://gitea.marek-novak.cz/mnovak/ArenaPublic" diff --git a/README.md b/README.md index de5e084..d8c95ce 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # ArenaPublic The open core of Arena Domi, the Domi game library: pure Rust parsers for game launcher files (Steam -`libraryfolders.vdf` and `appmanifest_.acf`, Epic `.item`, GOG entries), the library model, and later the -frametime statistics and replay-ring logic. No I/O: inputs are bytes or values, outputs are data. Builds for -Windows, Android and WebAssembly. +`libraryfolders.vdf` and `appmanifest_.acf`, Epic `.item`, GOG entries), the library model, and the +overlay's pure logic (frametime statistics, game detection, the shortcut); later the replay-ring logic. No I/O: +inputs are bytes or values, outputs are data. Builds for Windows, Android and WebAssembly. ## Licence @@ -26,7 +26,7 @@ received them; from this commit on, the code is under CPAL-1.0. | Crate | Lib | What it holds | | :-- | :-- | :-- | -| `crates/arena-core` | `arena_core` | launcher parsers, `WinPath`, `GameId`, `Launch`, the `Game` / `Library` model, `merge` | +| `crates/arena-core` | `arena_core` | launcher parsers, `WinPath`, `GameId`, `Launch`, the `Game` / `Library` model, `merge`; for the overlay `frames`, `detect`, `hotkey` | ## `arena-core` in one screen @@ -73,8 +73,27 @@ match &game.launch { | `Game` | `{ id, source, title, install_dir, launch, cover }`; serde round trip validates every field | | `ParseError` | typed, `Display`, never carries input text | +For the overlay agent (0.2.0): + +```rust +use arena_core::{frames, detect::{self, Detection, How, Marks}, hotkey::{self, Hotkey}}; + +// Frametimes in ms → avg FPS (frames / time), 1 % and 0.1 % lows (nearest-rank percentile, capped at the +// average), stutters (>= 2.5 x the median of the 60 frames before and >= 25 ms). None for empty or bad input. +let st: Option = frames::stats(&frametimes_ms); + +// Launched by Arena > inside an install_dir (deepest wins) > marked by the user. Outside every install_dir and +// not marked: never a game. Whole path components, ignoring case. +let d: Option = detect::detect(&exe, launched_by_arena, &library.games, &marks); + +// "Ctrl+Shift+G" ⇄ Hotkey; refuses bare letters and Windows-reserved keys; Win32 values for RegisterHotKey. +let h: Hotkey = hotkey::parse("Ctrl+Shift+G")?; +let (fs_modifiers, vk) = (h.win32_modifiers(), h.virtual_key()); +``` + `Game`, `Library`, `GameId`, `WinPath` and `Launch` serialise with serde, and deserialising runs the same checks -as the parsers, so a tampered `library.json` cannot smuggle in a bad path or launch string. +as the parsers, so a tampered `library.json` cannot smuggle in a bad path or launch string. The same holds for `Marks` (a JSON +array of exe paths in the agent's `overlay.json`) and `Hotkey` (its text form in `settings.json`). Docs: [`docs/FORMATS.md`](docs/FORMATS.md) (what each parser accepts and refuses, every cap) and [`docs/PORTABILITY.md`](docs/PORTABILITY.md) (the target checks). diff --git a/crates/arena-core/src/detect.rs b/crates/arena-core/src/detect.rs new file mode 100644 index 0000000..158702f --- /dev/null +++ b/crates/arena-core/src/detect.rs @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: CPAL-1.0 +// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz + +//! Which running exe is a game, for the overlay agent. +//! +//! The agent hands in the foreground process's exe path (already a [`WinPath`]: absolute, no `..`, no UNC or +//! `\\?\`, so it cannot climb out of a folder), whether Arena launched it, the library and the user's marks. +//! [`detect`] applies three rules, first match wins: +//! +//! 1. **Launched**: Arena started it. Always a game; `game` is the library game whose folder holds the exe, if +//! any (a launcher stub or a Domi app may live elsewhere: the window's `launched` message says which game). +//! 2. **InstallDir**: the exe lies inside a game's `install_dir`, or is that game's own launch exe. The deepest +//! install folder wins (an expansion in a sub-folder beats the base game), then library order. +//! 3. **Marked**: the user said "This is a game" for exactly this exe ([`Marks`]); `game` is `None`. +//! +//! **An exe outside every `install_dir` is never auto-detected**: without Arena launching it or a mark, it is not a +//! game. Paths compare the way Windows does: ignoring case, `/` and `\` alike, on whole components, so +//! `C:\Games\Foo` never claims `C:\Games\FooBar\x.exe`. A drive root as an install folder (a manual game picked at +//! `D:\game.exe`) claims only that game's own exe, never the whole drive. + +use crate::error::ParseError; +use crate::id::GameId; +use crate::launch::Launch; +use crate::limits::MAX_MARKS; +use crate::model::Game; +use crate::path::WinPath; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// A detected game. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Detection { + /// The library game, when one is known. + pub game: Option, + /// Which rule matched. + pub how: How, +} + +/// Which rule detected the game (in JSON: `launched`, `install_dir`, `marked`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum How { + /// Arena launched it. + Launched, + /// It is inside a game's install folder (or is the game's launch exe). + InstallDir, + /// The user marked this exe as a game. + Marked, +} + +/// Detects whether `exe` is a game; see the [module docs](self) for the rules. +pub fn detect(exe: &WinPath, launched_by_arena: bool, library: &[Game], marked: &Marks) -> Option { + let in_library = find_game(exe, library); + if launched_by_arena { + return Some(Detection { game: in_library, how: How::Launched }); + } + if let Some(game) = in_library { + return Some(Detection { game: Some(game), how: How::InstallDir }); + } + marked.contains(exe).then_some(Detection { game: None, how: How::Marked }) +} + +/// The library game that owns `exe`: its own launch exe, else the deepest install folder that strictly contains it. +fn find_game(exe: &WinPath, library: &[Game]) -> Option { + let depth = exe.components().count(); + let mut best: Option<(usize, &GameId)> = None; + for game in library { + let own_exe = matches!(&game.launch, Launch::Exe { exe: e, .. } if e.eq_ignore_case(exe)); + let score = match &game.install_dir { + _ if own_exe => Some(usize::MAX), + Some(dir) => { + let d = dir.components().count(); + (d > 0 && d < depth && exe.starts_with(dir)).then_some(d) + } + None => None, + }; + if let Some(s) = score + && best.is_none_or(|(b, _)| s > b) + { + best = Some((s, &game.id)); + } + } + best.map(|(_, id)| id.clone()) +} + +/// The exes the user marked as games ("This is a game"), keyed by the normalised path ignoring case. +/// +/// Persisted in the agent's `overlay.json` as a JSON array of paths, sorted by the case-folded key, with the first +/// spelling kept. Loading checks every path as a [`WinPath`], folds spellings of the same exe into one, and refuses +/// more than [`crate::limits::MAX_MARKS`]. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "Vec", into = "Vec")] +pub struct Marks(BTreeMap); + +impl Marks { + /// No marks. + pub const fn new() -> Marks { + Marks(BTreeMap::new()) + } + + /// Marks `exe`. `Ok(true)` when it was new, `Ok(false)` when it was already marked (the first spelling stays), + /// `Err(TooMany("marks"))` when [`crate::limits::MAX_MARKS`] are already marked. + pub fn insert(&mut self, exe: WinPath) -> Result { + let key = exe.key(); + if self.0.contains_key(&key) { + return Ok(false); + } + if self.0.len() >= MAX_MARKS { + return Err(ParseError::TooMany("marks")); + } + self.0.insert(key, exe); + Ok(true) + } + + /// Unmarks `exe`; true when it was marked. + pub fn remove(&mut self, exe: &WinPath) -> bool { + self.0.remove(&exe.key()).is_some() + } + + /// True when `exe` is marked, in any spelling. + pub fn contains(&self, exe: &WinPath) -> bool { + self.0.contains_key(&exe.key()) + } + + /// The marked exes, sorted by the case-folded path. + pub fn iter(&self) -> impl Iterator { + self.0.values() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl TryFrom> for Marks { + type Error = ParseError; + + fn try_from(paths: Vec) -> Result { + let mut marks = Marks::new(); + for p in paths { + marks.insert(p)?; + } + Ok(marks) + } +} + +impl From for Vec { + fn from(m: Marks) -> Vec { + m.0.into_values().collect() + } +} diff --git a/crates/arena-core/src/frames.rs b/crates/arena-core/src/frames.rs new file mode 100644 index 0000000..08ea869 --- /dev/null +++ b/crates/arena-core/src/frames.rs @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: CPAL-1.0 +// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz + +//! Frametime statistics for the overlay's performance widget. +//! +//! Input: the frametimes of one window of play, in milliseconds, in the order the frames were presented (the +//! agent gets them from PresentMon). Output: [`FrameStats`]. Definitions: +//! +//! - **avg FPS** = frames / total time (`frames / seconds`), not the mean of per-frame FPS. +//! - **1 % low** and **0.1 % low** = the FPS of the frametime at the 99th and the 99.9th percentile +//! (`1000 / frametime_ms`). The percentile is nearest-rank: the frametimes sorted ascending, the value at rank +//! `ceil(p × frames)` (1-based). Each low is capped at avg FPS: when a few very long frames sit above the +//! percentile, the percentile frame can be faster than the average, and a "low" above the average would mislead. +//! So `low_0_1 <= low_1 <= avg_fps` always. +//! - **stutter** = a frametime ≥ 2.5 × the median of the 60 frames before it **and** ≥ 25 ms. Both bounds are +//! inclusive. The first 60 frames have no full history and are never stutters. The median of the 60 is the mean +//! of the 30th and 31st smallest. +//! +//! Refused (`None`): an empty series, more than [`crate::limits::MAX_FRAMES`] frametimes, any NaN, infinite or +//! negative frametime, and a series with no time in it (all zero). A zero frametime is allowed (`-0.0` counts as +//! zero); it only adds a frame. + +use crate::limits::MAX_FRAMES; +use serde::{Deserialize, Serialize}; + +/// Frames of history the stutter rule looks back over. +const STUTTER_WINDOW: usize = 60; +/// A stutter is at least this many times the median of the window ... +const STUTTER_RATIO: f64 = 2.5; +/// ... and at least this long, in milliseconds. +const STUTTER_MIN_MS: f64 = 25.0; + +/// Statistics over one series of frametimes; see the [module docs](self) for the definitions. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct FrameStats { + /// Frames per second over the whole series: `frames / seconds`. + pub avg_fps: f64, + /// The 1 % low: the FPS of the 99th-percentile frametime, at most `avg_fps`. + pub low_1: f64, + /// The 0.1 % low: the FPS of the 99.9th-percentile frametime, at most `low_1`. + pub low_0_1: f64, + /// How many frames were stutters. + pub stutters: u32, + /// How many frametimes the series had. + pub frames: u32, + /// The sum of the frametimes, in seconds. + pub seconds: f64, +} + +/// The statistics of `frametimes_ms`, or `None` when the series is refused (see the [module docs](self)). +pub fn stats(frametimes_ms: &[f32]) -> Option { + let n = frametimes_ms.len(); + if n == 0 || n > MAX_FRAMES { + return None; + } + if frametimes_ms.iter().any(|f| !f.is_finite() || *f < 0.0) { + return None; + } + let frames = u32::try_from(n).ok()?; + let total_ms: f64 = frametimes_ms.iter().map(|&f| f64::from(f)).sum(); + if total_ms <= 0.0 || !total_ms.is_finite() { + return None; + } + let seconds = total_ms / 1000.0; + let avg_fps = f64::from(frames) / seconds; + + let mut sorted = frametimes_ms.to_vec(); + sorted.sort_unstable_by(f32::total_cmp); + let low_1 = fps(percentile(&sorted, 99, 100)?).min(avg_fps); + let low_0_1 = fps(percentile(&sorted, 999, 1000)?).min(low_1); + + let stats = FrameStats { avg_fps, low_1, low_0_1, stutters: stutters(frametimes_ms), frames, seconds }; + [stats.avg_fps, stats.low_1, stats.low_0_1, stats.seconds].iter().all(|v| v.is_finite()).then_some(stats) +} + +/// The FPS of one frametime; a zero frametime is infinitely fast (then capped by the caller). +fn fps(frametime_ms: f32) -> f64 { + let ms = f64::from(frametime_ms); + if ms > 0.0 { 1000.0 / ms } else { f64::INFINITY } +} + +/// Nearest-rank percentile `num / den` of an ascending, non-empty slice: the value at rank `ceil(n × num / den)`. +/// Integer arithmetic, so 99 % of 100 frames is exactly rank 99. +fn percentile(sorted: &[f32], num: u64, den: u64) -> Option { + let n = u64::try_from(sorted.len()).ok()?; + let rank = (n * num).div_ceil(den).max(1); + sorted.get(usize::try_from(rank - 1).ok()?).copied() +} + +/// Counts stutters with a sorted sliding window of the previous [`STUTTER_WINDOW`] frametimes. +fn stutters(frametimes_ms: &[f32]) -> u32 { + let mut window: Vec = Vec::with_capacity(STUTTER_WINDOW + 1); + let mut count: u32 = 0; + for (i, &ft) in frametimes_ms.iter().enumerate() { + if window.len() == STUTTER_WINDOW { + let ms = f64::from(ft); + if ms >= STUTTER_MIN_MS && median(&window).is_some_and(|m| ms >= STUTTER_RATIO * m) { + count = count.saturating_add(1); + } + // Slide: drop the frame that leaves the window. + if let Some(&old) = i.checked_sub(STUTTER_WINDOW).and_then(|j| frametimes_ms.get(j)) { + if let Ok(at) = window.binary_search_by(|w| w.total_cmp(&old)) { + window.remove(at); + } + } + } + let at = window.partition_point(|w| w.total_cmp(&ft).is_lt()); + window.insert(at, ft); + } + count +} + +/// The median of an ascending window of even length: the mean of the two middle values. +fn median(sorted: &[f32]) -> Option { + let half = sorted.len() / 2; + let lo = f64::from(*sorted.get(half.checked_sub(1)?)?); + let hi = f64::from(*sorted.get(half)?); + Some((lo + hi) / 2.0) +} diff --git a/crates/arena-core/src/hotkey.rs b/crates/arena-core/src/hotkey.rs new file mode 100644 index 0000000..53a46ff --- /dev/null +++ b/crates/arena-core/src/hotkey.rs @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: CPAL-1.0 +// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz + +//! The overlay shortcut: `Ctrl+Shift+G` and friends, as text in `settings.json` and as Win32 values. +//! +//! Grammar: modifiers then one key, joined by `+`; spaces around each part are ignored; names ignore case. +//! +//! - Modifiers: `Ctrl`, `Alt`, `Shift`, `Win`, each at most once, in any order. +//! - Key (last): a letter `A`–`Z`, a digit `0`–`9`, or `F1`–`F24` (no leading zero). +//! +//! Refused: +//! +//! - A letter or digit with no modifier, or with Shift alone: that is typing, not a shortcut +//! ([`HotkeyError::NoModifier`]). A function key alone is allowed. +//! - Keys Windows reserves ([`HotkeyError::Reserved`]): `Ctrl+Alt+Del` (the secure attention sequence, with any +//! other modifiers too), `Ctrl+Shift+Esc` (Task Manager), `Win+L` (lock), `Alt+F4` (closes the active window) and +//! `F12` with any modifiers (Windows keeps it for the debugger, so `RegisterHotKey` must not take it). +//! `Del` and `Esc` are recognised only to name these; they are not keys a shortcut may use. +//! +//! [`Display`](std::fmt::Display) writes the canonical form: `Ctrl`, `Alt`, `Shift`, `Win` in that order, then the +//! key, uppercase, so `parse(&h.to_string()) == Ok(h)`. Whether Windows lets Arena register a valid shortcut (it +//! may be taken, as `Win+G` is by the Game Bar) is only known at `RegisterHotKey` time, in the agent. + +use crate::limits::MAX_HOTKEY; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::str::FromStr; + +/// The modifier keys of a shortcut. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Modifiers { + pub ctrl: bool, + pub alt: bool, + pub shift: bool, + pub win: bool, +} + +/// The non-modifier key of a shortcut. [`Hotkey::new`] checks the value: `Letter` holds `'A'..='Z'`, `Digit` +/// `0..=9`, `F` `1..=24`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Key { + Letter(char), + Digit(u8), + F(u8), +} + +impl Key { + fn is_valid(self) -> bool { + match self { + Key::Letter(c) => c.is_ascii_uppercase(), + Key::Digit(d) => d <= 9, + Key::F(n) => (1..=24).contains(&n), + } + } + + /// The Win32 virtual-key code (`VK_*`): `0x41`–`0x5A` for letters, `0x30`–`0x39` for digits, `0x70`–`0x87` + /// for `F1`–`F24`. + fn virtual_key(self) -> u32 { + match self { + Key::Letter(c) => u32::from(c), + Key::Digit(d) => 0x30 + u32::from(d), + Key::F(n) => 0x6F + u32::from(n), + } + } +} + +/// A checked overlay shortcut; see the [module docs](self). The default is `Ctrl+Shift+G`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct Hotkey { + modifiers: Modifiers, + key: Key, +} + +/// Why a shortcut was refused. Never carries input text. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum HotkeyError { + /// Nothing but spaces. + Empty, + /// Longer than [`crate::limits::MAX_HOTKEY`] bytes. + TooLong, + /// An empty part: a leading, trailing or doubled `+`. + Malformed, + /// A part before the key is not `Ctrl`, `Alt`, `Shift` or `Win`. + UnknownModifier, + /// The same modifier twice. + DuplicateModifier, + /// Only modifiers, no key. + MissingKey, + /// The key is not a letter, a digit or `F1`–`F24`. + UnknownKey, + /// A letter or digit without Ctrl, Alt or Win. + NoModifier, + /// A combination Windows keeps for itself. + Reserved, +} + +impl fmt::Display for HotkeyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + HotkeyError::Empty => "the shortcut is empty", + HotkeyError::TooLong => "the shortcut is too long", + HotkeyError::Malformed => "the shortcut has an empty part", + HotkeyError::UnknownModifier => "modifiers are Ctrl, Alt, Shift and Win", + HotkeyError::DuplicateModifier => "a modifier appears twice", + HotkeyError::MissingKey => "the shortcut has no key", + HotkeyError::UnknownKey => "the key must be a letter, a digit or F1 to F24", + HotkeyError::NoModifier => "a letter or digit needs Ctrl, Alt or Win", + HotkeyError::Reserved => "Windows reserves this shortcut", + }) + } +} + +impl std::error::Error for HotkeyError {} + +impl Hotkey { + /// Checks a shortcut built from parts, with the same rules as [`parse`]. + pub fn new(modifiers: Modifiers, key: Key) -> Result { + if !key.is_valid() { + return Err(HotkeyError::UnknownKey); + } + let bare = matches!(key, Key::Letter(_) | Key::Digit(_)); + if bare && !(modifiers.ctrl || modifiers.alt || modifiers.win) { + return Err(HotkeyError::NoModifier); + } + let only = |m: Modifiers| modifiers == m; + let none = Modifiers::default(); + let reserved = key == Key::F(12) + || (key == Key::Letter('L') && only(Modifiers { win: true, ..none })) + || (key == Key::F(4) && only(Modifiers { alt: true, ..none })); + if reserved { + return Err(HotkeyError::Reserved); + } + Ok(Hotkey { modifiers, key }) + } + + pub fn modifiers(&self) -> Modifiers { + self.modifiers + } + + pub fn key(&self) -> Key { + self.key + } + + /// The `fsModifiers` for `RegisterHotKey`: `MOD_ALT` 0x1, `MOD_CONTROL` 0x2, `MOD_SHIFT` 0x4, `MOD_WIN` 0x8. + /// (`MOD_NOREPEAT` is the caller's choice.) + pub fn win32_modifiers(&self) -> u32 { + let m = self.modifiers; + u32::from(m.alt) | (u32::from(m.ctrl) << 1) | (u32::from(m.shift) << 2) | (u32::from(m.win) << 3) + } + + /// The `vk` for `RegisterHotKey`. + pub fn virtual_key(&self) -> u32 { + self.key.virtual_key() + } +} + +impl Default for Hotkey { + /// `Ctrl+Shift+G`. + fn default() -> Hotkey { + Hotkey { modifiers: Modifiers { ctrl: true, alt: false, shift: true, win: false }, key: Key::Letter('G') } + } +} + +/// Parses a shortcut such as `"Ctrl+Shift+G"`; see the [module docs](self) for the grammar and refusals. +pub fn parse(s: &str) -> Result { + if s.len() > MAX_HOTKEY { + return Err(HotkeyError::TooLong); + } + if s.trim_matches(' ').is_empty() { + return Err(HotkeyError::Empty); + } + let mut parts: Vec<&str> = s.split('+').map(|p| p.trim_matches(' ')).collect(); + if parts.iter().any(|p| p.is_empty()) { + return Err(HotkeyError::Malformed); + } + let key = parts.pop().ok_or(HotkeyError::Empty)?; + let mut m = Modifiers::default(); + for part in parts { + let slot = modifier(&mut m, part).ok_or(HotkeyError::UnknownModifier)?; + if *slot { + return Err(HotkeyError::DuplicateModifier); + } + *slot = true; + } + if modifier(&mut Modifiers::default(), key).is_some() { + return Err(HotkeyError::MissingKey); + } + // Named only to refuse them as reserved. + let ci = |name: &str| key.eq_ignore_ascii_case(name); + if ((ci("Del") || ci("Delete")) && m.ctrl && m.alt) || ((ci("Esc") || ci("Escape")) && m.ctrl && m.shift) { + return Err(HotkeyError::Reserved); + } + Hotkey::new(m, parse_key(key).ok_or(HotkeyError::UnknownKey)?) +} + +/// The flag in `m` that `name` sets, if it names a modifier. +fn modifier<'a>(m: &'a mut Modifiers, name: &str) -> Option<&'a mut bool> { + let ci = |n: &str| name.eq_ignore_ascii_case(n); + if ci("Ctrl") { + Some(&mut m.ctrl) + } else if ci("Alt") { + Some(&mut m.alt) + } else if ci("Shift") { + Some(&mut m.shift) + } else if ci("Win") { + Some(&mut m.win) + } else { + None + } +} + +fn parse_key(s: &str) -> Option { + let mut chars = s.chars(); + let first = chars.next()?; + let rest = chars.as_str(); + if rest.is_empty() { + return if first.is_ascii_alphabetic() { + Some(Key::Letter(first.to_ascii_uppercase())) + } else { + first.to_digit(10).and_then(|d| u8::try_from(d).ok()).map(Key::Digit) + }; + } + let canonical = !rest.starts_with('0') && rest.len() <= 2 && rest.bytes().all(|b| b.is_ascii_digit()); + if !first.eq_ignore_ascii_case(&'F') || !canonical { + return None; + } + let n: u8 = rest.parse().ok()?; + (1..=24).contains(&n).then_some(Key::F(n)) +} + +impl fmt::Display for Hotkey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let m = self.modifiers; + for (on, name) in [(m.ctrl, "Ctrl"), (m.alt, "Alt"), (m.shift, "Shift"), (m.win, "Win")] { + if on { + write!(f, "{name}+")?; + } + } + match self.key { + Key::Letter(c) => write!(f, "{c}"), + Key::Digit(d) => write!(f, "{d}"), + Key::F(n) => write!(f, "F{n}"), + } + } +} + +impl FromStr for Hotkey { + type Err = HotkeyError; + + fn from_str(s: &str) -> Result { + parse(s) + } +} + +impl TryFrom for Hotkey { + type Error = HotkeyError; + + fn try_from(s: String) -> Result { + parse(&s) + } +} + +impl From for String { + fn from(h: Hotkey) -> String { + h.to_string() + } +} diff --git a/crates/arena-core/src/lib.rs b/crates/arena-core/src/lib.rs index 3eb220e..6c36916 100644 --- a/crates/arena-core/src/lib.rs +++ b/crates/arena-core/src/lib.rs @@ -13,6 +13,9 @@ //! registry). [`merge`] dedupes the scans into one library. //! //! Launch strings are built by [`Launch::uri`] only from validated, parsed fields. +//! +//! For the overlay agent: [`frames`] (frametime statistics: average FPS, 1 % and 0.1 % lows, stutters), [`detect`] +//! (which running exe is a game, and the user's "This is a game" marks) and [`hotkey`] (the overlay shortcut). #![forbid(unsafe_code)] #![deny( @@ -35,6 +38,10 @@ mod path; mod text; pub mod vdf; +pub mod detect; +pub mod frames; +pub mod hotkey; + pub mod domi; pub mod epic; pub mod gog; diff --git a/crates/arena-core/src/limits.rs b/crates/arena-core/src/limits.rs index 5ef290d..ed6f25d 100644 --- a/crates/arena-core/src/limits.rs +++ b/crates/arena-core/src/limits.rs @@ -42,3 +42,9 @@ pub const MAX_URL: usize = 2048; pub const MAX_HOST: usize = 253; /// Most games one [`crate::merge`] call accepts over all scans; the rest are dropped. pub const MAX_GAMES: usize = 100_000; +/// Most frametimes one [`crate::frames::stats`] call accepts (about 73 minutes at 240 FPS); more is refused. +pub const MAX_FRAMES: usize = 1 << 20; +/// Most exes the user may mark as games ([`crate::detect::Marks`]). +pub const MAX_MARKS: usize = 4096; +/// Longest shortcut text [`crate::hotkey::parse`] accepts, in bytes (`Ctrl+Alt+Shift+Win+F24` is 22). +pub const MAX_HOTKEY: usize = 64; diff --git a/crates/arena-core/tests/detect.rs b/crates/arena-core/tests/detect.rs new file mode 100644 index 0000000..337714d --- /dev/null +++ b/crates/arena-core/tests/detect.rs @@ -0,0 +1,293 @@ +// SPDX-License-Identifier: CPAL-1.0 +// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz + +//! Game detection for the overlay: the three rules, Windows path matching, and the persisted marks. + +use arena_core::detect::{Detection, How, Marks, detect}; +use arena_core::{Game, GameId, Launch, ParseError, Source, WinPath, limits, manual}; +use proptest::prelude::*; + +fn p(s: &str) -> WinPath { + WinPath::parse(s).unwrap() +} + +fn steam(app: u32, title: &str, dir: &str) -> Game { + let id = GameId::new(Source::Steam, &app.to_string()).unwrap(); + Game { + id, + source: Source::Steam, + title: title.into(), + install_dir: Some(p(dir)), + launch: Launch::steam(app).unwrap(), + cover: None, + } +} + +fn domi(app: &str) -> Game { + Game { + id: GameId::new(Source::Domi, app).unwrap(), + source: Source::Domi, + title: app.into(), + install_dir: None, + launch: Launch::domi_link(app).unwrap(), + cover: None, + } +} + +fn library() -> Vec { + vec![ + steam(10, "Foo", r"C:\Games\Foo"), + steam(20, "FooBar", r"C:\Games\FooBar"), + steam(30, "Nested", r"C:\Games\Foo\Expansion"), + domi("lapilli"), + ] +} + +fn id(s: &str) -> Option { + Some(s.parse().unwrap()) +} + +fn found(game: &str, how: How) -> Option { + Some(Detection { game: id(game), how }) +} + +const NONE: &Marks = &Marks::new(); + +// --- Rule 1: an exe outside every install_dir is never auto-detected --- + +#[test] +fn outside_every_install_dir_is_not_detected() { + let lib = library(); + for exe in [ + r"C:\Windows\System32\notepad.exe", + r"C:\Games\foo.exe", + r"C:\Games\Fo\game.exe", + r"C:\Games\FooBarBaz\game.exe", + r"C:\Games\Foo Bar\game.exe", + r"D:\Games\Foo\game.exe", + r"C:\Program Files\Steam\steam.exe", + ] { + assert_eq!(detect(&p(exe), false, &lib, NONE), None, "{exe}"); + } + assert_eq!(detect(&p(r"C:\x.exe"), false, &[], NONE), None); +} + +#[test] +fn inside_an_install_dir_is_detected() { + let lib = library(); + assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), false, &lib, NONE), found("steam:10", How::InstallDir)); + assert_eq!(detect(&p(r"C:\Games\Foo\bin\x64\foo.exe"), false, &lib, NONE), found("steam:10", How::InstallDir)); + assert_eq!(detect(&p(r"C:\Games\FooBar\fb.exe"), false, &lib, NONE), found("steam:20", How::InstallDir)); +} + +#[test] +fn prefix_of_a_segment_never_matches() { + // C:\Games\Foo must not claim C:\Games\FooBar's exes, in either direction, whatever the order. + let only_foo = vec![steam(10, "Foo", r"C:\Games\Foo")]; + assert_eq!(detect(&p(r"C:\Games\FooBar\fb.exe"), false, &only_foo, NONE), None); + let only_foobar = vec![steam(20, "FooBar", r"C:\Games\FooBar")]; + assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), false, &only_foobar, NONE), None); + assert_eq!(detect(&p(r"C:\Games\Foo.exe"), false, &only_foo, NONE), None); +} + +#[test] +fn the_deepest_install_dir_wins() { + let lib = library(); + let exe = p(r"C:\Games\Foo\Expansion\exp.exe"); + assert_eq!(detect(&exe, false, &lib, NONE), found("steam:30", How::InstallDir)); + let mut rev = lib.clone(); + rev.reverse(); + assert_eq!(detect(&exe, false, &rev, NONE), found("steam:30", How::InstallDir)); +} + +#[test] +fn the_install_dir_itself_is_not_an_exe_inside_it() { + let lib = library(); + assert_eq!(detect(&p(r"C:\Games\FooBar"), false, &lib, NONE), None); +} + +#[test] +fn a_drive_root_install_dir_does_not_claim_the_whole_drive() { + // A manual game picked at D:\game.exe has the install folder D:\ — that must not make every exe on D: a game. + let g = manual::game(r"D:\game.exe", Some("Root game")).unwrap(); + assert_eq!(g.install_dir, Some(p(r"D:\"))); + let lib = vec![g.clone()]; + assert_eq!(detect(&p(r"D:\Tools\editor.exe"), false, &lib, NONE), None); + assert_eq!(detect(&p(r"D:\other.exe"), false, &lib, NONE), None); + // Its own exe is still found, through the game's launch exe. + assert_eq!(detect(&p(r"d:\GAME.EXE"), false, &lib, NONE), Some(Detection { game: Some(g.id), how: How::InstallDir })); +} + +#[test] +fn a_game_s_own_launch_exe_is_detected() { + let g = manual::game(r"E:\Old\Thing\thing.exe", None).unwrap(); + let lib = vec![g.clone()]; + assert_eq!(detect(&p(r"E:\Old\Thing\thing.exe"), false, &lib, NONE).map(|d| d.how), Some(How::InstallDir)); + assert_eq!(detect(&p(r"E:\Old\Thing\helper.exe"), false, &lib, NONE).and_then(|d| d.game), Some(g.id)); +} + +// --- Windows path rules --- + +#[test] +fn matching_ignores_case_and_separator_style() { + let lib = library(); + for exe in [r"c:\games\foo\foo.exe", r"C:\GAMES\FOO\FOO.EXE", "C:/Games/foo/Bin/foo.exe", r"c:\\Games\\\Foo\\x.exe"] + { + assert_eq!(detect(&p(exe), false, &lib, NONE), found("steam:10", How::InstallDir), "{exe}"); + } + let upper = vec![steam(10, "Foo", r"C:\GAMES\FOO")]; + assert_eq!(detect(&p(r"c:\games\foo\a.exe"), false, &upper, NONE), found("steam:10", How::InstallDir)); +} + +#[test] +fn non_ascii_case_folds_too() { + let lib = vec![steam(40, "Hra", r"C:\Hry\Žluťoučký Kůň")]; + assert_eq!(detect(&p(r"C:\HRY\ŽLUŤOUČKÝ KŮŇ\kun.exe"), false, &lib, NONE), found("steam:40", How::InstallDir)); +} + +#[test] +fn dot_dot_never_escapes() { + // A path with `..` cannot even be built, so `C:\Games\Foo\..\Other\x.exe` can never pass as inside Foo. + for s in [ + r"C:\Games\Foo\..\Other\x.exe", + r"C:\Games\Foo\..\..\Windows\x.exe", + r"C:\Games\Foo\.\x.exe", + r"C:\Games\Foo.\x.exe", + r"C:\Games\Foo \x.exe", + r"\\?\C:\Games\Foo\x.exe", + r"\\server\share\Games\Foo\x.exe", + ] { + assert!(WinPath::parse(s).is_err(), "{s}"); + } + // Nor can a mark or a game folder carry one in through JSON. + assert!(serde_json::from_str::(r#"["C:\\Games\\Foo\\..\\x.exe"]"#).is_err()); + // An exe in a sibling folder is not inside, even if a join tried to climb. + assert!(p(r"C:\Games\Foo").join(r"..\FooBar\fb.exe").is_err()); +} + +// --- Rule 2: launched by Arena --- + +#[test] +fn launched_by_arena_is_always_detected() { + let lib = library(); + assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), true, &lib, NONE), found("steam:10", How::Launched)); + // Outside every install dir (a launcher stub, a Domi app): still a game, the window says which. + assert_eq!( + detect(&p(r"C:\Users\u\AppData\Local\Lapilli\lapilli.exe"), true, &lib, NONE), + Some(Detection { game: None, how: How::Launched }) + ); + assert_eq!(detect(&p(r"C:\x.exe"), true, &[], NONE), Some(Detection { game: None, how: How::Launched })); +} + +#[test] +fn launched_beats_marked() { + let mut marks = Marks::new(); + marks.insert(p(r"C:\Games\Foo\foo.exe")).unwrap(); + assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), true, &library(), &marks).map(|d| d.how), Some(How::Launched)); +} + +// --- Rule 3: marked ("This is a game") --- + +#[test] +fn marked_exe_outside_install_dirs_is_detected_without_a_game() { + let mut marks = Marks::new(); + assert!(marks.insert(p(r"D:\Emulators\retro.exe")).unwrap()); + let lib = library(); + assert_eq!(detect(&p(r"D:\Emulators\retro.exe"), false, &lib, &marks), Some(Detection { game: None, how: How::Marked })); + assert_eq!(detect(&p(r"d:\emulators\RETRO.exe"), false, &lib, &marks).map(|d| d.how), Some(How::Marked)); + // Only that exe: not its folder, not its neighbours. + assert_eq!(detect(&p(r"D:\Emulators\other.exe"), false, &lib, &marks), None); + assert_eq!(detect(&p(r"D:\Emulators\retro.exe\x.exe"), false, &lib, &marks), None); +} + +#[test] +fn marked_exe_inside_an_install_dir_reports_the_game() { + let mut marks = Marks::new(); + marks.insert(p(r"C:\Games\Foo\foo.exe")).unwrap(); + assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), false, &library(), &marks), found("steam:10", How::InstallDir)); +} + +#[test] +fn marks_are_keyed_by_the_normalised_path() { + let mut marks = Marks::new(); + assert!(marks.insert(p(r"C:\Emu\Retro.exe")).unwrap()); + assert!(!marks.insert(p("c:/emu//RETRO.EXE")).unwrap(), "same exe, another spelling"); + assert_eq!(marks.len(), 1); + assert!(marks.contains(&p(r"c:\EMU\retro.exe"))); + assert!(marks.remove(&p(r"C:\EMU\RETRO.EXE"))); + assert!(marks.is_empty()); + assert!(!marks.remove(&p(r"C:\Emu\Retro.exe"))); +} + +#[test] +fn marks_persist_through_json() { + let mut marks = Marks::new(); + marks.insert(p(r"D:\Emu\Retro.exe")).unwrap(); + marks.insert(p(r"C:\Tools\Game.exe")).unwrap(); + let json = serde_json::to_string(&marks).unwrap(); + // A plain array of paths, the first spelling kept, sorted by the case-folded key. + assert_eq!(json, r#"["C:\\Tools\\Game.exe","D:\\Emu\\Retro.exe"]"#); + let back: Marks = serde_json::from_str(&json).unwrap(); + assert_eq!(back, marks); + assert_eq!(detect(&p(r"d:\emu\retro.exe"), false, &[], &back).map(|d| d.how), Some(How::Marked)); +} + +#[test] +fn marks_json_is_checked() { + // Spellings of one exe collapse on load; bad paths and non-strings are refused. + let m: Marks = serde_json::from_str(r#"["C:\\A\\x.exe","c:/a/X.EXE"]"#).unwrap(); + assert_eq!(m.len(), 1); + for bad in [r#"["relative\\x.exe"]"#, r#"["\\\\srv\\s\\x.exe"]"#, r#"[1]"#, r#"{"a":1}"#, r#""C:\\x.exe""#] { + assert!(serde_json::from_str::(bad).is_err(), "{bad}"); + } +} + +#[test] +fn marks_are_capped() { + let mut marks = Marks::new(); + for i in 0..limits::MAX_MARKS { + marks.insert(p(&format!(r"C:\G\{i}.exe"))).unwrap(); + } + assert_eq!(marks.insert(p(r"C:\G\one-more.exe")), Err(ParseError::TooMany("marks"))); + // Re-marking one already there is fine at the cap. + assert_eq!(marks.insert(p(r"C:\G\0.exe")), Ok(false)); + let json = serde_json::to_string(&marks).unwrap(); + assert!(serde_json::from_str::(&json).is_ok()); + let over: Vec = (0..=limits::MAX_MARKS).map(|i| format!(r"C:\G\{i}.exe")).collect(); + assert!(serde_json::from_str::(&serde_json::to_string(&over).unwrap()).is_err()); +} + +#[test] +fn how_serialises_snake_case() { + let d = Detection { game: id("steam:10"), how: How::InstallDir }; + assert_eq!(serde_json::to_string(&d).unwrap(), r#"{"game":"steam:10","how":"install_dir"}"#); + assert_eq!(serde_json::to_string(&How::Launched).unwrap(), r#""launched""#); + assert_eq!(serde_json::to_string(&How::Marked).unwrap(), r#""marked""#); +} + +proptest! { + /// Whatever the folder names, auto-detection only ever claims exes inside an install dir, on whole segments. + #[test] + fn auto_detection_never_leaves_install_dirs( + dirs in proptest::collection::vec("[A-Za-z]{1,4}( [A-Za-z]{1,3})?", 1..4), + exe in r"[A-Za-z]{1,4}(\\[A-Za-z]{1,4}){0,3}\\[a-z]{1,4}\.exe", + ) { + // Letters can spell device names (`con`, `nul`): those paths do not exist, so skip them. + prop_assume!(dirs.iter().all(|d| WinPath::parse(&format!(r"C:\Games\{d}")).is_ok())); + let exe = WinPath::parse(&format!(r"C:\Games\{exe}")); + prop_assume!(exe.is_ok()); + let exe = exe.unwrap(); + let lib: Vec = dirs.iter().enumerate() + .map(|(i, d)| steam(i as u32 + 1, d, &format!(r"C:\Games\{d}"))) + .collect(); + let first = exe.components().nth(1).unwrap().to_lowercase(); + let expected = dirs.iter().any(|d| d.to_lowercase() == first); + let got = detect(&exe, false, &lib, NONE); + prop_assert_eq!(got.is_some(), expected); + if let Some(d) = got { + prop_assert_eq!(d.how, How::InstallDir); + let game = lib.iter().find(|g| Some(&g.id) == d.game.as_ref()).unwrap(); + prop_assert!(exe.starts_with(game.install_dir.as_ref().unwrap())); + } + } +} diff --git a/crates/arena-core/tests/frames.rs b/crates/arena-core/tests/frames.rs new file mode 100644 index 0000000..770e66f --- /dev/null +++ b/crates/arena-core/tests/frames.rs @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: CPAL-1.0 +// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz + +//! Frametime statistics: known answers on generated series, refusals, and properties. + +use arena_core::frames::{FrameStats, stats}; +use arena_core::limits; +use proptest::prelude::*; + +const EPS: f64 = 1e-6; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= EPS * b.abs().max(1.0) +} + +fn s(ft: &[f32]) -> FrameStats { + stats(ft).expect("valid series") +} + +/// A fixed pseudo-random permutation, so order-independence is tested without a dependency. +fn shuffled(mut v: Vec) -> Vec { + let mut x: u64 = 0x9e37_79b9_7f4a_7c15; + for i in (1..v.len()).rev() { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + v.swap(i, (x % (i as u64 + 1)) as usize); + } + v +} + +#[test] +fn constant_series() { + let st = s(&[16.0; 1000]); + assert_eq!(st.frames, 1000); + assert!(close(st.seconds, 16.0)); + assert!(close(st.avg_fps, 62.5)); + assert!(close(st.low_1, 62.5)); + assert!(close(st.low_0_1, 62.5)); + assert_eq!(st.stutters, 0); +} + +#[test] +fn single_frame() { + let st = s(&[25.0]); + assert_eq!(st.frames, 1); + assert!(close(st.seconds, 0.025)); + assert!(close(st.avg_fps, 40.0)); + assert!(close(st.low_1, 40.0)); + assert!(close(st.low_0_1, 40.0)); + assert_eq!(st.stutters, 0); +} + +#[test] +fn percentiles_are_nearest_rank() { + // 1..=100 ms in a scrambled order: the 99th percentile is 99 ms, the 99.9th is 100 ms. + let ft = shuffled((1..=100).map(|i| i as f32).collect()); + let st = s(&ft); + assert!(close(st.seconds, 5.05)); + assert!(close(st.avg_fps, 100.0 / 5.05)); + assert!(close(st.low_1, 1000.0 / 99.0)); + assert!(close(st.low_0_1, 10.0)); +} + +#[test] +fn one_percent_of_slow_frames_sets_both_lows() { + // 1000 frames: 980 at 10 ms, 20 at 20 ms. Rank 990 and rank 999 both fall in the 20 ms block. + let mut ft = vec![10.0f32; 980]; + ft.extend([20.0f32; 20]); + let st = s(&shuffled(ft)); + assert!(close(st.seconds, 10.2)); + assert!(close(st.avg_fps, 1000.0 / 10.2)); + assert!(close(st.low_1, 50.0)); + assert!(close(st.low_0_1, 50.0)); +} + +#[test] +fn point_one_percent_low_sees_what_one_percent_low_does_not() { + // 1000 frames: 995 at 10 ms, 5 at 40 ms. Rank 990 is 10 ms, rank 999 is 40 ms. + let mut ft = vec![10.0f32; 995]; + ft.extend([40.0f32; 5]); + let st = s(&shuffled(ft)); + assert!(close(st.avg_fps, 1000.0 / 10.15)); + // The percentile frame (10 ms = 100 FPS) is faster than the average: the low is capped at the average. + assert!(close(st.low_1, st.avg_fps)); + assert!(close(st.low_0_1, 25.0)); +} + +#[test] +fn a_few_huge_frames_cap_the_one_percent_low_at_the_average() { + // 995 at 10 ms and 5 one-second hangs: the 99th-percentile frame is 10 ms (100 FPS), the average is ~66.9. + let mut ft = vec![10.0f32; 995]; + ft.extend([1000.0f32; 5]); + let st = s(&ft); + assert!(close(st.avg_fps, 1000.0 / 14.95)); + assert!(close(st.low_1, st.avg_fps)); + assert!(close(st.low_0_1, 1.0)); +} + +#[test] +fn stutter_needs_both_conditions() { + // 100 Hz baseline; frames 100.. are spikes separated by 100 calm frames. + let mut ft = vec![10.0f32; 100]; + ft.push(30.0); // 3x and >= 25 ms: a stutter + ft.extend([10.0f32; 100]); + ft.push(24.0); // 2.4x and < 25 ms: no + ft.extend([10.0f32; 100]); + ft.push(25.0); // exactly 2.5x and exactly 25 ms: a stutter (both bounds inclusive) + ft.extend([10.0f32; 100]); + assert_eq!(s(&ft).stutters, 2); +} + +#[test] +fn stutter_relative_to_a_slow_baseline() { + // At 60 FPS (16.67 ms) a 40 ms frame is 2.4x the median: not a stutter; 42 ms is 2.52x: a stutter. + let base = 1000.0f32 / 60.0; + let mut ft = vec![base; 60]; + ft.push(40.0); + ft.extend(vec![base; 60]); + ft.push(42.0); + assert_eq!(s(&ft).stutters, 1); + // At 30 FPS a 50 ms frame is only 1.5x: never a stutter, though it is over 25 ms. + let mut slow = vec![33.3f32; 80]; + slow.push(50.0); + assert_eq!(s(&slow).stutters, 0); +} + +#[test] +fn no_stutter_before_sixty_frames_of_history() { + let mut ft = vec![10.0f32; 59]; + ft.push(100.0); // frame 59 has only 59 frames before it + assert_eq!(s(&ft).stutters, 0); + let mut ft = vec![10.0f32; 60]; + ft.push(100.0); // frame 60 has a full window + assert_eq!(s(&ft).stutters, 1); +} + +#[test] +fn consecutive_spikes_each_count_and_the_window_slides() { + let mut ft = vec![10.0f32; 60]; + ft.extend([50.0f32; 3]); + ft.extend([10.0f32; 10]); + assert_eq!(s(&ft).stutters, 3); + // After 30 slow frames the window's median is no longer 10 ms (it is the mean of 10 and 50 = 30 ms), so the + // 31st slow frame is not a stutter any more. + let mut ft = vec![10.0f32; 60]; + ft.extend([50.0f32; 40]); + let st = s(&ft); + // Frames 60..=89 see a median of 10 ms (fewer than 30 slow frames before them) → 30 stutters; frame 90 sees + // 30 slow and 30 fast, median 30 ms, and 50 < 75 ms. + assert_eq!(st.stutters, 30); +} + +#[test] +fn zero_frametimes_are_allowed_when_time_passes() { + let mut ft = vec![0.0f32; 10]; + ft.push(10.0); + let st = s(&ft); + assert_eq!(st.frames, 11); + assert!(close(st.avg_fps, 1100.0)); + assert!(st.low_1 <= st.avg_fps && st.low_0_1 <= st.low_1); +} + +#[test] +fn refusals() { + assert_eq!(stats(&[]), None); + assert_eq!(stats(&[0.0, 0.0]), None, "no time passed"); + assert_eq!(stats(&[16.0, f32::NAN]), None); + assert_eq!(stats(&[16.0, f32::INFINITY]), None); + assert_eq!(stats(&[f32::NEG_INFINITY]), None); + assert_eq!(stats(&[16.0, -0.5]), None); + assert_eq!(stats(&[-0.0, 16.0]).map(|s| s.frames), Some(2), "-0.0 is zero, not negative"); +} + +#[test] +fn length_cap() { + let at_cap = vec![1.0f32; limits::MAX_FRAMES]; + assert_eq!(stats(&at_cap).map(|s| s.frames as usize), Some(limits::MAX_FRAMES)); + let over = vec![1.0f32; limits::MAX_FRAMES + 1]; + assert_eq!(stats(&over), None); +} + +#[test] +fn huge_frametimes_stay_finite() { + let st = s(&[f32::MAX, f32::MAX, 1.0]); + assert!(st.avg_fps.is_finite() && st.seconds.is_finite() && st.avg_fps > 0.0); +} + +#[test] +fn serialises_for_the_overlay() { + let st = s(&[10.0; 100]); + let json = serde_json::to_value(st).unwrap(); + for k in ["avg_fps", "low_1", "low_0_1", "stutters", "frames", "seconds"] { + assert!(json.get(k).is_some(), "missing {k}"); + } + let back: FrameStats = serde_json::from_value(json).unwrap(); + assert_eq!(back, st); +} + +fn frametime() -> impl Strategy { + prop_oneof![ + 6 => 1.0f32..40.0, + 2 => 0.0f32..1000.0, + 1 => Just(0.0f32), + 1 => 0.0f32..f32::MAX, + ] +} + +fn any_f32() -> impl Strategy { + prop_oneof![ + 4 => frametime(), + 1 => Just(f32::NAN), + 1 => Just(f32::INFINITY), + 1 => Just(f32::NEG_INFINITY), + 1 => -1000.0f32..0.0, + 1 => any::(), + ] +} + +proptest! { + #[test] + fn never_panics(ft in proptest::collection::vec(any_f32(), 0..400)) { + let _ = stats(&ft); + } + + #[test] + fn bad_input_is_refused(mut ft in proptest::collection::vec(frametime(), 0..200), bad in prop_oneof![ + Just(f32::NAN), Just(f32::INFINITY), Just(f32::NEG_INFINITY), -1e9f32..-1e-9 + ], at in any::()) { + let i = at.index(ft.len() + 1); + ft.insert(i, bad); + prop_assert_eq!(stats(&ft), None); + } + + #[test] + fn invariants(ft in proptest::collection::vec(frametime(), 1..400)) { + if let Some(st) = stats(&ft) { + prop_assert_eq!(st.frames as usize, ft.len()); + for v in [st.avg_fps, st.low_1, st.low_0_1, st.seconds] { + prop_assert!(v.is_finite() && v >= 0.0); + } + prop_assert!(st.avg_fps > 0.0); + prop_assert!(st.low_1 <= st.avg_fps); + prop_assert!(st.low_0_1 <= st.low_1); + prop_assert!((st.stutters as usize) < ft.len().saturating_sub(59).max(1)); + } else { + // Only a series with no time in it is refused here. + prop_assert!(ft.iter().all(|&f| f == 0.0)); + } + } + + #[test] + fn order_does_not_change_avg_or_lows(ft in proptest::collection::vec(1.0f32..100.0, 1..300)) { + let a = s(&ft); + let mut rev = ft.clone(); + rev.reverse(); + let b = s(&rev); + prop_assert!(close(a.avg_fps, b.avg_fps)); + prop_assert_eq!(a.low_1, b.low_1); + prop_assert_eq!(a.low_0_1, b.low_0_1); + } +} diff --git a/crates/arena-core/tests/hotkey.rs b/crates/arena-core/tests/hotkey.rs new file mode 100644 index 0000000..271b941 --- /dev/null +++ b/crates/arena-core/tests/hotkey.rs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: CPAL-1.0 +// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz + +//! Overlay shortcuts: parsing, the canonical form, refusals, and the Win32 values. + +use arena_core::hotkey::{Hotkey, HotkeyError, Key, Modifiers, parse}; +use arena_core::limits; +use proptest::prelude::*; + +const CTRL_SHIFT: Modifiers = Modifiers { ctrl: true, alt: false, shift: true, win: false }; + +#[test] +fn the_default_shortcut() { + let h = parse("Ctrl+Shift+G").unwrap(); + assert_eq!(h.modifiers(), CTRL_SHIFT); + assert_eq!(h.key(), Key::Letter('G')); + assert_eq!(h.to_string(), "Ctrl+Shift+G"); + assert_eq!(Hotkey::default(), h); +} + +#[test] +fn canonical_form() { + for (input, canonical) in [ + ("ctrl+shift+g", "Ctrl+Shift+G"), + ("Shift+Ctrl+G", "Ctrl+Shift+G"), + (" Ctrl + Shift + g ", "Ctrl+Shift+G"), + ("WIN+ALT+f5", "Alt+Win+F5"), + ("win+g", "Win+G"), + ("Alt+1", "Alt+1"), + ("Ctrl+Alt+Shift+Win+Z", "Ctrl+Alt+Shift+Win+Z"), + ("F1", "F1"), + ("shift+f24", "Shift+F24"), + ("Ctrl+0", "Ctrl+0"), + ("Ctrl+F10", "Ctrl+F10"), + ] { + assert_eq!(parse(input).map(|h| h.to_string()), Ok(canonical.to_string()), "{input}"); + } +} + +#[test] +fn bare_letters_and_digits_are_refused() { + for s in ["G", "g", "7", "Shift+G", "Shift+5", "shift+a"] { + assert_eq!(parse(s), Err(HotkeyError::NoModifier), "{s}"); + } + // A function key alone is fine (it types nothing). + assert!(parse("F9").is_ok()); +} + +#[test] +fn keys_windows_reserves_are_refused() { + for s in [ + "Ctrl+Alt+Del", + "Ctrl+Alt+Delete", + "ctrl+alt+shift+del", + "Ctrl+Shift+Esc", + "Ctrl+Shift+Escape", + "Win+L", + "win+l", + "Alt+F4", + "F12", + "Ctrl+F12", + "Shift+Win+F12", + ] { + assert_eq!(parse(s), Err(HotkeyError::Reserved), "{s}"); + } + // Close neighbours are fine. + for s in ["Win+Shift+L", "Ctrl+L", "Ctrl+Alt+F4", "F11", "Win+G"] { + assert!(parse(s).is_ok(), "{s}"); + } +} + +#[test] +fn malformed_input() { + assert_eq!(parse(""), Err(HotkeyError::Empty)); + assert_eq!(parse(" "), Err(HotkeyError::Empty)); + assert_eq!(parse("Ctrl+"), Err(HotkeyError::Malformed)); + assert_eq!(parse("+G"), Err(HotkeyError::Malformed)); + assert_eq!(parse("Ctrl++G"), Err(HotkeyError::Malformed)); + assert_eq!(parse("Ctrl+Shift"), Err(HotkeyError::MissingKey)); + assert_eq!(parse("Win"), Err(HotkeyError::MissingKey)); + assert_eq!(parse("Ctrl+Ctrl+G"), Err(HotkeyError::DuplicateModifier)); + assert_eq!(parse("ctrl+CTRL+G"), Err(HotkeyError::DuplicateModifier)); + assert_eq!(parse("Hyper+G"), Err(HotkeyError::UnknownModifier)); + assert_eq!(parse("G+Ctrl"), Err(HotkeyError::UnknownModifier), "the key comes last"); + assert_eq!(parse("Ctrl+G+H"), Err(HotkeyError::UnknownModifier)); + for k in ["Tab", "Space", "Esc", "Del", "F0", "F25", "F01", "GG", "10", "Ž", "Ctrl+é", "+", "F1 2"] { + let s = if k.contains('+') { k.to_string() } else { format!("Ctrl+{k}") }; + assert!(matches!(parse(&s), Err(HotkeyError::UnknownKey | HotkeyError::Malformed)), "{s}"); + } + assert_eq!(parse("Ctrl+Tab"), Err(HotkeyError::UnknownKey)); + assert_eq!(parse(&format!("Ctrl+{}", "G".repeat(limits::MAX_HOTKEY))), Err(HotkeyError::TooLong)); + assert_eq!(parse("Ctrl+\u{0}"), Err(HotkeyError::UnknownKey)); +} + +#[test] +fn new_checks_the_same_rules() { + let none = Modifiers::default(); + let alt = Modifiers { alt: true, ..none }; + assert_eq!(Hotkey::new(none, Key::Letter('G')), Err(HotkeyError::NoModifier)); + assert_eq!(Hotkey::new(alt, Key::F(4)), Err(HotkeyError::Reserved)); + assert_eq!(Hotkey::new(alt, Key::Letter('g')), Err(HotkeyError::UnknownKey), "letters are uppercase"); + assert_eq!(Hotkey::new(alt, Key::Letter('1')), Err(HotkeyError::UnknownKey)); + assert_eq!(Hotkey::new(alt, Key::Digit(10)), Err(HotkeyError::UnknownKey)); + assert_eq!(Hotkey::new(alt, Key::F(0)), Err(HotkeyError::UnknownKey)); + assert_eq!(Hotkey::new(alt, Key::F(25)), Err(HotkeyError::UnknownKey)); + assert_eq!(Hotkey::new(CTRL_SHIFT, Key::Letter('G')), Ok(Hotkey::default())); +} + +#[test] +fn win32_values() { + let h = parse("Ctrl+Shift+G").unwrap(); + assert_eq!(h.win32_modifiers(), 0x0002 | 0x0004); + assert_eq!(h.virtual_key(), 0x47); + assert_eq!(parse("Win+G").unwrap().win32_modifiers(), 0x0008); + assert_eq!(parse("Alt+0").unwrap().win32_modifiers(), 0x0001); + assert_eq!(parse("Alt+0").unwrap().virtual_key(), 0x30); + assert_eq!(parse("Alt+9").unwrap().virtual_key(), 0x39); + assert_eq!(parse("Alt+A").unwrap().virtual_key(), 0x41); + assert_eq!(parse("Alt+Z").unwrap().virtual_key(), 0x5A); + assert_eq!(parse("F1").unwrap().virtual_key(), 0x70); + assert_eq!(parse("F24").unwrap().virtual_key(), 0x87); + assert_eq!(parse("F1").unwrap().win32_modifiers(), 0); +} + +#[test] +fn serde_uses_the_text_form() { + let h = Hotkey::default(); + assert_eq!(serde_json::to_string(&h).unwrap(), r#""Ctrl+Shift+G""#); + assert_eq!(serde_json::from_str::(r#""shift+ctrl+g""#).unwrap(), h); + for bad in [r#""G""#, r#""Win+L""#, r#""""#, "7", r#"{"key":"G"}"#] { + assert!(serde_json::from_str::(bad).is_err(), "{bad}"); + } +} + +#[test] +fn errors_display_without_input() { + for e in [ + HotkeyError::Empty, + HotkeyError::TooLong, + HotkeyError::Malformed, + HotkeyError::UnknownModifier, + HotkeyError::DuplicateModifier, + HotkeyError::MissingKey, + HotkeyError::UnknownKey, + HotkeyError::NoModifier, + HotkeyError::Reserved, + ] { + assert!(!e.to_string().is_empty()); + } +} + +fn modifiers() -> impl Strategy { + (any::(), any::(), any::(), any::()) + .prop_map(|(ctrl, alt, shift, win)| Modifiers { ctrl, alt, shift, win }) +} + +fn key() -> impl Strategy { + prop_oneof![ + proptest::char::range('A', 'Z').prop_map(Key::Letter), + (0u8..=9).prop_map(Key::Digit), + (1u8..=24).prop_map(Key::F), + ] +} + +proptest! { + #[test] + fn parse_display_round_trip(m in modifiers(), k in key()) { + match Hotkey::new(m, k) { + Ok(h) => { + prop_assert_eq!(parse(&h.to_string()), Ok(h)); + prop_assert_eq!(parse(&h.to_string().to_lowercase()), Ok(h)); + } + Err(e) => prop_assert!(matches!(e, HotkeyError::NoModifier | HotkeyError::Reserved)), + } + } + + #[test] + fn parse_never_panics_and_is_canonical(s in r"((?i)(ctrl|alt|shift|win|control|meta| |\+)){0,6}[A-Za-z0-9 ]{0,4}|\PC{0,24}") { + if let Ok(h) = parse(&s) { + let text = h.to_string(); + prop_assert_eq!(parse(&text), Ok(h)); + prop_assert!(text.len() <= limits::MAX_HOTKEY); + prop_assert!(h.modifiers() != Modifiers::default() || matches!(h.key(), Key::F(_))); + } + } +} diff --git a/crates/arena-core/tests/purity.rs b/crates/arena-core/tests/purity.rs new file mode 100644 index 0000000..c6dc756 --- /dev/null +++ b/crates/arena-core/tests/purity.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: CPAL-1.0 +// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz + +//! Static checks on the crate's own sources: no I/O or OS calls (decision 15, `docs/PORTABILITY.md`) and no +//! process access of any kind (DAY2 mandatory test: no handle with write or memory-read rights to another process). + +use std::path::Path; + +const IO: [&str; 8] = + ["std::fs", "std::process", "std::net", "std::env", "std::time", "SystemTime", "Instant", "Command"]; + +const PROCESS_ACCESS: [&str; 10] = [ + "PROCESS_VM_READ", + "PROCESS_VM_WRITE", + "PROCESS_VM_OPERATION", + "PROCESS_ALL_ACCESS", + "ReadProcessMemory", + "WriteProcessMemory", + "CreateRemoteThread", + "SetWindowsHookEx", + "DuplicateHandle", + "OpenProcess", +]; + +#[test] +fn sources_have_no_io_and_no_process_access() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files = 0; + let mut hits = Vec::new(); + for entry in std::fs::read_dir(&src).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "rs") { + files += 1; + let text = std::fs::read_to_string(&path).unwrap(); + for (n, line) in text.lines().enumerate() { + for word in IO.iter().chain(PROCESS_ACCESS.iter()) { + if line.contains(word) { + hits.push(format!("{}:{}: {word}", path.display(), n + 1)); + } + } + } + } + } + assert!(files >= 10, "found only {files} source files under {}", src.display()); + assert!(hits.is_empty(), "forbidden API names in arena-core sources:\n{}", hits.join("\n")); +} diff --git a/docs/FORMATS.md b/docs/FORMATS.md index bcde79b..4ab146b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -27,6 +27,9 @@ reads capped bytes and passes them in. | `MAX_URL` | 2048 bytes | a web-game URL | `TooLong("url")` | | `MAX_HOST` | 253 bytes | the URL's host | `BadValue("url")` | | `MAX_GAMES` | 100 000 | games one `merge` call considers | the rest are dropped | +| `MAX_FRAMES` | 1 048 576 | frametimes one `frames::stats` call takes | `None` | +| `MAX_MARKS` | 4096 | exes marked as games (`detect::Marks`) | `TooMany("marks")` | +| `MAX_HOTKEY` | 64 bytes | shortcut text for `hotkey::parse` | `HotkeyError::TooLong` | ## Errors @@ -201,3 +204,25 @@ the allow-list, so launching a stored web game goes through `uri_checked`. Steam > Epic > GOG > Domi > Manual. Games of the same source are never dropped for sharing a folder; games without an install folder are never dropped here. 3. The result is sorted by title (lowercased, by code point), then by id, so it does not depend on scan order. + +## Overlay: frametimes, detection, shortcut + +**`frames::stats(&[f32])`** (milliseconds, presentation order) → `FrameStats { avg_fps, low_1, low_0_1, stutters, +frames, seconds }`. `avg_fps = frames / seconds`; the lows are `1000 / frametime` at the nearest-rank 99th and +99.9th percentile (rank `ceil(p × n)`), each capped so `low_0_1 <= low_1 <= avg_fps`; a stutter is a frame +`>= 2.5 ×` the median of the 60 frames before it (mean of the 30th and 31st smallest) **and** `>= 25 ms`; the first +60 frames are never stutters. `None` for an empty series, over `MAX_FRAMES`, any NaN, infinite or negative value, +or no time at all (zeros alone). + +**`detect::detect(exe, launched_by_arena, library, marks)`**, first match wins: `Launched` (Arena started it; the +game if its folder holds the exe), `InstallDir` (the game's own launch exe, else the deepest `install_dir` strictly +containing the exe; drive roots never count as a containing folder), `Marked` (exactly this exe, `game: None`). +Otherwise `None`: an exe outside every install folder is never auto-detected. Comparison is component-wise and +ignores case; `WinPath` already refuses `..`, `.`, UNC and `\\?\`. `Marks` serialises as a sorted JSON array of +paths; loading re-checks each path and folds spellings of one exe. + +**`hotkey::parse(&str)`**: `Mod+...+Key`, spaces around parts ignored, names ignore case. Modifiers `Ctrl Alt Shift +Win` (each once); key `A`–`Z`, `0`–`9`, `F1`–`F24`, last. Errors: `Empty`, `TooLong`, `Malformed` (empty part), +`UnknownModifier`, `DuplicateModifier`, `MissingKey`, `UnknownKey`, `NoModifier` (a letter or digit without Ctrl, +Alt or Win), `Reserved` (`Ctrl+Alt+Del`, `Ctrl+Shift+Esc`, `Win+L`, `Alt+F4`, any `F12`). `Display` is canonical +(`Ctrl+Alt+Shift+Win+`); serde uses that text.