From 5c17aac8d4b082e5d6471ce4a5f5f8b9b68020b4 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sun, 22 Nov 2026 22:58:26 +0100 Subject: [PATCH] [core] API: compiling Seam 1 skeleton (types, signatures, stubs) --- .gitattributes | 1 + Cargo.lock | 238 ++++++++++++++++++++++++++++++++ Cargo.toml | 8 +- crates/arena-core/Cargo.toml | 20 +++ crates/arena-core/src/domi.rs | 25 ++++ crates/arena-core/src/epic.rs | 18 +++ crates/arena-core/src/error.rs | 61 ++++++++ crates/arena-core/src/gog.rs | 33 +++++ crates/arena-core/src/id.rs | 127 +++++++++++++++++ crates/arena-core/src/launch.rs | 103 ++++++++++++++ crates/arena-core/src/lib.rs | 50 +++++++ crates/arena-core/src/limits.rs | 45 ++++++ crates/arena-core/src/manual.rs | 16 +++ crates/arena-core/src/model.rs | 74 ++++++++++ crates/arena-core/src/path.rs | 104 ++++++++++++++ crates/arena-core/src/steam.rs | 38 +++++ crates/arena-core/src/text.rs | 30 ++++ crates/arena-core/src/vdf.rs | 92 ++++++++++++ rustfmt.toml | 2 + 19 files changed, 1084 insertions(+), 1 deletion(-) create mode 100644 .gitattributes create mode 100644 Cargo.lock create mode 100644 crates/arena-core/Cargo.toml create mode 100644 crates/arena-core/src/domi.rs create mode 100644 crates/arena-core/src/epic.rs create mode 100644 crates/arena-core/src/error.rs create mode 100644 crates/arena-core/src/gog.rs create mode 100644 crates/arena-core/src/id.rs create mode 100644 crates/arena-core/src/launch.rs create mode 100644 crates/arena-core/src/lib.rs create mode 100644 crates/arena-core/src/limits.rs create mode 100644 crates/arena-core/src/manual.rs create mode 100644 crates/arena-core/src/model.rs create mode 100644 crates/arena-core/src/path.rs create mode 100644 crates/arena-core/src/steam.rs create mode 100644 crates/arena-core/src/text.rs create mode 100644 crates/arena-core/src/vdf.rs create mode 100644 rustfmt.toml diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..26830d8 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,238 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arena-core" +version = "0.1.0" +dependencies = [ + "proptest", + "serde", + "serde_json", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "unarray", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index a848b85..8e9ca55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,9 @@ [workspace] -resolver = "2" +resolver = "3" members = ["crates/*"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MPL-2.0" +repository = "https://gitea.marek-novak.cz/mnovak/ArenaPublic" diff --git a/crates/arena-core/Cargo.toml b/crates/arena-core/Cargo.toml new file mode 100644 index 0000000..960cad3 --- /dev/null +++ b/crates/arena-core/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "arena-core" +description = "Arena Domi core: strict parsers for game launcher files and the game library model. Pure, no I/O." +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[lib] +name = "arena_core" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[dev-dependencies] +proptest = { version = "1.12", default-features = false, features = ["std"] } + +[lints.rust] +unsafe_code = "forbid" diff --git a/crates/arena-core/src/domi.rs b/crates/arena-core/src/domi.rs new file mode 100644 index 0000000..e268dc0 --- /dev/null +++ b/crates/arena-core/src/domi.rs @@ -0,0 +1,25 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Domi games: Atrium registry entries with `kind = "game"`, launched through their `domi-://open` link, or +//! web games (Rosea, Moin) opened by URL. + +use crate::error::ParseError; +use crate::model::Game; + +/// How a Domi game starts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DomiLaunch<'a> { + /// `domi-://open`; `app` follows the Atrium id rules. + Link { app: &'a str }, + /// A web game: `https://` only, the host must be one of `allowed_hosts`. + Web { url: &'a str, allowed_hosts: &'a [&'a str] }, +} + +/// The game for one Domi entry. `id` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end) and +/// becomes `domi:`; `name` is the title. No install folder. +pub fn game(id: &str, name: &str, launch: DomiLaunch<'_>) -> Result { + let _ = (id, name, launch); + Err(ParseError::BadId) +} diff --git a/crates/arena-core/src/epic.rs b/crates/arena-core/src/epic.rs new file mode 100644 index 0000000..48c3023 --- /dev/null +++ b/crates/arena-core/src/epic.rs @@ -0,0 +1,18 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Epic Games Launcher: one JSON `.item` manifest per installed app in +//! `%ProgramData%\Epic\EpicGamesLauncher\Data\Manifests`. Launch is +//! `com.epicgames.launcher://apps/?action=launch&silent=true`. + +use crate::error::ParseError; +use crate::model::Game; + +/// The game described by one `.item` manifest. Reads `AppName`, `DisplayName` and `InstallLocation` (all +/// required strings) and `MainGameAppName` (optional; when it names another app the file is an add-on and gives +/// [`ParseError::NotAGame`]). Other fields are ignored but must still be well-formed JSON within the caps. +pub fn item(json: &[u8]) -> Result { + let _ = json; + Err(ParseError::Syntax { at: 0 }) +} diff --git a/crates/arena-core/src/error.rs b/crates/arena-core/src/error.rs new file mode 100644 index 0000000..abc6b9e --- /dev/null +++ b/crates/arena-core/src/error.rs @@ -0,0 +1,61 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use std::fmt; + +/// Why an input was refused. The `&'static str` names the field or the token kind; it never carries input text, +/// so an error is always safe to log. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum ParseError { + /// The input is larger than [`crate::limits::MAX_FILE`]. + TooLarge, + /// Objects are nested deeper than [`crate::limits::MAX_DEPTH`]. + TooDeep, + /// A string or the whole input is not valid UTF-8. + NotUtf8, + /// The text is malformed at this byte offset. + Syntax { at: usize }, + /// A required field is absent. + Missing(&'static str), + /// A field has the wrong type (an object where a string belongs, a number where a string belongs, ...). + WrongType(&'static str), + /// A path field is not a valid [`crate::WinPath`] or escapes where it must stay. + BadPath(&'static str), + /// An id (Steam app id, Epic app name, GOG id, Domi id, [`crate::GameId`]) is malformed or out of range. + BadId, + /// A key or an entry appears twice. + Duplicate(&'static str), + /// A key, value or field is longer than its cap. + TooLong(&'static str), + /// More entries than the cap allows. + TooMany(&'static str), + /// A text field, URL or argument holds characters it may not hold. + BadValue(&'static str), + /// The file is valid but describes something that is not a game (a Steam redistributable, an Epic add-on). + /// Callers skip these quietly. + NotAGame(&'static str), +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ParseError::TooLarge => write!(f, "input is larger than {} bytes", crate::limits::MAX_FILE), + ParseError::TooDeep => write!(f, "nesting is deeper than {} levels", crate::limits::MAX_DEPTH), + ParseError::NotUtf8 => f.write_str("text is not valid UTF-8"), + ParseError::Syntax { at } => write!(f, "syntax error at byte {at}"), + ParseError::Missing(what) => write!(f, "missing field: {what}"), + ParseError::WrongType(what) => write!(f, "wrong type for field: {what}"), + ParseError::BadPath(what) => write!(f, "invalid path: {what}"), + ParseError::BadId => f.write_str("invalid id"), + ParseError::Duplicate(what) => write!(f, "duplicate: {what}"), + ParseError::TooLong(what) => write!(f, "too long: {what}"), + ParseError::TooMany(what) => write!(f, "too many: {what}"), + ParseError::BadValue(what) => write!(f, "invalid value: {what}"), + ParseError::NotAGame(what) => write!(f, "not a game: {what}"), + } + } +} + +impl std::error::Error for ParseError {} diff --git a/crates/arena-core/src/gog.rs b/crates/arena-core/src/gog.rs new file mode 100644 index 0000000..101be8c --- /dev/null +++ b/crates/arena-core/src/gog.rs @@ -0,0 +1,33 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! GOG: the app reads one registry key per installed game (assumption, verify on the PC: +//! `HKLM\SOFTWARE\WOW6432Node\GOG.com\Games\` with the values `gameID`, `gameName`, `path`, `exe`, +//! `workingDir`, `launchParam`) and passes the values in. Launch is the `.exe` directly. + +use crate::error::ParseError; +use crate::model::Game; + +/// The registry values of one GOG game, as the app read them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GogEntry { + /// `gameID`: 1 to 20 digits. + pub game_id: String, + /// `gameName`: the title. + pub name: String, + /// `path`: the install folder, absolute. + pub path: String, + /// `exe`: the program, absolute or relative to `path`; must end in `.exe` and lie inside `path`. + pub exe: String, + /// `workingDir`: absolute or relative to `path`; empty or absent means the exe's folder. + pub working_dir: Option, + /// `launchParam`: arguments, split on spaces with `"` grouping. + pub launch_params: Option, +} + +/// The game for one GOG entry. +pub fn game(e: &GogEntry) -> Result { + let _ = e; + Err(ParseError::BadId) +} diff --git a/crates/arena-core/src/id.rs b/crates/arena-core/src/id.rs new file mode 100644 index 0000000..a175759 --- /dev/null +++ b/crates/arena-core/src/id.rs @@ -0,0 +1,127 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use crate::error::ParseError; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::str::FromStr; + +/// Where a game came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +#[non_exhaustive] +pub enum Source { + Steam, + Epic, + Gog, + Manual, + Domi, +} + +impl Source { + /// Every source, in declaration order. + pub const ALL: [Source; 5] = [Source::Steam, Source::Epic, Source::Gog, Source::Manual, Source::Domi]; + + /// The lowercase name used in a [`GameId`] and in JSON: `steam`, `epic`, `gog`, `manual`, `domi`. + pub fn as_str(self) -> &'static str { + match self { + Source::Steam => "steam", + Source::Epic => "epic", + Source::Gog => "gog", + Source::Manual => "manual", + Source::Domi => "domi", + } + } + + /// Which source wins when two games share an install folder: Steam > Epic > GOG > Domi > Manual. + pub fn priority(self) -> u8 { + match self { + Source::Steam => 5, + Source::Epic => 4, + Source::Gog => 3, + Source::Domi => 2, + Source::Manual => 1, + } + } +} + +impl fmt::Display for Source { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl FromStr for Source { + type Err = ParseError; + + /// Strict: exactly one of the lowercase names. + fn from_str(s: &str) -> Result { + Source::ALL.into_iter().find(|src| src.as_str() == s).ok_or(ParseError::BadId) + } +} + +/// A game's id: `:`, only `[a-z0-9:._-]`, at most [`crate::limits::MAX_GAME_ID`] bytes. +/// +/// The native part is checked per source: Steam a canonical non-zero `u32`, Epic `[a-z0-9_-]{1,64}` (the app +/// name, lowercased), GOG 1 to 20 digits, Manual 16 lowercase hex digits, Domi an Atrium id. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct GameId(String); + +impl GameId { + /// Builds and checks `:`. + pub fn new(source: Source, native: &str) -> Result { + let _ = (source, native); + Err(ParseError::BadId) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// The source named by the prefix. + pub fn source(&self) -> Source { + Source::Manual + } + + /// The part after `:`. + pub fn native(&self) -> &str { + "" + } +} + +impl fmt::Display for GameId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl FromStr for GameId { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + let _ = s; + Err(ParseError::BadId) + } +} + +impl TryFrom for GameId { + type Error = ParseError; + + fn try_from(s: String) -> Result { + s.parse() + } +} + +impl From for String { + fn from(id: GameId) -> String { + id.0 + } +} + +impl AsRef for GameId { + fn as_ref(&self) -> &str { + &self.0 + } +} diff --git a/crates/arena-core/src/launch.rs b/crates/arena-core/src/launch.rs new file mode 100644 index 0000000..9a185f1 --- /dev/null +++ b/crates/arena-core/src/launch.rs @@ -0,0 +1,103 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use crate::error::ParseError; +use crate::path::WinPath; +use serde::{Deserialize, Serialize}; + +/// How to start a game. The protocol variants become a URI through [`Launch::uri`]; [`Launch::Exe`] is started +/// directly (never through a shell) with an explicit working folder. +/// +/// The fields are public so callers can match on them, but every builder ([`Launch::steam`], [`Launch::epic`], +/// [`Launch::exe`], [`Launch::domi_link`], [`Launch::web`]) validates, deserialising validates, and +/// [`Launch::uri`] validates again, so a hand-built bad value yields no URI. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", try_from = "LaunchRepr")] +pub enum Launch { + /// `steam://rungameid/`. + SteamRunGameId(u32), + /// `com.epicgames.launcher://apps/?action=launch&silent=true`; `app_name` is `[A-Za-z0-9_-]{1,64}`. + Epic { app_name: String }, + /// GOG and manual games: the `.exe`, its working folder and the arguments, passed as separate arguments. + Exe { exe: WinPath, working_dir: WinPath, args: Vec }, + /// `domi-://open`; `app` follows the Atrium id rules. + DomiLink { app: String }, + /// A web game: `https://` only, the host on an allow-list the caller passes in. + Url(String), +} + +impl Launch { + /// A Steam launch; the app id may not be 0. + pub fn steam(app_id: u32) -> Result { + let _ = app_id; + Err(ParseError::BadId) + } + + /// An Epic launch; `app_name` must match `[A-Za-z0-9_-]{1,64}`. + pub fn epic(app_name: &str) -> Result { + let _ = app_name; + Err(ParseError::BadId) + } + + /// A direct launch. `exe` must end in `.exe` (so never a `.bat`, `.cmd` or `.lnk`, which Windows would hand to + /// a shell); each argument is checked (no control characters, caps on count and length). + pub fn exe(exe: WinPath, working_dir: WinPath, args: Vec) -> Result { + let _ = (exe, working_dir, args); + Err(ParseError::BadPath("exe")) + } + + /// A Domi app link; `app` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end). + pub fn domi_link(app: &str) -> Result { + let _ = app; + Err(ParseError::BadId) + } + + /// A web game. The URL must be `https://[/path][?query][#fragment]` with no user info and no port, and + /// `host` must equal (ignoring case) one of `allowed_hosts`. The scheme and host are lowercased. + pub fn web(url: &str, allowed_hosts: &[&str]) -> Result { + let _ = (url, allowed_hosts); + Err(ParseError::BadValue("url")) + } + + /// The exact URI for the protocol variants, rebuilt from the validated fields; `None` for [`Launch::Exe`] and + /// for any field that fails validation. For [`Launch::Url`] this checks the URL's form only; use + /// [`Launch::uri_checked`] to apply the host allow-list again. + pub fn uri(&self) -> Option { + None + } + + /// As [`Launch::uri`], and a [`Launch::Url`] must also have its host in `allowed_hosts`. + pub fn uri_checked(&self, allowed_hosts: &[&str]) -> Option { + let _ = allowed_hosts; + None + } +} + +/// The wire shape of [`Launch`]; deserialising goes through it so every field is validated. +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum LaunchRepr { + SteamRunGameId(u32), + Epic { app_name: String }, + Exe { exe: WinPath, working_dir: WinPath, args: Vec }, + DomiLink { app: String }, + Url(String), +} + +impl TryFrom for Launch { + type Error = ParseError; + + fn try_from(r: LaunchRepr) -> Result { + match r { + LaunchRepr::SteamRunGameId(id) => Launch::steam(id), + LaunchRepr::Epic { app_name } => Launch::epic(&app_name), + LaunchRepr::Exe { exe, working_dir, args } => Launch::exe(exe, working_dir, args), + LaunchRepr::DomiLink { app } => Launch::domi_link(&app), + LaunchRepr::Url(url) => { + let _ = url; + Err(ParseError::BadValue("url")) + } + } + } +} diff --git a/crates/arena-core/src/lib.rs b/crates/arena-core/src/lib.rs new file mode 100644 index 0000000..5ae9da6 --- /dev/null +++ b/crates/arena-core/src/lib.rs @@ -0,0 +1,50 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The pure core of Arena Domi: strict parsers for game launcher files and the game library model. +//! +//! Nothing here touches the file system, processes, the network, the environment, the registry or the clock. +//! Inputs are bytes or values; outputs are [`Game`]s and a merged [`Library`]. Every parser treats its input as +//! hostile: sizes, depth, lengths and counts are capped ([`limits`]), errors are typed ([`ParseError`]) and no input +//! can make the crate panic. +//! +//! Sources: [`steam`] (`libraryfolders.vdf`, `appmanifest_.acf`), [`epic`] (`.item` JSON), [`gog`] (registry +//! values the app passes in), [`manual`] (an `.exe` the user picked) and [`domi`] (Domi games from the Atrium +//! registry). [`merge`] dedupes the scans into one library. +//! +//! Launch strings are built by [`Launch::uri`] only from validated, parsed fields. + +#![forbid(unsafe_code)] +#![deny( + clippy::unwrap_used, + clippy::expect_used, + clippy::indexing_slicing, + clippy::string_slice, + clippy::panic, + clippy::todo, + clippy::unimplemented, + clippy::unreachable +)] + +mod error; +mod id; +mod launch; +pub mod limits; +mod model; +mod path; +mod text; +pub mod vdf; + +pub mod domi; +pub mod epic; +pub mod gog; +pub mod manual; +pub mod steam; + +pub use domi::DomiLaunch; +pub use error::ParseError; +pub use id::{GameId, Source}; +pub use launch::Launch; +pub use model::{CoverHint, Game, Library, merge}; +pub use path::WinPath; diff --git a/crates/arena-core/src/limits.rs b/crates/arena-core/src/limits.rs new file mode 100644 index 0000000..5ccb420 --- /dev/null +++ b/crates/arena-core/src/limits.rs @@ -0,0 +1,45 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Every cap the parsers enforce. Anything over a cap is refused, never truncated. `docs/FORMATS.md` lists them +//! with the error each one gives. + +/// Largest input file (VDF, ACF, `.item` JSON), in bytes. +pub const MAX_FILE: usize = 1 << 20; +/// Deepest nesting of objects (VDF `{`, JSON `{` and `[`). +pub const MAX_DEPTH: usize = 32; +/// Longest VDF key, in bytes after unescaping. +pub const MAX_KEY: usize = 256; +/// Longest VDF value, in bytes after unescaping. +pub const MAX_VALUE: usize = 4096; +/// Most escape sequences in one VDF string. +pub const MAX_ESCAPES: usize = 256; +/// Most key/value pairs in one VDF document, counted over every level. +pub const MAX_ENTRIES: usize = 65_536; +/// Most Steam library folders in one `libraryfolders.vdf`. +pub const MAX_LIBRARIES: usize = 64; +/// Longest Windows path, in UTF-16 code units (`MAX_PATH`). +pub const MAX_PATH: usize = 260; +/// Longest game title, in characters after trimming. +pub const MAX_TITLE: usize = 256; +/// Longest [`crate::GameId`], in bytes. +pub const MAX_GAME_ID: usize = 96; +/// Longest Epic app name, in bytes (`[A-Za-z0-9_-]{1,64}`). +pub const MAX_EPIC_APP: usize = 64; +/// Longest Domi app id, in bytes (Atrium id rules: `[a-z0-9-]{1,32}`, no `-` at either end). +pub const MAX_DOMI_ID: usize = 32; +/// Longest GOG game id, in digits. +pub const MAX_GOG_ID: usize = 20; +/// Longest launch-parameter string a GOG entry may carry, in bytes. +pub const MAX_ARGS_LINE: usize = 4096; +/// Most arguments an [`crate::Launch::Exe`] may carry. +pub const MAX_ARGS: usize = 32; +/// Longest single argument, in bytes. +pub const MAX_ARG: usize = 1024; +/// Longest web-game URL, in bytes. +pub const MAX_URL: usize = 2048; +/// Longest host name in a web-game URL, in bytes. +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; diff --git a/crates/arena-core/src/manual.rs b/crates/arena-core/src/manual.rs new file mode 100644 index 0000000..85fd63a --- /dev/null +++ b/crates/arena-core/src/manual.rs @@ -0,0 +1,16 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! A game the user added by picking its `.exe`. + +use crate::error::ParseError; +use crate::model::Game; + +/// The game for an `.exe` the user picked. The id is `manual:<16 hex>`, a stable hash of the path ignoring case, +/// so adding the same file twice gives the same id. The title defaults to the file name without `.exe`; the +/// install and working folder are the exe's folder; no arguments. +pub fn game(exe: &str, title: Option<&str>) -> Result { + let _ = (exe, title); + Err(ParseError::BadPath("exe")) +} diff --git a/crates/arena-core/src/model.rs b/crates/arena-core/src/model.rs new file mode 100644 index 0000000..9055cc0 --- /dev/null +++ b/crates/arena-core/src/model.rs @@ -0,0 +1,74 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use crate::id::{GameId, Source}; +use crate::launch::Launch; +use crate::path::WinPath; +use serde::{Deserialize, Serialize}; + +/// One game in the library. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Game { + pub id: GameId, + pub source: Source, + /// Display title: trimmed, 1 to [`crate::limits::MAX_TITLE`] characters, no control characters. + pub title: String, + pub install_dir: Option, + pub launch: Launch, + pub cover: Option, +} + +/// Where the tile's picture comes from. No online lookups, ever. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CoverHint { + /// Steam's own local library cache for this app id (the app finds the file). + SteamLibraryCache { app_id: u32 }, + /// A picture file on disk. + LocalFile(WinPath), + /// A lettered tile: the title's first letter or digit on a colour of this hue (0 to 359). + Lettered { letter: char, hue: u16 }, +} + +impl CoverHint { + /// The lettered tile for a game: the first letter or digit of `title` (uppercased; `#` when there is none) and a + /// hue derived from `id`, so a game keeps its colour across scans. + pub fn lettered(title: &str, id: &GameId) -> CoverHint { + crate::text::lettered(title, id) + } +} + +/// The merged library, ordered by title. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Library { + pub games: Vec, +} + +impl Library { + /// The game with this id. + pub fn get(&self, id: &GameId) -> Option<&Game> { + self.games.iter().find(|g| &g.id == id) + } + + pub fn len(&self) -> usize { + self.games.len() + } + + pub fn is_empty(&self) -> bool { + self.games.is_empty() + } +} + +/// Merges per-source scans into one library. +/// +/// - The same [`GameId`] is kept once (its first occurrence). +/// - Games of different sources with the same install folder (compared ignoring case): only the highest +/// [`Source::priority`] stays (Steam > Epic > GOG > Domi > Manual). Games of the same source are never dropped +/// for sharing a folder. +/// - The result is sorted by title (ignoring case), then by id, so the order does not depend on scan order. +/// - At most [`crate::limits::MAX_GAMES`] games are considered; the rest are dropped. +pub fn merge(scans: Vec>) -> Library { + let _ = scans; + Library::default() +} diff --git a/crates/arena-core/src/path.rs b/crates/arena-core/src/path.rs new file mode 100644 index 0000000..752e526 --- /dev/null +++ b/crates/arena-core/src/path.rs @@ -0,0 +1,104 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use crate::error::ParseError; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::str::FromStr; + +/// An absolute Windows path with a drive letter, checked and normalised. +/// +/// Refused: anything not starting with `X:\` (so UNC `\\server\share`, `\\?\` and `\\.\` too), `.` and `..` +/// components, NUL and other control characters, `<>:"|?*` (a `:` only after the drive letter), device names +/// (`CON`, `NUL`, `COM1`, ...) as any component, components ending in a dot or a space, and paths over +/// [`crate::limits::MAX_PATH`] UTF-16 units. Normalised: `/` becomes `\`, repeated separators collapse, the drive +/// letter is uppercase and a trailing separator is dropped (except on the drive root `X:\`). +/// +/// Equality is exact on the normalised text; [`WinPath::eq_ignore_case`] compares the way Windows does. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct WinPath(String); + +impl WinPath { + /// Checks and normalises `s`. + pub fn parse(s: &str) -> Result { + let _ = s; + Err(ParseError::BadPath("path")) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// Appends a relative path (`a\b` or `a/b`); the same component rules apply and it may not climb out. + pub fn join(&self, relative: &str) -> Result { + let _ = relative; + Err(ParseError::BadPath("path")) + } + + /// The containing folder, or `None` for a drive root. + pub fn parent(&self) -> Option { + None + } + + /// The last component, or `None` for a drive root. + pub fn file_name(&self) -> Option<&str> { + None + } + + /// The components after the drive root. + pub fn components(&self) -> impl Iterator { + std::iter::empty() + } + + /// The case-folded form Windows treats as the same place, for comparing and deduping. + pub fn key(&self) -> String { + self.0.to_lowercase() + } + + /// True when both name the same place, ignoring case. + pub fn eq_ignore_case(&self, other: &WinPath) -> bool { + self.key() == other.key() + } + + /// True when `self` is `base` or lies inside it (component-wise, ignoring case). + pub fn starts_with(&self, base: &WinPath) -> bool { + let _ = base; + false + } +} + +impl fmt::Display for WinPath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl FromStr for WinPath { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + WinPath::parse(s) + } +} + +impl TryFrom for WinPath { + type Error = ParseError; + + fn try_from(s: String) -> Result { + WinPath::parse(&s) + } +} + +impl From for String { + fn from(p: WinPath) -> String { + p.0 + } +} + +impl AsRef for WinPath { + fn as_ref(&self) -> &str { + &self.0 + } +} diff --git a/crates/arena-core/src/steam.rs b/crates/arena-core/src/steam.rs new file mode 100644 index 0000000..83d4470 --- /dev/null +++ b/crates/arena-core/src/steam.rs @@ -0,0 +1,38 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Steam: `config/libraryfolders.vdf` lists the library folders; each installed app has +//! `/steamapps/appmanifest_.acf`. Launch is `steam://rungameid/`. + +use crate::error::ParseError; +use crate::model::Game; +use crate::path::WinPath; + +/// The library folders listed in `libraryfolders.vdf` (both the current layout, `"0" { "path" "..." }`, and the +/// old one, `"1" "D:\\SteamLibrary"`). At most [`crate::limits::MAX_LIBRARIES`]; a path listed twice is refused. +pub fn library_folders(vdf: &[u8]) -> Result, ParseError> { + let _ = vdf; + Err(ParseError::Syntax { at: 0 }) +} + +/// The game described by `appmanifest_.acf` inside `library` (the folder holding `steamapps`). The install +/// folder is `\steamapps\common\`, where `installdir` must be one plain folder name. +/// Steam's own redistributables and runtimes ([`is_tool`]) give [`ParseError::NotAGame`]. +pub fn app_manifest(acf: &[u8], library: &WinPath) -> Result { + let _ = (acf, library); + Err(ParseError::Syntax { at: 0 }) +} + +/// The app id in a file name `appmanifest_.acf` (exact, lowercase, canonical id), for filtering a folder +/// listing; `None` for any other name. +pub fn app_id_from_manifest_name(name: &str) -> Option { + let _ = name; + None +} + +/// Steam apps that are not games: the common redistributables and the Linux runtimes. +pub fn is_tool(app_id: u32) -> bool { + let _ = app_id; + false +} diff --git a/crates/arena-core/src/text.rs b/crates/arena-core/src/text.rs new file mode 100644 index 0000000..245d9db --- /dev/null +++ b/crates/arena-core/src/text.rs @@ -0,0 +1,30 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Small shared helpers: title checks, a stable hash, the lettered cover. + +use crate::error::ParseError; +use crate::id::GameId; +use crate::model::CoverHint; + +/// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control characters. +pub(crate) fn title(s: &str, field: &'static str) -> Result { + let _ = s; + Err(ParseError::Missing(field)) +} + +/// FNV-1a, 64 bit: stable across builds and platforms (unlike `std`'s hasher). +pub(crate) fn fnv1a64(bytes: &[u8]) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +pub(crate) fn lettered(title: &str, id: &GameId) -> CoverHint { + let _ = (title, id); + CoverHint::Lettered { letter: '#', hue: 0 } +} diff --git a/crates/arena-core/src/vdf.rs b/crates/arena-core/src/vdf.rs new file mode 100644 index 0000000..ed00a76 --- /dev/null +++ b/crates/arena-core/src/vdf.rs @@ -0,0 +1,92 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! A strict tokenizer, parser and writer for Valve's KeyValues text format (VDF), as used by Steam's +//! `libraryfolders.vdf` and `appmanifest_.acf`. +//! +//! Accepted: quoted strings with the escapes `\\`, `\"`, `\n`, `\t` and `\r`; `{` and `}`; whitespace (space, tab, +//! CR, LF); `//` comments to the end of the line; one UTF-8 byte-order mark at the start. Refused: unquoted +//! tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control characters or line breaks inside +//! a string, NUL anywhere, empty keys, a key repeated on the same level (ignoring ASCII case), and anything over the +//! caps in [`crate::limits`]. + +use crate::error::ParseError; + +/// One token and the byte offset where it starts. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Token { + pub kind: TokenKind, + pub at: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TokenKind { + /// `{` + Open, + /// `}` + Close, + /// A quoted string, unescaped. + Str(String), +} + +/// A value: a string or a nested object. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Value { + Str(String), + Obj(Obj), +} + +/// An ordered list of key/value pairs with unique keys (ignoring ASCII case). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Obj { + entries: Vec<(String, Value)>, +} + +impl Obj { + pub fn new() -> Obj { + Obj::default() + } + + /// Appends a pair. Refuses an empty key, a key or value over its cap, and a key already present. + pub fn insert(&mut self, key: String, value: Value) -> Result<(), ParseError> { + let _ = (key, value); + Err(ParseError::Missing("key")) + } + + /// The value under `key`, ignoring ASCII case. + pub fn get(&self, key: &str) -> Option<&Value> { + self.entries.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v) + } + + /// The pairs in file order. + pub fn iter(&self) -> impl Iterator { + self.entries.iter().map(|(k, v)| (k.as_str(), v)) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +/// Splits `input` into tokens. Checks size, UTF-8, escapes and string lengths; not nesting. +pub fn tokenize(input: &[u8]) -> Result, ParseError> { + let _ = input; + Err(ParseError::Syntax { at: 0 }) +} + +/// Parses a whole document: a sequence of top-level pairs. +pub fn parse(input: &[u8]) -> Result { + let _ = input; + Err(ParseError::Syntax { at: 0 }) +} + +/// Writes a document in Valve's layout (tabs, one pair per line). [`parse`] of the result gives `doc` back. +pub fn write(doc: &Obj) -> String { + let _ = doc; + String::new() +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max"