9 Commits

Author SHA1 Message Date
mnovak 95d031fef9 [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.
2026-11-26 03:27:03 +01:00
mnovak 43701bbadc [core] WIP: frames, detect, hotkey modules with tests; caps, docs, version 0.2.0 (fmt/clippy/wasm/android not yet run) 2026-11-25 14:32:16 +01:00
mnovak 871d69de1c [repo] Merge: chore/cpal (licence CPAL-1.0, version 0.1.1, PR #2) 2026-11-23 00:14:24 +01:00
mnovak b3d5291bb1 [repo] Licence: CPAL-1.0 (Mark, 2026-11-23), Exhibit B credit in README, SPDX headers, version 0.1.1 2026-11-23 00:14:14 +01:00
mnovak 0ac5223086 [repo] Merge: feature/core (arena-core 0.1.0: strict launcher parsers, library model, merge, PR #1) 2026-11-22 23:37:58 +01:00
mnovak 81b7fdf11d [core] Tests: WinPath, GameId and join properties; error Display 2026-11-22 23:36:08 +01:00
mnovak cf5ba34bed [core] Parsers: strict VDF, Steam, Epic, GOG, manual and Domi sources, WinPath, GameId, Launch URIs, merge 2026-11-22 23:26:18 +01:00
mnovak e85f160f88 [core] Tests: fixtures and mandatory tests (valid, hostile, property, launch, dedupe) ahead of the code 2026-11-22 23:06:46 +01:00
mnovak 5c17aac8d4 [core] API: compiling Seam 1 skeleton (types, signatures, stubs) 2026-11-22 22:58:26 +01:00
63 changed files with 5974 additions and 350 deletions
+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
Generated
+238
View File
@@ -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.2.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"
+7 -1
View File
@@ -1,3 +1,9 @@
[workspace] [workspace]
resolver = "2" resolver = "3"
members = ["crates/*"] members = ["crates/*"]
[workspace.package]
version = "0.2.0"
edition = "2024"
license = "CPAL-1.0"
repository = "https://gitea.marek-novak.cz/mnovak/ArenaPublic"
+140 -345
View File
@@ -1,373 +1,168 @@
Mozilla Public License Version 2.0 Common Public Attribution License Version 1.0 (CPAL)
==================================
1. Definitions 1. “Definitions”
--------------
1.1. "Contributor" 1.0.1 “Commercial Use” means distribution or otherwise making the Covered Code available to a third party.
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version" 1.1 “Contributor” means each entity that creates or contributes to the creation of Modifications.
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution" 1.2 “Contributor Version” means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor.
means Covered Software of a particular Contributor.
1.4. "Covered Software" 1.3 “Covered Code” means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof.
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses" 1.4 “Electronic Distribution Mechanism” means a mechanism generally accepted in the software development community for the electronic transfer of data.
means
(a) that the initial Contributor has attached the notice described 1.5 “Executable” means Covered Code in any form other than Source Code.
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of 1.6 “Initial Developer” means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A.
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form" 1.7 “Larger Work” means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.
means any form of the work other than Source Code Form.
1.7. "Larger Work" 1.8 “License” means this document.
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License" 1.8.1 “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
means this document.
1.9. "Licensable" 1.9 “Modifications” means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is:
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications" A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
means any of the following:
(a) any file in Source Code Form that results from an addition to, B. Any new file that contains any part of the Original Code or previous Modifications.
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered 1.10 “Original Code” means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License.
Software.
1.11. "Patent Claims" of a Contributor 1.10.1 “Patent Claims” means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License" 1.11 “Source Code” means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor’s choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge.
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form" 1.12 “You” (or “Your”) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, “You” includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
means the form of the work preferred for making modifications.
1.14. "You" (or "Your") 2. Source Code License.
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions 2.1 The Initial Developer Grant.
-------------------------------- The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims:
2.1. Grants (a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and
Each Contributor hereby grants You a world-wide, royalty-free, (b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof).
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) (c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License.
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer (d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices.
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date 2.2 Contributor Grant.
Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license
The licenses granted in Section 2.1 with respect to any Contribution (a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope (b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
The licenses granted in this Section 2 are the only rights granted under (c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code.
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License. (d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor: 3. Distribution Obligations.
(a) for any code that a Contributor has removed from Covered Software; 3.1 Application of License.
or The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients’ rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5.
(b) for infringements caused by: (i) Your and any other third party's 3.2 Availability of Source Code.
modifications of Covered Software, or (ii) the combination of its Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party.
Contributions with other software (except as part of its Contributor
Version); or 3.3 Description of Modifications.
You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code.
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions. 3.4 Intellectual Property Matters
This License does not grant any rights in the trademarks, service marks, (a) Third Party Claims. If Contributor has knowledge that a license under a third party’s intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled “LEGAL” which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained.
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4). (b) Contributor APIs. If Contributor’s Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file.
2.4. Subsequent Licenses (c) Representations. Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor’s Modifications are Contributor’s original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License.
No Contributor makes additional grants as a result of Your choice to 3.5 Required Notices.
distribute the Covered Software under a subsequent version of this You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients’ rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3). 3.6 Distribution of Executable Versions.
You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients’ rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient’s rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer, Original Developer or any Contributor. You hereby agree to indemnify the Initial Developer, Original Developer and every Contributor for any liability incurred by the Initial Developer, Original Developer or such Contributor as a result of any such terms You offer.
2.5. Representation
3.7 Larger Works.
Each Contributor represents that the Contributor believes its You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code.
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License. 4. Inability to Comply Due to Statute or Regulation.
If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
2.6. Fair Use
5. Application of this License.
This License is not intended to limit any rights You have under This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code.
applicable copyright doctrines of fair use, fair dealing, or other
equivalents. 6. Versions of the License.
2.7. Conditions 6.1 New Versions.
Socialtext, Inc. (“Socialtext”) may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number.
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1. 6.2 Effect of New Versions.
Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Socialtext. No one other than Socialtext has the right to modify the terms applicable to Covered Code created under this License.
3. Responsibilities
------------------- 6.3 Derivative Works.
If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases “Socialtext”, “CPAL” or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the CPAL. (Filling in the name of the Initial Developer, Original Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.)
3.1. Distribution of Source Form
7. DISCLAIMER OF WARRANTY.
All distribution of Covered Software in Source Code Form, including any COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER, ORIGINAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source 8. TERMINATION.
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not 8.1 This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
attempt to alter or restrict the recipients' rights in the Source Code
Form. 8.2 If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer, Original Developer or a Contributor (the Initial Developer, Original Developer or Contributor against whom You file such action is referred to as “Participant”) alleging that:
3.2. Distribution of Executable Form (a) such Participant’s Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above.
If You distribute Covered Software in Executable Form then: (b) any software, hardware, or device, other than such Participant’s Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant.
(a) such Covered Software must also be made available in Source Code 8.3 If You assert a patent infringement claim against Participant alleging that such Participant’s Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license.
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code 8.4 In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination.
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and 9. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ORIGINAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY’S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the 10. U.S. GOVERNMENT END USERS.
license for the Executable Form does not attempt to limit or alter The Covered Code is a “commercial item,” as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of “commercial computer software” and “commercial computer software documentation,” as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein.
the recipients' rights in the Source Code Form under this License.
11. MISCELLANEOUS.
3.3. Distribution of a Larger Work This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys’ fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License.
You may create and distribute a Larger Work under terms of Your choice, 12. RESPONSIBILITY FOR CLAIMS.
provided that You also comply with the requirements of this License for As between Initial Developer, Original Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer, Original Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the 13. MULTIPLE-LICENSED CODE.
Covered Software is not Incompatible With Secondary Licenses, this Initial Developer may designate portions of the Covered Code as Multiple-Licensed. Multiple-Licensed means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the CPAL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A.
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of 14. ADDITIONAL TERM: ATTRIBUTION
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary (a) As a modest attribution to the organizer of the development of the Original Code (“Original Developer”), in the hope that its promotional value may help justify the time, money and effort invested in writing the Original Code, the Original Developer may include in Exhibit B (“Attribution Information”) a requirement that each time an Executable and Source Code or a Larger Work is launched or initially run (which includes initiating a session), a prominent display of the Original Developer’s Attribution Information (as defined below) must occur on the graphic user interface employed by the end user to access such Covered Code (which may include display on a splash screen), if any. The size of the graphic image should be consistent with the size of the other elements of the Attribution Information. If the access by the end user to the Executable and Source Code does not create a graphic user interface for access to the Covered Code, this obligation shall not apply. If the Original Code displays such Attribution Information in a particular form (such as in the form of a splash screen, notice at login, an “about” display, or dedicated attribution area on user interface screens), continued use of such form for that Attribution Information is one way of meeting this requirement for notice.
License(s).
(b) Attribution information may only include a copyright notice, a brief phrase, graphic image and a URL (“Attribution Information”) and is subject to the Attribution Limits as defined below. For these purposes, prominent shall mean display for sufficient duration to give reasonable notice to the user of the identity of the Original Developer and that if You include Attribution Information or similar information for other parties, You must ensure that the Attribution Information for the Original Developer shall be no less prominent than such Attribution Information or similar information for the other party. For greater certainty, the Original Developer may choose to specify in Exhibit B below that the above attribution requirement only applies to an Executable and Source Code resulting from the Original Code or any Modification, but not a Larger Work. The intent is to provide for reasonably modest attribution, therefore the Original Developer cannot require that You display, at any time, more than the following information as Attribution Information: (a) a copyright notice including the name of the Original Developer; (b) a word or one phrase (not exceeding 10 words); (c) one graphic image provided by the Original Developer; and (d) a URL (collectively, the “Attribution Limits”).
3.4. Notices
(c) If Exhibit B does not include any Attribution Information, then there are no requirements for You to display any Attribution Information of the Original Developer.
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, (d) You acknowledge that all trademarks, service marks and/or trade names contained within the Attribution Information distributed with the Covered Code are the exclusive property of their owners and may only be used with the permission of their owners, or under circumstances otherwise permitted by law or as expressly set out in this License.
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to 15. ADDITIONAL TERM: NETWORK USE.
the extent required to remedy known factual inaccuracies. The term “External Deployment” means the use, distribution, or communication of the Original Code or Modifications in any way such that the Original Code or Modifications may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2.
3.5. Application of Additional Terms EXHIBIT A. Common Public Attribution License Version 1.0.
You may choose to offer, and to charge a fee for, warranty, support, "The contents of this file are subject to the Common Public Attribution License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/license/cpal_1-0. The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 have been added to cover use of software over a computer network and provide for limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B.
indemnity or liability obligations to one or more recipients of Covered Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
Software. However, You may do so only on Your own behalf, and not on The Original Code is ArenaPublic.
behalf of any Contributor. You must make it absolutely clear that any The Original Developer is the Initial Developer.
such warranty, support, indemnity, or liability obligation is offered by The Initial Developer of the Original Code is Marek Novák. All portions of the code written by Marek Novák are Copyright (c) 2026. All Rights Reserved.
You alone, and You hereby agree to indemnify every Contributor for any Contributor: none."
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional EXHIBIT B. Attribution Information
disclaimers of warranty and limitations of liability specific to any
jurisdiction. Attribution Copyright Notice: Copyright (c) 2026 Marek Novák
Attribution Phrase (not exceeding 10 words): Built on Domi
4. Inability to Comply Due to Statute or Regulation Attribution URL: https://aula.marek-novak.cz
--------------------------------------------------- Graphic Image as provided in the Covered Code, if any: none.
Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
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/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+105 -4
View File
@@ -1,8 +1,109 @@
# ArenaPublic # ArenaPublic
The open core of Arena Domi, the Domi game library: pure Rust parsers for game launcher files (Steam The open core of Arena Domi, the Domi game library: pure Rust parsers for game launcher files (Steam
`libraryfolders.vdf` and `appmanifest_<id>.acf`, Epic `.item`, GOG entries), the library model, and later the `libraryfolders.vdf` and `appmanifest_<id>.acf`, Epic `.item`, GOG entries), the library model, and the
frametime statistics and replay-ring logic. No I/O: inputs are bytes or values, outputs are data. Builds for overlay's pure logic (frametime statistics, game detection, the shortcut); later the replay-ring logic. No I/O:
Windows, Android and WebAssembly. inputs are bytes or values, outputs are data. Builds for Windows, Android and WebAssembly.
Licence: MPL-2.0 (see LICENSE). ## Licence
ArenaPublic is licensed under the **Common Public Attribution License 1.0** (SPDX `CPAL-1.0`); see `LICENSE`.
Anyone who redistributes ArenaPublic, or a Larger Work built on it, must show the Exhibit B credit wherever
CPAL §14 asks for it (display in Larger Works is required):
| Field | Value |
| :-- | :-- |
| Attribution Copyright Notice | Copyright (c) 2026 Marek Novák |
| Attribution Phrase | Built on Domi |
| Attribution URL | https://aula.marek-novak.cz |
| Graphic Image | none |
Versions before this change (up to and including tag `core-v0.1.0`) stay available under MPL-2.0 to those who
received them; from this commit on, the code is under CPAL-1.0.
## Crates
| Crate | Lib | What it holds |
| :-- | :-- | :-- |
| `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
Pure: no `std::fs`, `std::process`, network, environment, registry or clock. The window app reads the files and
registry values (capped) and hands the bytes or values in. Every parser treats its input as hostile: caps on size,
depth, lengths and counts, typed errors, no panics, `#![forbid(unsafe_code)]`.
```rust
use arena_core::{merge, steam, epic, gog, manual, domi, DomiLaunch, WinPath, Launch};
// Steam: the library folders, then one manifest per installed app.
let libraries: Vec<WinPath> = steam::library_folders(&vdf_bytes)?;
let game = steam::app_manifest(&acf_bytes, &libraries[0])?; // Err(NotAGame) for redistributables
let id = steam::app_id_from_manifest_name("appmanifest_10.acf"); // Some(10): filter a folder listing
// Epic: one `.item` JSON manifest per app.
let game = epic::item(&item_bytes)?; // Err(NotAGame) for add-ons
// GOG: registry values the app read.
let game = gog::game(&gog::GogEntry { game_id, name, path, exe, working_dir, launch_params })?;
// A game the user picked, and a Domi game from the Atrium registry.
let game = manual::game(r"D:\Games\Old\old.exe", None)?;
let game = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" })?;
let game = domi::game("rosea", "Rosea", DomiLaunch::Web { url, allowed_hosts: &["rosea.example.org"] })?;
// One library: the same id once, the same install folder kept for the best source
// (Steam > Epic > GOG > Domi > Manual), ordered by title.
let library = merge(vec![steam_games, epic_games, gog_games, domi_games, manual_games]);
// Launching: a URI for the protocol variants, built only from validated fields.
match &game.launch {
Launch::Exe { exe, working_dir, args } => { /* Command::new(exe).current_dir(working_dir).args(args) */ }
Launch::Url(_) => { let uri = game.launch.uri_checked(&allowed_hosts); }
other => { let uri = other.uri(); } // steam://, com.epicgames.launcher://, domi-<app>://
}
```
| Type | Rule |
| :-- | :-- |
| `GameId` | `<source>:<native>`, `[a-z0-9:._-]`, at most 96 bytes, checked per source; `Display` + strict `FromStr` |
| `WinPath` | absolute with a drive letter; no UNC, `\\?\`, `..`, NUL, device names; at most 260 UTF-16 units |
| `Launch` | `SteamRunGameId(u32)`, `Epic { app_name }`, `Exe { exe, working_dir, args }`, `DomiLink { app }`, `Url` |
| `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::FrameStats> = frames::stats(&frametimes_ms);
// Launched by Arena > marked off ("not a game": None) > marked on > inside an install_dir (deepest wins).
// 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);
// "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. The same holds for
`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/PORTABILITY.md`](docs/PORTABILITY.md) (the target checks).
## Commands
```
cargo test # unit, hostile, property, launch and dedupe tests
cargo clippy --all-targets -- -D warnings
cargo fmt --check
```
+20
View File
@@ -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"
+218
View File
@@ -0,0 +1,218 @@
// 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 these rules, first match wins:
//!
//! 1. **Launched**: Arena started it. Always a game, whatever the marks; `game` is the library game that owns the
//! exe, if any (a launcher stub or a Domi app may live elsewhere: the window's `launched` message says which).
//! 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.
//!
//! **An exe outside every `install_dir` is never auto-detected**: without Arena launching it or an "on" 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<GameId>,
/// 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 a game's launch exe or inside a game's install folder.
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<Detection> {
let in_library = find_game(exe, library);
if launched_by_arena {
return Some(Detection { game: in_library, how: How::Launched });
}
match marked.get(exe) {
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 }),
}
}
/// 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<GameId> {
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 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 `{ "on": [paths], "off": [paths] }`, each sorted by the case-folded
/// path, first spelling kept. Loading also accepts a plain array of paths (the first 0.2.0 form), read as `on`.
/// 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)]
#[serde(try_from = "MarksRepr", into = "MarksWire")]
pub struct Marks(BTreeMap<String, (WinPath, bool)>);
impl Marks {
/// No marks.
pub const fn new() -> Marks {
Marks(BTreeMap::new())
}
/// Marks `exe` as a game (`is_game`) or as not a game, replacing any earlier mark on it. `Ok(true)` when that
/// changed something, `Ok(false)` when the exe already had this mark (the first spelling stays),
/// `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();
if let Some(slot) = self.0.get_mut(&key) {
let changed = slot.1 != is_game;
slot.1 = is_game;
return Ok(changed);
}
if self.0.len() >= MAX_MARKS {
return Err(ParseError::TooMany("marks"));
}
self.0.insert(key, (exe, is_game));
Ok(true)
}
/// Removes any mark on `exe`, back to the automatic rules; true when there was one.
pub fn clear(&mut self, exe: &WinPath) -> bool {
self.0.remove(&exe.key()).is_some()
}
/// 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 {
self.get(exe) == Some(true)
}
/// True when `exe` is marked as not a game.
pub fn contains_off(&self, exe: &WinPath) -> bool {
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 {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
/// 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;
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();
for p in on {
marks.set(p, true)?;
}
for p in off {
if marks.contains(&p) {
return Err(ParseError::Duplicate("marks"));
}
marks.set(p, false)?;
}
Ok(marks)
}
}
impl From<Marks> for MarksWire {
fn from(m: Marks) -> MarksWire {
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() }
}
}
+42
View File
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Domi games: Atrium registry entries with `kind = "game"`, launched through their `domi-<app>://open` link, or
//! web games (Rosea, Moin) opened by URL.
use crate::error::ParseError;
use crate::id::{GameId, Source};
use crate::launch::Launch;
use crate::model::{CoverHint, Game};
use crate::text;
/// How a Domi game starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DomiLaunch<'a> {
/// `domi-<app>://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:<id>`; `name` is the title. No install folder.
pub fn game(id: &str, name: &str, launch: DomiLaunch<'_>) -> Result<Game, ParseError> {
if !text::is_atrium_id(id) {
return Err(ParseError::BadId);
}
let title = text::title(name, "name")?;
let launch = match launch {
DomiLaunch::Link { app } => Launch::domi_link(app)?,
DomiLaunch::Web { url, allowed_hosts } => Launch::web(url, allowed_hosts)?,
};
let id = GameId::new(Source::Domi, id)?;
Ok(Game {
cover: Some(CoverHint::lettered(&title, &id)),
id,
source: Source::Domi,
title,
install_dir: None,
launch,
})
}
+143
View File
@@ -0,0 +1,143 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Epic Games Launcher: one JSON `.item` manifest per installed app in
//! `%ProgramData%\Epic\EpicGamesLauncher\Data\Manifests`. Launch is
//! `com.epicgames.launcher://apps/<AppName>?action=launch&silent=true`.
use crate::error::ParseError;
use crate::id::{GameId, Source};
use crate::launch::Launch;
use crate::limits::{MAX_DEPTH, MAX_FILE};
use crate::model::{CoverHint, Game};
use crate::path::WinPath;
use crate::text;
use serde::de::IgnoredAny;
use serde::{Deserialize, Deserializer};
use serde_json::Value;
/// The fields read from a manifest. Present-but-`null` is kept apart from absent, so `null` is a wrong type.
#[derive(Deserialize)]
struct Raw {
#[serde(rename = "AppName", default, deserialize_with = "present")]
app_name: Option<Value>,
#[serde(rename = "DisplayName", default, deserialize_with = "present")]
display_name: Option<Value>,
#[serde(rename = "InstallLocation", default, deserialize_with = "present")]
install_location: Option<Value>,
#[serde(rename = "MainGameAppName", default, deserialize_with = "present")]
main_game_app_name: Option<Value>,
}
const FIELDS: [&str; 4] = ["AppName", "DisplayName", "InstallLocation", "MainGameAppName"];
fn present<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {
Value::deserialize(d).map(Some)
}
/// 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<Game, ParseError> {
if json.len() > MAX_FILE {
return Err(ParseError::TooLarge);
}
let whole = std::str::from_utf8(json).map_err(|_| ParseError::NotUtf8)?;
let (bom, text) = match whole.strip_prefix('\u{feff}') {
Some(rest) => (3, rest),
None => (0, whole),
};
check_depth(text)?;
// serde would read a struct from an array too; only an object is a manifest.
if !text.trim_start().starts_with('{') {
return Err(match serde_json::from_str::<IgnoredAny>(text) {
Ok(_) => ParseError::WrongType("item"),
Err(e) => map_error(&e, text, bom),
});
}
let raw: Raw = serde_json::from_str(text).map_err(|e| map_error(&e, text, bom))?;
let app_name = required(raw.app_name.as_ref(), "AppName")?;
let display_name = required(raw.display_name.as_ref(), "DisplayName")?;
let install_location = required(raw.install_location.as_ref(), "InstallLocation")?;
let main_game = optional(raw.main_game_app_name.as_ref(), "MainGameAppName")?;
let launch = Launch::epic(app_name)?;
let title = text::title(display_name, "DisplayName")?;
let install_dir = WinPath::parse(install_location).map_err(|_| ParseError::BadPath("InstallLocation"))?;
if main_game.is_some_and(|m| m != app_name) {
return Err(ParseError::NotAGame("Epic add-on"));
}
let id = GameId::new(Source::Epic, &app_name.to_ascii_lowercase())?;
Ok(Game {
cover: Some(CoverHint::lettered(&title, &id)),
id,
source: Source::Epic,
title,
install_dir: Some(install_dir),
launch,
})
}
fn required<'a>(v: Option<&'a Value>, field: &'static str) -> Result<&'a str, ParseError> {
optional(v, field)?.ok_or(ParseError::Missing(field))
}
fn optional<'a>(v: Option<&'a Value>, field: &'static str) -> Result<Option<&'a str>, ParseError> {
match v {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s)),
Some(_) => Err(ParseError::WrongType(field)),
}
}
/// Refuses nesting deeper than `MAX_DEPTH` before serde sees the text (objects and arrays both count; brackets
/// inside strings do not).
fn check_depth(text: &str) -> Result<(), ParseError> {
let mut depth = 0usize;
let mut in_string = false;
let mut escaped = false;
for b in text.bytes() {
if in_string {
match (escaped, b) {
(true, _) => escaped = false,
(false, b'\\') => escaped = true,
(false, b'"') => in_string = false,
_ => {}
}
continue;
}
match b {
b'"' => in_string = true,
b'{' | b'[' => {
depth += 1;
if depth > MAX_DEPTH {
return Err(ParseError::TooDeep);
}
}
b'}' | b']' => depth = depth.saturating_sub(1),
_ => {}
}
}
Ok(())
}
/// Turns a serde_json error into a typed one: a repeated field, a document that is not an object, or a syntax
/// error at a byte offset into the original input.
fn map_error(e: &serde_json::Error, text: &str, bom: usize) -> ParseError {
if e.is_data() {
let msg = e.to_string();
if msg.starts_with("duplicate field") {
let field = FIELDS.into_iter().find(|f| msg.contains(&format!("`{f}`"))).unwrap_or("field");
return ParseError::Duplicate(field);
}
return ParseError::WrongType("item");
}
ParseError::Syntax { at: bom + offset(text, e.line(), e.column()) }
}
/// The byte offset of serde_json's 1-based line and column, clamped to the text.
fn offset(text: &str, line: usize, column: usize) -> usize {
let line_start: usize = text.split_inclusive('\n').take(line.saturating_sub(1)).map(str::len).sum();
(line_start + column.saturating_sub(1)).min(text.len().saturating_sub(1))
}
+60
View File
@@ -0,0 +1,60 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
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 {}
+119
View File
@@ -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<FrameStats> {
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<f32> {
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<f32> = 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))
&& 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<f64> {
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)
}
+67
View File
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! GOG: the app reads one registry key per installed game (assumption, verify on the PC:
//! `HKLM\SOFTWARE\WOW6432Node\GOG.com\Games\<gameID>` 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::id::{GameId, Source};
use crate::launch::{Launch, split_args};
use crate::limits::MAX_GOG_ID;
use crate::model::{CoverHint, Game};
use crate::path::WinPath;
use crate::text;
/// 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<String>,
/// `launchParam`: arguments, split on spaces with `"` grouping.
pub launch_params: Option<String>,
}
/// The game for one GOG entry.
pub fn game(e: &GogEntry) -> Result<Game, ParseError> {
if !(1..=MAX_GOG_ID).contains(&e.game_id.len()) || !e.game_id.bytes().all(|b| b.is_ascii_digit()) {
return Err(ParseError::BadId);
}
let title = text::title(&e.name, "name")?;
let path = WinPath::parse(&e.path).map_err(|_| ParseError::BadPath("path"))?;
let exe = resolve(&path, &e.exe).map_err(|_| ParseError::BadPath("exe"))?;
if !exe.starts_with(&path) || exe == path || !text::is_exe(&exe) {
return Err(ParseError::BadPath("exe"));
}
let working_dir = match e.working_dir.as_deref().map(str::trim) {
None | Some("") => exe.parent().ok_or(ParseError::BadPath("exe"))?,
Some(w) => resolve(&path, w).map_err(|_| ParseError::BadPath("working_dir"))?,
};
let args = match e.launch_params.as_deref() {
None => Vec::new(),
Some(line) => split_args(line)?,
};
let id = GameId::new(Source::Gog, &e.game_id)?;
Ok(Game {
cover: Some(CoverHint::lettered(&title, &id)),
id,
source: Source::Gog,
title,
install_dir: Some(path),
launch: Launch::exe(exe, working_dir, args)?,
})
}
/// An absolute path as it is, a relative one inside `base`.
fn resolve(base: &WinPath, s: &str) -> Result<WinPath, ParseError> {
let absolute = s.get(1..2) == Some(":") || s.starts_with(['\\', '/']);
if absolute { WinPath::parse(s) } else { base.join(s) }
}
+269
View File
@@ -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<Hotkey, HotkeyError> {
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<Hotkey, HotkeyError> {
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<Key> {
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<Self, Self::Err> {
parse(s)
}
}
impl TryFrom<String> for Hotkey {
type Error = HotkeyError;
fn try_from(s: String) -> Result<Self, Self::Error> {
parse(&s)
}
}
impl From<Hotkey> for String {
fn from(h: Hotkey) -> String {
h.to_string()
}
}
+149
View File
@@ -0,0 +1,149 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
use crate::error::ParseError;
use crate::limits::{MAX_GAME_ID, MAX_GOG_ID};
use crate::text;
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<Self, Self::Err> {
Source::ALL.into_iter().find(|src| src.as_str() == s).ok_or(ParseError::BadId)
}
}
/// A game's id: `<source>:<native 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 `<source>:<native>`.
pub fn new(source: Source, native: &str) -> Result<GameId, ParseError> {
if !native_ok(source, native) {
return Err(ParseError::BadId);
}
let id = format!("{source}:{native}");
if id.len() > MAX_GAME_ID {
return Err(ParseError::BadId);
}
Ok(GameId(id))
}
pub fn as_str(&self) -> &str {
&self.0
}
/// The source named by the prefix.
pub fn source(&self) -> Source {
// Every GameId was built by `new`, so the prefix is a known source.
self.0.split_once(':').and_then(|(s, _)| s.parse().ok()).unwrap_or(Source::Manual)
}
/// The part after `<source>:`.
pub fn native(&self) -> &str {
self.0.split_once(':').map_or("", |(_, n)| n)
}
}
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<Self, Self::Err> {
if s.len() > MAX_GAME_ID {
return Err(ParseError::BadId);
}
let (source, native) = s.split_once(':').ok_or(ParseError::BadId)?;
GameId::new(source.parse()?, native)
}
}
/// The per-source rule for the part after `<source>:`.
fn native_ok(source: Source, native: &str) -> bool {
match source {
Source::Steam => text::canonical_u32(native).is_some(),
Source::Epic => text::is_epic_app(native) && !native.bytes().any(|b| b.is_ascii_uppercase()),
Source::Gog => (1..=MAX_GOG_ID).contains(&native.len()) && native.bytes().all(|b| b.is_ascii_digit()),
Source::Manual => native.len() == 16 && native.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')),
Source::Domi => text::is_atrium_id(native),
}
}
impl TryFrom<String> for GameId {
type Error = ParseError;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}
impl From<GameId> for String {
fn from(id: GameId) -> String {
id.0
}
}
impl AsRef<str> for GameId {
fn as_ref(&self) -> &str {
&self.0
}
}
+247
View File
@@ -0,0 +1,247 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
use crate::error::ParseError;
use crate::limits::{MAX_ARG, MAX_ARGS, MAX_ARGS_LINE, MAX_HOST, MAX_URL};
use crate::path::WinPath;
use crate::text;
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/<id>`.
SteamRunGameId(u32),
/// `com.epicgames.launcher://apps/<app_name>?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<String> },
/// `domi-<app>://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<Launch, ParseError> {
if app_id == 0 {
return Err(ParseError::BadId);
}
Ok(Launch::SteamRunGameId(app_id))
}
/// An Epic launch; `app_name` must match `[A-Za-z0-9_-]{1,64}`.
pub fn epic(app_name: &str) -> Result<Launch, ParseError> {
if !text::is_epic_app(app_name) {
return Err(ParseError::BadId);
}
Ok(Launch::Epic { app_name: app_name.to_owned() })
}
/// 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<String>) -> Result<Launch, ParseError> {
if !text::is_exe(&exe) {
return Err(ParseError::BadPath("exe"));
}
check_args(&args)?;
Ok(Launch::Exe { exe, working_dir, args })
}
/// 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<Launch, ParseError> {
if !text::is_atrium_id(app) {
return Err(ParseError::BadId);
}
Ok(Launch::DomiLink { app: app.to_owned() })
}
/// A web game. The URL must be `https://<host>[/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<Launch, ParseError> {
let (normal, host_len) = check_url(url)?;
if !host_allowed(&normal, host_len, allowed_hosts) {
return Err(ParseError::BadValue("url"));
}
Ok(Launch::Url(normal))
}
/// 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 (and that it is
/// already normalised); use [`Launch::uri_checked`] to apply the host allow-list again.
pub fn uri(&self) -> Option<String> {
match self {
Launch::SteamRunGameId(id) => (*id != 0).then(|| format!("steam://rungameid/{id}")),
Launch::Epic { app_name } => text::is_epic_app(app_name)
.then(|| format!("com.epicgames.launcher://apps/{app_name}?action=launch&silent=true")),
Launch::DomiLink { app } => text::is_atrium_id(app).then(|| format!("domi-{app}://open")),
Launch::Url(url) => match check_url(url) {
Ok((normal, _)) if &normal == url => Some(normal),
_ => None,
},
Launch::Exe { .. } => 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<String> {
match self {
Launch::Url(url) => match check_url(url) {
Ok((normal, host_len)) if &normal == url && host_allowed(&normal, host_len, allowed_hosts) => {
Some(normal)
}
_ => None,
},
other => other.uri(),
}
}
}
/// Arguments of an exe launch: at most `MAX_ARGS`, each at most `MAX_ARG` bytes, no control characters.
fn check_args(args: &[String]) -> Result<(), ParseError> {
if args.len() > MAX_ARGS {
return Err(ParseError::TooMany("args"));
}
for a in args {
if a.len() > MAX_ARG {
return Err(ParseError::TooLong("arg"));
}
if a.chars().any(char::is_control) {
return Err(ParseError::BadValue("args"));
}
}
Ok(())
}
/// Splits a launch-parameter line into arguments: spaces separate, `"` groups (and is removed), nothing else is
/// special. Refuses control characters (tabs included) and an unclosed quote.
pub(crate) fn split_args(line: &str) -> Result<Vec<String>, ParseError> {
const BAD: ParseError = ParseError::BadValue("launch_params");
if line.len() > MAX_ARGS_LINE {
return Err(ParseError::TooLong("launch_params"));
}
if line.chars().any(char::is_control) {
return Err(BAD);
}
let mut args = Vec::new();
let mut cur = String::new();
let mut quoted = false;
let mut started = false;
for c in line.chars() {
match c {
'"' => {
quoted = !quoted;
started = true;
}
' ' if !quoted => {
if started {
args.push(std::mem::take(&mut cur));
started = false;
}
}
_ => {
cur.push(c);
started = true;
}
}
}
if quoted {
return Err(BAD);
}
if started {
args.push(cur);
}
Ok(args)
}
/// Bytes allowed after the host: RFC 3986 unreserved, reserved and `%`, minus nothing else. No spaces, quotes,
/// backslashes, angle brackets, braces, `|`, `^` or backticks; nothing outside ASCII (percent-encode it).
fn url_tail_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b"-._~:/?#[]@!$&'()*+,;=%".contains(&b)
}
/// Checks a web-game URL and returns it normalised (lowercase scheme and host) with the host's length.
fn check_url(url: &str) -> Result<(String, usize), ParseError> {
const BAD: ParseError = ParseError::BadValue("url");
if url.len() > MAX_URL {
return Err(ParseError::TooLong("url"));
}
let scheme = url.get(..8).ok_or(BAD)?;
if !scheme.eq_ignore_ascii_case("https://") {
return Err(BAD);
}
let rest = url.get(8..).ok_or(BAD)?;
let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let host = rest.get(..host_end).ok_or(BAD)?.to_ascii_lowercase();
let tail = rest.get(host_end..).ok_or(BAD)?;
if !host_ok(&host) {
return Err(BAD);
}
let tb = tail.as_bytes();
for (i, &b) in tb.iter().enumerate() {
if !url_tail_byte(b) {
return Err(BAD);
}
if b == b'%' {
let hex = tb.get(i + 1..i + 3).ok_or(BAD)?;
if !hex.iter().all(u8::is_ascii_hexdigit) {
return Err(BAD);
}
}
}
let mut normal = String::with_capacity(url.len());
normal.push_str("https://");
normal.push_str(&host);
normal.push_str(tail);
Ok((normal, host.len()))
}
/// A DNS name: dot-separated labels of `[a-z0-9-]{1,63}`, no `-` at either end of a label, at most `MAX_HOST`.
/// So no user info (`@`), no port (`:`), no IPv6 literal (`[`).
fn host_ok(host: &str) -> bool {
(1..=MAX_HOST).contains(&host.len())
&& host.split('.').all(|l| {
(1..=63).contains(&l.len())
&& !l.starts_with('-')
&& !l.ends_with('-')
&& l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
})
}
fn host_allowed(normal: &str, host_len: usize, allowed: &[&str]) -> bool {
normal.get(8..8 + host_len).is_some_and(|host| allowed.iter().any(|a| a.eq_ignore_ascii_case(host)))
}
/// 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<String> },
DomiLink { app: String },
Url(String),
}
impl TryFrom<LaunchRepr> for Launch {
type Error = ParseError;
/// Validates like the builders. A URL's host cannot be checked here (no allow-list), so launching a web game
/// read back from storage should go through [`Launch::uri_checked`].
fn try_from(r: LaunchRepr) -> Result<Self, Self::Error> {
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) => check_url(&url).map(|(normal, _)| Launch::Url(normal)),
}
}
}
+56
View File
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! 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_<id>.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.
//!
//! 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(
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 detect;
pub mod frames;
pub mod hotkey;
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;
+50
View File
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! 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;
/// 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;
+39
View File
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! A game the user added by picking its `.exe`.
use crate::error::ParseError;
use crate::id::{GameId, Source};
use crate::launch::Launch;
use crate::model::{CoverHint, Game};
use crate::path::WinPath;
use crate::text;
/// 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<Game, ParseError> {
const BAD: ParseError = ParseError::BadPath("exe");
let exe = WinPath::parse(exe).map_err(|_| BAD)?;
if !text::is_exe(&exe) {
return Err(BAD);
}
let dir = exe.parent().ok_or(BAD)?;
let title = match title {
Some(t) => text::title(t, "title")?,
None => {
let name = exe.file_name().ok_or(BAD)?;
text::title(name.get(..name.len() - 4).ok_or(BAD)?, "title")?
}
};
let id = GameId::new(Source::Manual, &format!("{:016x}", text::fnv1a64(exe.key().as_bytes())))?;
Ok(Game {
cover: Some(CoverHint::lettered(&title, &id)),
id,
source: Source::Manual,
title,
install_dir: Some(dir.clone()),
launch: Launch::exe(exe, dir, Vec::new())?,
})
}
+125
View File
@@ -0,0 +1,125 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
use crate::error::ParseError;
use crate::id::{GameId, Source};
use crate::launch::Launch;
use crate::limits::MAX_GAMES;
use crate::path::WinPath;
use crate::text;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
/// One game in the library.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "GameRepr")]
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<WinPath>,
pub launch: Launch,
pub cover: Option<CoverHint>,
}
/// The wire shape of [`Game`]; deserialising goes through it so the title is checked and the id matches the source.
#[derive(Deserialize)]
struct GameRepr {
id: GameId,
source: Source,
title: String,
install_dir: Option<WinPath>,
launch: Launch,
cover: Option<CoverHint>,
}
impl TryFrom<GameRepr> for Game {
type Error = ParseError;
fn try_from(r: GameRepr) -> Result<Self, Self::Error> {
if r.id.source() != r.source {
return Err(ParseError::BadId);
}
Ok(Game {
title: text::title(&r.title, "title")?,
id: r.id,
source: r.source,
install_dir: r.install_dir,
launch: r.launch,
cover: r.cover,
})
}
}
/// 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<Game>,
}
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<Vec<Game>>) -> Library {
let mut seen: BTreeSet<GameId> = BTreeSet::new();
let mut games: Vec<Game> = Vec::new();
for g in scans.into_iter().flatten().take(MAX_GAMES) {
if seen.insert(g.id.clone()) {
games.push(g);
}
}
let mut best: BTreeMap<String, u8> = BTreeMap::new();
for g in &games {
if let Some(dir) = &g.install_dir {
let e = best.entry(dir.key()).or_insert(0);
*e = (*e).max(g.source.priority());
}
}
games.retain(|g| match &g.install_dir {
Some(dir) => best.get(&dir.key()).is_none_or(|&b| g.source.priority() >= b),
None => true,
});
games.sort_by_cached_key(|g| (g.title.to_lowercase(), g.id.clone()));
Library { games }
}
+172
View File
@@ -0,0 +1,172 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
use crate::error::ParseError;
use crate::limits::MAX_PATH;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
const BAD: ParseError = ParseError::BadPath("path");
const SEPARATORS: [char; 2] = ['\\', '/'];
/// `X:\`
const ROOT_LEN: usize = 3;
/// Device names Windows opens instead of a file, whatever the folder or extension.
const DEVICES: [&str; 32] = [
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
"COM8", "COM9", "COM¹", "COM²", "COM³", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8",
"LPT9", "LPT¹", "LPT²", "LPT³",
];
/// 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<WinPath, ParseError> {
// Cheap bound first: no valid path has more than 4 bytes per UTF-16 unit.
if s.len() > 4 * MAX_PATH {
return Err(BAD);
}
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic).ok_or(BAD)?;
if chars.next() != Some(':') {
return Err(BAD);
}
let rest = chars.as_str();
if !rest.starts_with(SEPARATORS) {
return Err(BAD);
}
let mut out = String::with_capacity(s.len());
out.push(drive.to_ascii_uppercase());
out.push_str(":\\");
let mut first = true;
for comp in rest.split(SEPARATORS).filter(|c| !c.is_empty()) {
check_component(comp)?;
if !first {
out.push('\\');
}
first = false;
out.push_str(comp);
}
if out.encode_utf16().count() > MAX_PATH {
return Err(BAD);
}
Ok(WinPath(out))
}
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<WinPath, ParseError> {
if relative.is_empty() || relative.starts_with(SEPARATORS) {
return Err(BAD);
}
let mut joined = String::with_capacity(self.0.len() + 1 + relative.len());
joined.push_str(&self.0);
if !joined.ends_with('\\') {
joined.push('\\');
}
joined.push_str(relative);
WinPath::parse(&joined)
}
/// The containing folder, or `None` for a drive root.
pub fn parent(&self) -> Option<WinPath> {
self.file_name()?;
let cut = self.0.rfind('\\')?;
let head = if cut < ROOT_LEN { self.0.get(..ROOT_LEN)? } else { self.0.get(..cut)? };
Some(WinPath(head.to_owned()))
}
/// The last component, or `None` for a drive root.
pub fn file_name(&self) -> Option<&str> {
self.components().last()
}
/// The components after the drive root.
pub fn components(&self) -> impl Iterator<Item = &str> {
self.0.get(ROOT_LEN..).unwrap_or_default().split('\\').filter(|c| !c.is_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 same_drive = self.0.get(..1).zip(base.0.get(..1)).is_some_and(|(a, b)| a.eq_ignore_ascii_case(b));
if !same_drive {
return false;
}
let mut mine = self.components();
base.components().all(|b| mine.next().is_some_and(|m| m.to_lowercase() == b.to_lowercase()))
}
}
/// One path component, between separators.
fn check_component(c: &str) -> Result<(), ParseError> {
if c == "." || c == ".." || c.ends_with('.') || c.ends_with(' ') {
return Err(BAD);
}
if c.chars().any(|ch| ch.is_control() || matches!(ch, '<' | '>' | ':' | '"' | '|' | '?' | '*')) {
return Err(BAD);
}
let stem = c.split('.').next().unwrap_or(c).trim_end_matches(' ');
if DEVICES.iter().any(|d| d.eq_ignore_ascii_case(stem)) {
return Err(BAD);
}
Ok(())
}
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<Self, Self::Err> {
WinPath::parse(s)
}
}
impl TryFrom<String> for WinPath {
type Error = ParseError;
fn try_from(s: String) -> Result<Self, Self::Error> {
WinPath::parse(&s)
}
}
impl From<WinPath> for String {
fn from(p: WinPath) -> String {
p.0
}
}
impl AsRef<str> for WinPath {
fn as_ref(&self) -> &str {
&self.0
}
}
+111
View File
@@ -0,0 +1,111 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Steam: `config/libraryfolders.vdf` lists the library folders; each installed app has
//! `<library>/steamapps/appmanifest_<id>.acf`. Launch is `steam://rungameid/<id>`.
use crate::error::ParseError;
use crate::id::{GameId, Source};
use crate::launch::Launch;
use crate::limits::MAX_LIBRARIES;
use crate::model::{CoverHint, Game};
use crate::path::WinPath;
use crate::text;
use crate::vdf::{self, Obj, Value};
/// Steam's own redistributables and runtimes: installed like games, never played.
const TOOLS: [u32; 7] = [
228_980, // Steamworks Common Redistributables
1_070_560, // Steam Linux Runtime 1.0 (scout)
1_391_110, // Steam Linux Runtime 2.0 (soldier)
1_628_350, // Steam Linux Runtime 3.0 (sniper)
1_493_710, // Proton Experimental
1_826_330, // Proton EasyAntiCheat Runtime
1_161_040, // Proton BattlEye Runtime
];
/// 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.
/// Keys under the root that are not plain numbers (`contentstatsid`, ...) are skipped.
pub fn library_folders(vdf: &[u8]) -> Result<Vec<WinPath>, ParseError> {
let doc = vdf::parse(vdf)?;
let root = obj(&doc, "libraryfolders")?;
let mut out: Vec<WinPath> = Vec::new();
for (key, value) in root.iter() {
if !key.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
let raw = match value {
Value::Str(s) => s.as_str(),
Value::Obj(o) => string(o, "path")?,
};
let path = WinPath::parse(raw).map_err(|_| ParseError::BadPath("path"))?;
if out.iter().any(|p| p.eq_ignore_case(&path)) {
return Err(ParseError::Duplicate("path"));
}
if out.len() >= MAX_LIBRARIES {
return Err(ParseError::TooMany("libraries"));
}
out.push(path);
}
Ok(out)
}
/// The game described by `appmanifest_<id>.acf` inside `library` (the folder holding `steamapps`). The install
/// folder is `<library>\steamapps\common\<installdir>`, 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<Game, ParseError> {
let doc = vdf::parse(acf)?;
let state = obj(&doc, "AppState")?;
let app_id = text::canonical_u32(string(state, "appid")?).ok_or(ParseError::BadId)?;
let title = text::title(string(state, "name")?, "name")?;
let installdir = string(state, "installdir")?;
if is_tool(app_id) {
return Err(ParseError::NotAGame("Steam redistributable or runtime"));
}
if installdir.is_empty() || installdir.contains(['\\', '/']) {
return Err(ParseError::BadPath("installdir"));
}
let install_dir = library
.join("steamapps")
.and_then(|p| p.join("common"))
.and_then(|p| p.join(installdir))
.map_err(|_| ParseError::BadPath("installdir"))?;
Ok(Game {
id: GameId::new(Source::Steam, &app_id.to_string())?,
source: Source::Steam,
title,
install_dir: Some(install_dir),
launch: Launch::steam(app_id)?,
cover: Some(CoverHint::SteamLibraryCache { app_id }),
})
}
/// The app id in a file name `appmanifest_<id>.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<u32> {
text::canonical_u32(name.strip_prefix("appmanifest_")?.strip_suffix(".acf")?)
}
/// Steam apps that are not games: the common redistributables and the Linux runtimes.
pub fn is_tool(app_id: u32) -> bool {
TOOLS.contains(&app_id)
}
/// The object under `key`.
fn obj<'a>(o: &'a Obj, key: &'static str) -> Result<&'a Obj, ParseError> {
match o.get(key) {
Some(Value::Obj(inner)) => Ok(inner),
Some(Value::Str(_)) => Err(ParseError::WrongType(key)),
None => Err(ParseError::Missing(key)),
}
}
/// The string under `key`.
fn string<'a>(o: &'a Obj, key: &'static str) -> Result<&'a str, ParseError> {
match o.get(key) {
Some(Value::Str(s)) => Ok(s),
Some(Value::Obj(_)) => Err(ParseError::WrongType(key)),
None => Err(ParseError::Missing(key)),
}
}
+84
View File
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Small shared checks: titles, ids, numbers, a stable hash, the lettered cover.
use crate::error::ParseError;
use crate::id::GameId;
use crate::limits::{MAX_DOMI_ID, MAX_EPIC_APP, MAX_TITLE};
use crate::model::CoverHint;
use crate::path::WinPath;
/// Bidirectional-override characters, which could make a title display as something else.
fn is_bidi_control(c: char) -> bool {
matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{200e}' | '\u{200f}' | '\u{061c}')
}
/// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control or bidi-override characters.
pub(crate) fn title(s: &str, field: &'static str) -> Result<String, ParseError> {
let t = s.trim();
if t.is_empty() {
return Err(ParseError::Missing(field));
}
if t.chars().nth(MAX_TITLE).is_some() {
return Err(ParseError::TooLong(field));
}
if t.chars().any(|c| c.is_control() || is_bidi_control(c)) {
return Err(ParseError::BadValue(field));
}
Ok(t.to_owned())
}
/// A canonical decimal `u32` other than 0: digits only, no sign, no leading zero, no whitespace.
pub(crate) fn canonical_u32(s: &str) -> Option<u32> {
let b = s.as_bytes();
if b.is_empty() || b.len() > 10 || !b.iter().all(u8::is_ascii_digit) || b.first() == Some(&b'0') {
return None;
}
s.parse::<u32>().ok()
}
/// `[A-Za-z0-9_-]{1,64}`.
pub(crate) fn is_epic_app(s: &str) -> bool {
(1..=MAX_EPIC_APP).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
/// Atrium id rules: `[a-z0-9-]{1,32}`, not starting or ending with `-`.
pub(crate) fn is_atrium_id(s: &str) -> bool {
(1..=MAX_DOMI_ID).contains(&s.len())
&& !s.starts_with('-')
&& !s.ends_with('-')
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// True when the last component ends in `.exe` (ignoring case) and has a name before it.
pub(crate) fn is_exe(p: &WinPath) -> bool {
p.file_name()
.is_some_and(|n| n.len() > 4 && n.get(n.len() - 4..).is_some_and(|ext| ext.eq_ignore_ascii_case(".exe")))
}
/// 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 letter = title
.chars()
.find(|c| c.is_alphanumeric())
.map(|c| {
let mut up = c.to_uppercase();
match (up.next(), up.next()) {
(Some(u), None) => u,
_ => c,
}
})
.unwrap_or('#');
let hue = u16::try_from(fnv1a64(id.as_str().as_bytes()) % 360).unwrap_or(0);
CoverHint::Lettered { letter, hue }
}
+340
View File
@@ -0,0 +1,340 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! A strict tokenizer, parser and writer for Valve's KeyValues text format (VDF), as used by Steam's
//! `libraryfolders.vdf` and `appmanifest_<id>.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: input that is not
//! UTF-8 as a whole, unquoted tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control
//! characters (other than tab) or line breaks inside a string, NUL anywhere, empty keys, a key repeated in the same
//! object (ignoring ASCII case), and anything over the caps in [`crate::limits`].
use crate::error::ParseError;
use crate::limits::{MAX_DEPTH, MAX_ENTRIES, MAX_ESCAPES, MAX_FILE, MAX_KEY, MAX_VALUE};
use std::collections::BTreeMap;
/// 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). It carries its own caps: at most
/// [`MAX_DEPTH`] levels of objects below it and [`MAX_ENTRIES`] pairs in total, so every `Obj` can be written and
/// read back.
#[derive(Debug, Clone, Default)]
pub struct Obj {
entries: Vec<(String, Value)>,
/// ASCII-lowercased key -> position in `entries`.
index: BTreeMap<String, usize>,
/// Levels of objects inside this one (0 when it holds only strings).
depth: usize,
/// Pairs at every level, this one included.
total: usize,
}
impl PartialEq for Obj {
fn eq(&self, other: &Obj) -> bool {
self.entries == other.entries
}
}
impl Eq for Obj {}
impl Obj {
pub fn new() -> Obj {
Obj::default()
}
/// Appends a pair. Refuses an empty key, a key or value over its cap, a key already present, an object value
/// that would nest deeper than [`MAX_DEPTH`], and more than [`MAX_ENTRIES`] pairs in total.
pub fn insert(&mut self, key: String, value: Value) -> Result<(), ParseError> {
if key.is_empty() {
return Err(ParseError::Missing("key"));
}
if key.len() > MAX_KEY {
return Err(ParseError::TooLong("key"));
}
writable(&key, "key")?;
let (depth, added) = match &value {
Value::Str(s) if s.len() > MAX_VALUE => return Err(ParseError::TooLong("value")),
Value::Str(s) => {
writable(s, "value")?;
(0, 1)
}
Value::Obj(o) => (o.depth + 1, o.total + 1),
};
if depth > MAX_DEPTH {
return Err(ParseError::TooDeep);
}
let total = self.total + added;
if total > MAX_ENTRIES {
return Err(ParseError::TooMany("entries"));
}
let folded = key.to_ascii_lowercase();
if self.index.contains_key(&folded) {
return Err(ParseError::Duplicate("key"));
}
self.index.insert(folded, self.entries.len());
self.entries.push((key, value));
self.depth = self.depth.max(depth);
self.total = total;
Ok(())
}
/// The value under `key`, ignoring ASCII case.
pub fn get(&self, key: &str) -> Option<&Value> {
let i = *self.index.get(&key.to_ascii_lowercase())?;
self.entries.get(i).map(|(_, v)| v)
}
/// The pairs in file order.
pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
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()
}
}
/// A string [`write`] can carry and [`parse`] reads back: no control characters other than tab, CR and LF, and at
/// most [`MAX_ESCAPES`] characters that need an escape.
fn writable(s: &str, what: &'static str) -> Result<(), ParseError> {
let mut escapes = 0usize;
for c in s.chars() {
match c {
'\\' | '"' | '\n' | '\r' => escapes += 1,
'\t' => {}
c if c.is_ascii_control() => return Err(ParseError::BadValue(what)),
_ => {}
}
}
if escapes > MAX_ESCAPES {
return Err(ParseError::TooMany("escapes"));
}
Ok(())
}
/// Reads tokens one at a time.
struct Lexer<'a> {
input: &'a [u8],
pos: usize,
}
impl<'a> Lexer<'a> {
fn new(input: &'a [u8]) -> Result<Lexer<'a>, ParseError> {
if input.len() > MAX_FILE {
return Err(ParseError::TooLarge);
}
if std::str::from_utf8(input).is_err() {
return Err(ParseError::NotUtf8);
}
let pos = if input.starts_with(b"\xEF\xBB\xBF") { 3 } else { 0 };
Ok(Lexer { input, pos })
}
fn peek(&self, ahead: usize) -> Option<u8> {
self.input.get(self.pos + ahead).copied()
}
fn next_token(&mut self) -> Result<Option<Token>, ParseError> {
loop {
let at = self.pos;
let Some(b) = self.peek(0) else { return Ok(None) };
match b {
b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1,
b'/' if self.peek(1) == Some(b'/') => self.skip_comment()?,
b'{' => {
self.pos += 1;
return Ok(Some(Token { kind: TokenKind::Open, at }));
}
b'}' => {
self.pos += 1;
return Ok(Some(Token { kind: TokenKind::Close, at }));
}
b'"' => {
let s = self.string()?;
return Ok(Some(Token { kind: TokenKind::Str(s), at }));
}
_ => return Err(ParseError::Syntax { at }),
}
}
}
/// Skips `//...` up to (not including) the line break. NUL is refused here too.
fn skip_comment(&mut self) -> Result<(), ParseError> {
while let Some(b) = self.peek(0) {
match b {
b'\n' => break,
0 => return Err(ParseError::Syntax { at: self.pos }),
_ => self.pos += 1,
}
}
Ok(())
}
/// A quoted string starting at `self.pos`; an unterminated one is reported at its opening quote.
fn string(&mut self) -> Result<String, ParseError> {
let start = self.pos;
self.pos += 1;
let mut buf: Vec<u8> = Vec::new();
let mut escapes = 0usize;
loop {
let Some(b) = self.peek(0) else { return Err(ParseError::Syntax { at: start }) };
match b {
b'"' => {
self.pos += 1;
break;
}
b'\\' => {
let decoded = match self.peek(1) {
None => return Err(ParseError::Syntax { at: start }),
Some(b'\\') => b'\\',
Some(b'"') => b'"',
Some(b'n') => b'\n',
Some(b't') => b'\t',
Some(b'r') => b'\r',
Some(_) => return Err(ParseError::Syntax { at: self.pos }),
};
escapes += 1;
if escapes > MAX_ESCAPES {
return Err(ParseError::TooMany("escapes"));
}
buf.push(decoded);
self.pos += 2;
}
b'\t' => {
buf.push(b);
self.pos += 1;
}
0x00..=0x1f | 0x7f => return Err(ParseError::Syntax { at: self.pos }),
_ => {
buf.push(b);
self.pos += 1;
}
}
if buf.len() > MAX_VALUE {
return Err(ParseError::TooLong("value"));
}
}
String::from_utf8(buf).map_err(|_| ParseError::NotUtf8)
}
}
/// Splits `input` into tokens. Checks size, UTF-8, escapes and string lengths; not nesting.
pub fn tokenize(input: &[u8]) -> Result<Vec<Token>, ParseError> {
let mut lx = Lexer::new(input)?;
let mut out = Vec::new();
while let Some(t) = lx.next_token()? {
out.push(t);
}
Ok(out)
}
/// Parses a whole document: a sequence of top-level pairs.
pub fn parse(input: &[u8]) -> Result<Obj, ParseError> {
let mut lx = Lexer::new(input)?;
parse_obj(&mut lx, 0)
}
/// Reads pairs until `}` (inside an object, `depth > 0`) or the end of input (at the top, `depth == 0`).
/// Recursion is bounded by `MAX_DEPTH`.
fn parse_obj(lx: &mut Lexer<'_>, depth: usize) -> Result<Obj, ParseError> {
let end = lx.input.len();
let mut obj = Obj::new();
loop {
let key = match lx.next_token()? {
None if depth == 0 => return Ok(obj),
None => return Err(ParseError::Syntax { at: end }),
Some(Token { kind: TokenKind::Close, .. }) if depth > 0 => return Ok(obj),
Some(Token { kind: TokenKind::Close | TokenKind::Open, at }) => return Err(ParseError::Syntax { at }),
Some(Token { kind: TokenKind::Str(k), .. }) => k,
};
if key.len() > MAX_KEY {
return Err(ParseError::TooLong("key"));
}
let value = match lx.next_token()? {
None => return Err(ParseError::Syntax { at: end }),
Some(Token { kind: TokenKind::Str(s), .. }) => Value::Str(s),
Some(Token { kind: TokenKind::Open, .. }) => {
if depth >= MAX_DEPTH {
return Err(ParseError::TooDeep);
}
Value::Obj(parse_obj(lx, depth + 1)?)
}
Some(Token { kind: TokenKind::Close, at }) => return Err(ParseError::Syntax { at }),
};
obj.insert(key, value)?;
}
}
/// 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 mut out = String::new();
write_obj(doc, 0, &mut out);
out
}
fn write_obj(o: &Obj, indent: usize, out: &mut String) {
for (k, v) in &o.entries {
push_tabs(out, indent);
push_quoted(out, k);
match v {
Value::Str(s) => {
out.push_str("\t\t");
push_quoted(out, s);
out.push('\n');
}
Value::Obj(inner) => {
out.push('\n');
push_tabs(out, indent);
out.push_str("{\n");
write_obj(inner, indent + 1, out);
push_tabs(out, indent);
out.push_str("}\n");
}
}
}
}
fn push_tabs(out: &mut String, n: usize) {
out.extend(std::iter::repeat_n('\t', n));
}
fn push_quoted(out: &mut String, s: &str) {
out.push('"');
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
_ => out.push(c),
}
}
out.push('"');
}
+405
View File
@@ -0,0 +1,405 @@
// 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<Game> {
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<GameId> {
Some(s.parse().unwrap())
}
fn found(game: &str, how: How) -> Option<Detection> {
Some(Detection { game: id(game), how })
}
const NONE: &Marks = &Marks::new();
// --- 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::<Marks>(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());
}
// --- 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));
}
// --- marked on ("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_on_inside_an_install_dir_is_marked_and_names_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::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]
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();
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();
// Two arrays of paths, each sorted by the case-folded key, the first spelling kept.
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();
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"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]
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);
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}");
}
}
#[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::<Marks>(&json).is_ok());
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());
// 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]
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<Game> = 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()));
}
}
}
+119
View File
@@ -0,0 +1,119 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Epic `.item` manifests: valid fixtures and the hostile ones that are Epic-specific.
use arena_core::{CoverHint, Launch, ParseError, Source, WinPath, epic, limits};
#[test]
fn valid_item() {
let g = epic::item(include_bytes!("fixtures/epic/valid.item")).unwrap();
assert_eq!(g.id.as_str(), "epic:exampleracer_main-01");
assert_eq!(g.source, Source::Epic);
assert_eq!(g.title, "Example Racer");
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"C:\Program Files\Epic Games\ExampleRacer"));
assert_eq!(g.launch, Launch::Epic { app_name: "ExampleRacer_Main-01".into() });
assert_eq!(
g.launch.uri().as_deref(),
Some("com.epicgames.launcher://apps/ExampleRacer_Main-01?action=launch&silent=true")
);
assert!(matches!(g.cover, Some(CoverHint::Lettered { letter: 'E', .. })), "{:?}", g.cover);
}
#[test]
fn bom_is_accepted() {
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(include_bytes!("fixtures/epic/valid.item"));
assert!(epic::item(&bytes).is_ok());
}
#[test]
fn addon_is_not_a_game() {
let r = epic::item(include_bytes!("fixtures/epic/addon.item"));
assert!(matches!(r, Err(ParseError::NotAGame(_))), "{r:?}");
}
#[test]
fn wrong_type_app_name() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/wrongtype.item")), Err(ParseError::WrongType("AppName")));
}
#[test]
fn wrong_type_for_each_field() {
let cases = [
(r#"{"AppName":"A","DisplayName":["x"],"InstallLocation":"C:\\G"}"#, "DisplayName"),
(r#"{"AppName":"A","DisplayName":"x","InstallLocation":{"a":1}}"#, "InstallLocation"),
(r#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G","MainGameAppName":7}"#, "MainGameAppName"),
(r#"{"AppName":null,"DisplayName":"x","InstallLocation":"C:\\G"}"#, "AppName"),
];
for (json, field) in cases {
assert_eq!(epic::item(json.as_bytes()), Err(ParseError::WrongType(field)), "{json}");
}
assert_eq!(epic::item(b"[]"), Err(ParseError::WrongType("item")));
assert_eq!(epic::item(b"\"text\""), Err(ParseError::WrongType("item")));
}
#[test]
fn duplicate_key() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/dupkey.item")), Err(ParseError::Duplicate("AppName")));
}
#[test]
fn traversal_in_install_location() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/traversal.item")), Err(ParseError::BadPath("InstallLocation")));
}
#[test]
fn unc_install_location() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/unc.item")), Err(ParseError::BadPath("InstallLocation")));
}
#[test]
fn injected_app_name() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/badappname.item")), Err(ParseError::BadId));
}
#[test]
fn app_name_rules() {
let long = "a".repeat(limits::MAX_EPIC_APP + 1);
for bad in ["", " A", "A B", "a.b", "a/b", "a%20", "a?b", "ä", long.as_str()] {
let json = format!(r#"{{"AppName":"{bad}","DisplayName":"x","InstallLocation":"C:\\G"}}"#);
assert_eq!(epic::item(json.as_bytes()), Err(ParseError::BadId), "{bad:?}");
}
let ok = "A".repeat(limits::MAX_EPIC_APP);
let json = format!(r#"{{"AppName":"{ok}","DisplayName":"x","InstallLocation":"C:\\G"}}"#);
assert!(epic::item(json.as_bytes()).is_ok());
}
#[test]
fn missing_fields() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/missing.item")), Err(ParseError::Missing("AppName")));
assert_eq!(epic::item(br#"{"AppName":"A","InstallLocation":"C:\\G"}"#), Err(ParseError::Missing("DisplayName")));
assert_eq!(epic::item(br#"{"AppName":"A","DisplayName":"x"}"#), Err(ParseError::Missing("InstallLocation")));
}
#[test]
fn trailing_garbage() {
assert!(matches!(epic::item(include_bytes!("fixtures/epic/trailing.item")), Err(ParseError::Syntax { .. })));
}
#[test]
fn absurd_number() {
let r = epic::item(include_bytes!("fixtures/epic/absurd.item"));
assert!(matches!(r, Err(ParseError::Syntax { .. }) | Err(ParseError::WrongType("AppName"))), "{r:?}");
}
#[test]
fn syntax_error_offset_points_into_the_input() {
let json = b"{\n \"AppName\": \"A\",\n oops\n}";
match epic::item(json) {
Err(ParseError::Syntax { at }) => assert!(at < json.len(), "{at}"),
other => panic!("{other:?}"),
}
}
#[test]
fn main_game_equal_to_app_name_is_a_game() {
let json = br#"{"AppName":"A","MainGameAppName":"A","DisplayName":"x","InstallLocation":"C:\\G"}"#;
assert!(epic::item(json).is_ok());
}
+6
View File
@@ -0,0 +1,6 @@
{
"FormatVersion": 0,
"DisplayName": "Absurd Number",
"InstallLocation": "C:\\Games\\Absurd",
"AppName": 1e999999
}
+7
View File
@@ -0,0 +1,7 @@
{
"FormatVersion": 0,
"DisplayName": "Example Racer - Bonus Cars",
"InstallLocation": "C:\\Program Files\\Epic Games\\ExampleRacer",
"AppName": "ExampleRacerBonusCars",
"MainGameAppName": "ExampleRacer_Main-01"
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Injected",
"InstallLocation": "C:\\Games\\Injected",
"AppName": "x?action=uninstall&a=../../"
}
+6
View File
@@ -0,0 +1,6 @@
{
"DisplayName": "Twice",
"InstallLocation": "C:\\Games\\Twice",
"AppName": "TwiceA",
"AppName": "TwiceB"
}
+4
View File
@@ -0,0 +1,4 @@
{
"DisplayName": "No App Name",
"InstallLocation": "C:\\Games\\NoAppName"
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Trailing",
"InstallLocation": "C:\\Games\\Trailing",
"AppName": "Trailing"
} {"AppName": "Second"}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Escape Artist",
"InstallLocation": "C:\\Games\\..\\Windows\\System32",
"AppName": "EscapeArtist"
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Remote",
"InstallLocation": "\\\\evil-server\\share\\Game",
"AppName": "Remote"
}
+26
View File
@@ -0,0 +1,26 @@
{
"FormatVersion": 0,
"bIsIncompleteInstall": false,
"LaunchCommand": "",
"LaunchExecutable": "ExampleRacer/Binaries/Win64/ExampleRacer.exe",
"ManifestLocation": "C:\\ProgramData\\Epic\\EpicGamesLauncher\\Data\\Manifests",
"bIsApplication": true,
"bIsExecutable": true,
"bIsManaged": false,
"bNeedsValidation": false,
"bRequiresAuth": true,
"bCanRunOffline": true,
"DisplayName": "Example Racer",
"InstallationGuid": "00000000000000000000000000000001",
"InstallLocation": "C:\\Program Files\\Epic Games\\ExampleRacer",
"CatalogNamespace": "example",
"CatalogItemId": "00000000000000000000000000000002",
"AppName": "ExampleRacer_Main-01",
"AppVersionString": "1.0.0",
"MainGameCatalogNamespace": "example",
"MainGameCatalogItemId": "00000000000000000000000000000002",
"MainGameAppName": "ExampleRacer_Main-01",
"AppCategories": ["public", "games", "applications"],
"ExpectingDLCInstalled": {},
"InstallTags": []
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Wrong Type",
"InstallLocation": "C:\\Games\\WrongType",
"AppName": 12345
}
@@ -0,0 +1,33 @@
"AppState"
{
"appid" "1234560"
"universe" "1"
"LauncherPath" "C:\\Program Files (x86)\\Steam\\steam.exe"
"name" "Example Quest: The \"Quoted\" Edition"
"StateFlags" "4"
"installdir" "Example Quest"
"LastUpdated" "0"
"SizeOnDisk" "1000"
"StagingSize" "0"
"buildid" "1"
"LastOwner" "0"
"AutoUpdateBehavior" "0"
"AllowOtherDownloadsWhileRunning" "0"
"ScheduledAutoUpdate" "0"
"InstalledDepots"
{
"1234561"
{
"manifest" "1"
"size" "1000"
}
}
"UserConfig"
{
"language" "english"
}
"MountedConfig"
{
"language" "english"
}
}
@@ -0,0 +1,8 @@
"AppState"
{
"appid" "228980"
"universe" "1"
"name" "Steamworks Common Redistributables"
"StateFlags" "4"
"installdir" "Steamworks Shared"
}
@@ -0,0 +1,6 @@
"AppState"
{
"appid" "1234571"
"name" "Somewhere Else"
"installdir" "C:\\Windows"
}
@@ -0,0 +1,6 @@
"AppState"
{
"appid" "99999999999999999999999999"
"name" "Absurd"
"installdir" "Absurd"
}
@@ -0,0 +1,7 @@
"AppState"
{
"appid" "1234573"
"name" "First Name"
"installdir" "Twice"
"Name" "Second Name"
}
@@ -0,0 +1,6 @@
"AppState"
{
"appid" "1234570"
"name" "Escape Artist"
"installdir" "..\\..\\..\\Windows\\System32"
}
@@ -0,0 +1,5 @@
"AppState"
{
"appid" "1234574"
"name" "Never Ends
}
@@ -0,0 +1,9 @@
"AppState"
{
"appid"
{
"value" "1234572"
}
"name" "Wrong Type"
"installdir" "Wrong Type"
}
@@ -0,0 +1,30 @@
"libraryfolders"
{
"0"
{
"path" "C:\\Program Files (x86)\\Steam"
"label" ""
"contentid" "1111111111111111111"
"totalsize" "0"
"update_clean_bytes_tally" "0"
"time_last_update_verified" "0"
"apps"
{
"228980" "0"
"1234560" "1000"
}
}
"1"
{
"path" "D:\\SteamLibrary"
"label" "Games"
"contentid" "2222222222222222222"
"totalsize" "1000000000000"
"update_clean_bytes_tally" "0"
"time_last_update_verified" "0"
"apps"
{
"7654320" "2000"
}
}
}
@@ -0,0 +1,11 @@
"libraryfolders"
{
"0"
{
"path" "D:\\SteamLibrary"
}
"1"
{
"path" "d:\\steamlibrary\\"
}
}
@@ -0,0 +1,8 @@
// An older Steam layout: numbered keys hold the path directly.
"LibraryFolders"
{
"TimeNextStatsReport" "0"
"ContentStatsID" "-1"
"1" "D:\\SteamLibrary"
"2" "E:/Games/Steam"
}
@@ -0,0 +1,7 @@
"libraryfolders"
{
"0"
{
"path" "\\\\evil-server\\share\\Steam"
}
}
@@ -0,0 +1,10 @@
"libraryfolders"
{
"0"
{
"path"
{
"drive" "C:"
}
}
}
+262
View File
@@ -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<f32>) -> Vec<f32> {
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<Value = f32> {
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<Value = f32> {
prop_oneof![
4 => frametime(),
1 => Just(f32::NAN),
1 => Just(f32::INFINITY),
1 => Just(f32::NEG_INFINITY),
1 => -1000.0f32..0.0,
1 => any::<f32>(),
]
}
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::<prop::sample::Index>()) {
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);
}
}
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! GOG entries built from registry values the app passes in.
use arena_core::gog::{GogEntry, game};
use arena_core::{Launch, ParseError, Source, WinPath, limits};
fn entry() -> GogEntry {
GogEntry {
game_id: "1207658924".into(),
name: "Example Saga".into(),
path: r"C:\GOG Games\Example Saga".into(),
exe: r"C:\GOG Games\Example Saga\bin\x64\saga.exe".into(),
working_dir: Some(r"C:\GOG Games\Example Saga\bin\x64".into()),
launch_params: Some(r#"-skipintro "-profile=Slot One""#.into()),
}
}
fn exe_parts(l: &Launch) -> (&str, &str, Vec<&str>) {
match l {
Launch::Exe { exe, working_dir, args } => {
(exe.as_str(), working_dir.as_str(), args.iter().map(String::as_str).collect())
}
other => panic!("{other:?}"),
}
}
#[test]
fn valid_entry() {
let g = game(&entry()).unwrap();
assert_eq!(g.id.as_str(), "gog:1207658924");
assert_eq!(g.source, Source::Gog);
assert_eq!(g.title, "Example Saga");
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"C:\GOG Games\Example Saga"));
let (exe, wd, args) = exe_parts(&g.launch);
assert_eq!(exe, r"C:\GOG Games\Example Saga\bin\x64\saga.exe");
assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64");
assert_eq!(args, ["-skipintro", "-profile=Slot One"]);
assert_eq!(g.launch.uri(), None, "an exe launch has no URI");
}
#[test]
fn relative_exe_and_defaults() {
let mut e = entry();
e.exe = r"bin\x64\saga.exe".into();
e.working_dir = Some(String::new());
e.launch_params = Some(" ".into());
let g = game(&e).unwrap();
let (exe, wd, args) = exe_parts(&g.launch);
assert_eq!(exe, r"C:\GOG Games\Example Saga\bin\x64\saga.exe");
assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64");
assert!(args.is_empty());
e.working_dir = None;
e.launch_params = None;
let g = game(&e).unwrap();
let (_, wd, args) = exe_parts(&g.launch);
assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64");
assert!(args.is_empty());
e.working_dir = Some("data".into());
let g = game(&e).unwrap();
let (_, wd, _) = exe_parts(&g.launch);
assert_eq!(wd, r"C:\GOG Games\Example Saga\data");
}
#[test]
fn bad_ids() {
for bad in ["", "abc", "12a", "-1", " 1", "123456789012345678901", "1.5"] {
let mut e = entry();
e.game_id = bad.into();
assert_eq!(game(&e), Err(ParseError::BadId), "{bad:?}");
}
let mut e = entry();
e.game_id = "1".repeat(limits::MAX_GOG_ID);
assert!(game(&e).is_ok());
}
#[test]
fn bad_paths() {
let cases: [(&str, &str, &str); 9] = [
(r"\\server\share\Game", r"\\server\share\Game\g.exe", "path"),
(r"C:\GOG Games\..\Windows", r"C:\Windows\g.exe", "path"),
(r"relative\Game", r"relative\Game\g.exe", "path"),
(r"C:\GOG Games\Example Saga", r"C:\Windows\System32\cmd.exe", "exe"),
(r"C:\GOG Games\Example Saga", r"..\..\Windows\System32\cmd.exe", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\run.bat", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\run.cmd", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\game.exe.lnk", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga Evil\g.exe", "exe"),
];
for (path, exe, field) in cases {
let mut e = entry();
e.path = path.into();
e.exe = exe.into();
e.working_dir = None;
assert_eq!(game(&e), Err(ParseError::BadPath(field)), "{path} {exe}");
}
let mut e = entry();
e.working_dir = Some(r"\\?\C:\x".into());
assert_eq!(game(&e), Err(ParseError::BadPath("working_dir")));
}
#[test]
fn exe_extension_ignores_case() {
let mut e = entry();
e.exe = r"C:\GOG Games\Example Saga\SAGA.EXE".into();
assert!(game(&e).is_ok());
}
#[test]
fn bad_args() {
for bad in ["a\u{0}b", "a\nb", "a\rb", "\"unclosed", "a\u{7}"] {
let mut e = entry();
e.launch_params = Some(bad.into());
assert_eq!(game(&e), Err(ParseError::BadValue("launch_params")), "{bad:?}");
}
let mut e = entry();
e.launch_params = Some(vec!["-a"; limits::MAX_ARGS + 1].join(" "));
assert_eq!(game(&e), Err(ParseError::TooMany("args")));
e.launch_params = Some("x".repeat(limits::MAX_ARG + 1));
assert_eq!(game(&e), Err(ParseError::TooLong("arg")));
e.launch_params = Some("x ".repeat(limits::MAX_ARGS_LINE));
assert_eq!(game(&e), Err(ParseError::TooLong("launch_params")));
}
#[test]
fn shell_metacharacters_stay_inside_one_argument() {
let mut e = entry();
e.launch_params = Some(r#""a & calc" |b ^c %PATH%"#.into());
let g = game(&e).unwrap();
let (_, _, args) = exe_parts(&g.launch);
assert_eq!(args, ["a & calc", "|b", "^c", "%PATH%"]);
}
#[test]
fn bad_title() {
let mut e = entry();
e.name = " ".into();
assert_eq!(game(&e), Err(ParseError::Missing("name")));
e.name = "x".repeat(limits::MAX_TITLE + 1);
assert_eq!(game(&e), Err(ParseError::TooLong("name")));
e.name = "a\u{1b}[31mred".into();
assert_eq!(game(&e), Err(ParseError::BadValue("name")));
}
+322
View File
@@ -0,0 +1,322 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Hostile input across every parser: refused with a typed error, never a panic.
use arena_core::gog::GogEntry;
use arena_core::limits::{MAX_DEPTH, MAX_ENTRIES, MAX_ESCAPES, MAX_FILE, MAX_KEY, MAX_VALUE};
use arena_core::{ParseError, WinPath, epic, gog, manual, steam, vdf};
fn lib() -> WinPath {
WinPath::parse(r"D:\SteamLibrary").unwrap()
}
const FIXTURES: [&[u8]; 23] = [
include_bytes!("fixtures/steam/libraryfolders.vdf"),
include_bytes!("fixtures/steam/libraryfolders_old.vdf"),
include_bytes!("fixtures/steam/libraryfolders_wrongtype.vdf"),
include_bytes!("fixtures/steam/libraryfolders_unc.vdf"),
include_bytes!("fixtures/steam/libraryfolders_dup.vdf"),
include_bytes!("fixtures/steam/appmanifest_1234560.acf"),
include_bytes!("fixtures/steam/appmanifest_228980.acf"),
include_bytes!("fixtures/steam/appmanifest_traversal.acf"),
include_bytes!("fixtures/steam/appmanifest_absolute.acf"),
include_bytes!("fixtures/steam/appmanifest_wrongtype.acf"),
include_bytes!("fixtures/steam/appmanifest_dupkey.acf"),
include_bytes!("fixtures/steam/appmanifest_absurd.acf"),
include_bytes!("fixtures/steam/appmanifest_unterminated.acf"),
include_bytes!("fixtures/epic/valid.item"),
include_bytes!("fixtures/epic/addon.item"),
include_bytes!("fixtures/epic/wrongtype.item"),
include_bytes!("fixtures/epic/dupkey.item"),
include_bytes!("fixtures/epic/traversal.item"),
include_bytes!("fixtures/epic/unc.item"),
include_bytes!("fixtures/epic/badappname.item"),
include_bytes!("fixtures/epic/missing.item"),
include_bytes!("fixtures/epic/trailing.item"),
include_bytes!("fixtures/epic/absurd.item"),
];
/// Runs every byte parser over `input`; any panic fails the test.
fn all_parsers(input: &[u8]) {
let _ = vdf::tokenize(input);
let _ = vdf::parse(input);
let _ = steam::library_folders(input);
let _ = steam::app_manifest(input, &lib());
let _ = epic::item(input);
}
// ---- huge files -------------------------------------------------------------------------------------------
#[test]
fn huge_file_is_refused_before_parsing() {
let mut big = b"\"AppState\" { \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"N\" }".to_vec();
big.resize(MAX_FILE + 1, b' ');
assert_eq!(vdf::tokenize(&big), Err(ParseError::TooLarge));
assert_eq!(vdf::parse(&big), Err(ParseError::TooLarge));
assert_eq!(steam::library_folders(&big), Err(ParseError::TooLarge));
assert_eq!(steam::app_manifest(&big, &lib()), Err(ParseError::TooLarge));
let mut json = br#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G"}"#.to_vec();
json.resize(MAX_FILE + 1, b' ');
assert_eq!(epic::item(&json), Err(ParseError::TooLarge));
}
#[test]
fn exactly_max_file_is_still_read() {
let mut ok = b"\"AppState\" { \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"N\" }".to_vec();
ok.resize(MAX_FILE, b' ');
assert!(steam::app_manifest(&ok, &lib()).is_ok());
}
// ---- deep nesting -----------------------------------------------------------------------------------------
fn nested_vdf(depth: usize) -> Vec<u8> {
let mut s = Vec::new();
for _ in 0..depth {
s.extend_from_slice(b"\"k\" { ");
}
for _ in 0..depth {
s.extend_from_slice(b"} ");
}
s
}
#[test]
fn deep_vdf_is_refused() {
assert!(vdf::parse(&nested_vdf(MAX_DEPTH)).is_ok());
assert_eq!(vdf::parse(&nested_vdf(MAX_DEPTH + 1)), Err(ParseError::TooDeep));
// Far deeper than any stack would survive with naive recursion.
assert_eq!(vdf::parse(&nested_vdf(100_000)), Err(ParseError::TooDeep));
assert_eq!(steam::library_folders(&nested_vdf(5_000)), Err(ParseError::TooDeep));
}
#[test]
fn deep_json_is_refused() {
let deep = |n: usize| {
let mut s = String::from(r#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G","Deep":"#);
s.push_str(&"[".repeat(n));
s.push_str(&"]".repeat(n));
s.push('}');
s
};
assert!(epic::item(deep(MAX_DEPTH - 1).as_bytes()).is_ok());
assert_eq!(epic::item(deep(MAX_DEPTH).as_bytes()), Err(ParseError::TooDeep));
assert_eq!(epic::item(deep(200_000).as_bytes()), Err(ParseError::TooDeep));
// Brackets inside strings do not count.
let in_string = format!(r#"{{"AppName":"A","DisplayName":"{}","InstallLocation":"C:\\G"}}"#, "[".repeat(200));
assert!(epic::item(in_string.as_bytes()).is_ok());
}
// ---- wrong types ------------------------------------------------------------------------------------------
#[test]
fn wrong_types_everywhere() {
let acf = |body: &str| format!("\"AppState\" {{ {body} }}");
let cases = [
(acf("\"appid\" { } \"name\" \"N\" \"installdir\" \"N\""), "appid"),
(acf("\"appid\" \"10\" \"name\" { } \"installdir\" \"N\""), "name"),
(acf("\"appid\" \"10\" \"name\" \"N\" \"installdir\" { }"), "installdir"),
("\"AppState\" \"text\"".to_string(), "AppState"),
];
for (text, field) in cases {
assert_eq!(steam::app_manifest(text.as_bytes(), &lib()), Err(ParseError::WrongType(field)), "{text}");
}
assert_eq!(
steam::library_folders(b"\"libraryfolders\" { \"0\" { \"path\" { } } }"),
Err(ParseError::WrongType("path"))
);
}
// ---- bad paths --------------------------------------------------------------------------------------------
#[test]
fn bad_library_paths() {
for bad in [r"..\\Steam", r"C:\\Steam\\..\\..\\Windows", r"\\\\?\\C:\\Steam", r"Steam", "C:\\\\CON", "C:"] {
let text = format!("\"libraryfolders\" {{ \"0\" {{ \"path\" \"{bad}\" }} }}");
assert_eq!(steam::library_folders(text.as_bytes()), Err(ParseError::BadPath("path")), "{bad}");
}
}
#[test]
fn bad_paths_in_every_source() {
let r = epic::item(include_bytes!("fixtures/epic/traversal.item"));
assert_eq!(r, Err(ParseError::BadPath("InstallLocation")));
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_traversal.acf"), &lib());
assert_eq!(r, Err(ParseError::BadPath("installdir")));
let e = GogEntry {
game_id: "1".into(),
name: "G".into(),
path: r"C:\G\..\..".into(),
exe: r"C:\g.exe".into(),
working_dir: None,
launch_params: None,
};
assert_eq!(gog::game(&e), Err(ParseError::BadPath("path")));
assert_eq!(manual::game(r"C:\G\..\g.exe", None), Err(ParseError::BadPath("exe")));
}
// ---- non-UTF-8 --------------------------------------------------------------------------------------------
#[test]
fn non_utf8_names_are_refused() {
let mut acf = b"\"AppState\" { \"appid\" \"10\" \"name\" \"Bad ".to_vec();
acf.extend_from_slice(&[0xC3, 0x28, 0xFF]);
acf.extend_from_slice(b"\" \"installdir\" \"N\" }");
assert_eq!(vdf::tokenize(&acf), Err(ParseError::NotUtf8));
assert_eq!(steam::app_manifest(&acf, &lib()), Err(ParseError::NotUtf8));
let mut key = b"\"AppState\" { \"".to_vec();
key.extend_from_slice(&[0xED, 0xA0, 0x80]); // an encoded surrogate
key.extend_from_slice(b"\" \"x\" }");
assert_eq!(steam::app_manifest(&key, &lib()), Err(ParseError::NotUtf8));
let mut json = br#"{"AppName":"A","DisplayName":""#.to_vec();
json.extend_from_slice(&[0x80, 0x80]);
json.extend_from_slice(br#"","InstallLocation":"C:\\G"}"#);
assert_eq!(epic::item(&json), Err(ParseError::NotUtf8));
// Outside a string too.
assert_eq!(epic::item(&[b'{', 0xFF, b'}']), Err(ParseError::NotUtf8));
}
#[test]
fn bytes_outside_strings_are_refused_too() {
assert_eq!(vdf::tokenize(&[0xFF]), Err(ParseError::NotUtf8));
assert_eq!(vdf::tokenize(&[&b"\"a\" \"b\" // comment "[..], &[0xFF]].concat()), Err(ParseError::NotUtf8));
}
// ---- NUL and control bytes --------------------------------------------------------------------------------
#[test]
fn nul_bytes_are_refused() {
assert_eq!(vdf::tokenize(b"\"a\0b\" \"c\""), Err(ParseError::Syntax { at: 2 }));
assert_eq!(vdf::tokenize(b"\"a\" \0 \"c\""), Err(ParseError::Syntax { at: 4 }));
assert!(matches!(epic::item(b"{\"AppName\":\"A\0\"}"), Err(ParseError::Syntax { .. })));
let json = br#"{"AppName":"A","DisplayName":"x\u0000y","InstallLocation":"C:\\G"}"#;
assert_eq!(epic::item(json), Err(ParseError::BadValue("DisplayName")));
let json = br#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G\u0000"}"#;
assert_eq!(epic::item(json), Err(ParseError::BadPath("InstallLocation")));
}
#[test]
fn raw_control_characters_in_vdf_strings_are_refused() {
for b in [0x01u8, 0x07, 0x0A, 0x0D, 0x1B, 0x7F] {
let input = [b'"', b'a', b, b'"'];
assert_eq!(vdf::tokenize(&input), Err(ParseError::Syntax { at: 2 }), "{b:#x}");
}
assert!(vdf::tokenize(b"\"a\tb\"").is_ok(), "a raw tab is allowed");
}
// ---- unterminated -----------------------------------------------------------------------------------------
#[test]
fn unterminated_strings_and_objects() {
assert_eq!(vdf::tokenize(b"\"abc"), Err(ParseError::Syntax { at: 0 }));
assert_eq!(vdf::tokenize(b"\"a\" \"b"), Err(ParseError::Syntax { at: 4 }));
assert!(matches!(vdf::parse(b"\"a\" { \"b\" \"c\""), Err(ParseError::Syntax { .. })));
assert!(matches!(epic::item(br#"{"AppName":"A"#), Err(ParseError::Syntax { .. })));
assert!(matches!(epic::item(b"{"), Err(ParseError::Syntax { .. })));
assert!(matches!(epic::item(b""), Err(ParseError::Syntax { .. })));
}
// ---- duplicates -------------------------------------------------------------------------------------------
#[test]
fn duplicate_keys_and_ids() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_dupkey.acf"), &lib());
assert_eq!(r, Err(ParseError::Duplicate("key")));
let r =
steam::library_folders(b"\"libraryfolders\" { \"0\" { \"path\" \"C:\\\\A\" } \"0\" { \"path\" \"C:\\\\B\" } }");
assert_eq!(r, Err(ParseError::Duplicate("key")));
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_dup.vdf"));
assert_eq!(r, Err(ParseError::Duplicate("path")));
assert_eq!(epic::item(include_bytes!("fixtures/epic/dupkey.item")), Err(ParseError::Duplicate("AppName")));
let json = br#"{"AppName":"A","DisplayName":"x","DisplayName":"y","InstallLocation":"C:\\G"}"#;
assert_eq!(epic::item(json), Err(ParseError::Duplicate("DisplayName")));
}
// ---- caps on lengths, counts, escapes ---------------------------------------------------------------------
#[test]
fn long_keys_and_values() {
let key = format!("\"{}\" \"v\"", "k".repeat(MAX_KEY + 1));
assert_eq!(vdf::parse(key.as_bytes()), Err(ParseError::TooLong("key")));
let key_ok = format!("\"{}\" \"v\"", "k".repeat(MAX_KEY));
assert!(vdf::parse(key_ok.as_bytes()).is_ok());
let value = format!("\"k\" \"{}\"", "v".repeat(MAX_VALUE + 1));
assert_eq!(vdf::parse(value.as_bytes()), Err(ParseError::TooLong("value")));
assert_eq!(vdf::tokenize(value.as_bytes()), Err(ParseError::TooLong("value")));
let value_ok = format!("\"k\" \"{}\"", "v".repeat(MAX_VALUE));
assert!(vdf::parse(value_ok.as_bytes()).is_ok());
}
#[test]
fn too_many_escapes() {
let s = format!("\"k\" \"{}\"", "\\\\".repeat(MAX_ESCAPES + 1));
assert_eq!(vdf::tokenize(s.as_bytes()), Err(ParseError::TooMany("escapes")));
let ok = format!("\"k\" \"{}\"", "\\\\".repeat(MAX_ESCAPES));
assert!(vdf::tokenize(ok.as_bytes()).is_ok());
}
#[test]
fn too_many_entries() {
let mut s = String::from("\"root\" {\n");
for i in 0..MAX_ENTRIES {
s.push_str(&format!("\"{i}\" \"\"\n"));
}
s.push_str("}\n");
assert!(s.len() <= MAX_FILE, "the test document must fit the file cap");
assert_eq!(vdf::parse(s.as_bytes()), Err(ParseError::TooMany("entries")));
}
#[test]
fn absurd_numbers() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absurd.acf"), &lib());
assert_eq!(r, Err(ParseError::BadId));
let r = epic::item(include_bytes!("fixtures/epic/absurd.item"));
assert!(r.is_err());
let e = GogEntry {
game_id: "9".repeat(10_000),
name: "G".into(),
path: r"C:\G".into(),
exe: r"C:\G\g.exe".into(),
working_dir: None,
launch_params: None,
};
assert_eq!(gog::game(&e), Err(ParseError::BadId));
}
#[test]
fn huge_strings_into_value_builders() {
let huge = "a".repeat(10 * MAX_FILE);
assert!(manual::game(&huge, None).is_err());
assert!(manual::game(r"C:\G\g.exe", Some(&huge)).is_err());
assert!(WinPath::parse(&huge).is_err());
assert!(huge.parse::<arena_core::GameId>().is_err());
}
// ---- never panics -----------------------------------------------------------------------------------------
#[test]
fn every_truncation_of_every_fixture() {
for f in FIXTURES {
for end in 0..=f.len() {
all_parsers(&f[..end]);
}
}
}
#[test]
fn every_single_byte_corruption_of_every_fixture() {
let replacements = [0x00u8, b'"', b'\\', b'{', b'}', b'[', b']', b':', b',', 0xFF, 0xC3, b'\n'];
for f in FIXTURES {
for i in 0..f.len() {
for &r in &replacements {
let mut m = f.to_vec();
m[i] = r;
all_parsers(&m);
}
}
}
}
+190
View File
@@ -0,0 +1,190 @@
// 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::<Hotkey>(r#""shift+ctrl+g""#).unwrap(), h);
for bad in [r#""G""#, r#""Win+L""#, r#""""#, "7", r#"{"key":"G"}"#] {
assert!(serde_json::from_str::<Hotkey>(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<Value = Modifiers> {
(any::<bool>(), any::<bool>(), any::<bool>(), any::<bool>()).prop_map(|(ctrl, alt, shift, win)| Modifiers {
ctrl,
alt,
shift,
win,
})
}
fn key() -> impl Strategy<Value = Key> {
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(_)));
}
}
}
+221
View File
@@ -0,0 +1,221 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Launch strings contain only parsed, validated fields: nothing raw from a file reaches a URI or an argument.
use arena_core::gog::GogEntry;
use arena_core::{Launch, ParseError, WinPath, epic, gog, limits, steam};
use proptest::prelude::*;
fn is_epic_app(s: &str) -> bool {
!s.is_empty()
&& s.len() <= limits::MAX_EPIC_APP
&& s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
fn is_domi_id(s: &str) -> bool {
!s.is_empty()
&& s.len() <= limits::MAX_DOMI_ID
&& !s.starts_with('-')
&& !s.ends_with('-')
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// The URI is exactly the template filled with the field, and the field passes its rule.
fn check_uri(l: &Launch) {
let uri = l.uri();
match l {
Launch::SteamRunGameId(id) => {
assert_eq!(uri, (*id != 0).then(|| format!("steam://rungameid/{id}")));
}
Launch::Epic { app_name } => {
let want = is_epic_app(app_name)
.then(|| format!("com.epicgames.launcher://apps/{app_name}?action=launch&silent=true"));
assert_eq!(uri, want, "{app_name:?}");
}
Launch::DomiLink { app } => {
assert_eq!(uri, is_domi_id(app).then(|| format!("domi-{app}://open")), "{app:?}");
}
Launch::Exe { .. } => assert_eq!(uri, None),
Launch::Url(u) => {
if let Some(got) = &uri {
assert_eq!(got, u);
assert!(got.starts_with("https://"));
assert!(got.bytes().all(|b| b.is_ascii_graphic() && b != b'\\' && b != b'"'), "{got:?}");
}
}
}
}
#[test]
fn fixture_uris_are_templates_of_parsed_fields() {
let lib = WinPath::parse(r"D:\SteamLibrary").unwrap();
let s = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_1234560.acf"), &lib).unwrap();
check_uri(&s.launch);
assert_eq!(s.launch.uri().unwrap(), "steam://rungameid/1234560");
let e = epic::item(include_bytes!("fixtures/epic/valid.item")).unwrap();
check_uri(&e.launch);
assert_eq!(e.launch.uri().unwrap(), "com.epicgames.launcher://apps/ExampleRacer_Main-01?action=launch&silent=true");
}
#[test]
fn hand_built_bad_values_give_no_uri() {
let bad = [
Launch::SteamRunGameId(0),
Launch::Epic { app_name: String::new() },
Launch::Epic { app_name: "Fortnite?action=uninstall".into() },
Launch::Epic { app_name: "a/../../b".into() },
Launch::Epic { app_name: "a b".into() },
Launch::Epic { app_name: "a".repeat(65) },
Launch::DomiLink { app: "Lapilli".into() },
Launch::DomiLink { app: "x://evil".into() },
Launch::DomiLink { app: "-x".into() },
Launch::Url("javascript:alert(1)".into()),
Launch::Url("http://example.org/".into()),
Launch::Url("https://example.org/a b".into()),
Launch::Url("https://user@example.org/".into()),
Launch::Url("file:///C:/Windows/System32/calc.exe".into()),
];
for l in &bad {
assert_eq!(l.uri(), None, "{l:?}");
assert_eq!(l.uri_checked(&["example.org"]), None, "{l:?}");
check_uri(l);
}
let exe = Launch::Exe {
exe: WinPath::parse(r"C:\G\g.exe").unwrap(),
working_dir: WinPath::parse(r"C:\G").unwrap(),
args: vec![],
};
assert_eq!(exe.uri(), None);
}
#[test]
fn url_needs_allowed_host_when_checked() {
let l = Launch::web("https://games.example.org/x", &["games.example.org"]).unwrap();
assert_eq!(l.uri_checked(&["GAMES.example.org"]).as_deref(), Some("https://games.example.org/x"));
assert_eq!(l.uri_checked(&[]), None);
assert_eq!(Launch::web("https://games.example.org/x", &[]), Err(ParseError::BadValue("url")));
}
#[test]
fn builders_validate() {
assert_eq!(Launch::steam(0), Err(ParseError::BadId));
assert_eq!(Launch::steam(10).unwrap(), Launch::SteamRunGameId(10));
assert_eq!(Launch::epic("a?b"), Err(ParseError::BadId));
assert_eq!(Launch::domi_link("A"), Err(ParseError::BadId));
let exe = WinPath::parse(r"C:\G\g.exe").unwrap();
let dir = WinPath::parse(r"C:\G").unwrap();
assert_eq!(
Launch::exe(WinPath::parse(r"C:\G\g.bat").unwrap(), dir.clone(), vec![]),
Err(ParseError::BadPath("exe"))
);
assert_eq!(Launch::exe(exe.clone(), dir.clone(), vec!["a\u{0}".into()]), Err(ParseError::BadValue("args")));
assert_eq!(Launch::exe(exe.clone(), dir.clone(), vec!["a\nb".into()]), Err(ParseError::BadValue("args")));
assert_eq!(
Launch::exe(exe.clone(), dir.clone(), vec!["x".repeat(limits::MAX_ARG + 1)]),
Err(ParseError::TooLong("arg"))
);
assert_eq!(
Launch::exe(exe.clone(), dir.clone(), vec![String::new(); limits::MAX_ARGS + 1]),
Err(ParseError::TooMany("args"))
);
assert!(Launch::exe(exe, dir, vec!["--fine".into(), "with space".into()]).is_ok());
}
#[test]
fn gog_args_are_exactly_the_split_params() {
let e = GogEntry {
game_id: "1".into(),
name: "G".into(),
path: r"C:\G".into(),
exe: r"C:\G\g.exe".into(),
working_dir: None,
launch_params: Some(r#" -a "b c" d"#.into()),
};
let g = gog::game(&e).unwrap();
match g.launch {
Launch::Exe { args, .. } => assert_eq!(args, ["-a", "b c", "d"]),
other => panic!("{other:?}"),
}
}
#[test]
fn deserialising_validates_every_field() {
let good = r#"{"epic":{"app_name":"Fortnite"}}"#;
assert_eq!(serde_json::from_str::<Launch>(good).unwrap(), Launch::Epic { app_name: "Fortnite".into() });
for bad in [
r#"{"epic":{"app_name":"a?b"}}"#,
r#"{"steam_run_game_id":0}"#,
r#"{"steam_run_game_id":4294967296}"#,
r#"{"domi_link":{"app":"X"}}"#,
r#"{"url":"http://example.org/"}"#,
r#"{"exe":{"exe":"C:\\G\\g.bat","working_dir":"C:\\G","args":[]}}"#,
r#"{"exe":{"exe":"C:\\G\\..\\g.exe","working_dir":"C:\\G","args":[]}}"#,
r#"{"exe":{"exe":"C:\\G\\g.exe","working_dir":"C:\\G","args":["a\u0000"]}}"#,
] {
assert!(serde_json::from_str::<Launch>(bad).is_err(), "{bad}");
}
}
#[test]
fn serde_round_trip() {
let all = [
Launch::steam(10).unwrap(),
Launch::epic("A_b-1").unwrap(),
Launch::domi_link("lapilli").unwrap(),
Launch::web("https://games.example.org/p?q=1", &["games.example.org"]).unwrap(),
Launch::exe(WinPath::parse(r"C:\G\g.exe").unwrap(), WinPath::parse(r"C:\G").unwrap(), vec!["-x".into()])
.unwrap(),
];
for l in all {
let json = serde_json::to_string(&l).unwrap();
assert_eq!(serde_json::from_str::<Launch>(&json).unwrap(), l, "{json}");
}
}
proptest! {
#[test]
fn epic_uri_only_from_valid_names(name in ".{0,80}") {
let l = Launch::Epic { app_name: name.clone() };
check_uri(&l);
prop_assert_eq!(Launch::epic(&name).is_ok(), is_epic_app(&name));
}
#[test]
fn epic_uri_from_generated_valid_names(name in "[A-Za-z0-9_-]{1,64}") {
let l = Launch::epic(&name).unwrap();
prop_assert_eq!(l.uri().unwrap(), format!("com.epicgames.launcher://apps/{name}?action=launch&silent=true"));
}
#[test]
fn domi_uri_only_from_valid_ids(app in ".{0,40}") {
check_uri(&Launch::DomiLink { app });
}
#[test]
fn steam_uri_any_id(id in any::<u32>()) {
check_uri(&Launch::SteamRunGameId(id));
}
#[test]
fn url_uri_never_escapes_the_rules(url in "(https?://)?[a-zA-Z0-9.:@/?#%&=_ \\\\\"-]{0,60}") {
let l = Launch::Url(url);
check_uri(&l);
}
#[test]
fn epic_manifest_app_name_reaches_uri_only_when_valid(name in "[ -~]{0,70}") {
let json = serde_json::json!({"AppName": name, "DisplayName": "x", "InstallLocation": "C:\\G"}).to_string();
match epic::item(json.as_bytes()) {
Ok(g) => {
prop_assert!(is_epic_app(&name));
prop_assert_eq!(g.launch.uri().unwrap(), format!("com.epicgames.launcher://apps/{name}?action=launch&silent=true"));
}
Err(e) => {
prop_assert!(!is_epic_app(&name));
prop_assert_eq!(e, ParseError::BadId);
}
}
}
}
+135
View File
@@ -0,0 +1,135 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Manual games (an `.exe` the user picked) and Domi games (Atrium registry entries).
use arena_core::{CoverHint, DomiLaunch, Launch, ParseError, Source, WinPath, domi, limits, manual};
#[test]
fn manual_game() {
let g = manual::game(r"D:\Games\Old Thing\OldThing.exe", None).unwrap();
assert_eq!(g.source, Source::Manual);
assert_eq!(g.title, "OldThing");
assert!(g.id.as_str().starts_with("manual:"));
assert_eq!(g.id.native().len(), 16);
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"D:\Games\Old Thing"));
match &g.launch {
Launch::Exe { exe, working_dir, args } => {
assert_eq!(exe.as_str(), r"D:\Games\Old Thing\OldThing.exe");
assert_eq!(working_dir.as_str(), r"D:\Games\Old Thing");
assert!(args.is_empty());
}
other => panic!("{other:?}"),
}
assert!(matches!(g.cover, Some(CoverHint::Lettered { letter: 'O', hue }) if hue < 360));
}
#[test]
fn manual_id_is_stable_and_ignores_case_and_slashes() {
let a = manual::game(r"D:\Games\Old Thing\OldThing.exe", None).unwrap();
let b = manual::game("d:/games/old thing/OLDTHING.EXE", Some("Renamed")).unwrap();
assert_eq!(a.id, b.id);
assert_eq!(b.title, "Renamed");
let c = manual::game(r"D:\Games\Other\OldThing.exe", None).unwrap();
assert_ne!(a.id, c.id);
}
#[test]
fn manual_refuses_bad_exe() {
for bad in [
r"OldThing.exe",
r"\\server\share\x.exe",
r"\\?\C:\x.exe",
r"\\.\C:\x.exe",
r"C:\Games\..\Windows\x.exe",
r"C:\Games\run.bat",
r"C:\Games\run.cmd",
r"C:\",
r"C:\Games\CON.exe",
"C:\\Games\\x\u{0}.exe",
"",
] {
assert_eq!(manual::game(bad, None), Err(ParseError::BadPath("exe")), "{bad:?}");
}
}
#[test]
fn manual_refuses_bad_title() {
assert_eq!(manual::game(r"C:\G\x.exe", Some(" ")), Err(ParseError::Missing("title")));
assert_eq!(manual::game(r"C:\G\x.exe", Some("a\u{0}b")), Err(ParseError::BadValue("title")));
}
#[test]
fn domi_link_game() {
let g = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" }).unwrap();
assert_eq!(g.id.as_str(), "domi:lapilli");
assert_eq!(g.source, Source::Domi);
assert_eq!(g.title, "Lapilli");
assert_eq!(g.install_dir, None);
assert_eq!(g.launch, Launch::DomiLink { app: "lapilli".into() });
assert_eq!(g.launch.uri().as_deref(), Some("domi-lapilli://open"));
}
#[test]
fn domi_web_game() {
let hosts = ["rosea.example.org", "moin.example.org"];
let g = domi::game(
"rosea",
"Rosea",
DomiLaunch::Web { url: "HTTPS://Rosea.Example.org/play?x=1#top", allowed_hosts: &hosts },
)
.unwrap();
assert_eq!(g.launch, Launch::Url("https://rosea.example.org/play?x=1#top".into()));
assert_eq!(g.launch.uri().as_deref(), Some("https://rosea.example.org/play?x=1#top"));
assert_eq!(g.launch.uri_checked(&hosts).as_deref(), Some("https://rosea.example.org/play?x=1#top"));
assert_eq!(g.launch.uri_checked(&["other.example.org"]), None);
}
#[test]
fn domi_refuses_bad_ids() {
let long = "a".repeat(limits::MAX_DOMI_ID + 1);
for bad in ["", "-x", "x-", "X", "a_b", "a.b", "a b", "ä", long.as_str()] {
assert_eq!(domi::game(bad, "N", DomiLaunch::Link { app: "ok" }), Err(ParseError::BadId), "{bad:?}");
assert_eq!(domi::game("ok", "N", DomiLaunch::Link { app: bad }), Err(ParseError::BadId), "{bad:?}");
}
assert!(domi::game(&"a".repeat(limits::MAX_DOMI_ID), "N", DomiLaunch::Link { app: "a-1" }).is_ok());
}
#[test]
fn domi_refuses_bad_urls() {
let hosts = ["rosea.example.org"];
let long = format!("https://rosea.example.org/{}", "a".repeat(limits::MAX_URL));
for bad in [
"http://rosea.example.org/",
"javascript:alert(1)",
"file:///C:/Windows/System32/calc.exe",
"https://evil.example.org/",
"https://rosea.example.org.evil.example/",
"https://sub.rosea.example.org/",
"https://user@rosea.example.org/",
"https://rosea.example.org:8443/",
"https://rosea.example.org/a b",
"https://rosea.example.org/a\\b",
"https://rosea.example.org/\u{0}",
"https://rosea.example.org/%zz",
"https://rosea.example.org/\"quote",
"https:///path",
"https://",
" https://rosea.example.org/",
"https://[::1]/",
"https://rosea..example.org/",
"https://-rosea.example.org/",
long.as_str(),
] {
let r = domi::game("rosea", "Rosea", DomiLaunch::Web { url: bad, allowed_hosts: &hosts });
assert!(matches!(r, Err(ParseError::BadValue("url")) | Err(ParseError::TooLong("url"))), "{bad:?}: {r:?}");
}
}
#[test]
fn domi_web_host_without_path() {
let hosts = ["moin.example.org"];
let g =
domi::game("moin", "Moin", DomiLaunch::Web { url: "https://moin.example.org", allowed_hosts: &hosts }).unwrap();
assert_eq!(g.launch.uri().as_deref(), Some("https://moin.example.org"));
}
+152
View File
@@ -0,0 +1,152 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Dedupe and ordering in `merge`.
use arena_core::{CoverHint, DomiLaunch, Game, GameId, Launch, Library, Source, WinPath, domi, gog, manual, merge};
fn game(source: Source, native: &str, title: &str, dir: Option<&str>) -> Game {
let id = GameId::new(source, native).unwrap();
let launch = match source {
Source::Steam => Launch::steam(native.parse().unwrap()).unwrap(),
Source::Epic => Launch::epic(native).unwrap(),
Source::Domi => Launch::domi_link(native).unwrap(),
_ => {
let d = WinPath::parse(dir.unwrap()).unwrap();
Launch::exe(d.join("g.exe").unwrap(), d, vec![]).unwrap()
}
};
Game {
cover: Some(CoverHint::lettered(title, &id)),
id,
source,
title: title.into(),
install_dir: dir.map(|d| WinPath::parse(d).unwrap()),
launch,
}
}
fn ids(lib: &Library) -> Vec<&str> {
lib.games.iter().map(|g| g.id.as_str()).collect()
}
#[test]
fn same_id_kept_once_first_wins() {
let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha"));
let mut a2 = a.clone();
a2.title = "Alpha (again)".into();
let lib = merge(vec![vec![a.clone(), a2.clone()], vec![a2]]);
assert_eq!(lib.len(), 1);
assert_eq!(lib.games[0].title, "Alpha");
}
#[test]
fn same_install_dir_keeps_the_best_source() {
let dir = r"C:\Games\Shared";
let steam = game(Source::Steam, "10", "Shared S", Some(dir));
let epic = game(Source::Epic, "shared", "Shared E", Some(r"c:\games\SHARED"));
let gog = game(Source::Gog, "20", "Shared G", Some(dir));
let man = game(Source::Manual, "0123456789abcdef", "Shared M", Some(dir));
let lib = merge(vec![vec![man.clone()], vec![gog.clone()], vec![epic.clone()], vec![steam.clone()]]);
assert_eq!(ids(&lib), ["steam:10"]);
let lib = merge(vec![vec![man.clone()], vec![gog.clone()], vec![epic.clone()]]);
assert_eq!(ids(&lib), ["epic:shared"]);
let lib = merge(vec![vec![man.clone(), gog.clone()]]);
assert_eq!(ids(&lib), ["gog:20"]);
}
#[test]
fn domi_beats_manual_on_the_same_folder() {
let dir = r"C:\Domi\Lapilli";
let mut d = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" }).unwrap();
d.install_dir = Some(WinPath::parse(dir).unwrap());
let m = manual::game(r"C:\Domi\Lapilli\lapilli.exe", None).unwrap();
let lib = merge(vec![vec![m], vec![d]]);
assert_eq!(ids(&lib), ["domi:lapilli"]);
}
#[test]
fn same_source_same_folder_keeps_both() {
let a = game(Source::Steam, "10", "A", Some(r"D:\S\common\X"));
let b = game(Source::Steam, "11", "B", Some(r"D:\S\common\X"));
let lib = merge(vec![vec![a, b]]);
assert_eq!(ids(&lib), ["steam:10", "steam:11"]);
}
#[test]
fn no_install_dir_never_dedupes_by_folder() {
let a = domi::game("rosea", "Rosea", DomiLaunch::Link { app: "rosea" }).unwrap();
let b = domi::game("moin", "Moin", DomiLaunch::Link { app: "moin" }).unwrap();
let lib = merge(vec![vec![a], vec![b]]);
assert_eq!(ids(&lib), ["domi:moin", "domi:rosea"]);
}
#[test]
fn different_folders_are_different_games() {
let a = game(Source::Steam, "10", "Same Title", Some(r"D:\S\common\X"));
let b = game(Source::Gog, "20", "Same Title", Some(r"C:\GOG Games\X"));
let lib = merge(vec![vec![a], vec![b]]);
assert_eq!(lib.len(), 2);
}
#[test]
fn ordered_by_title_ignoring_case_then_id_and_independent_of_scan_order() {
let games = vec![
game(Source::Steam, "30", "zeta", Some(r"D:\z")),
game(Source::Epic, "b", "Beta", Some(r"D:\b")),
game(Source::Gog, "1", "alpha", Some(r"D:\a1")),
game(Source::Steam, "2", "Alpha", Some(r"D:\a2")),
game(Source::Manual, "0123456789abcdef", "Ärger", Some(r"D:\ae")),
];
let forward = merge(vec![games.clone()]);
let mut rev = games.clone();
rev.reverse();
let backward = merge(vec![rev.into_iter().map(|g| vec![g]).collect::<Vec<_>>().concat()]);
assert_eq!(forward, backward);
assert_eq!(ids(&forward), ["gog:1", "steam:2", "epic:b", "steam:30", "manual:0123456789abcdef"]);
}
#[test]
fn library_lookup() {
let g = gog::game(&gog::GogEntry {
game_id: "5".into(),
name: "Five".into(),
path: r"C:\G5".into(),
exe: r"C:\G5\five.exe".into(),
working_dir: None,
launch_params: None,
})
.unwrap();
let lib = merge(vec![vec![g.clone()]]);
assert_eq!(lib.get(&"gog:5".parse().unwrap()), Some(&g));
assert_eq!(lib.get(&"gog:6".parse().unwrap()), None);
assert!(merge(vec![]).is_empty());
}
#[test]
fn library_json_round_trip() {
let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha"));
let b = domi::game(
"rosea",
"Rosea",
DomiLaunch::Web { url: "https://rosea.example.org/", allowed_hosts: &["rosea.example.org"] },
)
.unwrap();
let lib = merge(vec![vec![a, b]]);
let json = serde_json::to_string(&lib).unwrap();
let back: Library = serde_json::from_str(&json).unwrap();
assert_eq!(back, lib);
}
#[test]
fn library_json_refuses_mismatched_or_bad_games() {
let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha"));
let json = serde_json::to_string(&Library { games: vec![a] }).unwrap();
let wrong_source = json.replace(r#""source":"steam""#, r#""source":"epic""#);
assert!(serde_json::from_str::<Library>(&wrong_source).is_err());
let bad_title = json.replace(r#""title":"Alpha""#, r#""title":"\u0000""#);
assert!(serde_json::from_str::<Library>(&bad_title).is_err());
let bad_path = json.replace(r#"D:\\S\\common\\Alpha"#, r#"D:\\S\\..\\Alpha"#);
assert!(serde_json::from_str::<Library>(&bad_path).is_err());
}
+249
View File
@@ -0,0 +1,249 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! `WinPath` and `GameId`: the two validated value types everything else is built from.
use arena_core::{GameId, ParseError, Source, WinPath, limits};
use proptest::prelude::*;
proptest! {
#[test]
fn winpath_never_panics_and_normal_form_is_stable(s in r"([A-Za-z]:)?[\\/a-zA-Z0-9 .:<>|?*\x00-\x1f¹~$-]{0,40}") {
if let Ok(p) = WinPath::parse(&s) {
let again = WinPath::parse(p.as_str()).unwrap();
prop_assert_eq!(&again, &p);
prop_assert!(p.components().all(|c| c != ".." && c != "." && !c.contains('\0')));
prop_assert!(!p.as_str().contains('/'));
prop_assert!(p.as_str().get(1..3) == Some(":\\"));
if let Some(parent) = p.parent() {
prop_assert!(p.starts_with(&parent));
}
}
}
#[test]
fn winpath_join_never_climbs_out(rel in r"[a-zA-Z.\\/]{0,20}") {
let base = WinPath::parse(r"C:\Games\X").unwrap();
if let Ok(j) = base.join(&rel) {
prop_assert!(j.starts_with(&base));
}
}
#[test]
fn game_id_round_trips_or_refuses(s in r"[a-z]{0,7}:?[a-zA-Z0-9:._ -]{0,20}") {
if let Ok(id) = s.parse::<GameId>() {
prop_assert_eq!(id.to_string(), s.clone());
prop_assert!(s.len() <= limits::MAX_GAME_ID);
prop_assert!(s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b":._-".contains(&b)));
}
}
}
#[test]
fn errors_display_without_input_text() {
let all = [
ParseError::TooLarge,
ParseError::TooDeep,
ParseError::NotUtf8,
ParseError::Syntax { at: 7 },
ParseError::Missing("name"),
ParseError::WrongType("appid"),
ParseError::BadPath("installdir"),
ParseError::BadId,
ParseError::Duplicate("key"),
ParseError::TooLong("value"),
ParseError::TooMany("entries"),
ParseError::BadValue("url"),
ParseError::NotAGame("Epic add-on"),
];
for e in all {
let text = e.to_string();
assert!(!text.is_empty());
let as_error: &dyn std::error::Error = &e;
assert_eq!(as_error.to_string(), text);
}
assert_eq!(ParseError::Syntax { at: 7 }.to_string(), "syntax error at byte 7");
}
fn p(s: &str) -> WinPath {
WinPath::parse(s).unwrap()
}
#[test]
fn winpath_accepts_and_normalises() {
assert_eq!(p(r"C:\Games\X").as_str(), r"C:\Games\X");
assert_eq!(p(r"c:\Games\X\").as_str(), r"C:\Games\X");
assert_eq!(p("d:/Games//X/").as_str(), r"D:\Games\X");
assert_eq!(p(r"C:\").as_str(), r"C:\");
assert_eq!(p("C:/").as_str(), r"C:\");
assert_eq!(p(r"C:\Program Files (x86)\Steam").as_str(), r"C:\Program Files (x86)\Steam");
assert_eq!(p(r"C:\Hry\Příliš žluťoučký kůň").as_str(), r"C:\Hry\Příliš žluťoučký kůň");
assert_eq!(p(r"C:\a.b\.hidden\x..y").as_str(), r"C:\a.b\.hidden\x..y");
assert_eq!(p(r"C:\CONSOLE\NULL\COM10\LPT").as_str(), r"C:\CONSOLE\NULL\COM10\LPT");
}
#[test]
fn winpath_refuses() {
let long = format!(r"C:\{}", "a".repeat(limits::MAX_PATH));
for bad in [
"",
"C:",
"C:Games",
r"\Games",
"Games",
r"1:\x",
r"\\server\share",
r"\\?\C:\x",
r"\\.\C:\x",
r"\??\C:\x",
"//server/share",
r"C:\..",
r"C:\Games\..\Windows",
r"C:\Games\.\x",
"C:\\Games\\x\u{0}",
"C:\\Games\\x\ny",
"C:\\Games\\x\u{1f}",
r"C:\Games\x:stream",
r"C:\Games\a*b",
r"C:\Games\a?b",
r#"C:\Games\a"b"#,
r"C:\Games\a<b",
r"C:\Games\a>b",
r"C:\Games\a|b",
r"C:\CON",
r"C:\con.txt",
r"C:\Games\nul",
r"C:\Games\Aux.log",
r"C:\Games\prn",
r"C:\Games\COM1",
r"C:\Games\lpt9.dat",
r"C:\Games\COM¹",
r"C:\Games\CONIN$",
r"C:\Games\conout$",
r"C:\Games\NUL .txt",
r"C:\Games\trailing.",
r"C:\Games\trailing ",
long.as_str(),
] {
assert!(matches!(WinPath::parse(bad), Err(ParseError::BadPath(_))), "{bad:?}");
}
}
#[test]
fn winpath_length_counts_utf16_units() {
let ok = format!(r"C:\{}", "a".repeat(limits::MAX_PATH - 3));
assert!(WinPath::parse(&ok).is_ok());
// One astral character is two UTF-16 units.
let astral = format!(r"C:\{}😀", "a".repeat(limits::MAX_PATH - 4));
assert!(WinPath::parse(&astral).is_err());
}
#[test]
fn winpath_join_parent_file_name() {
let base = p(r"C:\Games");
assert_eq!(base.join(r"A\b.exe").unwrap().as_str(), r"C:\Games\A\b.exe");
assert_eq!(base.join("A/b.exe").unwrap().as_str(), r"C:\Games\A\b.exe");
for bad in ["", r"..\x", r"A\..\..\x", r"\x", r"D:\x", "D:x", r"\\s\x", "a\u{0}"] {
assert!(base.join(bad).is_err(), "{bad:?}");
}
assert_eq!(p(r"C:\Games\A").parent(), Some(p(r"C:\Games")));
assert_eq!(p(r"C:\Games").parent(), Some(p(r"C:\")));
assert_eq!(p(r"C:\").parent(), None);
assert_eq!(p(r"C:\Games\b.exe").file_name(), Some("b.exe"));
assert_eq!(p(r"C:\").file_name(), None);
assert_eq!(p(r"C:\a\b").components().collect::<Vec<_>>(), ["a", "b"]);
}
#[test]
fn winpath_join_respects_length() {
let base = p(r"C:\Games");
assert!(base.join(&"a".repeat(limits::MAX_PATH)).is_err());
}
#[test]
fn winpath_compare_ignoring_case() {
assert!(p(r"C:\Games\X").eq_ignore_case(&p(r"c:\GAMES\x")));
assert!(p(r"C:\Games\X\bin\x.exe").starts_with(&p(r"c:\games\x")));
assert!(p(r"C:\Games\X").starts_with(&p(r"C:\Games\X")));
assert!(p(r"C:\Games\X").starts_with(&p(r"C:\")));
assert!(!p(r"C:\Games\XY").starts_with(&p(r"C:\Games\X")));
assert!(!p(r"D:\Games\X").starts_with(&p(r"C:\Games")));
assert!(!p(r"C:\Games").starts_with(&p(r"C:\Games\X")));
}
#[test]
fn winpath_serde_validates() {
let ok: WinPath = serde_json::from_str(r#""C:\\Games""#).unwrap();
assert_eq!(ok.as_str(), r"C:\Games");
assert!(serde_json::from_str::<WinPath>(r#""C:\\Games\\..\\x""#).is_err());
assert_eq!(serde_json::to_string(&ok).unwrap(), r#""C:\\Games""#);
}
#[test]
fn game_id_round_trip() {
for s in ["steam:1234560", "epic:exampleracer_main-01", "gog:1207658924", "manual:0123456789abcdef", "domi:lapilli"]
{
let id: GameId = s.parse().unwrap();
assert_eq!(id.to_string(), s);
assert_eq!(id.source().as_str(), s.split(':').next().unwrap());
assert_eq!(id.native(), s.split_once(':').unwrap().1);
}
assert_eq!(GameId::new(Source::Steam, "10").unwrap().as_str(), "steam:10");
assert_eq!("epic:a".parse::<GameId>().unwrap().source(), Source::Epic);
}
#[test]
fn game_id_refuses() {
let long = format!("epic:{}", "a".repeat(limits::MAX_GAME_ID));
for bad in [
"",
"steam",
"steam:",
":10",
"Steam:10",
"steam:0",
"steam:01",
"steam:4294967296",
"steam:-1",
"steam:1a",
"xbox:10",
"epic:A",
"epic:a.b",
"epic:a:b",
"gog:abc",
"gog:123456789012345678901",
"manual:0123",
"manual:0123456789ABCDEF",
"manual:0123456789abcdeg",
"domi:-x",
"domi:a_b",
"domi:../x",
"steam:10 ",
" steam:10",
"steam:10\u{0}",
long.as_str(),
] {
assert_eq!(bad.parse::<GameId>(), Err(ParseError::BadId), "{bad:?}");
}
assert_eq!(GameId::new(Source::Gog, "x"), Err(ParseError::BadId));
}
#[test]
fn game_id_serde_validates() {
let id: GameId = serde_json::from_str(r#""steam:10""#).unwrap();
assert_eq!(serde_json::to_string(&id).unwrap(), r#""steam:10""#);
assert!(serde_json::from_str::<GameId>(r#""steam:../x""#).is_err());
}
#[test]
fn source_names() {
for s in Source::ALL {
assert_eq!(s.as_str().parse::<Source>().unwrap(), s);
assert_eq!(s.to_string(), s.as_str());
}
assert!("Steam".parse::<Source>().is_err());
assert!(Source::Steam.priority() > Source::Epic.priority());
assert!(Source::Epic.priority() > Source::Gog.priority());
assert!(Source::Gog.priority() > Source::Domi.priority());
assert!(Source::Domi.priority() > Source::Manual.priority());
}
+46
View File
@@ -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"));
}
+180
View File
@@ -0,0 +1,180 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Steam: valid fixtures and the hostile ones that are Steam-specific.
use arena_core::{CoverHint, Launch, ParseError, Source, WinPath, steam};
fn lib() -> WinPath {
WinPath::parse(r"D:\SteamLibrary").unwrap()
}
#[test]
fn library_folders_current_layout() {
let dirs = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders.vdf")).unwrap();
let dirs: Vec<&str> = dirs.iter().map(WinPath::as_str).collect();
assert_eq!(dirs, [r"C:\Program Files (x86)\Steam", r"D:\SteamLibrary"]);
}
#[test]
fn library_folders_old_layout() {
let dirs = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_old.vdf")).unwrap();
let dirs: Vec<&str> = dirs.iter().map(WinPath::as_str).collect();
assert_eq!(dirs, [r"D:\SteamLibrary", r"E:\Games\Steam"]);
}
#[test]
fn library_folders_empty_root_is_empty_list() {
assert_eq!(steam::library_folders(b"\"libraryfolders\"\n{\n}\n").unwrap(), Vec::<WinPath>::new());
}
#[test]
fn library_folders_needs_the_root_key() {
assert_eq!(steam::library_folders(b"\"other\" { }"), Err(ParseError::Missing("libraryfolders")));
assert_eq!(steam::library_folders(b"\"libraryfolders\" \"x\""), Err(ParseError::WrongType("libraryfolders")));
}
#[test]
fn library_folders_refuses_path_object() {
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_wrongtype.vdf"));
assert_eq!(r, Err(ParseError::WrongType("path")));
}
#[test]
fn library_folders_refuses_missing_path() {
let r = steam::library_folders(b"\"libraryfolders\" { \"0\" { \"label\" \"\" } }");
assert_eq!(r, Err(ParseError::Missing("path")));
}
#[test]
fn library_folders_refuses_unc() {
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_unc.vdf"));
assert_eq!(r, Err(ParseError::BadPath("path")));
}
#[test]
fn library_folders_refuses_the_same_folder_twice() {
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_dup.vdf"));
assert_eq!(r, Err(ParseError::Duplicate("path")));
}
#[test]
fn library_folders_caps_the_count() {
let mut s = String::from("\"libraryfolders\"\n{\n");
for i in 0..=arena_core::limits::MAX_LIBRARIES {
s.push_str(&format!("\"{i}\" {{ \"path\" \"D:\\\\Lib{i}\" }}\n"));
}
s.push_str("}\n");
assert_eq!(steam::library_folders(s.as_bytes()), Err(ParseError::TooMany("libraries")));
}
#[test]
fn app_manifest_valid() {
let g = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_1234560.acf"), &lib()).unwrap();
assert_eq!(g.id.as_str(), "steam:1234560");
assert_eq!(g.source, Source::Steam);
assert_eq!(g.title, "Example Quest: The \"Quoted\" Edition");
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"D:\SteamLibrary\steamapps\common\Example Quest"));
assert_eq!(g.launch, Launch::SteamRunGameId(1_234_560));
assert_eq!(g.launch.uri().as_deref(), Some("steam://rungameid/1234560"));
assert_eq!(g.cover, Some(CoverHint::SteamLibraryCache { app_id: 1_234_560 }));
}
#[test]
fn app_manifest_redistributable_is_not_a_game() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_228980.acf"), &lib());
assert!(matches!(r, Err(ParseError::NotAGame(_))), "{r:?}");
assert!(steam::is_tool(228_980));
assert!(!steam::is_tool(1_234_560));
}
#[test]
fn app_manifest_refuses_traversal_in_installdir() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_traversal.acf"), &lib());
assert_eq!(r, Err(ParseError::BadPath("installdir")));
}
#[test]
fn app_manifest_refuses_absolute_installdir() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absolute.acf"), &lib());
assert_eq!(r, Err(ParseError::BadPath("installdir")));
}
#[test]
fn app_manifest_refuses_appid_object() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_wrongtype.acf"), &lib());
assert_eq!(r, Err(ParseError::WrongType("appid")));
}
#[test]
fn app_manifest_refuses_duplicate_keys_ignoring_case() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_dupkey.acf"), &lib());
assert_eq!(r, Err(ParseError::Duplicate("key")));
}
#[test]
fn app_manifest_refuses_absurd_appid() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absurd.acf"), &lib());
assert_eq!(r, Err(ParseError::BadId));
}
#[test]
fn app_manifest_refuses_line_break_in_string() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_unterminated.acf"), &lib());
assert!(matches!(r, Err(ParseError::Syntax { .. })), "{r:?}");
}
#[test]
fn app_manifest_appid_rules() {
for bad in ["0", "-1", "+5", "01", " 5", "5 ", "4294967296", "1e3", "0x10", ""] {
let acf = format!("\"AppState\" {{ \"appid\" \"{bad}\" \"name\" \"N\" \"installdir\" \"N\" }}");
assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()), Err(ParseError::BadId), "appid {bad:?}");
}
let acf = "\"AppState\" { \"appid\" \"4294967295\" \"name\" \"N\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()).unwrap().launch, Launch::SteamRunGameId(u32::MAX));
}
#[test]
fn app_manifest_missing_fields() {
let no_name = "\"AppState\" { \"appid\" \"10\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(no_name.as_bytes(), &lib()), Err(ParseError::Missing("name")));
let no_dir = "\"AppState\" { \"appid\" \"10\" \"name\" \"N\" }";
assert_eq!(steam::app_manifest(no_dir.as_bytes(), &lib()), Err(ParseError::Missing("installdir")));
let no_id = "\"AppState\" { \"name\" \"N\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(no_id.as_bytes(), &lib()), Err(ParseError::Missing("appid")));
assert_eq!(steam::app_manifest(b"\"Other\" { }", &lib()), Err(ParseError::Missing("AppState")));
}
#[test]
fn app_manifest_refuses_blank_or_control_title() {
let blank = "\"AppState\" { \"appid\" \"10\" \"name\" \" \" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(blank.as_bytes(), &lib()), Err(ParseError::Missing("name")));
let ctl = "\"AppState\" { \"appid\" \"10\" \"name\" \"a\\tb\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(ctl.as_bytes(), &lib()), Err(ParseError::BadValue("name")));
}
#[test]
fn app_manifest_refuses_device_name_installdir() {
for bad in ["CON", "nul", "COM1", "lpt9.txt", "a/b", r"a\\b", ".", "..", "x:", "dots.", ""] {
let acf = format!("\"AppState\" {{ \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"{bad}\" }}");
assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()), Err(ParseError::BadPath("installdir")), "{bad:?}");
}
}
#[test]
fn manifest_names() {
assert_eq!(steam::app_id_from_manifest_name("appmanifest_1234560.acf"), Some(1_234_560));
for bad in [
"appmanifest_0.acf",
"appmanifest_01.acf",
"appmanifest_.acf",
"appmanifest_12.acf.bak",
"APPMANIFEST_12.ACF",
"appmanifest_99999999999.acf",
"appmanifest_-1.acf",
"libraryfolders.vdf",
"appmanifest_1 2.acf",
] {
assert_eq!(steam::app_id_from_manifest_name(bad), None, "{bad}");
}
}
+113
View File
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! The VDF tokenizer, parser and writer on hand-written input.
use arena_core::ParseError;
use arena_core::vdf::{self, Obj, TokenKind, Value};
#[test]
fn tokens_and_offsets() {
let t = vdf::tokenize(b"\"a\" {\n\t\"b\\\\c\" \"d\\\"e\"\n}").unwrap();
let kinds: Vec<&TokenKind> = t.iter().map(|t| &t.kind).collect();
assert_eq!(
kinds,
[
&TokenKind::Str("a".into()),
&TokenKind::Open,
&TokenKind::Str("b\\c".into()),
&TokenKind::Str("d\"e".into()),
&TokenKind::Close
]
);
let at: Vec<usize> = t.iter().map(|t| t.at).collect();
assert_eq!(at, [0, 4, 7, 14, 21]);
}
#[test]
fn escapes() {
let t = vdf::tokenize(br#""\n\t\r\\\"""#).unwrap();
assert_eq!(t[0].kind, TokenKind::Str("\n\t\r\\\"".into()));
for bad in [&br#""\x""#[..], br#""\0""#, br#""\'""#, br#""\""#, b"\"\\"] {
assert!(matches!(vdf::tokenize(bad), Err(ParseError::Syntax { .. })), "{:?}", String::from_utf8_lossy(bad));
}
}
#[test]
fn comments_and_whitespace() {
let doc = vdf::parse(b"// top\r\n\"a\" // after key\r\n{ \"b\" \"c\" } // end").unwrap();
let Some(Value::Obj(a)) = doc.get("A") else { panic!("{doc:?}") };
assert_eq!(a.get("b"), Some(&Value::Str("c".into())));
}
#[test]
fn refuses_unquoted_and_directives() {
for bad in [
&b"a { }"[..],
b"\"a\" b",
b"#include \"x.vdf\"",
b"#base \"x\"",
b"\"a\" \"b\" [$WIN32]",
b"/ x",
b"\"a\" { \"b\" \"c\" }}",
] {
assert!(matches!(vdf::parse(bad), Err(ParseError::Syntax { .. })), "{:?}", String::from_utf8_lossy(bad));
}
}
#[test]
fn structure_errors() {
assert!(matches!(vdf::parse(b"\"a\""), Err(ParseError::Syntax { .. })));
assert!(matches!(vdf::parse(b"\"a\" {"), Err(ParseError::Syntax { .. })));
assert!(matches!(vdf::parse(b"{ }"), Err(ParseError::Syntax { at: 0 })));
assert!(matches!(vdf::parse(b"\"a\" { { } }"), Err(ParseError::Syntax { .. })));
assert_eq!(vdf::parse(b"\"\" \"v\""), Err(ParseError::Missing("key")));
assert_eq!(vdf::parse(b"\"a\" \"1\" \"A\" \"2\""), Err(ParseError::Duplicate("key")));
assert!(vdf::parse(b"\"a\" { \"k\" \"1\" } \"b\" { \"k\" \"2\" }").is_ok(), "same key on different objects");
assert_eq!(vdf::parse(b"").unwrap(), Obj::new());
assert_eq!(vdf::parse(b" \n// only a comment").unwrap(), Obj::new());
}
#[test]
fn syntax_offset_is_where_the_problem_is() {
assert_eq!(vdf::parse(b"\"a\" \"b\"\n\"c\" x"), Err(ParseError::Syntax { at: 12 }));
assert_eq!(vdf::tokenize(b"\"ab\0\""), Err(ParseError::Syntax { at: 3 }));
}
#[test]
fn bom_only_at_the_start() {
assert!(vdf::parse(b"\xEF\xBB\xBF\"a\" \"b\"").is_ok());
assert!(vdf::parse(b"\"a\" \xEF\xBB\xBF\"b\"").is_err());
}
#[test]
fn obj_insert_rules() {
let mut o = Obj::new();
o.insert("Key".into(), Value::Str("v".into())).unwrap();
assert_eq!(o.insert("KEY".into(), Value::Str("w".into())), Err(ParseError::Duplicate("key")));
assert_eq!(o.insert(String::new(), Value::Str("w".into())), Err(ParseError::Missing("key")));
assert_eq!(o.insert("k".repeat(257), Value::Str("w".into())), Err(ParseError::TooLong("key")));
assert_eq!(o.insert("k2".into(), Value::Str("v".repeat(4097))), Err(ParseError::TooLong("value")));
assert_eq!(o.len(), 1);
assert_eq!(o.iter().next(), Some(("Key", &Value::Str("v".into()))));
}
#[test]
fn write_then_parse() {
let mut inner = Obj::new();
inner.insert("path".into(), Value::Str("C:\\Program Files (x86)\\Steam".into())).unwrap();
inner.insert("quote".into(), Value::Str("say \"hi\"\n\tbye".into())).unwrap();
let mut root = Obj::new();
root.insert("0".into(), Value::Obj(inner)).unwrap();
let mut doc = Obj::new();
doc.insert("libraryfolders".into(), Value::Obj(root)).unwrap();
let text = vdf::write(&doc);
assert!(text.contains(r#""path" "C:\\Program Files (x86)\\Steam""#), "{text}");
assert_eq!(vdf::parse(text.as_bytes()).unwrap(), doc);
}
#[test]
fn fixture_round_trips_through_the_writer() {
let doc = vdf::parse(include_bytes!("fixtures/steam/libraryfolders.vdf")).unwrap();
assert_eq!(vdf::parse(vdf::write(&doc).as_bytes()).unwrap(), doc);
}
+139
View File
@@ -0,0 +1,139 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Built on Domi, https://aula.marek-novak.cz
//! Property tests on the VDF tokenizer and parser: no panics on arbitrary bytes, and generated documents survive
//! a write/parse round trip.
use arena_core::vdf::{self, Obj, TokenKind, Value};
use arena_core::{WinPath, epic, steam};
use proptest::prelude::*;
/// Strings the format can carry: anything printable plus the characters the writer must escape.
fn vdf_string(max: usize) -> impl Strategy<Value = String> {
proptest::collection::vec(
prop_oneof![
8 => proptest::char::range(' ', '~'),
2 => Just('"'),
2 => Just('\\'),
1 => Just('\n'),
1 => Just('\t'),
1 => Just('\r'),
1 => proptest::char::range('\u{a0}', '\u{2fff}'),
1 => proptest::char::range('\u{1f300}', '\u{1f64f}'),
],
0..max,
)
.prop_map(|cs| cs.into_iter().collect())
}
fn key() -> impl Strategy<Value = String> {
vdf_string(12).prop_filter("keys are not empty", |k| !k.is_empty())
}
#[derive(Debug, Clone)]
enum Gen {
Str(String),
Obj(Vec<(String, Gen)>),
}
fn gen_value() -> impl Strategy<Value = Gen> {
let leaf = vdf_string(24).prop_map(Gen::Str);
leaf.prop_recursive(6, 64, 6, |inner| proptest::collection::vec((key(), inner), 0..6).prop_map(Gen::Obj))
}
/// Builds an `Obj`, dropping keys that repeat (ignoring ASCII case) as the format requires.
fn build(pairs: Vec<(String, Gen)>) -> Obj {
let mut o = Obj::new();
for (k, v) in pairs {
let v = match v {
Gen::Str(s) => Value::Str(s),
Gen::Obj(p) => Value::Obj(build(p)),
};
let _ = o.insert(k, v);
}
o
}
fn gen_doc() -> impl Strategy<Value = Obj> {
proptest::collection::vec((key(), gen_value()), 0..6).prop_map(build)
}
fn lib() -> WinPath {
WinPath::parse(r"D:\SteamLibrary").unwrap()
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
#[test]
fn tokenizer_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..2048)) {
let _ = vdf::tokenize(&bytes);
let _ = vdf::parse(&bytes);
let _ = steam::library_folders(&bytes);
let _ = steam::app_manifest(&bytes, &lib());
let _ = epic::item(&bytes);
}
#[test]
fn tokenizer_never_panics_on_vdf_like_bytes(
parts in proptest::collection::vec(
prop_oneof![
Just(&b"\""[..]), Just(&b"{"[..]), Just(&b"}"[..]), Just(&b"\\"[..]), Just(&b"//"[..]),
Just(&b"\n"[..]), Just(&b" "[..]), Just(&b"\\\""[..]), Just(&b"\\n"[..]), Just(&b"\0"[..]),
Just(&b"\xff"[..]), Just(&b"\xc3"[..]), Just(&b"key"[..]), Just(&b"\xEF\xBB\xBF"[..]),
Just(&b"\"AppState\""[..]), Just(&b"\"appid\""[..]), Just(&b"\"10\""[..]),
Just(&b"\"libraryfolders\""[..]), Just(&b"\"path\""[..]), Just(&b"\"C:\\\\G\""[..]),
],
0..200,
)
) {
let bytes: Vec<u8> = parts.concat();
let _ = vdf::tokenize(&bytes);
let _ = vdf::parse(&bytes);
let _ = steam::library_folders(&bytes);
let _ = steam::app_manifest(&bytes, &lib());
}
#[test]
fn tokens_carry_valid_offsets(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
if let Ok(tokens) = vdf::tokenize(&bytes) {
let mut last = None;
for t in &tokens {
prop_assert!(t.at < bytes.len());
prop_assert!(last.is_none_or(|l| l < t.at), "offsets increase");
last = Some(t.at);
let first = bytes[t.at];
match t.kind {
TokenKind::Open => prop_assert_eq!(first, b'{'),
TokenKind::Close => prop_assert_eq!(first, b'}'),
TokenKind::Str(_) => prop_assert_eq!(first, b'"'),
}
}
}
}
#[test]
fn syntax_errors_point_inside_the_input(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
if let Err(arena_core::ParseError::Syntax { at }) = vdf::parse(&bytes) {
prop_assert!(at <= bytes.len());
}
}
#[test]
fn generated_documents_round_trip(doc in gen_doc()) {
let text = vdf::write(&doc);
let back = vdf::parse(text.as_bytes());
prop_assert_eq!(back.as_ref(), Ok(&doc), "{}", text);
// Writing again is byte-identical.
prop_assert_eq!(vdf::write(&back.unwrap()), text);
}
#[test]
fn generated_strings_round_trip_through_tokens(s in vdf_string(200)) {
let mut o = Obj::new();
o.insert("k".into(), Value::Str(s.clone())).unwrap();
let tokens = vdf::tokenize(vdf::write(&o).as_bytes()).unwrap();
let kinds: Vec<TokenKind> = tokens.into_iter().map(|t| t.kind).collect();
prop_assert_eq!(kinds, vec![TokenKind::Str("k".into()), TokenKind::Str(s)]);
}
}
+234
View File
@@ -0,0 +1,234 @@
# Formats: what `arena-core` accepts and refuses
Every launcher file and value is hostile input. Each parser below either returns a fully validated `Game` (or list
of paths) or a typed `ParseError`; it never truncates, guesses or panics. Nothing is read from disk here: the app
reads capped bytes and passes them in.
## Caps (`arena_core::limits`)
| Constant | Value | Applies to | Error when exceeded |
| :-- | :-- | :-- | :-- |
| `MAX_FILE` | 1 MiB (1 048 576 bytes) | whole VDF, ACF or `.item` input | `TooLarge` |
| `MAX_DEPTH` | 32 | nesting of VDF objects; JSON objects and arrays together | `TooDeep` |
| `MAX_KEY` | 256 bytes | a VDF key, after unescaping | `TooLong("key")` |
| `MAX_VALUE` | 4096 bytes | any VDF string, after unescaping | `TooLong("value")` |
| `MAX_ESCAPES` | 256 | escape sequences in one VDF string | `TooMany("escapes")` |
| `MAX_ENTRIES` | 65 536 | key/value pairs in one VDF document, all levels | `TooMany("entries")` |
| `MAX_LIBRARIES` | 64 | Steam library folders | `TooMany("libraries")` |
| `MAX_PATH` | 260 UTF-16 units | every `WinPath` | `BadPath(field)` |
| `MAX_TITLE` | 256 characters | every title, after trimming | `TooLong(field)` |
| `MAX_GAME_ID` | 96 bytes | `GameId` | `BadId` |
| `MAX_EPIC_APP` | 64 bytes | Epic `AppName` | `BadId` |
| `MAX_DOMI_ID` | 32 bytes | Domi / Atrium id | `BadId` |
| `MAX_GOG_ID` | 20 digits | GOG `gameID` | `BadId` |
| `MAX_ARGS_LINE` | 4096 bytes | GOG `launchParam` | `TooLong("launch_params")` |
| `MAX_ARGS` | 32 | arguments of an exe launch | `TooMany("args")` |
| `MAX_ARG` | 1024 bytes | one argument | `TooLong("arg")` |
| `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 on or off, together (`detect::Marks`) | `TooMany("marks")` |
| `MAX_HOTKEY` | 64 bytes | shortcut text for `hotkey::parse` | `HotkeyError::TooLong` |
## Errors
`ParseError` is `#[non_exhaustive]` and implements `Display` and `std::error::Error`. The `&'static str` names
the field; an error never carries input text, so it is always safe to log.
| Variant | Meaning |
| :-- | :-- |
| `TooLarge` | input over `MAX_FILE` |
| `TooDeep` | nesting over `MAX_DEPTH` |
| `NotUtf8` | the input (VDF: as a whole; JSON: as a whole) is not valid UTF-8 |
| `Syntax { at }` | malformed at byte offset `at` of the input (BOM included) |
| `Missing(field)` | a required field is absent (or a title is blank) |
| `WrongType(field)` | an object where a string belongs, a number for a string, a non-object `.item`, ... |
| `BadPath(field)` | not a valid `WinPath`, or a path that leaves where it must stay |
| `BadId` | Steam app id, Epic app name, GOG id, Domi id or `GameId` malformed or out of range |
| `Duplicate(field)` | a key or entry appears twice (`"key"` for VDF keys, the field name for JSON) |
| `TooLong(field)` / `TooMany(field)` | over a cap above |
| `BadValue(field)` | control or bidi-override characters in a title, a bad URL, a bad argument |
| `NotAGame(why)` | a valid file for something that is not a game: callers skip it quietly |
## Shared rules
**Titles** (Steam `name`, Epic `DisplayName`, GOG `gameName`, manual title, Domi name): trimmed; blank is
`Missing`; over 256 characters is `TooLong`; any control character (C0, DEL, C1) or bidi override (U+202A–202E,
U+2066–2069, U+200E, U+200F, U+061C) is `BadValue`.
**`WinPath`**: must start `X:\` or `X:/` with an ASCII drive letter. Refused: UNC (`\\server\share`), `\\?\`,
`\\.\`, `\??\`, drive-relative `C:x`, rooted `\x`, components `.` and `..`, components ending in `.` or space,
control characters, `< > : " | ? *` (a `:` only after the drive letter, so no alternate data streams), device names
as the stem of any component (`CON PRN AUX NUL CONIN$ CONOUT$ COM0-9 COM¹²³ LPT0-9 LPT¹²³`, any case, any
extension, trailing spaces ignored), more than 260 UTF-16 units. Normalised: `/` to `\`, repeated separators
collapsed, drive letter uppercase, trailing separator dropped (`C:\` stays). `join` takes a relative path under the
same rules (so it cannot climb out); `starts_with` compares component-wise ignoring case.
**`GameId`**: `<source>:<native>` with the source one of `steam epic gog manual domi`, at most 96 bytes. Native
part: Steam a canonical non-zero `u32` (no sign, no leading zero); Epic `[a-z0-9_-]{1,64}` (the app name lowercased,
so two Epic apps differing only in case share an id and dedupe); GOG 1–20 digits; Manual exactly 16 lowercase hex
digits (FNV-1a 64 of the exe path, case-folded); Domi the Atrium id rule.
**Atrium id** (Domi ids and `domi-<app>://` links): `[a-z0-9-]{1,32}`, not starting or ending with `-`.
## VDF / KeyValues text (`arena_core::vdf`)
Accepted:
- one optional UTF-8 BOM at the very start;
- whitespace: space, tab, CR, LF;
- `//` comments to the end of the line;
- `{`, `}` and quoted strings `"..."`;
- escapes `\\`, `\"`, `\n`, `\t`, `\r`;
- a raw tab inside a string.
Refused (`Syntax { at }` unless noted):
- input that is not UTF-8 anywhere, comments included (`NotUtf8`);
- NUL anywhere, raw control characters other than tab inside a string, raw CR or LF inside a string;
- any other escape (`\x`, `\0`, `\'`, ...), a backslash at end of input;
- unterminated strings (reported at the opening quote) and unclosed objects (reported at end of input);
- unquoted tokens, `#include`, `#base`, `[$CONDITION]` tags, a single `/`;
- a `{` or `}` where a key belongs, a `}` where a value belongs, a key with no value;
- an empty key (`Missing("key")`), a key repeated in the same object, ignoring ASCII case (`Duplicate("key")`);
- anything over `MAX_FILE`, `MAX_DEPTH`, `MAX_KEY`, `MAX_VALUE`, `MAX_ESCAPES`, `MAX_ENTRIES`.
`vdf::write` emits Valve's layout (tabs, `"key"\t\t"value"`, `{` / `}` on their own lines) and escapes `\`, `"`,
LF and CR. `Obj::insert` applies the same caps and character rules as the parser, so any `Obj` built in code writes
and parses back to itself (property-tested), provided the written text stays under `MAX_FILE`.
## Steam `libraryfolders.vdf` (`steam::library_folders`)
Accepted: a root key `libraryfolders` (any case) holding an object. Under it, every key made only of digits is a
library: either the current layout `"0" { "path" "C:\\..." ... }` or the old one `"1" "D:\\SteamLibrary"`. Other
keys (`contentstatsid`, `TimeNextStatsReport`, ...) and every other field of a library (`label`, `apps`, ...) are
ignored, though they must still parse within the caps.
Refused: no root (`Missing("libraryfolders")`), a string root (`WrongType("libraryfolders")`), a library object
without `path` (`Missing("path")`) or with an object `path` (`WrongType("path")`), a path that is not a `WinPath`
(`BadPath("path")`), the same folder twice ignoring case and trailing separators (`Duplicate("path")`), more than
64 libraries (`TooMany("libraries")`).
## Steam `appmanifest_<id>.acf` (`steam::app_manifest`)
Reads `AppState` → `appid`, `name`, `installdir` (all required strings). Everything else is ignored.
- `appid`: canonical non-zero `u32`; else `BadId` (so `0`, `01`, `+5`, `-1`, ` 5`, `1e3`, `4294967296` and longer
are refused).
- `name`: the title rules.
- `installdir`: one plain folder name (no `\` or `/`, not `.` or `..`, no device name, ...); the install folder is
`<library>\steamapps\common\<installdir>` and must still be a valid `WinPath`; else `BadPath("installdir")`.
- Steam's redistributables and runtimes (`steam::is_tool`: 228980, 1070560, 1391110, 1628350, 1493710, 1826330,
1161040) give `NotAGame`.
Result: `steam:<id>`, launch `steam://rungameid/<id>`, cover `SteamLibraryCache { app_id }`.
`steam::app_id_from_manifest_name` accepts exactly `appmanifest_<canonical id>.acf` (lowercase), for filtering a
folder listing before reading anything.
## Epic `.item` (`epic::item`)
The input must be UTF-8 (one BOM allowed), at most 1 MiB and at most 32 levels of objects and arrays (checked
before parsing; brackets inside strings do not count), a single JSON object with nothing after it.
Reads `AppName`, `DisplayName`, `InstallLocation` (required strings) and `MainGameAppName` (optional string).
Unknown fields are ignored but must be valid JSON. Refused: `null` or any non-string for those fields
(`WrongType(field)`), a missing one (`Missing(field)`), any of them twice (`Duplicate(field)`), a document that is
not an object (`WrongType("item")`), syntax errors including trailing data and out-of-range numbers in read fields
(`Syntax { at }`).
- `AppName`: `[A-Za-z0-9_-]{1,64}`; else `BadId`. It is the only field that reaches the launch URI.
- `DisplayName`: the title rules (error field `DisplayName`).
- `InstallLocation`: a `WinPath`; else `BadPath("InstallLocation")`.
- `MainGameAppName` present and different from `AppName`: an add-on, `NotAGame`.
Result: `epic:<appname lowercased>`, launch `com.epicgames.launcher://apps/<AppName>?action=launch&silent=true`,
a lettered cover. `bIsIncompleteInstall` is not read: the Epic launcher handles a half-installed game itself.
## GOG (`gog::game`)
Values the app reads from the registry (assumption, verify on the PC: `HKLM\SOFTWARE\WOW6432Node\GOG.com\Games\
<gameID>` and the HKCU twin), passed in as `GogEntry`.
- `game_id`: 1–20 ASCII digits; else `BadId`.
- `name`: the title rules (error field `name`).
- `path`: a `WinPath`; else `BadPath("path")`. It becomes the install folder.
- `exe`: absolute, or relative to `path`; must lie strictly inside `path` (component-wise, ignoring case) and end in
`.exe` (ignoring case), so never a `.bat`, `.cmd` or `.lnk`; else `BadPath("exe")`.
- `working_dir`: absent or blank means the exe's folder; otherwise absolute or relative to `path`; else
`BadPath("working_dir")`.
- `launch_params`: at most 4096 bytes (`TooLong("launch_params")`), no control characters (tabs included) and no
unclosed `"` (`BadValue("launch_params")`). Split on spaces; `"` groups and is removed; nothing else (no
backslash escapes, no variables) is special. Then at most 32 arguments of at most 1024 bytes each.
Result: `gog:<gameID>`, `Launch::Exe` (started directly, never through a shell), a lettered cover.
## Manual (`manual::game`)
`exe` must be a `WinPath` ending in `.exe` (ignoring case) with a name before the extension; else `BadPath("exe")`.
The title is the given one, or the file name without `.exe`; title rules with error field `title`. Install and
working folder: the exe's folder; no arguments. Id: `manual:<FNV-1a 64 of the case-folded path, 16 hex>`, so the
same file added twice (any case, `/` or `\`) is the same game.
## Domi (`domi::game`)
`id` and a `DomiLaunch::Link { app }` follow the Atrium id rule; else `BadId`. `name` follows the title rules
(error field `name`). No install folder.
`DomiLaunch::Web { url, allowed_hosts }`: `https://` (scheme any case) + host + optional path, query and fragment.
The host is lowercased and must be a DNS name (labels `[a-z0-9-]{1,63}`, no `-` at either end, no empty label, at
most 253 bytes) equal, ignoring case, to one of `allowed_hosts`; subdomains are not implied. Refused: other schemes,
user info (`@`), ports, IP-literal brackets, spaces, `"`, `\`, `<`, `>`, `^`, `` ` ``, `{`, `|`, `}`, any non-ASCII
byte (percent-encode it), `%` not followed by two hex digits, more than 2048 bytes. Errors: `BadValue("url")` or
`TooLong("url")`.
## Launch strings
`Launch::uri` rebuilds the URI from the variant's fields and re-validates them every time, so a hand-built or
tampered value yields `None`:
| Variant | URI | Field rule |
| :-- | :-- | :-- |
| `SteamRunGameId(id)` | `steam://rungameid/<id>` | `id != 0` |
| `Epic { app_name }` | `com.epicgames.launcher://apps/<app_name>?action=launch&silent=true` | `[A-Za-z0-9_-]{1,64}` |
| `DomiLink { app }` | `domi-<app>://open` | Atrium id |
| `Url(url)` | the URL itself | the URL rules, already normalised; `uri_checked(hosts)` also checks the host |
| `Exe { .. }` | none | `.exe` only; arguments checked as above |
Deserialising a `Launch`, `Game` or `Library` runs the same checks; a stored URL's host cannot be checked without
the allow-list, so launching a stored web game goes through `uri_checked`.
## Dedupe (`merge`)
1. Scans are concatenated in order (at most `MAX_GAMES`); a `GameId` seen before is dropped (first wins).
2. For each install folder (compared ignoring case), only the games of the highest-priority source stay:
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,
whatever the marks; the game if the library owns the exe); `None` when the exe is marked **off** ("This is not a
game"); `Marked` when it is marked **on** ("This is a game"; the game if the library owns 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). 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 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
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+<KEY>`); serde uses that text.
+37
View File
@@ -0,0 +1,37 @@
# Portability
Decision 15: `arena-core` stays pure (no I/O, no OS calls) and builds for Windows, Android and WebAssembly. It
uses only `core`/`alloc`/`std` collections and strings plus `serde` and `serde_json`; no `std::fs`,
`std::process`, `std::net`, `std::env`, `std::time` and no `unsafe`.
## Targets checked
| Target | Why |
| :-- | :-- |
| `x86_64-pc-windows-msvc` | the window app on the PC |
| `wasm32-unknown-unknown` | the PWA companion |
| `aarch64-linux-android` | the Android companion |
## Commands
From the repository root (both targets are installed with `rustup target add wasm32-unknown-unknown
aarch64-linux-android`):
```
cargo check -p arena-core
cargo check -p arena-core --target wasm32-unknown-unknown
cargo check -p arena-core --target aarch64-linux-android
```
`cargo check` needs no Android NDK: the crate has no build script and no C dependency, so nothing links.
## Keeping it pure
A quick audit that no I/O crept in (should print nothing):
```
grep -rnE "std::(fs|process|net|env|time)|SystemTime|Instant|Command" crates/arena-core/src
```
Decision 15 asks CI to run the three `cargo check` lines from `core-v0.1.0` on; this repository has no CI file
yet, so for now they are run by hand before each tag.
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"