[core] Detect: Marks hold on and off sets; arena-core 0.2.0 checks pass

Marks keeps one verdict per exe: on ("This is a game") or off ("This is
not a game"). detect: Launched > marked off (None) > marked on (Marked,
with the library game if any) > InstallDir. Serde writes
{"on": [...], "off": [...]} and still reads the plain array as on;
an exe in both lists is refused, MAX_MARKS counts both.

Also: collapsible-if for clippy, rustfmt, README and FORMATS updated.
Checked: cargo test -p arena-core (183 passed), clippy -D warnings,
fmt --check, check for wasm32-unknown-unknown and aarch64-linux-android.
This commit is contained in:
2026-11-26 03:27:03 +01:00
parent 43701bbadc
commit 95d031fef9
6 changed files with 251 additions and 64 deletions
+6 -4
View File
@@ -82,8 +82,9 @@ use arena_core::{frames, detect::{self, Detection, How, Marks}, hotkey::{self, H
// average), stutters (>= 2.5 x the median of the 60 frames before and >= 25 ms). None for empty or bad input. // 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::FrameStats> = frames::stats(&frametimes_ms); let st: Option<frames::FrameStats> = frames::stats(&frametimes_ms);
// Launched by Arena > inside an install_dir (deepest wins) > marked by the user. Outside every install_dir and // Launched by Arena > marked off ("not a game": None) > marked on > inside an install_dir (deepest wins).
// not marked: never a game. Whole path components, ignoring case. // Outside every install_dir and not marked on: never a game. Whole path components, ignoring case.
marks.set(exe.clone(), true)?; // the "This is a game" toggle; false = off
let d: Option<Detection> = detect::detect(&exe, launched_by_arena, &library.games, &marks); let d: Option<Detection> = detect::detect(&exe, launched_by_arena, &library.games, &marks);
// "Ctrl+Shift+G" ⇄ Hotkey; refuses bare letters and Windows-reserved keys; Win32 values for RegisterHotKey. // "Ctrl+Shift+G" ⇄ Hotkey; refuses bare letters and Windows-reserved keys; Win32 values for RegisterHotKey.
@@ -92,8 +93,9 @@ 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 `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. The same holds for `Marks` (a JSON as the parsers, so a tampered `library.json` cannot smuggle in a bad path or launch string. The same holds for
array of exe paths in the agent's `overlay.json`) and `Hotkey` (its text form in `settings.json`). `Marks` (`{"on": [...], "off": [...]}` 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: [`docs/FORMATS.md`](docs/FORMATS.md) (what each parser accepts and refuses, every cap) and
[`docs/PORTABILITY.md`](docs/PORTABILITY.md) (the target checks). [`docs/PORTABILITY.md`](docs/PORTABILITY.md) (the target checks).
+100 -37
View File
@@ -5,16 +5,18 @@
//! //!
//! The agent hands in the foreground process's exe path (already a [`WinPath`]: absolute, no `..`, no UNC or //! 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. //! `\\?\`, 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: //! [`detect`] applies these rules, first match wins:
//! //!
//! 1. **Launched**: Arena started it. Always a game; `game` is the library game whose folder holds the exe, if //! 1. **Launched**: Arena started it. Always a game, whatever the marks; `game` is the library game that owns the
//! any (a launcher stub or a Domi app may live elsewhere: the window's `launched` message says which game). //! exe, if any (a launcher stub or a Domi app may live elsewhere: the window's `launched` message says which).
//! 2. **InstallDir**: the exe lies inside a game's `install_dir`, or is that game's own launch exe. The deepest //! 2. **Marked off**: the user said "This is not a game" for exactly this exe: `None`, even inside an install folder.
//! 3. **Marked on**: the user said "This is a game" for exactly this exe: [`How::Marked`], with the library game
//! that owns the exe if there is one.
//! 4. **InstallDir**: the exe is a game's own launch exe, or lies inside a game's `install_dir`. The deepest
//! install folder wins (an expansion in a sub-folder beats the base game), then library order. //! 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 //! **An exe outside every `install_dir` is never auto-detected**: without Arena launching it or an "on" mark, it is
//! game. Paths compare the way Windows does: ignoring case, `/` and `\` alike, on whole components, so //! 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 //! `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. //! `D:\game.exe`) claims only that game's own exe, never the whole drive.
@@ -42,7 +44,7 @@ pub struct Detection {
pub enum How { pub enum How {
/// Arena launched it. /// Arena launched it.
Launched, Launched,
/// It is inside a game's install folder (or is the game's launch exe). /// It is a game's launch exe or inside a game's install folder.
InstallDir, InstallDir,
/// The user marked this exe as a game. /// The user marked this exe as a game.
Marked, Marked,
@@ -54,10 +56,11 @@ pub fn detect(exe: &WinPath, launched_by_arena: bool, library: &[Game], marked:
if launched_by_arena { if launched_by_arena {
return Some(Detection { game: in_library, how: How::Launched }); return Some(Detection { game: in_library, how: How::Launched });
} }
if let Some(game) = in_library { match marked.get(exe) {
return Some(Detection { game: Some(game), how: How::InstallDir }); Some(false) => None,
Some(true) => Some(Detection { game: in_library, how: How::Marked }),
None => in_library.map(|game| 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. /// The library game that owns `exe`: its own launch exe, else the deepest install folder that strictly contains it.
@@ -83,14 +86,16 @@ fn find_game(exe: &WinPath, library: &[Game]) -> Option<GameId> {
best.map(|(_, id)| id.clone()) best.map(|(_, id)| id.clone())
} }
/// The exes the user marked as games ("This is a game"), keyed by the normalised path ignoring case. /// The user's verdicts on single exes: `on` ("This is a game") and `off` ("This is not a game"), keyed by the
/// normalised path ignoring case. An exe is in at most one of the two; setting one clears the other.
/// ///
/// Persisted in the agent's `overlay.json` as a JSON array of paths, sorted by the case-folded key, with the first /// Persisted in the agent's `overlay.json` as `{ "on": [paths], "off": [paths] }`, each sorted by the case-folded
/// spelling kept. Loading checks every path as a [`WinPath`], folds spellings of the same exe into one, and refuses /// path, first spelling kept. Loading also accepts a plain array of paths (the first 0.2.0 form), read as `on`.
/// more than [`crate::limits::MAX_MARKS`]. /// Loading checks every path as a [`WinPath`], folds spellings of the same exe, refuses an exe in both lists
/// (`Duplicate("marks")`) and more than [`crate::limits::MAX_MARKS`] marks in all (`TooMany("marks")`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "Vec<WinPath>", into = "Vec<WinPath>")] #[serde(try_from = "MarksRepr", into = "MarksWire")]
pub struct Marks(BTreeMap<String, WinPath>); pub struct Marks(BTreeMap<String, (WinPath, bool)>);
impl Marks { impl Marks {
/// No marks. /// No marks.
@@ -98,35 +103,64 @@ impl Marks {
Marks(BTreeMap::new()) Marks(BTreeMap::new())
} }
/// Marks `exe`. `Ok(true)` when it was new, `Ok(false)` when it was already marked (the first spelling stays), /// Marks `exe` as a game (`is_game`) or as not a game, replacing any earlier mark on it. `Ok(true)` when that
/// `Err(TooMany("marks"))` when [`crate::limits::MAX_MARKS`] are already marked. /// changed something, `Ok(false)` when the exe already had this mark (the first spelling stays),
pub fn insert(&mut self, exe: WinPath) -> Result<bool, ParseError> { /// `Err(TooMany("marks"))` for a new exe when [`crate::limits::MAX_MARKS`] exes are already marked.
pub fn set(&mut self, exe: WinPath, is_game: bool) -> Result<bool, ParseError> {
let key = exe.key(); let key = exe.key();
if self.0.contains_key(&key) { if let Some(slot) = self.0.get_mut(&key) {
return Ok(false); let changed = slot.1 != is_game;
slot.1 = is_game;
return Ok(changed);
} }
if self.0.len() >= MAX_MARKS { if self.0.len() >= MAX_MARKS {
return Err(ParseError::TooMany("marks")); return Err(ParseError::TooMany("marks"));
} }
self.0.insert(key, exe); self.0.insert(key, (exe, is_game));
Ok(true) Ok(true)
} }
/// Unmarks `exe`; true when it was marked. /// Removes any mark on `exe`, back to the automatic rules; true when there was one.
pub fn remove(&mut self, exe: &WinPath) -> bool { pub fn clear(&mut self, exe: &WinPath) -> bool {
self.0.remove(&exe.key()).is_some() self.0.remove(&exe.key()).is_some()
} }
/// True when `exe` is marked, in any spelling. /// The mark on `exe`, in any spelling: `Some(true)` on, `Some(false)` off, `None` unmarked.
pub fn get(&self, exe: &WinPath) -> Option<bool> {
self.0.get(&exe.key()).map(|(_, on)| *on)
}
/// Shorthand for `set(exe, true)`: marks `exe` as a game.
pub fn insert(&mut self, exe: WinPath) -> Result<bool, ParseError> {
self.set(exe, true)
}
/// Removes an "on" mark from `exe`; true when it had one. An "off" mark stays.
pub fn remove(&mut self, exe: &WinPath) -> bool {
self.contains(exe) && self.clear(exe)
}
/// True when `exe` is marked as a game.
pub fn contains(&self, exe: &WinPath) -> bool { pub fn contains(&self, exe: &WinPath) -> bool {
self.0.contains_key(&exe.key()) self.get(exe) == Some(true)
} }
/// The marked exes, sorted by the case-folded path. /// True when `exe` is marked as not a game.
pub fn iter(&self) -> impl Iterator<Item = &WinPath> { pub fn contains_off(&self, exe: &WinPath) -> bool {
self.0.values() self.get(exe) == Some(false)
} }
/// The exes marked as games, sorted by the case-folded path.
pub fn on(&self) -> impl Iterator<Item = &WinPath> {
self.0.values().filter(|(_, on)| *on).map(|(p, _)| p)
}
/// The exes marked as not games, sorted by the case-folded path.
pub fn off(&self) -> impl Iterator<Item = &WinPath> {
self.0.values().filter(|(_, on)| !*on).map(|(p, _)| p)
}
/// Marks of both kinds.
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.0.len() self.0.len()
} }
@@ -136,20 +170,49 @@ impl Marks {
} }
} }
impl TryFrom<Vec<WinPath>> for Marks { /// What `overlay.json` may hold: the current object, or a plain array (all `on`, the first 0.2.0 form).
#[derive(Deserialize)]
#[serde(untagged)]
enum MarksRepr {
Plain(Vec<WinPath>),
Split(MarksWire),
}
/// The written form.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct MarksWire {
#[serde(default)]
on: Vec<WinPath>,
#[serde(default)]
off: Vec<WinPath>,
}
impl TryFrom<MarksRepr> for Marks {
type Error = ParseError; type Error = ParseError;
fn try_from(paths: Vec<WinPath>) -> Result<Self, Self::Error> { fn try_from(repr: MarksRepr) -> Result<Self, Self::Error> {
let (on, off) = match repr {
MarksRepr::Plain(on) => (on, Vec::new()),
MarksRepr::Split(w) => (w.on, w.off),
};
let mut marks = Marks::new(); let mut marks = Marks::new();
for p in paths { for p in on {
marks.insert(p)?; marks.set(p, true)?;
}
for p in off {
if marks.contains(&p) {
return Err(ParseError::Duplicate("marks"));
}
marks.set(p, false)?;
} }
Ok(marks) Ok(marks)
} }
} }
impl From<Marks> for Vec<WinPath> { impl From<Marks> for MarksWire {
fn from(m: Marks) -> Vec<WinPath> { fn from(m: Marks) -> MarksWire {
m.0.into_values().collect() let (on, off): (Vec<_>, Vec<_>) = m.0.into_values().partition(|(_, on)| *on);
MarksWire { on: on.into_iter().map(|(p, _)| p).collect(), off: off.into_iter().map(|(p, _)| p).collect() }
} }
} }
+4 -4
View File
@@ -98,10 +98,10 @@ fn stutters(frametimes_ms: &[f32]) -> u32 {
count = count.saturating_add(1); count = count.saturating_add(1);
} }
// Slide: drop the frame that leaves the window. // 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 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)) { && let Ok(at) = window.binary_search_by(|w| w.total_cmp(&old))
window.remove(at); {
} window.remove(at);
} }
} }
let at = window.partition_point(|w| w.total_cmp(&ft).is_lt()); let at = window.partition_point(|w| w.total_cmp(&ft).is_lt());
+122 -10
View File
@@ -53,7 +53,7 @@ fn found(game: &str, how: How) -> Option<Detection> {
const NONE: &Marks = &Marks::new(); const NONE: &Marks = &Marks::new();
// --- Rule 1: an exe outside every install_dir is never auto-detected --- // --- an exe outside every install_dir is never auto-detected ---
#[test] #[test]
fn outside_every_install_dir_is_not_detected() { fn outside_every_install_dir_is_not_detected() {
@@ -115,7 +115,10 @@ fn a_drive_root_install_dir_does_not_claim_the_whole_drive() {
assert_eq!(detect(&p(r"D:\Tools\editor.exe"), false, &lib, NONE), None); 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); assert_eq!(detect(&p(r"D:\other.exe"), false, &lib, NONE), None);
// Its own exe is still found, through the game's launch exe. // 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 })); assert_eq!(
detect(&p(r"d:\GAME.EXE"), false, &lib, NONE),
Some(Detection { game: Some(g.id), how: How::InstallDir })
);
} }
#[test] #[test]
@@ -165,7 +168,7 @@ fn dot_dot_never_escapes() {
assert!(p(r"C:\Games\Foo").join(r"..\FooBar\fb.exe").is_err()); assert!(p(r"C:\Games\Foo").join(r"..\FooBar\fb.exe").is_err());
} }
// --- Rule 2: launched by Arena --- // --- launched by Arena ---
#[test] #[test]
fn launched_by_arena_is_always_detected() { fn launched_by_arena_is_always_detected() {
@@ -186,14 +189,17 @@ fn launched_beats_marked() {
assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), true, &library(), &marks).map(|d| d.how), Some(How::Launched)); 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") --- // --- marked on ("This is a game") ---
#[test] #[test]
fn marked_exe_outside_install_dirs_is_detected_without_a_game() { fn marked_exe_outside_install_dirs_is_detected_without_a_game() {
let mut marks = Marks::new(); let mut marks = Marks::new();
assert!(marks.insert(p(r"D:\Emulators\retro.exe")).unwrap()); assert!(marks.insert(p(r"D:\Emulators\retro.exe")).unwrap());
let lib = library(); 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),
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)); 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. // 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\other.exe"), false, &lib, &marks), None);
@@ -201,10 +207,75 @@ fn marked_exe_outside_install_dirs_is_detected_without_a_game() {
} }
#[test] #[test]
fn marked_exe_inside_an_install_dir_reports_the_game() { fn marked_on_inside_an_install_dir_is_marked_and_names_the_game() {
let mut marks = Marks::new(); let mut marks = Marks::new();
marks.insert(p(r"C:\Games\Foo\foo.exe")).unwrap(); 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)); assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), false, &library(), &marks), found("steam:10", How::Marked));
}
// --- marked off ("This is not a game") ---
#[test]
fn marked_off_is_never_auto_detected() {
let lib = library();
let mut marks = Marks::new();
// A crash reporter inside a game's folder would be found by its install folder ...
let reporter = p(r"C:\Games\Foo\CrashReporter.exe");
assert_eq!(detect(&reporter, false, &lib, NONE), found("steam:10", How::InstallDir));
// ... until the user says it is not a game, in any spelling.
assert!(marks.set(p("c:/games/foo/crashreporter.EXE"), false).unwrap());
assert!(marks.contains_off(&reporter));
assert!(!marks.contains(&reporter));
assert_eq!(marks.get(&reporter), Some(false));
assert_eq!(detect(&reporter, false, &lib, &marks), None);
// Only that exe: the game next to it is still found.
assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), false, &lib, &marks), found("steam:10", How::InstallDir));
// A game's own launch exe can be switched off too.
let g = manual::game(r"E:\Old\thing.exe", None).unwrap();
let mut m2 = Marks::new();
m2.set(p(r"E:\Old\thing.exe"), false).unwrap();
assert_eq!(detect(&p(r"E:\Old\thing.exe"), false, &[g], &m2), None);
}
#[test]
fn launched_by_arena_beats_marked_off() {
let mut marks = Marks::new();
marks.set(p(r"C:\Games\Foo\foo.exe"), false).unwrap();
marks.set(p(r"C:\Elsewhere\stub.exe"), false).unwrap();
assert_eq!(detect(&p(r"C:\Games\Foo\foo.exe"), true, &library(), &marks), found("steam:10", How::Launched));
assert_eq!(
detect(&p(r"C:\Elsewhere\stub.exe"), true, &library(), &marks),
Some(Detection { game: None, how: How::Launched })
);
}
#[test]
fn on_and_off_replace_each_other() {
let exe = p(r"D:\Emu\Retro.exe");
let mut marks = Marks::new();
assert_eq!(marks.get(&exe), None);
assert_eq!(marks.set(exe.clone(), true), Ok(true));
assert_eq!(marks.set(exe.clone(), true), Ok(false), "already on");
assert_eq!(marks.set(p(r"d:\emu\RETRO.EXE"), false), Ok(true), "on -> off");
assert_eq!(marks.len(), 1, "one exe, never in both sets");
assert_eq!(marks.on().count(), 0);
assert_eq!(marks.off().collect::<Vec<_>>(), vec![&exe], "first spelling kept");
assert_eq!(detect(&exe, false, &[], &marks), None);
// `remove` takes away only an "on" mark; `clear` takes away either.
assert!(!marks.remove(&exe));
assert!(marks.contains_off(&exe));
assert_eq!(marks.set(exe.clone(), true), Ok(true), "off -> on");
assert_eq!(detect(&exe, false, &[], &marks).map(|d| d.how), Some(How::Marked));
assert!(marks.clear(&exe));
assert!(!marks.clear(&exe));
assert!(marks.is_empty());
// Switching a mark at the cap does not count as a new exe.
let mut full = Marks::new();
for i in 0..limits::MAX_MARKS {
full.set(p(&format!(r"C:\G\{i}.exe")), i % 2 == 0).unwrap();
}
assert_eq!(full.set(p(r"C:\G\0.exe"), false), Ok(true));
assert_eq!(full.set(p(r"C:\G\new.exe"), false), Err(ParseError::TooMany("marks")));
} }
#[test] #[test]
@@ -224,12 +295,35 @@ fn marks_persist_through_json() {
let mut marks = Marks::new(); let mut marks = Marks::new();
marks.insert(p(r"D:\Emu\Retro.exe")).unwrap(); marks.insert(p(r"D:\Emu\Retro.exe")).unwrap();
marks.insert(p(r"C:\Tools\Game.exe")).unwrap(); marks.insert(p(r"C:\Tools\Game.exe")).unwrap();
marks.set(p(r"C:\Games\Foo\CrashReporter.exe"), false).unwrap();
marks.set(p(r"C:\Games\Foo\Launcher.exe"), false).unwrap();
let json = serde_json::to_string(&marks).unwrap(); let json = serde_json::to_string(&marks).unwrap();
// A plain array of paths, the first spelling kept, sorted by the case-folded key. // Two arrays of paths, each sorted by the case-folded key, the first spelling kept.
assert_eq!(json, r#"["C:\\Tools\\Game.exe","D:\\Emu\\Retro.exe"]"#); assert_eq!(
json,
concat!(
r#"{"on":["C:\\Tools\\Game.exe","D:\\Emu\\Retro.exe"],"#,
r#""off":["C:\\Games\\Foo\\CrashReporter.exe","C:\\Games\\Foo\\Launcher.exe"]}"#
)
);
let back: Marks = serde_json::from_str(&json).unwrap(); let back: Marks = serde_json::from_str(&json).unwrap();
assert_eq!(back, marks); assert_eq!(back, marks);
assert_eq!(serde_json::to_string(&back).unwrap(), json);
assert_eq!(detect(&p(r"d:\emu\retro.exe"), false, &[], &back).map(|d| d.how), Some(How::Marked)); assert_eq!(detect(&p(r"d:\emu\retro.exe"), false, &[], &back).map(|d| d.how), Some(How::Marked));
assert_eq!(detect(&p(r"c:\games\foo\launcher.exe"), false, &library(), &back), None);
// Empty marks write both keys.
assert_eq!(serde_json::to_string(&Marks::new()).unwrap(), r#"{"on":[],"off":[]}"#);
}
#[test]
fn the_plain_array_form_still_loads_as_on() {
let m: Marks = serde_json::from_str(r#"["C:\\Tools\\Game.exe","D:\\Emu\\Retro.exe"]"#).unwrap();
assert_eq!(m.len(), 2);
assert!(m.contains(&p(r"c:\tools\game.exe")) && m.contains(&p(r"D:\Emu\Retro.exe")));
assert_eq!(m.off().count(), 0);
// Written back in the new form.
assert_eq!(serde_json::to_string(&m).unwrap(), r#"{"on":["C:\\Tools\\Game.exe","D:\\Emu\\Retro.exe"],"off":[]}"#);
assert_eq!(serde_json::from_str::<Marks>("[]").unwrap(), Marks::new());
} }
#[test] #[test]
@@ -237,7 +331,22 @@ fn marks_json_is_checked() {
// Spellings of one exe collapse on load; bad paths and non-strings are refused. // 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(); let m: Marks = serde_json::from_str(r#"["C:\\A\\x.exe","c:/a/X.EXE"]"#).unwrap();
assert_eq!(m.len(), 1); 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""#] { let m: Marks = serde_json::from_str(r#"{"off":["C:\\A\\x.exe","c:/a/X.EXE"]}"#).unwrap();
assert_eq!((m.len(), m.on().count()), (1, 0), "a missing list is empty");
assert_eq!(serde_json::from_str::<Marks>("{}").unwrap(), Marks::new());
for bad in [
r#"["relative\\x.exe"]"#,
r#"["\\\\srv\\s\\x.exe"]"#,
r#"[1]"#,
r#"{"a":1}"#,
r#"{"on":[],"off":[],"extra":[]}"#,
r#"{"on":"C:\\x.exe"}"#,
r#"{"off":["C:\\G\\..\\x.exe"]}"#,
r#""C:\\x.exe""#,
"null",
// One exe in both lists, in two spellings: the verdict is unknown, so refuse.
r#"{"on":["C:\\A\\x.exe"],"off":["c:/a/X.EXE"]}"#,
] {
assert!(serde_json::from_str::<Marks>(bad).is_err(), "{bad}"); assert!(serde_json::from_str::<Marks>(bad).is_err(), "{bad}");
} }
} }
@@ -255,6 +364,9 @@ fn marks_are_capped() {
assert!(serde_json::from_str::<Marks>(&json).is_ok()); assert!(serde_json::from_str::<Marks>(&json).is_ok());
let over: Vec<String> = (0..=limits::MAX_MARKS).map(|i| format!(r"C:\G\{i}.exe")).collect(); let over: Vec<String> = (0..=limits::MAX_MARKS).map(|i| format!(r"C:\G\{i}.exe")).collect();
assert!(serde_json::from_str::<Marks>(&serde_json::to_string(&over).unwrap()).is_err()); assert!(serde_json::from_str::<Marks>(&serde_json::to_string(&over).unwrap()).is_err());
// The cap counts both lists together.
let (on, off) = over.split_at(limits::MAX_MARKS / 2);
assert!(serde_json::from_value::<Marks>(serde_json::json!({ "on": on, "off": off })).is_err());
} }
#[test] #[test]
+6 -2
View File
@@ -150,8 +150,12 @@ fn errors_display_without_input() {
} }
fn modifiers() -> impl Strategy<Value = Modifiers> { fn modifiers() -> impl Strategy<Value = Modifiers> {
(any::<bool>(), any::<bool>(), any::<bool>(), any::<bool>()) (any::<bool>(), any::<bool>(), any::<bool>(), any::<bool>()).prop_map(|(ctrl, alt, shift, win)| Modifiers {
.prop_map(|(ctrl, alt, shift, win)| Modifiers { ctrl, alt, shift, win }) ctrl,
alt,
shift,
win,
})
} }
fn key() -> impl Strategy<Value = Key> { fn key() -> impl Strategy<Value = Key> {
+13 -7
View File
@@ -28,7 +28,7 @@ reads capped bytes and passes them in.
| `MAX_HOST` | 253 bytes | the URL's host | `BadValue("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_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_FRAMES` | 1 048 576 | frametimes one `frames::stats` call takes | `None` |
| `MAX_MARKS` | 4096 | exes marked as games (`detect::Marks`) | `TooMany("marks")` | | `MAX_MARKS` | 4096 | exes marked on or off, together (`detect::Marks`) | `TooMany("marks")` |
| `MAX_HOTKEY` | 64 bytes | shortcut text for `hotkey::parse` | `HotkeyError::TooLong` | | `MAX_HOTKEY` | 64 bytes | shortcut text for `hotkey::parse` | `HotkeyError::TooLong` |
## Errors ## Errors
@@ -214,12 +214,18 @@ frames, seconds }`. `avg_fps = frames / seconds`; the lows are `1000 / frametime
60 frames are never stutters. `None` for an empty series, over `MAX_FRAMES`, any NaN, infinite or negative value, 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). or no time at all (zeros alone).
**`detect::detect(exe, launched_by_arena, library, marks)`**, first match wins: `Launched` (Arena started it; the **`detect::detect(exe, launched_by_arena, library, marks)`**, first match wins: `Launched` (Arena started it,
game if its folder holds the exe), `InstallDir` (the game's own launch exe, else the deepest `install_dir` strictly whatever the marks; the game if the library owns the exe); `None` when the exe is marked **off** ("This is not a
containing the exe; drive roots never count as a containing folder), `Marked` (exactly this exe, `game: None`). game"); `Marked` when it is marked **on** ("This is a game"; the game if the library owns the exe); `InstallDir`
Otherwise `None`: an exe outside every install folder is never auto-detected. Comparison is component-wise and (the game's own launch exe, else the deepest `install_dir` strictly containing the exe; drive roots never count as
ignores case; `WinPath` already refuses `..`, `.`, UNC and `\\?\`. `Marks` serialises as a sorted JSON array of a containing folder). Otherwise `None`: an exe outside every install folder is never auto-detected. Comparison is
paths; loading re-checks each path and folds spellings of one exe. component-wise and ignores case; `WinPath` already refuses `..`, `.`, UNC and `\\?\`. Marks are per exe, never
per folder, and an exe is in at most one set.
`Marks` serialises as `{"on": [paths], "off": [paths]}`, each sorted by the case-folded path. Loading also takes a
plain array of paths as `on` (the first 0.2.0 form), treats a missing list as empty, refuses unknown keys, re-checks
each path, folds spellings of one exe, and refuses an exe in both lists (`Duplicate("marks")`) or more than
`MAX_MARKS` in all (`TooMany("marks")`).
**`hotkey::parse(&str)`**: `Mod+...+Key`, spaces around parts ignored, names ignore case. Modifiers `Ctrl Alt Shift **`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), Win` (each once); key `A`–`Z`, `0`–`9`, `F1`–`F24`, last. Errors: `Empty`, `TooLong`, `Malformed` (empty part),