feat(input): does a game support controllers - what the store lists, the input libraries it loaded, how it was played (D163) (#469)

* feat(input): the arithmetic of controller statistics - classes, batteries, makers, one pad seen twice (D155-D163)

Nothing reads a device yet. Domain.Input says whether an XInput state or a DualSense report is a pad in use and what
its battery is, adds a battery's readings up, counts switches and decides when two entries are one pad;
Application.Input holds one session's slices and turns them into a reading a second; InputSessionBuilder turns a
session's readings into its totals, its controllers as JSON and its timeline. TelemetrySample can carry a reading.

Every byte and reading under test was written by hand: no report from a real controller has passed through this code.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* feat(input): a session can store what it was played with - schema 0024, the .partial file's chunk 11, both tiers (D160)

Nine columns on sessions (the time in front and its four classes, the switches of method, the sources that answered,
the controllers as JSON) and three on games (what a store lists of controller support), ADD COLUMN only. The .partial
file gains chunk 11, so a session recovered after the Agent died keeps its readings. SessionFinalizer.Build stores
them before the tier branch: hooked, unhooked and recovered sessions alike. The input series are sensor_blobs rows
named input.*, which the sensors' read now leaves out and FindInputSensorsAsync returns.

Nothing produces a reading yet. A ledger this build has opened cannot be opened by 0.1.0-beta.49 or earlier.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* feat(input): the input reader, which the Agent does not start yet - raw input for controllers, XInput, the time of the last input (D155, D158, D159)

Application.Input.InputReader takes a slice about ten times a second from Infrastructure.Input.Win32InputBackend, on
the thread of InputDeviceHub, which exists only while a session has a view of it. It opens no device, sends nothing
to one and registers for no keyboard or mouse. tools/input-readonly-check.ps1 holds its Windows calls to a list.

With no controller at hand, what the reader does with one connected is not established.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(input): an arm of XInputPad.Battery's switch said what the default says (Qodana, on #464 after it merged)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(input): no using that makes the file's own qualified names redundant (InspectCode)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(input): what InspectCode reported in the reader's tests - redundant casts, a hub disposed twice, a suppression not needed

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* wip(input): the Agent records what a session was played with - the switch, the terms, the legal texts

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* style(input): import order in the Agent's composition; no redundant qualifier in a test (InspectCode)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* wip(input): what a store lists of controller support, the input libraries, the game page's three rows

* wip(input): the game page's details tests expect the three controller rows; the library names test without ToLowerInvariant

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* docs(guide): the settings page listed Controllers and input twice

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Fable 5.2 authored and GitHub committed 2026-11-14 22:15:54 +00:00
1 parent a6bebc4adf
commit aa30659313
29 files changed
+1412 -11

No files matched your search

+6
View File
@@ -48,6 +48,12 @@ numeric core and does not move; the heading is the full version — corrected 20
figures come with the same release. Xbox-compatible controllers and the DualSense are read for use; another
controller is listed and never counted as in use. **None of this had been read from a real controller when it was
written** — it was checked against data written by hand (`LIMITATIONS.md` §Controllers and input).
- **A game's page says what is known about controller support — three things, and no verdict** (D163). *Controller
support (store)*: what Steam lists for the game — full, partial, or none — read from the Steam app's own file on
your PC when you open the page; nothing is asked of the store, and a game that is not Steam's reads N/A. *Input
libraries loaded*: which of XInput, DirectInput, Windows.Gaming.Input, GameInput and SDL the game had loaded the
last time it was measured from inside. *Usually played with*: the share of the time in front with a controller,
the keyboard and mouse, both and neither, over the sessions that recorded it. English, Vietnamese, Japanese.
- **The terms are shown once: Privacy Policy 2.22 and Disclaimer 2.18.** Both said FrameLedger never reads input.
They now say what is read — that a controller, or the keyboard or mouse, is in use — what is kept, and what never
is (`docs/legal-drift-history.md`).
+5
View File
@@ -173,6 +173,11 @@ game — so it is there for a game FrameLedger does not measure as well.
cent.
- **Steam Input shows a controller twice** — the one you hold and an Xbox pad Steam presents for it. FrameLedger
folds the two into one when they move together; with another remapper it may list two.
- **"Does this game support controllers?" has no single answer here.** The game's page shows what Steam lists
(read from the Steam app's file on your PC — only Steam games have it, and only on a PC where Steam knows the
game), which input libraries the game loaded the last time it was measured from inside (several engines load one
whether the game uses a controller or not), and how you have actually played it. FrameLedger does not turn them
into a Yes or a No. ([Detection](docs/05_DETECTION.md))
- **Nothing is read until you have accepted the Privacy Policy that describes it.** After an update, sessions
recorded before FrameLedger has been opened once have no such figures, and say so in their notes.
- **None of this had been read from a real controller when 0.1.0-beta.50 was written.** It was checked against data
+42
View File
@@ -471,6 +471,48 @@ names no census lists; which feature each serves is not established.)* The sessi
difference ("the game ships 3.7.10.0: another copy was loaded"); since beta.24 the DLSS line says where each DLSS
library was loaded from (the game, the graphics driver, Windows) — by folder, never who put it there.
## Does a game support controllers — three pieces of evidence, no verdict (0.1.0-beta.50, owner decision D163)
**The owner's request, 2026-11-14:** "check whether the game supports controllers, shown in its details." From
outside a game FrameLedger can know that a controller was in use while the game was in front — not what the game
did with it — and a store's listing is the store's word. So the game's page shows three rows, each with where it
comes from, and FrameLedger adds no Yes or No of its own (`App.Services.ControllerEvidence`):
| Row | What it says | From | When it is N/A |
|---|---|---|---|
| **Controller support (store)** | *Full — as Steam lists it*, *Partial — as Steam lists it*, *Steam lists none* | `games.controller_support` (schema 0024), read from the Steam app's own file on this PC | a game no store file on this PC describes: not a Steam game, or Steam has no record of it here |
| **Input libraries loaded** | each interface with the files seen — `XInput (xinput1_4.dll)`, `SDL (SDL2.dll)` — or *None seen* | the module snapshot of the newest session measured from inside (`sessions.runtime_modules`) | a game never measured from inside: an unhooked session takes no snapshot (`04_CAPTURE`) |
| **Usually played with** | the share of the time in front with a controller, the keyboard and mouse, both, neither, over the sessions that recorded it | `sessions.input_*` (`03_METRICS` §Input) | no session has recorded it |
### What a store lists
**Steam's `appcache\appinfo.vdf`, on the disk** (`Infrastructure.Import.SteamAppInfo`). The Steam client keeps a copy
of the store's application records there; a record's `common` section may hold `controller_support` = `full` or
`partial`, and a record without it lists none. **No request is made to any store** (CLAUDE.md rule 8 — the
setting `privacy.online_metadata` is still read by nothing). Only format 41 is read (magic `0x07564429`, keys as
numbers into a table of strings at the end of the file); another magic is refused with the reason and the row reads
N/A. The layout was checked on the developer's Steam folder on 2026-11-14: 3 581 records, every tree read to its
last byte, 1 284 *full*, 440 *partial*, 1 857 with no such key. No length in the file is trusted — a record or a
string that claims more than the file holds is a problem, and a file that cannot be read whole says nothing.
**Read when a game's page opens** (`App.Services.StoreControllerSupport`, from `GameLibrary.LoadAsync`): the game's
Steam record is found as Play and the artwork find it (`StoreRecords.Owning`), the file is read for that one
application, and the row is written only when the answer differs — `IGameRepository.SetControllerSupportAsync`,
the UI's write, which moves no `updated_at`. **A viewer reads nothing of this PC** (D52) and shows what the copy's
rows hold. GOG, Epic, itch and the Xbox app keep no such fact on the disk that this build knows of: their games read
N/A.
### Input libraries
`Domain.Input.InputLibraries`: `xinput1_4.dll`, `xinput1_3.dll`, `xinput9_1_0.dll`, `xinputuap.dll` (XInput);
`dinput8.dll`, `dinput.dll` (DirectInput); `windows.gaming.input.dll`; `gameinput.dll`; `sdl2.dll`, `sdl3.dll`
(SDL). The Agent's module snapshot looks for them beside the upscaling and frame-generation libraries
(`AgentServices`), so they are in `sessions.runtime_modules` — hooked sessions only, as that snapshot always was.
The session summary's *Libraries* line leaves them out; they are the game page's.
**Loaded is not used.** Several engines load XInput whether the game reads a controller or not, and Steam's own
overlay can bring an input library into a game. That is why this is one of three rows and not an answer.
## DLSS generation — evidence-bound (beta.24, owner decision D64)
**What a session can say about which DLSS ran, and nothing more.** `Domain.Detection.DlssGeneration` names a
+2 -2
View File
@@ -2,7 +2,7 @@
`%LOCALAPPDATA%\FrameLedger\ledger.db`. Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, `busy_timeout=5000`. `Microsoft.Data.Sqlite` + Dapper; all writes in explicit transactions.
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, *(since schema 0023, 2026-11-11)* `machine_profiles` and `session_advanced`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms`, and since schema 0011 (2026-09-25) the executable's own facts `exe_machine` / `exe_file_version` / `exe_product_version` / `library_versions`, written whole like the flags — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. **And since 2026-09-23 the Agent's relocator merges two entries for one executable under two drive letters** (`IGameMerge`, HANDOFF D26, `19_SAFETY` §A moved drive is the same executable): in one transaction it re-parents the dropped entry's `sessions` to the survivor (before the delete — `sessions.game_id` cascades), carries a block or a crash auto-disable still in force to the survivor (`hook_enabled` only ever to 0; `hook_blocked_reason` is copied, never originated or cleared), adds the crash counts, deletes the dropped `games` row, and then moves the survivor to the file's path (after the delete — `exe_path` is UNIQUE). It was the one Agent write that deletes a `games` row until beta.19; it never touches a consent column. **And since beta.19 (2026-10-12, D55) the Agent removes an entry whose game is no longer installed** (`IGamePrune`, `SqliteGamePrune`, asked by the detection sweep through `UninstalledEntryPrune`): one `DELETE` that holds every stored condition in the same statement — the same row at the same path, `removed_at` NULL, no session stored (`NOT EXISTS` on `sessions` — nothing cascades), no `hook_blocked_reason`, `hook_prescan_state` not `blocked`, no `ac_exception_at` and no `ac_exception_trial_failed_at` — behind `retention.remove_uninstalled_games`; a block, a grant and D38's mark are never removed with their entry (`19_SAFETY` §What a finding does to the game, *What clears it*). **And since 2026-09-23 the UI writes `record_sessions`** (schema 0009, FR-1.6): the entry's recording switch, which the Agent only reads — off, the watcher does not watch for the program. The script's one data change switches it off for entries an old import made for Steam's own tools (`SteamLibrarySource.KnownTools`, the ids as of the script); a twin merge keeps it off when either twin had it off. **And since 2026-09-25 the Agent's pre-scan of the library (`19_SAFETY` §What a finding does to the game) writes the hook-state columns of every entry, not only of those the user asked to hook** — `hook_prescan_state`, and on a finding `hook_enabled = 0` and `hook_blocked_reason` — and its own key, `hook_prescan_rules_version` / `hook_prescan_exe_size_bytes` / `hook_prescan_exe_mtime_ms` (schema 0010), through `IGameConsentStore.RecordPreScanAsync` only: columns that were already the Agent's, never over a block, never a new row. **And since 2026-09-26 (schema 0014, D33) the Agent writes the user-mode exception's columns** — `ac_exception_*` on `games` through `IGameConsentStore` only (eligibility from the sweep, a grant from the `SetAntiCheatException` command, every end), and `sessions.ac_exception_family` with the session — the grant only after the user accepted its disclosure in the UI, which asks and never writes. **And since 2026-10-03 (beta.11, D40) the Agent deletes sessions on request** — every session of one game or of every game, `DeleteSessions` over the pipe, through `ISessionRepository.DeleteSessionsAsync` in one transaction (segments, blobs and annotations cascade), never while one is being recorded; the UI asks and never deletes a session row itself *(for Delete all sessions; FR-1.4's removal is the App's own cascade, above — corrected 2026-10-04)*. **Maintenance (P4 PR-7) adds no writer:** the retention sweep on demand is the Agent's, asked over the pipe; the UI's `VACUUM` rewrites pages with the same contents and changes no row (§Retention built note). UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; ~~never a `hook_*` column~~ **and two downgrades** *(corrected 2026-10-04)*: *Change executable* (2026-09-21, `GameLibrary.ChangeExecutableAsync`) turns hooking off, clears the consent and pre-scan columns and ends an excepLine truncated
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, *(since schema 0023, 2026-11-11)* `machine_profiles` and `session_advanced`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms`, and since schema 0011 (2026-09-25) the executable's own facts `exe_machine` / `exe_file_version` / `exe_product_version` / `library_versions`, written whole like the flags — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). **And since 0.1.0-beta.50 (schema 0024, D163) the UI writes `controller_support`, `controller_support_source` and `controller_support_at`** — what the Steam app's own file on this PC lists, read when a game's page opens and written through `IGameRepository.SetControllerSupportAsync` only when it differs; no `updated_at` moves and no other column is touched. **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. **And since 2026-09-23 the Agent's relocator merges two entries for one executable under two drive letters** (`IGameMerge`, HANDOFF D26, `19_SAFETY` §A moved drive is the same executable): in one transaction it re-parents the dropped entry's `sessions` to the survivor (before the delete — `sessions.game_id` cascades), carries a block or a crash auto-disable still in force to the survivor (`hook_enabled` only ever to 0; `hook_blocked_reason` is copied, never originated or cleared), adds the crash counts, deletes the dropped `games` row, and then moves the survivor to the file's path (after the delete — `exe_path` is UNIQUE). It was the one Agent write that deletes a `games` row until beta.19; it never touches a consent column. **And since beta.19 (2026-10-12, D55) the Agent removes an entry whose game is no longer installed** (`IGamePrune`, `SqliteGamePrune`, asked by the detection sweep through `UninstalledEntryPrune`): one `DELETE` that holds every stored condition in the same statement — the same row at the same path, `removed_at` NULL, no session stored (`NOT EXISTS` on `sessions` — nothing cascades), no `hook_blocked_reason`, `hook_prescan_state` not `blocked`, no `ac_exception_at` and no `ac_exception_trial_failed_at` — behind `retention.remove_uninstalled_games`; a block, a grant and D38's mark are never removed with their entry (`19_SAFETY` §What a finding does to the game, *What clears it*). **And since 2026-09-23 the UI writes `record_sessions`** (schema 0009, FR-1.6): the entry's recording switch, which the Agent only reads — off, the watcher does not watch for the program. The script's one data change switches it off for entries an old import made for Steam's own tools (`SteamLibrarySource.KnownTools`, the ids as of the script); a twin merge keeps it off when either twin had it off. **And since 2026-09-25 the Agent's pre-scan of the library (`19_SAFETY` §What a finding does to the game) writes the hook-state columns of every entry, not only of those the user asked to hook** — `hook_prescan_state`, and on a finding `hook_enabled = 0` and `hook_blocked_reason` — and its own key, `hook_prescan_rules_version` / `hook_prescan_exe_size_bytes` / `hook_prescan_exe_mtime_ms` (schema 0010), through `IGameConsentStore.RecordPreScanAsync` only: columns that were already the Agent's, never over a block, never a new row. **And since 2026-09-26 (schema 0014, D33) the Agent writes the user-mode exception's columns** — `ac_exception_*` on `games` through `IGameConsentStore` only (eligibility from the sweep, a grant from the `SetAntiCheatException` command, every end), and `sessions.ac_exception_family` with the session — the grant only after the user accepted its disclosure in the UI, which asks and never writes. **And since 2026-10-03 (beta.11, D40) the Agent deletes sessions on request** — every session of one game or of every game, `DeleteSessions` over the pipe, through `ISessionRepository.DeleteSessionsAsync` in one transaction (segments, blobs and annotations cascade), never while one is being recorded; the UI asks and never deletes a session row itself *(for Delete all sessions; FR-1.4's removal is the App's own cascade, above — corrected 2026-10-04)*. **Maintenance (P4 PR-7) adds no writer:** the retention sweep on demand is the Agent's, asked over the pipe; the UI's `VACUUM` rewrites pages with the same contents and changes no row (§Retention built nLine truncated
## Schema (v2 — hook architecture)
@@ -857,7 +857,7 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
> (D156); on a game no store file describes. The series are `sensor_blobs` rows named `input.*` (§Blob encoding).
> `LatestVersion` is 24; `LedgerDatabaseTests.ScriptTwentyFourAddsTheInputColumnsAndAnEarlierSessionAndGameHaveNone`,
> the repository round trip. **Nothing produces a reading yet, and nothing writes the three `games` columns yet**:
> the reader, the switch and the store file are the pull requests after this one.
> the reader, the switch and the store file are the pull requests after this one *(all three are there since the pull requests that followed: `21_INPUT_DEVICES`, `05_DETECTION` §Does a game support controllers)*.
> **A beta.49 cannot open a ledger a later build migrated.**
> **`0022_dlss_nr.sql` (beta.34, 2026-11-06, owner decision D84) — DLSS 5's neural rendering, measured.** One REAL column,
+3 -2
View File
@@ -9,8 +9,9 @@ The numbers a session makes of it are in [`03_METRICS.md`](03_METRICS.md) §Inpu
> (`FrameLedger.Domain.Input`, `FrameLedger.Application.Input`, `Application.Recording.InputSessionBuilder`), the
> storage (schema 0024, the `.partial` file's chunk 11 — `06_DATA_MODEL`), the reader (`Application.Input.InputReader`,
> `Infrastructure.Input`) and its composition into the Agent (`capture.input_devices`, `Application.Input.InputTerms`)
> are written and under test. The screens, the store's word and the input libraries come in the pull requests after
> this one, and this note is rewritten by each. **No report from a real controller has passed through any of this code**
> are written and under test; and a game's page shows the three pieces of evidence for "supports controllers"
> (`05_DETECTION` §Does a game support controllers). The session's own screens come in the next pull request, and
> this note is rewritten by it. **No report from a real controller has passed through any of this code**
> (owner decision D157): the developer has no controller, and what happens on a real one is owner-only item 48.
## The owner's request and decisions (2026-11-14)
+3 -1
View File
@@ -74,7 +74,9 @@ stores of controllers and input and what it never does — which button, stick,
position, a serial number, a Bluetooth address; to §3A that these numbers, unlike Advanced metrics', **are** in an
export and in a bug report (D160); to §4 what is observed — the controllers' reports, looked at and not kept,
XInput's state and battery, the time of the last keyboard or mouse input, the window in front — and that nothing is
opened or sent; and narrows the sentence after it to what is still true. It also says, in §1 and §4, that nothing
opened or sent — and that the Steam app's own file of store records is read, on the disk, when a game's page is
opened, for whether the game is listed with controller support; and narrows the sentence after it to what is still
true. It also says, in §1 and §4, that nothing
of this is read until that version has been accepted on the PC (D156): the option is on unless switched off, and an
Agent that started before the App showed the document records without it. The **Disclaimer** (2.18) gains a
paragraph in §1 for what is read from outside the game about controllers, the keyboard and the mouse, and its "what
-1
View File
@@ -23,7 +23,6 @@ The link under them, *Read what the hook does and does not do*, opens the safety
| **Sensor interval (ms)** | How often the PC's sensors are read during a session. 500 to 2000 ms. With a value above 1000, not every reading of NVIDIA's latency report — made about once a second inside the game — becomes a point: each point is still one reading ([Advanced metrics](12-advanced-metrics.md)). *Agent.* | 1000 |
| **Raw series kept per game** | How many of each game's newest sessions keep their per-frame data; older ones keep their statistics. 0 keeps everything. *Agent.* | 20 |
| **Controllers and input** | Records what a session was played with: which game controllers were connected and in use, their battery level, and whether the keyboard or mouse was in use — as times, read from Windows and never from the game. No button, stick, key or text is kept, and nothing is sent to a controller. Nothing is read until you have accepted the Privacy Policy that describes it, so after an update the first sessions have no such figures until FrameLedger has been opened once. Off: nothing of this is read or stored. It applies from the next session; a session recorded while it was off is not filled in later. *Agent.* | On |
| **Controllers and input** | Records what a session was played with: which game controllers were connected and in use, their battery level, and whether the keyboard or mouse was in use — as times, read from Windows and never from the game. No button, stick, key or text is kept, and nothing is sent to a controller. Nothing is read until you have accepted the Privacy Policy that describes it, so after an update the first sessions have no such figures until FrameLedger has been opened once. Off: nothing of this is read or stored. It applies from the next session; a session recorded while it was off is not filled in later. *Agent.* | On |
| **Advanced metrics** | Reads more from the graphics driver and the hardware sensors during a session — the graphics card's memory and load in detail, each fan and voltage, what your display can do, the driver's settings for the game — and stores it with the session. In a game FrameLedger measures from inside it also reads what the game tells DLSS, Streamline and FSR, and — on an NVIDIA card, in a Direct3D 12 game that uses NVIDIA's library — asks the graphics driver about once a second how long each stage of a frame took ([Advanced metrics](12-advanced-metrics.md)). Off: nothing more is read or stored. It applies from the next session; a session recorded while it was off is not filled in later. While it is on, the **Advanced** page is in the list on the left ([Advanced metrics](12-advanced-metrics.md)). *Agent.* | Off |
## Data
+1 -1
View File
@@ -44,7 +44,7 @@ An exported session (CSV or JSON) and a bug report can contain your games' names
## 4. What the app can technically observe
To do its job, FrameLedger observes: which of *your tracked* executables — the entries in your library whose recording is on — are running, and their process trees; whether a game you enabled hooking for runs in an app container, and which of Windows' code-protection settings it runs under (for example, accepting only Microsoft-signed code), read from Windows before any injection; the parameters your games pass to the graphics APIs it intercepts (presentation, upscaling, ray tracing, pipeline creation) — and, only while Advanced metrics is on, more of the parameters of the upscaling calls, and the parameters of ten further calls it begins to intercept in a game only once a session with that option on has started there (the constants the game gives NVIDIA Streamline for each frame, the game's configuration of FSR frame generation, Streamline's answers to the game's four questions about a feature — which version it is, what it requires, whether it is supported and whether it is loaded — and the game switching a feature on or off, allocating and freeing its resources, and shutting Streamline down), which are then stored with the session (sizes, presets, exposure, sharpening, the jitter's size, the motion-vector scale, the depth range, the range of the field of view, flags, the reported frame time, the upscaler's own memory, how frame generation is configured, the versions and requirements of Streamline's features, whether each is supported and loaded, and how often the game switched it, allocated and freed its resources and shut Streamline down), never the camera's position, direction or matrices, and never what identifies the graphics card; and — only while Advanced metrics is on, only in a Direct3D 12 game that had itself loaded NVIDIA's driver library — the graphics driver's own report of the game's last frames and its low-latency state, which the component asks that driver for itself about once a second (it makes that call; the game does not), keeping only how long each stage took; the memory use of a tracked game's process — its dedicated and shared video memory, from Windows' GPU performance counters, and its working sets and commit, from Windows' process-memory information, for which a game it does not inject into is opened with the least access Windows offers and closed again (never its memory's content); loaded module names of a game being captured, the version information of its upscaling, frame-generation and neural-rendering libraries, and whether each was loaded from the game's folder or from the graphics driver's own copy (for detection and for the anti-cheat safety check); the names of the files in each library game's install folder, the version information of its executable and of the upscaling and neural-rendering libraries it ships, the content of its executable file (the markers of the engine and of the graphics libraries it carries, the libraries it imports, and the engine build name an Unreal Engine game carries), the version marks an engine keeps in its own files (Unity's player library and the header of its data file, the header of a Godot data pack, an RPG Maker game's title, core script and Game.ini, the library Game.ini names, and the version file of a Ren'Py game's engine), and the store files that name it (Steam's and GOG's, on your disk) and, for a game the Xbox app or the Microsoft Store installed, the package files in its install folder that describe it (`MicrosoftGame.config` and `appxmanifest.xml`) — to detect its engine, its engine version and its features and to check it for anti-cheat before any injection is possible; the lists of installed games that the Steam, GOG GALAXY, Epic Games and itch apps keep on your disk, and where GOG GALAXY is installed, the folders the Xbox app installs games into on each drive (named by the `.GamingRoot` file at the drive's root) with each game's package files, and Windows' answer to whether that game's package is installed for you — read when you import your library and when you press Play, to find the store that installed a game and hand the game to that store's app — Steam's and GOG GALAXY's also when you open a game's page, to find the artwork their apps keep for it; the cover and banner images that the Steam and GOG GALAXY apps keep on your disk for a game in your library and the logo and splash-screen images a game from the Xbox app ships in its own folder — read to show them on its page, never copied or sent anywhere; the size, position and state of a tracked game's window and the monitor it is on, read from Windows and not from the game, and — for a game FrameLedger injects into — whether the game asked for exclusive full-screen; the NVIDIA driver's settings for your tracked executables (read only: the DLSS and frame-generation overrides the NVIDIA App set); hardware sensor values from your graphics driver's own libraries; and — only while Advanced metrics is on — that driver's description of the graphLine truncated
To do its job, FrameLedger observes: which of *your tracked* executables — the entries in your library whose recording is on — are running, and their process trees; whether a game you enabled hooking for runs in an app container, and which of Windows' code-protection settings it runs under (for example, accepting only Microsoft-signed code), read from Windows before any injection; the parameters your games pass to the graphics APIs it intercepts (presentation, upscaling, ray tracing, pipeline creation) — and, only while Advanced metrics is on, more of the parameters of the upscaling calls, and the parameters of ten further calls it begins to intercept in a game only once a session with that option on has started there (the constants the game gives NVIDIA Streamline for each frame, the game's configuration of FSR frame generation, Streamline's answers to the game's four questions about a feature — which version it is, what it requires, whether it is supported and whether it is loaded — and the game switching a feature on or off, allocating and freeing its resources, and shutting Streamline down), which are then stored with the session (sizes, presets, exposure, sharpening, the jitter's size, the motion-vector scale, the depth range, the range of the field of view, flags, the reported frame time, the upscaler's own memory, how frame generation is configured, the versions and requirements of Streamline's features, whether each is supported and loaded, and how often the game switched it, allocated and freed its resources and shut Streamline down), never the camera's position, direction or matrices, and never what identifies the graphics card; and — only while Advanced metrics is on, only in a Direct3D 12 game that had itself loaded NVIDIA's driver library — the graphics driver's own report of the game's last frames and its low-latency state, which the component asks that driver for itself about once a second (it makes that call; the game does not), keeping only how long each stage took; the memory use of a tracked game's process — its dedicated and shared video memory, from Windows' GPU performance counters, and its working sets and commit, from Windows' process-memory information, for which a game it does not inject into is opened with the least access Windows offers and closed again (never its memory's content); loaded module names of a game being captured, the version information of its upscaling, frame-generation and neural-rendering libraries, and whether each was loaded from the game's folder or from the graphics driver's own copy (for detection and for the anti-cheat safety check); the names of the files in each library game's install folder, the version information of its executable and of the upscaling and neural-rendering libraries it ships, the content of its executable file (the markers of the engine and of the graphics libraries it carries, the libraries it imports, and the engine build name an Unreal Engine game carries), the version marks an engine keeps in its own files (Unity's player library and the header of its data file, the header of a Godot data pack, an RPG Maker game's title, core script and Game.ini, the library Game.ini names, and the version file of a Ren'Py game's engine), and the store files that name it (Steam's and GOG's, on your disk) and, for a game the Xbox app or the Microsoft Store installed, the package files in its install folder that describe it (`MicrosoftGame.config` and `appxmanifest.xml`) — to detect its engine, its engine version and its features and to check it for anti-cheat before any injection is possible; the lists of installed games that the Steam, GOG GALAXY, Epic Games and itch apps keep on your disk, and where GOG GALAXY is installed, the folders the Xbox app installs games into on each drive (named by the `.GamingRoot` file at the drive's root) with each game's package files, and Windows' answer to whether that game's package is installed for you — read when you import your library and when you press Play, to find the store that installed a game and hand the game to that store's app — Steam's and GOG GALAXY's also when you open a game's page, to find the artwork their apps keep for it; the cover and banner images that the Steam and GOG GALAXY apps keep on your disk for a game in your library and the logo and splash-screen images a game from the Xbox app ships in its own folder — read to show them on its page, never copied or sent anywhere; the size, position and state of a tracked game's window and the monitor it is on, read from Windows and not from the game, and — for a game FrameLedger injects into — whether the game asked for exclusive full-screen; the NVIDIA driver's settings for your tracked executables (read only: the DLSS and frame-generation overrides the NVIDIA App set); hardware sensor values from your graphics driver's own libraries; and — only while Advanced metrics is on — that driver's description of the graphLine truncated
It does **not** read game memory outside those API parameters, and does not read game saves, chat, what you type or which buttons you press — only that a controller, or the keyboard or mouse, was in use (§1) — network traffic, or anything unrelated to performance measurement. It records only for programs you added to your library and did not switch recording off for — a program whose recording is off is not watched at all — and injects only into games you individually enabled.
@@ -97,7 +97,9 @@ internal static class AgentServices
sp.GetRequiredService<LatestProcessSnapshot>()));
services.AddSingleton<ITargetLivenessSource, HeldProcessLivenessSource>();
services.AddSingleton<IRingAttacher>(static _ => new ShmRingAttacher(NativeAntiCheatGuard.BuildId()));
services.AddSingleton<IRuntimeModuleSnapshot>(static _ => new RuntimeModuleSnapshot(CensusNames.ModuleFileNames));
// The input libraries ride the same snapshot (D163): which of them a hooked game had loaded is one of the three
// pieces of evidence for "supports controllers". The App leaves them out of the Libraries line.
services.AddSingleton<IRuntimeModuleSnapshot>(static _ => new RuntimeModuleSnapshot([.. CensusNames.ModuleFileNames, .. Domain.Input.InputLibraries.FileNames]));
AddNvidia(services);
AddRecording(services, paths);
+5
View File
@@ -512,6 +512,11 @@ public partial class App : System.Windows.Application
services.AddSingleton<Application.Art.IStoreArtCache>(static _ => new GogArtCache());
services.AddSingleton<Application.Art.IStoreArtCache>(static _ => new XboxArtCache());
services.AddSingleton(static sp => new StoreRecordsReader(sp.GetServices<IStoreLibrarySource>()));
// D163: what the Steam app's own file on this PC lists of controller support, read when a game's page opens.
services.AddSingleton(static sp => new StoreControllerSupport(
sp.GetRequiredService<StoreRecordsReader>(),
sp.GetRequiredService<IGameRepository>(),
sp.GetRequiredService<UiMode>()));
services.AddSingleton(static sp => new GameArt(
sp.GetRequiredService<RegisteredSettings>(),
sp.GetRequiredService<StoreRecordsReader>(),
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Globalization;
using System.Text.Json;
using FrameLedger.Application.Persistence;
using FrameLedger.Domain.Input;
using FrameLedger.Domain.Sessions;
namespace FrameLedger.App.Services;
/// <summary>
/// "Does this game support controllers?" as the game's page answers it (owner decision D163): three pieces of
/// evidence, each with where it comes from, and no verdict. What the store's own file lists; which input libraries the
/// game had loaded when it was last measured from inside; how it has actually been played. From outside a game one
/// can know a controller was in use while the game was in front - not what the game did with it - so none of the
/// three is turned into a Yes or a No of FrameLedger's.
/// </summary>
public static class ControllerEvidence
{
/// <summary>What the store lists: Steam's word, or that no store file on this PC describes the game.</summary>
public static string StoreText(GameRow game)
{
ArgumentNullException.ThrowIfNull(game);
return game.ControllerSupport switch
{
"full" => Strings.GameDetail_Controller_Store_Full,
"partial" => Strings.GameDetail_Controller_Store_Partial,
"none" => Strings.GameDetail_Controller_Store_None,
_ => Strings.GameDetail_Controller_Store_Unknown,
};
}
/// <summary>
/// The input libraries the game had loaded in its newest session measured from inside that looked for them, each
/// interface with its files; that none was seen; or that no such session exists - a session that was not hooked
/// takes no module snapshot, and one recorded before 0.1.0-beta.50 did not look for these.
/// </summary>
public static string LibrariesText(IReadOnlyList<SessionRow> sessions)
{
ArgumentNullException.ThrowIfNull(sessions);
foreach (SessionRow session in sessions)
{
if (session.Tier != CaptureTier.Hooked || Modules(session.RuntimeModulesJson) is not { } modules)
{
continue;
}
// Whether the session looked cannot be read from one that found none of them: a session recorded before the
// names were added has none either. The newest hooked session with modules is the one asked.
string[] found = [.. modules.Keys
.Where(static m => InputLibraries.Is(m))
.GroupBy(static m => InputLibraries.ApiOf(m)!, StringComparer.Ordinal)
.OrderBy(static g => g.Key, StringComparer.Ordinal)
.Select(static g => g.Key + " (" + string.Join(", ", g.OrderBy(static f => f, StringComparer.OrdinalIgnoreCase)) + ")")];
return found.Length > 0 ? string.Join(Environment.NewLine, found) : Strings.GameDetail_Controller_Libraries_NoneSeen;
}
return Strings.GameDetail_Controller_Libraries_Unknown;
}
/// <summary>How the game has been played, over every session that recorded it: each class's share of the time in front, and how many sessions that is.</summary>
public static string PlayedWithText(IReadOnlyList<SessionRow> sessions)
{
ArgumentNullException.ThrowIfNull(sessions);
SessionRow[] recorded = [.. sessions.Where(static s => s.InputForegroundMs is > 0)];
long front = recorded.Sum(static s => s.InputForegroundMs ?? 0);
if (front <= 0)
{
return Strings.GameDetail_Controller_Played_Unknown;
}
return string.Format(
CultureInfo.CurrentCulture,
recorded.Length == 1 ? Strings.GameDetail_Controller_Played_One_Format : Strings.GameDetail_Controller_Played_Many_Format,
Formats.Share(100d * recorded.Sum(static s => s.InputControllerMs ?? 0) / front),
Formats.Share(100d * recorded.Sum(static s => s.InputKeyboardMouseMs ?? 0) / front),
Formats.Share(100d * recorded.Sum(static s => s.InputBothMs ?? 0) / front),
Formats.Share(100d * recorded.Sum(static s => s.InputIdleMs ?? 0) / front),
recorded.Length);
}
/// <summary>Whether a module is one of the input libraries - the session's Libraries line leaves those to this page.</summary>
public static bool IsInputLibrary(string moduleFileName) => InputLibraries.Is(moduleFileName);
private static Dictionary<string, string?>? Modules(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
return JsonSerializer.Deserialize(json, AppJsonContext.Default.DictionaryStringString) is { Count: > 0 } modules
? modules.ToDictionary(static m => m.Key, static m => (string?)m.Value, StringComparer.OrdinalIgnoreCase)
: null;
}
catch (JsonException)
{
return null;
}
}
}
+10 -1
View File
@@ -21,9 +21,12 @@ public sealed class GameLibrary
private readonly ISessionRepository _sessions;
private readonly ISessionAnnotationRepository _annotations;
private readonly TimeProvider _clock;
private readonly StoreControllerSupport? _controllers;
public GameLibrary(IGameRepository games, ISessionRepository sessions, ISessionAnnotationRepository annotations, TimeProvider? clock = null)
public GameLibrary(IGameRepository games, ISessionRepository sessions, ISessionAnnotationRepository annotations, TimeProvider? clock = null,
StoreControllerSupport? controllers = null)
{
_controllers = controllers;
_games = games ?? throw new ArgumentNullException(nameof(games));
_sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
_annotations = annotations ?? throw new ArgumentNullException(nameof(annotations));
@@ -47,6 +50,12 @@ public sealed class GameLibrary
return null;
}
// D163: what the store's own file on this PC lists of controller support, read as the page opens.
if (_controllers is not null)
{
row = await _controllers.RefreshAsync(row, ct).ConfigureAwait(false);
}
IReadOnlyList<SessionRow> sessions = await _sessions.ListByGameAsync(gameId, sessionLimit, ct).ConfigureAwait(false);
IReadOnlyList<SessionAnnotation> annotations = await _annotations.ListByGameAsync(gameId, ct).ConfigureAwait(false);
return new GameDetail(row, sessions, annotations.ToDictionary(static a => a.SessionId));
@@ -0,0 +1,96 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Globalization;
using FrameLedger.Application.Import;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Play;
using FrameLedger.Infrastructure.Import;
using Serilog;
namespace FrameLedger.App.Services;
/// <summary>
/// What the store that installed a game lists of controller support (owner decision D163): read from the Steam app's
/// own file on this PC when a game's page is opened, and written to the game's row when it differs. No request is
/// made to any store (CLAUDE.md rule 8) - a game no store file on this PC describes keeps what it had, which for most
/// is nothing.
/// </summary>
/// <remarks>
/// <para>
/// It is the store's word and one of three pieces of evidence the page shows; it is never FrameLedger's verdict.
/// </para>
/// <para>
/// <b>A viewer reads nothing of this PC</b> (D52): the copy it shows came from another PC, whose stores are not here.
/// It shows what the copy's rows hold.
/// </para>
/// </remarks>
public sealed class StoreControllerSupport
{
private const string _steam = "steam";
private readonly StoreRecordsReader _stores;
private readonly IGameRepository _games;
private readonly UiMode _mode;
private readonly Func<string?> _appInfoFile;
private readonly TimeProvider _clock;
/// <summary>A reader over the stores' records and the Steam app's own file.</summary>
/// <param name="stores">The stores' records of what they installed.</param>
/// <param name="games">Where the fact is written.</param>
/// <param name="mode">A viewer reads nothing of this PC.</param>
/// <param name="appInfoFile">Where Steam's file is; null is where the Steam app on this PC keeps it.</param>
/// <param name="clock">When the fact was read.</param>
public StoreControllerSupport(StoreRecordsReader stores, IGameRepository games, UiMode mode, Func<string?>? appInfoFile = null, TimeProvider? clock = null)
{
_stores = stores ?? throw new ArgumentNullException(nameof(stores));
_games = games ?? throw new ArgumentNullException(nameof(games));
_mode = mode ?? throw new ArgumentNullException(nameof(mode));
_appInfoFile = appInfoFile ?? SteamAppInfo.InstalledFile;
_clock = clock ?? TimeProvider.System;
}
/// <summary>The game's row with the store's word as it stands now: the row given when nothing could be read or nothing changed.</summary>
public async Task<GameRow> RefreshAsync(GameRow game, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(game);
if (_mode.IsViewer)
{
return game;
}
try
{
IReadOnlyList<StoreGame> records = await _stores.ReadAsync("controller support", [_steam], ct).ConfigureAwait(false);
if (StoreRecords.Owning(game.Fingerprint.ExePath, game.StoreId, records) is not { Platform: _steam } record
|| !uint.TryParse(record.StoreId, NumberStyles.None, CultureInfo.InvariantCulture, out uint appId)
|| _appInfoFile() is not { } file)
{
return game;
}
SteamAppInfoResult read = await Task.Run(() => SteamAppInfo.ReadControllerSupport(file, [appId]), ct).ConfigureAwait(false);
if (read.Problem is { } problem)
{
Log.Information("controller support: Steam's file was not read ({Problem})", problem);
return game;
}
if (!read.Support.TryGetValue(appId, out string? support) || string.Equals(support, game.ControllerSupport, StringComparison.Ordinal))
{
return game;
}
DateTimeOffset now = _clock.GetUtcNow();
return await _games.SetControllerSupportAsync(game.Id, support, SteamAppInfo.Source, now, ct).ConfigureAwait(false)
? game with { ControllerSupport = support, ControllerSupportSource = SteamAppInfo.Source, ControllerSupportAt = now }
: game;
}
catch (Exception e) when (e is not OperationCanceledException and not OutOfMemoryException)
{
// The page opens without it: a store's file is never a reason for a game's page to fail.
Log.Warning("controller support: {Message}", e.Message);
return game;
}
}
}
+36
View File
@@ -851,6 +851,18 @@ public static class Strings
nameof(GameDetail_AntiCheat_Header),
nameof(GameDetail_Back),
nameof(GameDetail_ChangeExe),
nameof(GameDetail_Controller_Libraries_Label),
nameof(GameDetail_Controller_Libraries_NoneSeen),
nameof(GameDetail_Controller_Libraries_Unknown),
nameof(GameDetail_Controller_Played_Label),
nameof(GameDetail_Controller_Played_Many_Format),
nameof(GameDetail_Controller_Played_One_Format),
nameof(GameDetail_Controller_Played_Unknown),
nameof(GameDetail_Controller_Store_Full),
nameof(GameDetail_Controller_Store_Label),
nameof(GameDetail_Controller_Store_None),
nameof(GameDetail_Controller_Store_Partial),
nameof(GameDetail_Controller_Store_Unknown),
nameof(GameDetail_DeleteSessions),
nameof(GameDetail_Details_Architecture),
nameof(GameDetail_Details_Engine),
@@ -3208,6 +3220,30 @@ public static class Strings
public static string GameDetail_ChangeExe => ResourceManager.GetString(nameof(GameDetail_ChangeExe), Culture) ?? nameof(GameDetail_ChangeExe);
public static string GameDetail_Controller_Libraries_Label => ResourceManager.GetString(nameof(GameDetail_Controller_Libraries_Label), Culture) ?? nameof(GameDetail_Controller_Libraries_Label);
public static string GameDetail_Controller_Libraries_NoneSeen => ResourceManager.GetString(nameof(GameDetail_Controller_Libraries_NoneSeen), Culture) ?? nameof(GameDetail_Controller_Libraries_NoneSeen);
public static string GameDetail_Controller_Libraries_Unknown => ResourceManager.GetString(nameof(GameDetail_Controller_Libraries_Unknown), Culture) ?? nameof(GameDetail_Controller_Libraries_Unknown);
public static string GameDetail_Controller_Played_Label => ResourceManager.GetString(nameof(GameDetail_Controller_Played_Label), Culture) ?? nameof(GameDetail_Controller_Played_Label);
public static string GameDetail_Controller_Played_Many_Format => ResourceManager.GetString(nameof(GameDetail_Controller_Played_Many_Format), Culture) ?? nameof(GameDetail_Controller_Played_Many_Format);
public static string GameDetail_Controller_Played_One_Format => ResourceManager.GetString(nameof(GameDetail_Controller_Played_One_Format), Culture) ?? nameof(GameDetail_Controller_Played_One_Format);
public static string GameDetail_Controller_Played_Unknown => ResourceManager.GetString(nameof(GameDetail_Controller_Played_Unknown), Culture) ?? nameof(GameDetail_Controller_Played_Unknown);
public static string GameDetail_Controller_Store_Full => ResourceManager.GetString(nameof(GameDetail_Controller_Store_Full), Culture) ?? nameof(GameDetail_Controller_Store_Full);
public static string GameDetail_Controller_Store_Label => ResourceManager.GetString(nameof(GameDetail_Controller_Store_Label), Culture) ?? nameof(GameDetail_Controller_Store_Label);
public static string GameDetail_Controller_Store_None => ResourceManager.GetString(nameof(GameDetail_Controller_Store_None), Culture) ?? nameof(GameDetail_Controller_Store_None);
public static string GameDetail_Controller_Store_Partial => ResourceManager.GetString(nameof(GameDetail_Controller_Store_Partial), Culture) ?? nameof(GameDetail_Controller_Store_Partial);
public static string GameDetail_Controller_Store_Unknown => ResourceManager.GetString(nameof(GameDetail_Controller_Store_Unknown), Culture) ?? nameof(GameDetail_Controller_Store_Unknown);
public static string GameDetail_DeleteSessions => ResourceManager.GetString(nameof(GameDetail_DeleteSessions), Culture) ?? nameof(GameDetail_DeleteSessions);
public static string GameDetail_Details_Architecture => ResourceManager.GetString(nameof(GameDetail_Details_Architecture), Culture) ?? nameof(GameDetail_Details_Architecture);
+48
View File
@@ -4485,6 +4485,54 @@
<value>NVIDIA App の上書き</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Libraries_Label" xml:space="preserve">
<value>読み込まれた入力ライブラリ</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Libraries_NoneSeen" xml:space="preserve">
<value>内部から計測した直近のセッションでは見つかりませんでした</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Libraries_Unknown" xml:space="preserve">
<value>N/A - ゲーム内部から計測したセッションでのみ分かります</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Played_Label" xml:space="preserve">
<value>ふだんのプレイ方法</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Played_Many_Format" xml:space="preserve">
<value>コントローラー {0} · キーボードとマウス {1} · 両方 {2} · 入力なし {3} - ゲームが前面にあった時間に対する割合、{4} セッション</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Played_One_Format" xml:space="preserve">
<value>コントローラー {0} · キーボードとマウス {1} · 両方 {2} · 入力なし {3} - ゲームが前面にあった時間に対する割合、{4} セッション</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Played_Unknown" xml:space="preserve">
<value>N/A - まだ記録したセッションがありません</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Store_Full" xml:space="preserve">
<value>フル対応 - Steam の記載</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Store_Label" xml:space="preserve">
<value>コントローラー対応 (ストア)</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Store_None" xml:space="preserve">
<value>Steam に対応の記載なし</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Store_Partial" xml:space="preserve">
<value>一部対応 - Steam の記載</value>
<comment>review</comment>
</data>
<data name="GameDetail_Controller_Store_Unknown" xml:space="preserve">
<value>N/A - この PC にはこのゲームを記載したストアのファイルがありません</value>
<comment>review</comment>
</data>
<data name="End_Running" xml:space="preserve">
<value>キャプチャは時間指定で、ゲームの実行中に終了しました。</value>
<comment>review</comment>
+36
View File
@@ -3374,6 +3374,42 @@ The documents below are the full terms; this summary does not replace them.</val
<data name="GameDetail_Details_NvidiaOverride" xml:space="preserve">
<value>NVIDIA App override</value>
</data>
<data name="GameDetail_Controller_Libraries_Label" xml:space="preserve">
<value>Input libraries loaded</value>
</data>
<data name="GameDetail_Controller_Libraries_NoneSeen" xml:space="preserve">
<value>None seen in the last session measured from inside</value>
</data>
<data name="GameDetail_Controller_Libraries_Unknown" xml:space="preserve">
<value>N/A - known only from a session measured from inside the game</value>
</data>
<data name="GameDetail_Controller_Played_Label" xml:space="preserve">
<value>Usually played with</value>
</data>
<data name="GameDetail_Controller_Played_Many_Format" xml:space="preserve">
<value>Controller {0} · keyboard and mouse {1} · both {2} · no input {3} - of the time in front, over {4} sessions</value>
</data>
<data name="GameDetail_Controller_Played_One_Format" xml:space="preserve">
<value>Controller {0} · keyboard and mouse {1} · both {2} · no input {3} - of the time in front, over {4} session</value>
</data>
<data name="GameDetail_Controller_Played_Unknown" xml:space="preserve">
<value>N/A - no session has recorded it yet</value>
</data>
<data name="GameDetail_Controller_Store_Full" xml:space="preserve">
<value>Full - as Steam lists it</value>
</data>
<data name="GameDetail_Controller_Store_Label" xml:space="preserve">
<value>Controller support (store)</value>
</data>
<data name="GameDetail_Controller_Store_None" xml:space="preserve">
<value>Steam lists none</value>
</data>
<data name="GameDetail_Controller_Store_Partial" xml:space="preserve">
<value>Partial - as Steam lists it</value>
</data>
<data name="GameDetail_Controller_Store_Unknown" xml:space="preserve">
<value>N/A - no store file on this PC describes this game</value>
</data>
<data name="End_Running" xml:space="preserve">
<value>The capture was bounded and ended while the game still ran.</value>
</data>
+36
View File
@@ -3369,6 +3369,42 @@ Các văn bản bên dưới là điều khoản đầy đủ; bản tóm tắt
<data name="GameDetail_Details_NvidiaOverride" xml:space="preserve">
<value>Ghi đè của NVIDIA App</value>
</data>
<data name="GameDetail_Controller_Libraries_Label" xml:space="preserve">
<value>Thư viện nhập đã nạp</value>
</data>
<data name="GameDetail_Controller_Libraries_NoneSeen" xml:space="preserve">
<value>Không thấy thư viện nào trong phiên gần nhất được đo từ bên trong</value>
</data>
<data name="GameDetail_Controller_Libraries_Unknown" xml:space="preserve">
<value>N/A - chỉ biết được từ một phiên được đo từ bên trong game</value>
</data>
<data name="GameDetail_Controller_Played_Label" xml:space="preserve">
<value>Thường chơi bằng</value>
</data>
<data name="GameDetail_Controller_Played_Many_Format" xml:space="preserve">
<value>Tay cầm {0} · bàn phím và chuột {1} · cả hai {2} · không thao tác {3} - trên thời gian game ở phía trước, qua {4} phiên</value>
</data>
<data name="GameDetail_Controller_Played_One_Format" xml:space="preserve">
<value>Tay cầm {0} · bàn phím và chuột {1} · cả hai {2} · không thao tác {3} - trên thời gian game ở phía trước, qua {4} phiên</value>
</data>
<data name="GameDetail_Controller_Played_Unknown" xml:space="preserve">
<value>N/A - chưa có phiên nào ghi lại</value>
</data>
<data name="GameDetail_Controller_Store_Full" xml:space="preserve">
<value>Đầy đủ - theo Steam ghi</value>
</data>
<data name="GameDetail_Controller_Store_Label" xml:space="preserve">
<value>Hỗ trợ tay cầm (cửa hàng)</value>
</data>
<data name="GameDetail_Controller_Store_None" xml:space="preserve">
<value>Steam không ghi hỗ trợ</value>
</data>
<data name="GameDetail_Controller_Store_Partial" xml:space="preserve">
<value>Một phần - theo Steam ghi</value>
</data>
<data name="GameDetail_Controller_Store_Unknown" xml:space="preserve">
<value>N/A - không có file cửa hàng nào trên máy này mô tả game này</value>
</data>
<data name="End_Running" xml:space="preserve">
<value>Phiên ghi có giới hạn thời gian và đã kết thúc khi game vẫn đang chạy.</value>
</data>
@@ -1278,6 +1278,12 @@ public sealed partial class GameDetailViewModel : ObservableObject
{
Details.Add(new GameDetailRow(Strings.GameDetail_Details_NvidiaOverride, NvidiaOverrides.OverridesText(profile)));
}
// 0.1.0-beta.50 (D163): "does it support controllers?" as three pieces of evidence, each with its source, and no
// verdict - what the store's own file lists, which input libraries the game loaded, how it has been played.
Details.Add(new GameDetailRow(Strings.GameDetail_Controller_Store_Label, ControllerEvidence.StoreText(row)));
Details.Add(new GameDetailRow(Strings.GameDetail_Controller_Libraries_Label, ControllerEvidence.LibrariesText(detail.Sessions)));
Details.Add(new GameDetailRow(Strings.GameDetail_Controller_Played_Label, ControllerEvidence.PlayedWithText(detail.Sessions)));
}
private void AddDetail(string label, string? value)
@@ -615,6 +615,9 @@ public sealed partial class SessionSummaryViewModel : ObservableObject
return null;
}
// The input libraries ride the same snapshot since 0.1.0-beta.50 (D163) and are the game page's to show, as
// evidence of controller support: this line stays the upscaling and frame-generation libraries'.
modules = modules?.Where(static m => !ControllerEvidence.IsInputLibrary(m.Key)).ToDictionary(static m => m.Key, static m => m.Value, StringComparer.OrdinalIgnoreCase);
if (modules is null || modules.Count == 0)
{
return null;
@@ -87,4 +87,12 @@ public interface IGameRepository
/// does not exist.
/// </summary>
ValueTask<bool> ApplyStoreMetadataAsync(long gameId, StoreMetadata store, CancellationToken ct = default);
/// <summary>
/// What the store's own file on the disk says of controller support (schema 0024, owner decision D163):
/// <c>full</c>, <c>partial</c> or <c>none</c>, the file it was read from and when. The UI's write - it reads the
/// store's file when a game's page is opened; never a hook column, and never a verdict of FrameLedger's. False when
/// no row has that id.
/// </summary>
ValueTask<bool> SetControllerSupportAsync(long gameId, string support, string source, DateTimeOffset at, CancellationToken ct = default);
}
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// The libraries through which a Windows game reads controllers, by file name (owner decision D163,
/// <c>05_DETECTION</c> §Input libraries): the second of the three pieces of evidence for "supports controllers". A
/// hooked session's module snapshot notes which of them the game had loaded.
/// </summary>
/// <remarks>
/// <b>Loaded is not used.</b> Several engines load XInput whether the game reads a pad or not, so a library here says
/// how a game COULD read a controller - which is why it is shown as evidence, beside what the store lists and how the
/// game was played, and never as a verdict.
/// </remarks>
public static class InputLibraries
{
private static readonly (string File, string Api)[] _known =
[
("xinput1_4.dll", "XInput"),
("xinput1_3.dll", "XInput"),
("xinput9_1_0.dll", "XInput"),
("xinputuap.dll", "XInput"),
("dinput8.dll", "DirectInput"),
("dinput.dll", "DirectInput"),
("windows.gaming.input.dll", "Windows.Gaming.Input"),
("gameinput.dll", "GameInput"),
("sdl2.dll", "SDL"),
("sdl3.dll", "SDL"),
];
/// <summary>The file names a module snapshot looks for, lower case.</summary>
public static IReadOnlyList<string> FileNames { get; } = [.. _known.Select(static k => k.File)];
/// <summary>The interface a file is - <c>XInput</c>, <c>DirectInput</c>, <c>Windows.Gaming.Input</c>, <c>GameInput</c>, <c>SDL</c> - or null when it is not an input library.</summary>
public static string? ApiOf(string? fileName)
{
foreach ((string file, string api) in _known)
{
if (string.Equals(file, fileName, StringComparison.OrdinalIgnoreCase))
{
return api;
}
}
return null;
}
/// <summary>Whether a file is an input library.</summary>
public static bool Is(string? fileName) => ApiOf(fileName) is not null;
}
@@ -0,0 +1,292 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Buffers.Binary;
using System.Text;
namespace FrameLedger.Infrastructure.Import;
/// <summary>
/// What the Steam app's own file on this PC says of controller support for a game (owner decision D163,
/// <c>05_DETECTION</c> §What a store lists): <c>appcache\appinfo.vdf</c>, the copy of the store's application records
/// the Steam client keeps on the disk. <b>A local file: no request is made to any store</b> (CLAUDE.md rule 8).
/// </summary>
/// <remarks>
/// <para>
/// <b>One fact is read.</b> Each record's <c>common</c> section may hold <c>controller_support</c> = <c>full</c> or
/// <c>partial</c>; a record without it lists none. Nothing else of a record is kept, and nothing is written.
/// </para>
/// <para>
/// <b>The format, version 41</b> (magic <c>0x07564429</c>) - the one the Steam client has written since mid-2024, and
/// the only one read; another magic is refused with the reason, and the fact then reads N/A. A header: the magic, a
/// universe, and the offset of a table of strings. Then one record per application until an id of zero: the id, the
/// size of what follows, sixty bytes of state and hashes, and a tree in Valve's binary key-value form whose keys are
/// numbers into that table. The layout was checked on the developer's own Steam folder on 2026-11-14 (3 581 records,
/// every tree read to its last byte); the tests' files are written by hand to the same layout.
/// </para>
/// <para>
/// <b>It trusts no length in the file.</b> A record or a string that claims more than the file holds ends the read
/// with a reason; what was found before it is not returned either - a file that cannot be read whole says nothing.
/// </para>
/// </remarks>
public static class SteamAppInfo
{
/// <summary><c>games.controller_support_source</c> for a fact read here.</summary>
public const string Source = "steam-appinfo";
public const string Full = "full";
public const string Partial = "partial";
/// <summary>The store's record is there and lists no controller support.</summary>
public const string None = "none";
private const uint _magic41 = 0x07564429;
private const int _headerBytes = 16;
private const int _recordStateBytes = 60;
private const int _maxDepth = 32;
private const byte _map = 0x00;
private const byte _string = 0x01;
private const byte _wideString = 0x05;
private const byte _end = 0x08;
private const byte _endAlternate = 0x0B;
/// <summary>Where the Steam app on this PC keeps the file, or null when Steam is not installed for this user.</summary>
public static string? InstalledFile() => SteamLibrarySource.InstalledRoot() is { } root ? Path.Combine(root, "appcache", "appinfo.vdf") : null;
/// <summary>Reads the file at <paramref name="path"/>; a file that is not there, cannot be opened or cannot be read is a result with a <see cref="SteamAppInfoResult.Problem"/>.</summary>
public static SteamAppInfoResult ReadControllerSupport(string path, IReadOnlyCollection<uint> appIds)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
ArgumentNullException.ThrowIfNull(appIds);
byte[] file;
try
{
// Steam rewrites the file while it runs: shared with every other reader and writer, and never locked.
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
if (stream.Length is 0 or > int.MaxValue)
{
return SteamAppInfoResult.Failed("the file is empty or too large");
}
file = new byte[stream.Length];
stream.ReadExactly(file);
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
return SteamAppInfoResult.Failed(e.GetType().Name);
}
return ReadControllerSupport(file, appIds);
}
/// <summary>
/// For each of <paramref name="appIds"/> that has a record in <paramref name="file"/>: <see cref="Full"/>,
/// <see cref="Partial"/> or <see cref="None"/>. An id with no record is not in the answer: the store's file does
/// not describe it.
/// </summary>
public static SteamAppInfoResult ReadControllerSupport(ReadOnlySpan<byte> file, IReadOnlyCollection<uint> appIds)
{
ArgumentNullException.ThrowIfNull(appIds);
if (file.Length < _headerBytes)
{
return SteamAppInfoResult.Failed("shorter than a header");
}
uint magic = BinaryPrimitives.ReadUInt32LittleEndian(file);
if (magic != _magic41)
{
return SteamAppInfoResult.Failed($"format 0x{magic:X8} is not the one this build reads (0x{_magic41:X8})");
}
long tableAt = BinaryPrimitives.ReadInt64LittleEndian(file[8..]);
if (tableAt < _headerBytes || tableAt > file.Length - 4 || !TryFindKeys(file[(int)tableAt..], out int common, out int support))
{
return SteamAppInfoResult.Failed("the table of strings cannot be read");
}
var found = new Dictionary<uint, string>();
return ReadRecords(file[..(int)tableAt], [.. appIds], common, support, found) is { } problem
? SteamAppInfoResult.Failed(problem)
: new SteamAppInfoResult(found, Problem: null);
}
/// <summary>Walks the records, which end where the table of strings begins; returns what is wrong with them, or null.</summary>
private static string? ReadRecords(ReadOnlySpan<byte> records, HashSet<uint> wanted, int common, int support, Dictionary<uint, string> found)
{
int tableAt = records.Length;
int at = _headerBytes;
while (true)
{
if (at > tableAt - 4)
{
return "a record runs into the table of strings";
}
uint appId = BinaryPrimitives.ReadUInt32LittleEndian(records[at..]);
if (appId == 0)
{
return null;
}
if (at > tableAt - 8)
{
return "a record has no size";
}
uint size = BinaryPrimitives.ReadUInt32LittleEndian(records[(at + 4)..]);
if (size < _recordStateBytes || size > tableAt - at - 8)
{
return "a record claims more than the file holds";
}
if (wanted.Contains(appId))
{
ReadOnlySpan<byte> tree = records.Slice(at + 8 + _recordStateBytes, (int)size - _recordStateBytes);
if (!TryReadSupport(tree, common, support, out string? value))
{
return "a record's tree cannot be read";
}
found[appId] = string.Equals(value, Full, StringComparison.OrdinalIgnoreCase) ? Full
: string.Equals(value, Partial, StringComparison.OrdinalIgnoreCase) ? Partial
: None;
}
at += 8 + (int)size;
}
}
/// <summary>The numbers of the two keys in the table: <c>u32 count</c>, then that many strings, each ended by a zero.</summary>
private static bool TryFindKeys(ReadOnlySpan<byte> table, out int common, out int support)
{
common = -1;
support = -1;
uint count = BinaryPrimitives.ReadUInt32LittleEndian(table);
ReadOnlySpan<byte> rest = table[4..];
for (int i = 0; i < count; i++)
{
int end = rest.IndexOf((byte)0);
if (end < 0)
{
return false;
}
ReadOnlySpan<byte> name = rest[..end];
if (name.SequenceEqual("common"u8))
{
common = i;
}
else if (name.SequenceEqual("controller_support"u8))
{
support = i;
}
rest = rest[(end + 1)..];
}
// A table without one of the two is a file in which no record can say anything of controllers: still a file read.
return true;
}
/// <summary>The value of <c>&lt;root&gt;/common/controller_support</c>; false when the tree is not well formed.</summary>
private static bool TryReadSupport(ReadOnlySpan<byte> tree, int common, int support, out string? value)
{
value = null;
int at = 0;
return TryWalk(tree, ref at, depth: 0, inCommon: false, common, support, ref value);
}
private static bool TryWalk(ReadOnlySpan<byte> tree, ref int at, int depth, bool inCommon, int common, int support, ref string? value)
{
if (depth > _maxDepth)
{
return false;
}
while (true)
{
if (at >= tree.Length)
{
// The root has no end mark of its own when the record's size ends it; a nested map must have one.
return depth == 0;
}
byte kind = tree[at++];
if (kind is _end or _endAlternate)
{
return true;
}
if (tree.Length - at < 4)
{
return false;
}
int key = BinaryPrimitives.ReadInt32LittleEndian(tree[at..]);
at += 4;
if (kind == _map)
{
// depth 0 is the root's own map ("appinfo"); its child "common" is at depth 1.
if (!TryWalk(tree, ref at, depth + 1, inCommon: depth == 1 && key == common, common, support, ref value))
{
return false;
}
continue;
}
int start = at;
if (!TrySkipValue(tree, ref at, kind))
{
return false;
}
if (kind == _string && inCommon && key == support)
{
value = Encoding.UTF8.GetString(tree[start..(at - 1)]).Trim();
}
}
}
private static bool TrySkipValue(ReadOnlySpan<byte> tree, ref int at, byte kind)
{
switch (kind)
{
case _string:
int end = tree[at..].IndexOf((byte)0);
if (end < 0)
{
return false;
}
at += end + 1;
return true;
case _wideString:
while (true)
{
if (tree.Length - at < 2)
{
return false;
}
bool last = tree[at] == 0 && tree[at + 1] == 0;
at += 2;
if (last)
{
return true;
}
}
case 0x02 or 0x03 or 0x04 or 0x06:
at += 4;
return at <= tree.Length;
case 0x07 or 0x0A:
at += 8;
return at <= tree.Length;
default:
return false;
}
}
}
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Infrastructure.Import;
/// <summary>What <see cref="SteamAppInfo"/> read.</summary>
/// <param name="Support">For each application asked about that has a record: <c>full</c>, <c>partial</c> or <c>none</c>. An id that is not here has no record in the file.</param>
/// <param name="Problem">Why the file could not be read, in a few words; null when it was. With a problem, <paramref name="Support"/> is empty.</param>
public sealed record SteamAppInfoResult(IReadOnlyDictionary<uint, string> Support, string? Problem)
{
public static SteamAppInfoResult Failed(string problem) => new(new Dictionary<uint, string>(), problem);
}
@@ -36,6 +36,11 @@ public sealed class SqliteGameRepository : IGameRepository
+ "ac_exception_lapsed_at, ac_exception_lapsed_reason, engine_version_source, ac_exception_trial_failed_at, "
+ "controller_support, controller_support_source, controller_support_at";
// Schema 0024 (D163): the store's word, read from its file on the disk. updated_at is not moved: nothing the user
// or the detection did changed.
private const string _setControllerSupport =
"UPDATE games SET controller_support = @support, controller_support_source = @source, controller_support_at = @at WHERE id = @id";
private const string _selectByPath = $"SELECT {_columns} FROM games WHERE exe_path = @path";
private const string _selectById = $"SELECT {_columns} FROM games WHERE id = @id";
@@ -234,6 +239,14 @@ public sealed class SqliteGameRepository : IGameRepository
_db.WriteAsync(async (c, tx, token) => await c.ExecuteAsync(new CommandDefinition(
_setRecording, new { id = gameId, record = record ? 1 : 0, now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }, tx, cancellationToken: token)).ConfigureAwait(false) == 1, ct);
public ValueTask<bool> SetControllerSupportAsync(long gameId, string support, string source, DateTimeOffset at, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(support);
ArgumentException.ThrowIfNullOrWhiteSpace(source);
return _db.WriteAsync(async (c, tx, token) => await c.ExecuteAsync(new CommandDefinition(
_setControllerSupport, new { id = gameId, support, source, at = at.ToUnixTimeMilliseconds() }, tx, cancellationToken: token)).ConfigureAwait(false) == 1, ct);
}
public ValueTask<bool> RemoveAsync(long gameId, bool keepSessions, CancellationToken ct = default) =>
_db.WriteAsync(async (c, tx, token) =>
{
@@ -0,0 +1,255 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Buffers.Binary;
using System.Globalization;
using System.IO;
using System.Text;
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Import;
using FrameLedger.Application.Persistence;
using FrameLedger.Domain.Sessions;
using FrameLedger.Infrastructure.Import;
namespace FrameLedger.App.Tests;
/// <summary>
/// "Does this game support controllers?" on the game's page (owner decision D163): three pieces of evidence, each with
/// where it comes from, and never a verdict - what the store's own file lists, which input libraries the game had
/// loaded, how it has been played. And where the store's word comes from: the Steam app's file on this PC, read when
/// the page opens, never in a viewer, never over the network.
/// </summary>
[Collection(StringsCultureCollection.Name)]
public sealed class ControllerEvidenceTests
{
private static readonly DateTimeOffset _t0 = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static SessionRow Session(long front = 0, long controller = 0, long keyboardMouse = 0, long both = 0, long idle = 0, bool hooked = true, string? modules = null) => new()
{
SessionGuid = Guid.NewGuid(),
GameId = 1,
SnapshotId = 1,
QpcEpoch = 0,
QpcFrequency = 10_000_000,
Mode = CaptureMode.Attach,
ExitStatus = ExitStatus.Normal,
StartedAt = _t0,
EndedAt = _t0.AddMinutes(10),
Tier = hooked ? CaptureTier.Hooked : CaptureTier.NotHooked,
RuntimeModulesJson = modules,
InputForegroundMs = front == 0 ? null : front,
InputControllerMs = front == 0 ? null : controller,
InputKeyboardMouseMs = front == 0 ? null : keyboardMouse,
InputBothMs = front == 0 ? null : both,
InputIdleMs = front == 0 ? null : idle,
};
private static GameRow Game(string? support) => new()
{
Id = 1,
Name = "A Game",
Fingerprint = new() { ExePath = @"C:\Games\A\a.exe", SizeBytes = 1, MtimeUnixMs = 1 },
HookEnabled = false,
HookCrashCount = 0,
AddedAt = _t0,
UpdatedAt = _t0,
ControllerSupport = support,
};
[Theory]
[InlineData("full", "Full - as Steam lists it")]
[InlineData("partial", "Partial - as Steam lists it")]
[InlineData("none", "Steam lists none")]
[InlineData(null, "N/A - no store file on this PC describes this game")]
[InlineData("a word a later release wrote", "N/A - no store file on this PC describes this game")]
public void TheStoresWordIsShownAsTheStoresAndItsAbsenceAsNotKnown(string? stored, string shown)
{
using var culture = new CultureScope("en");
ControllerEvidence.StoreText(Game(stored)).Should().Be(shown);
}
[Fact]
public void TheInputLibrariesAreThoseOfTheNewestSessionMeasuredFromInside()
{
using var culture = new CultureScope("en");
SessionRow[] sessions =
[
Session(hooked: false),
Session(modules: """{"nvngx_dlss.dll":"3.7.10.0","XINPUT1_4.dll":"10.0.26100.1","xinput9_1_0.dll":null,"SDL2.dll":"2.30.0.0"}"""),
Session(modules: """{"dinput8.dll":"10.0"}"""),
];
ControllerEvidence.LibrariesText(sessions).Should().Be("SDL (SDL2.dll)" + Environment.NewLine + "XInput (XINPUT1_4.dll, xinput9_1_0.dll)");
}
[Fact]
public void ASessionThatLoadedNoneSaysSoAndAGameNeverMeasuredFromInsideIsNotKnown()
{
using var culture = new CultureScope("en");
ControllerEvidence.LibrariesText([Session(modules: """{"nvngx_dlss.dll":"3.7.10.0"}""")]).Should().Be("None seen in the last session measured from inside");
ControllerEvidence.LibrariesText([Session(hooked: false, modules: """{"xinput1_4.dll":"1"}"""), Session(modules: null), Session(modules: "{ not json")])
.Should().Be("N/A - known only from a session measured from inside the game", "a session that was not hooked takes no snapshot, and one with none stored says nothing");
ControllerEvidence.LibrariesText([]).Should().Be("N/A - known only from a session measured from inside the game");
}
[Fact]
public void HowAGameWasPlayedIsTheSharesOfTheTimeInFrontOverEverySessionThatRecordedIt()
{
using var culture = new CultureScope("en");
SessionRow[] sessions =
[
Session(front: 600_000, controller: 500_000, keyboardMouse: 40_000, both: 10_000, idle: 50_000),
Session(),
Session(front: 400_000, controller: 330_000, keyboardMouse: 20_000, both: 0, idle: 50_000, hooked: false),
];
ControllerEvidence.PlayedWithText(sessions).Should().Be("Controller 83.0% · keyboard and mouse 6.0% · both 1.0% · no input 10.0% - of the time in front, over 2 sessions");
ControllerEvidence.PlayedWithText([sessions[0]]).Should().EndWith("over 1 session");
ControllerEvidence.PlayedWithText([Session(), Session(hooked: false)]).Should().Be("N/A - no session has recorded it yet");
ControllerEvidence.PlayedWithText([]).Should().Be("N/A - no session has recorded it yet");
}
/// <summary>The input libraries ride the session's module snapshot and are this page's to show: the summary's Libraries line stays what it was.</summary>
[Fact]
public void TheSessionsLibrariesLineLeavesTheInputLibrariesOut()
{
using var culture = new CultureScope("en");
SessionSummaryViewModel.LoadedLibraries("""{"nvngx_dlss.dll":"3.7.10.0","xinput1_4.dll":"10.0","SDL3.dll":"3.2"}""", [])
.Should().Contain("nvngx_dlss.dll").And.NotContain("xinput").And.NotContain("SDL3");
SessionSummaryViewModel.LoadedLibraries("""{"xinput1_4.dll":"10.0"}""", []).Should().BeNull("a session that loaded only input libraries has no Libraries line");
}
/// <summary>A file in Steam's format 41 with one record, for application 730, that lists <paramref name="support"/>.</summary>
private static string AppInfoFile(string directory, string? support)
{
string[] keys = ["appinfo", "common", "controller_support"];
byte[] Key(string name) => BitConverter.GetBytes(Array.IndexOf(keys, name));
byte[] value = support is null ? [] : [0x01, .. Key("controller_support"), .. Encoding.UTF8.GetBytes(support), 0];
byte[] tree = [0x00, .. Key("appinfo"), 0x00, .. Key("common"), .. value, 0x08, 0x08, 0x08];
byte[] records = [.. BitConverter.GetBytes(0x07564429u), .. BitConverter.GetBytes(1u), .. new byte[8],
.. BitConverter.GetBytes(730u), .. BitConverter.GetBytes((uint)(60 + tree.Length)), .. new byte[60], .. tree, .. BitConverter.GetBytes(0u)];
BinaryPrimitives.WriteInt64LittleEndian(records.AsSpan(8), records.Length);
string path = Path.Combine(directory, "appinfo.vdf");
File.WriteAllBytes(path, [.. records, .. BitConverter.GetBytes((uint)keys.Length), .. keys.SelectMany(static k => Encoding.UTF8.GetBytes(k).Append((byte)0))]);
return path;
}
private static StoreControllerSupport Reader(ScratchLedger s, string? file, bool viewer = false, params StoreGame[] installed) => new(
new StoreRecordsReader([new TestImages.Store("steam", [.. installed.Where(static g => string.Equals(g.Platform, "steam", StringComparison.Ordinal))]),
new TestImages.Store("gog", [.. installed.Where(static g => string.Equals(g.Platform, "gog", StringComparison.Ordinal))])]),
s.Games,
viewer ? new UiMode(IsViewer: true, Path.GetTempPath()) : UiMode.Profile,
() => file,
new FixedClock(_t0));
[Fact]
public async Task OpeningASteamGamesPageReadsWhatSteamsFileListsAndStoresIt()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
string folder = Directory.CreateTempSubdirectory("fl-steam-").FullName;
try
{
GameRow game = await s.GameAsync("Counter", Path.Combine(folder, "common", "Counter", "game.exe"));
var steam = new StoreGame("steam", "730", "Counter", Path.Combine(folder, "common", "Counter"), ExePath: null, Version: null);
StoreControllerSupport reader = Reader(s, AppInfoFile(folder, "partial"), viewer: false, steam);
GameRow read = await reader.RefreshAsync(game, Ct);
read.ControllerSupport.Should().Be("partial");
read.ControllerSupportSource.Should().Be(SteamAppInfo.Source);
read.ControllerSupportAt.Should().Be(_t0);
GameRow stored = (await s.Games.FindByIdAsync(game.Id, Ct))!;
stored.ControllerSupport.Should().Be("partial");
stored.ControllerSupportAt.Should().Be(_t0);
stored.UpdatedAt.Should().Be(game.UpdatedAt, "nothing the user or the detection did changed");
// Steam's record changes: the page follows it. The same answer again writes nothing.
GameRow again = await Reader(s, AppInfoFile(folder, null), viewer: false, steam).RefreshAsync(stored, Ct);
again.ControllerSupport.Should().Be("none", "Steam knows the game and lists no support");
(await Reader(s, AppInfoFile(folder, null), viewer: false, steam).RefreshAsync(again, Ct)).Should().BeSameAs(again);
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
[Fact]
public async Task AGameNoSteamRecordOwnsAViewerAndAFileThatCannotBeReadLeaveTheRowAsItWas()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
string folder = Directory.CreateTempSubdirectory("fl-steam-").FullName;
try
{
string file = AppInfoFile(folder, "full");
GameRow game = await s.GameAsync("Counter", Path.Combine(folder, "common", "Counter", "game.exe"));
var steam = new StoreGame("steam", "730", "Counter", Path.Combine(folder, "common", "Counter"), ExePath: null, Version: null);
var gog = new StoreGame("gog", "730", "Counter", Path.Combine(folder, "common", "Counter"), ExePath: null, Version: null);
var other = new StoreGame("steam", "999", "Other", Path.Combine(folder, "common", "Counter"), ExePath: null, Version: null);
var named = new StoreGame("steam", "not-a-number", "Counter", Path.Combine(folder, "common", "Counter"), ExePath: null, Version: null);
(await Reader(s, file).RefreshAsync(game, Ct)).Should().BeSameAs(game, "no store installed it");
(await Reader(s, file, viewer: false, gog).RefreshAsync(game, Ct)).Should().BeSameAs(game, "another store's game: Steam's file is not asked about it");
(await Reader(s, file, viewer: false, other).RefreshAsync(game, Ct)).Should().BeSameAs(game, "Steam's file has no record of that application");
(await Reader(s, file, viewer: false, named).RefreshAsync(game, Ct)).Should().BeSameAs(game);
(await Reader(s, file, viewer: true, steam).RefreshAsync(game, Ct)).Should().BeSameAs(game, "a viewer reads nothing of this PC (D52)");
(await Reader(s, file: null, viewer: false, steam).RefreshAsync(game, Ct)).Should().BeSameAs(game, "Steam is not installed");
(await Reader(s, Path.Combine(folder, "absent.vdf"), viewer: false, steam).RefreshAsync(game, Ct)).Should().BeSameAs(game, "a file that cannot be read says nothing");
(await s.Games.FindByIdAsync(game.Id, Ct))!.ControllerSupport.Should().BeNull();
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
[Fact]
public async Task TheGamesPageLoadsWithTheStoresWordAndWithoutAReaderAsBefore()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
string folder = Directory.CreateTempSubdirectory("fl-steam-").FullName;
try
{
GameRow game = await s.GameAsync("Counter", Path.Combine(folder, "common", "Counter", "game.exe"));
var steam = new StoreGame("steam", "730", "Counter", Path.Combine(folder, "common", "Counter"), ExePath: null, Version: null);
var library = new GameLibrary(s.Games, s.Sessions, s.Annotations, clock: null, Reader(s, AppInfoFile(folder, "full"), viewer: false, steam));
(await library.LoadAsync(game.Id, ct: Ct))!.Row.ControllerSupport.Should().Be("full");
(await s.Library.LoadAsync(game.Id, ct: Ct))!.Row.ControllerSupport.Should().Be("full", "it was stored, and a library with no reader shows what the row holds");
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
private sealed class FixedClock(DateTimeOffset now) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => now;
}
/// <summary>The strings' language and the numbers' culture, for the length of one test.</summary>
private sealed class CultureScope : IDisposable
{
private readonly CultureInfo? _strings = Strings.Culture;
private readonly CultureInfo _numbers = CultureInfo.CurrentCulture;
public CultureScope(string culture)
{
Strings.Culture = CultureInfo.GetCultureInfo(culture);
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
}
public void Dispose()
{
Strings.Culture = _strings;
CultureInfo.CurrentCulture = _numbers;
}
}
}
@@ -787,7 +787,12 @@ public sealed class GameDetailViewModelTests
new GameDetailRow("Product version", "1.0.2"),
new GameDetailRow("Store", "Steam build 20374416"),
new GameDetailRow("Engine", "Unreal Engine 5.3"),
new GameDetailRow("Ships with", "DLSS: nvngx_dlss.dll 3.7.10.0" + Environment.NewLine + "XeSS: libxess.dll (no version)"));
new GameDetailRow("Ships with", "DLSS: nvngx_dlss.dll 3.7.10.0" + Environment.NewLine + "XeSS: libxess.dll (no version)"),
// 0.1.0-beta.50 (D163): the three pieces of evidence for "supports controllers" are always there, each
// saying what it knows - here, nothing yet.
new GameDetailRow("Controller support (store)", "N/A - no store file on this PC describes this game"),
new GameDetailRow("Input libraries loaded", "N/A - known only from a session measured from inside the game"),
new GameDetailRow("Usually played with", "N/A - no session has recorded it yet"));
vm.HookToggleEnabled.Should().BeFalse("turning hooking on could only be refused");
vm.NotX64Text.Should().Contain("32-bit (x86)");
@@ -797,7 +802,9 @@ public sealed class GameDetailViewModelTests
vm.HookToggleEnabled.Should().BeTrue("a switch that is on can be turned off whatever the file is");
(GameDetailViewModel unread, _, _, _, _) = await BuildAsync(s, fresh.Id);
unread.Details.Should().ContainSingle().Which.Should().Be(new GameDetailRow("Runs as", Strings.GameDetail_Details_NotRead));
// The file facts are one row; the three controller rows are there whether the files were read or not.
unread.Details.Should().HaveCount(4);
unread.Details[0].Should().Be(new GameDetailRow("Runs as", Strings.GameDetail_Details_NotRead));
unread.NotX64Text.Should().BeNull("not read is not known 32-bit");
unread.HookToggleEnabled.Should().BeTrue();
}
@@ -127,6 +127,20 @@ internal sealed class FakeGameRepository : IGameRepository
public ValueTask<bool> RemoveAsync(long gameId, bool keepSessions, CancellationToken ct = default) => throw new NotSupportedException();
/// <summary>The UI's recording switch (2026-09-23), applied to the row so the watcher tests see it.</summary>
public ValueTask<bool> SetControllerSupportAsync(long gameId, string support, string source, DateTimeOffset at, CancellationToken ct = default)
{
foreach ((string key, GameRow row) in Rows)
{
if (row.Id == gameId)
{
Rows[key] = row with { ControllerSupport = support, ControllerSupportSource = source, ControllerSupportAt = at };
return ValueTask.FromResult(true);
}
}
return ValueTask.FromResult(false);
}
public ValueTask<bool> SetRecordingAsync(long gameId, bool record, CancellationToken ct = default)
{
foreach ((string key, GameRow row) in Rows)
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Domain.Input;
namespace FrameLedger.Domain.Tests.Input;
/// <summary>The libraries through which a Windows game reads controllers, by file name (owner decision D163).</summary>
public sealed class InputLibrariesTests
{
[Theory]
[InlineData("xinput1_4.dll", "XInput")]
[InlineData("XINPUT1_3.DLL", "XInput")]
[InlineData("xinput9_1_0.dll", "XInput")]
[InlineData("xinputuap.dll", "XInput")]
[InlineData("dinput8.dll", "DirectInput")]
[InlineData("DINPUT.dll", "DirectInput")]
[InlineData("Windows.Gaming.Input.dll", "Windows.Gaming.Input")]
[InlineData("GameInput.dll", "GameInput")]
[InlineData("SDL2.dll", "SDL")]
[InlineData("SDL3.dll", "SDL")]
public void AnInputLibraryIsNamedByTheInterfaceItIs(string file, string api)
{
InputLibraries.ApiOf(file).Should().Be(api);
InputLibraries.Is(file).Should().BeTrue();
}
[Theory]
[InlineData("nvngx_dlss.dll")]
[InlineData("xinput.dll")]
[InlineData("hid.dll")] // loaded by half of Windows: it says nothing of controllers
[InlineData("steam_api64.dll")]
[InlineData("")]
[InlineData(null)]
public void AnythingElseIsNotOne(string? file)
{
InputLibraries.ApiOf(file).Should().BeNull();
InputLibraries.Is(file).Should().BeFalse();
}
[Fact]
public void TheNamesASnapshotLooksForAreLowerCaseAndEachIsAnInputLibrary()
{
InputLibraries.FileNames.Should().HaveCount(10).And.OnlyHaveUniqueItems();
InputLibraries.FileNames.Should().OnlyContain(static f => InputLibraries.Is(f) && !f.Any(char.IsUpper));
}
}
@@ -0,0 +1,265 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Buffers.Binary;
using System.Text;
using FluentAssertions;
using FrameLedger.Infrastructure.Import;
namespace FrameLedger.Infrastructure.Tests.Import;
/// <summary>
/// What the Steam app's own file says of controller support (owner decision D163): read from files written here to
/// the layout of format 41 - which was checked against the developer's own Steam folder on 2026-11-14 - and, where a
/// Steam app is installed on the machine that runs the tests, from the real one.
/// </summary>
public sealed class SteamAppInfoTests
{
private const uint _magic41 = 0x07564429;
// The table of strings: a tree names its keys by their number here.
private static readonly string[] _keys = ["appinfo", "appid", "common", "name", "controller_support", "extended", "depots"];
private static byte[] Key(string name) => BitConverter.GetBytes(Array.IndexOf(_keys, name));
private static byte[] Map(string key, params byte[][] children) => [0x00, .. Key(key), .. children.SelectMany(static c => c), 0x08];
private static byte[] Text(string key, string value) => [0x01, .. Key(key), .. Encoding.UTF8.GetBytes(value), 0];
private static byte[] Number(string key, int value) => [0x02, .. Key(key), .. BitConverter.GetBytes(value)];
private static byte[] Wide(string key, string value) => [0x05, .. Key(key), .. Encoding.Unicode.GetBytes(value), 0, 0];
private static byte[] Long(string key, byte kind, long value) => [kind, .. Key(key), .. BitConverter.GetBytes(value)];
/// <summary>A record's tree as Steam writes one: the root map, and the end mark after it.</summary>
private static byte[] Tree(uint appId, string? support, params byte[][] more)
{
byte[][] common = support is null ? [Text("name", "A Game")] : [Text("name", "A Game"), Text("controller_support", support)];
byte[][] children = [Number("appid", (int)appId), Map("common", common), .. more];
return [.. Map("appinfo", children), 0x08];
}
/// <summary>A whole file: the header, each record with its sixty bytes of state, the zero id, the table of strings.</summary>
private static byte[] File(uint magic, IReadOnlyList<(uint AppId, byte[] Tree)> records, string[]? keys = null)
{
var bytes = new List<byte>();
bytes.AddRange(BitConverter.GetBytes(magic));
bytes.AddRange(BitConverter.GetBytes(1u));
bytes.AddRange(new byte[8]);
foreach ((uint appId, byte[] tree) in records)
{
bytes.AddRange(BitConverter.GetBytes(appId));
bytes.AddRange(BitConverter.GetBytes((uint)(60 + tree.Length)));
bytes.AddRange(Enumerable.Repeat((byte)0xAB, 60));
bytes.AddRange(tree);
}
bytes.AddRange(BitConverter.GetBytes(0u));
byte[] file = [.. bytes];
BinaryPrimitives.WriteInt64LittleEndian(file.AsSpan(8), file.Length);
string[] table = keys ?? _keys;
return [.. file, .. BitConverter.GetBytes((uint)table.Length), .. table.SelectMany(static k => Encoding.UTF8.GetBytes(k).Append((byte)0))];
}
private static byte[] Library() => File(_magic41,
[
(10, Tree(10, "full")),
(20, Tree(20, "partial", Map("extended", Text("name", "x"), Number("appid", 7)))),
(30, Tree(30, null)),
(40, Tree(40, "Full ")),
(50, Tree(50, "something a later Steam writes")),
]);
[Fact]
public void ARecordSaysFullPartialOrNothingAndAnIdWithNoRecordIsNotAnswered()
{
SteamAppInfoResult read = SteamAppInfo.ReadControllerSupport(Library(), [10, 20, 30, 40, 50, 999]);
read.Problem.Should().BeNull();
read.Support.Should().BeEquivalentTo(new Dictionary<uint, string>
{
[10] = SteamAppInfo.Full,
[20] = SteamAppInfo.Partial,
[30] = SteamAppInfo.None,
[40] = SteamAppInfo.Full,
[50] = SteamAppInfo.None,
});
read.Support.Should().NotContainKey(999u, "the store's file does not describe it: that is not 'none'");
}
[Fact]
public void OnlyTheApplicationsAskedAboutAreAnswered()
{
SteamAppInfo.ReadControllerSupport(Library(), [20]).Support.Should().ContainSingle().Which.Should().Be(new KeyValuePair<uint, string>(20, SteamAppInfo.Partial));
SteamAppInfo.ReadControllerSupport(Library(), []).Support.Should().BeEmpty();
}
/// <summary>The key is only the store's word under the record's own "common" section: the same key anywhere else in the tree says nothing.</summary>
[Fact]
public void TheKeyCountsOnlyInTheRecordsCommonSection()
{
byte[] elsewhere = [.. Map("appinfo", Number("appid", 1), Map("common", Text("name", "A")), Map("extended", Text("controller_support", "full"), Map("common", Text("controller_support", "full")))), 0x08];
byte[] atTheRoot = [.. Map("appinfo", Text("controller_support", "full"), Map("common", Text("name", "A"))), 0x08];
SteamAppInfoResult read = SteamAppInfo.ReadControllerSupport(File(_magic41, [(1, elsewhere), (2, atTheRoot)]), [1, 2]);
read.Problem.Should().BeNull();
read.Support.Should().BeEquivalentTo(new Dictionary<uint, string> { [1] = SteamAppInfo.None, [2] = SteamAppInfo.None });
}
[Fact]
public void EveryKindOfValueATreeCanHoldIsPassedOver()
{
byte[] tree =
[
.. Map("appinfo",
Number("appid", 1),
[0x03, .. Key("depots"), 0, 0, 128, 63],
[0x04, .. Key("depots"), 1, 2, 3, 4],
[0x06, .. Key("depots"), 255, 0, 0, 255],
Long("depots", 0x07, 123456789012345),
Long("depots", 0x0A, -5),
Wide("depots", "wide"),
Map("depots", Map("extended", Map("depots"))),
Map("common", Text("controller_support", "partial"))),
0x0B,
];
SteamAppInfo.ReadControllerSupport(File(_magic41, [(1, tree)]), [1]).Support[1].Should().Be(SteamAppInfo.Partial);
}
[Fact]
public void AFileOfAnotherFormatIsRefusedWithTheReason()
{
SteamAppInfoResult read = SteamAppInfo.ReadControllerSupport(File(0x07564428, [(10, Tree(10, "full"))]), [10]);
read.Support.Should().BeEmpty();
read.Problem.Should().Be("format 0x07564428 is not the one this build reads (0x07564429)");
}
[Fact]
public void AFileWhoseTableHasNeitherKeyIsReadAndEveryRecordListsNone()
{
byte[] file = File(_magic41, [(10, Tree(10, "full"))], keys: ["a", "b", "c", "d", "e", "f", "g"]);
SteamAppInfoResult read = SteamAppInfo.ReadControllerSupport(file, [10]);
read.Problem.Should().BeNull();
read.Support[10].Should().Be(SteamAppInfo.None);
}
/// <summary>No length in the file is trusted: cut anywhere, it is a problem and never a read past the end - and never half an answer.</summary>
[Fact]
public void AFileCutAtAnyByteIsAProblemOrAWholeAnswerAndNeverThrows()
{
byte[] whole = Library();
SteamAppInfo.ReadControllerSupport(whole, [10, 20, 30]).Support.Should().HaveCount(3);
for (int cut = 0; cut < whole.Length; cut++)
{
SteamAppInfoResult read = SteamAppInfo.ReadControllerSupport(whole.AsSpan(0, cut), [10, 20, 30]);
(read.Problem is not null || read.Support.Count == 3).Should().BeTrue($"cut at {cut}: a problem, or the whole answer");
if (read.Problem is not null)
{
read.Support.Should().BeEmpty($"cut at {cut}: a file that cannot be read whole says nothing");
}
}
}
[Theory]
[InlineData(4u)] // smaller than its own state
[InlineData(0xFFFFFFFFu)] // larger than the file
public void ARecordWhoseSizeIsNotPossibleIsAProblem(uint size)
{
byte[] file = Library();
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(16 + 4), size);
SteamAppInfoResult read = SteamAppInfo.ReadControllerSupport(file, [10]);
read.Problem.Should().Be("a record claims more than the file holds");
read.Support.Should().BeEmpty();
}
[Fact]
public void ATreeThatIsNotWellFormedIsAProblemOnlyForARecordThatIsAskedAbout()
{
byte[] unknownKind = [0x00, .. Key("appinfo"), 0x7F, .. Key("appid"), 1, 2, 3, 4, 0x08, 0x08];
byte[] unendedString = [0x00, .. Key("appinfo"), 0x01, .. Key("name"), (byte)'x'];
byte[] unendedMap = [0x00, .. Key("appinfo"), 0x00, .. Key("common")];
byte[] file = File(_magic41, [(1, unknownKind), (2, unendedString), (3, unendedMap), (4, Tree(4, "full"))]);
SteamAppInfo.ReadControllerSupport(file, [4]).Support[4].Should().Be(SteamAppInfo.Full, "the records before it are stepped over by their size");
foreach (uint bad in new uint[] { 1, 2, 3 })
{
SteamAppInfo.ReadControllerSupport(file, [bad, 4]).Problem.Should().Be("a record's tree cannot be read", $"record {bad}");
}
}
[Fact]
public void ATreeNestedDeeperThanAnyRecordIsRefusedRatherThanFollowed()
{
byte[] deep = Map("common");
for (int i = 0; i < 40; i++)
{
deep = Map("extended", deep);
}
SteamAppInfo.ReadControllerSupport(File(_magic41, [(1, [.. deep, 0x08])]), [1]).Problem.Should().Be("a record's tree cannot be read");
}
[Fact]
public void AFileThatIsNotThereOrIsEmptyIsAProblemAndNotAnException()
{
string dir = Path.Combine(Path.GetTempPath(), "fl-appinfo-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
SteamAppInfo.ReadControllerSupport(Path.Combine(dir, "absent.vdf"), [10]).Problem.Should().Be(nameof(FileNotFoundException));
string empty = Path.Combine(dir, "empty.vdf");
System.IO.File.WriteAllBytes(empty, []);
SteamAppInfo.ReadControllerSupport(empty, [10]).Problem.Should().Be("the file is empty or too large");
string good = Path.Combine(dir, "appinfo.vdf");
System.IO.File.WriteAllBytes(good, Library());
SteamAppInfo.ReadControllerSupport(good, [10]).Support[10].Should().Be(SteamAppInfo.Full);
SteamAppInfo.ReadControllerSupport(new byte[8], [10]).Problem.Should().Be("shorter than a header");
}
finally
{
Directory.Delete(dir, recursive: true);
}
}
/// <summary>
/// The real file, where a Steam app is installed for the user running the tests - CI's runner has none, and then
/// there is nothing to assert. It asserts the CONTRACT: the file this build's Steam client wrote is read without a
/// problem, and every answer is one of the three words.
/// </summary>
[Fact]
[Trait("Category", "Integration")]
public async Task TheSteamAppsOwnFileOnThisMachineIsReadWhereThereIsOne()
{
if (SteamAppInfo.InstalledFile() is not { } path || !System.IO.File.Exists(path))
{
return;
}
uint[] installed = [.. (await new SteamLibrarySource().ListAsync(TestContext.Current.CancellationToken))
.Select(static g => uint.TryParse(g.StoreId, out uint id) ? id : 0).Where(static id => id != 0)];
SteamAppInfoResult read = SteamAppInfo.ReadControllerSupport(path, installed);
if (read.Problem is { } problem && problem.StartsWith("format ", StringComparison.Ordinal))
{
// A Steam client that writes another format: the reader says so and the fact reads N/A. Not this test's to fail on.
return;
}
read.Problem.Should().BeNull();
read.Support.Values.Should().BeSubsetOf([SteamAppInfo.Full, SteamAppInfo.Partial, SteamAppInfo.None]);
ILookup<string, uint> by = read.Support.ToLookup(static p => p.Value, static p => p.Key, StringComparer.Ordinal);
TestContext.Current.SendDiagnosticMessage($"Steam's appinfo.vdf: {read.Support.Count} of {installed.Length} installed applications have a record; "
+ $"full {by[SteamAppInfo.Full].Count()}, partial {by[SteamAppInfo.Partial].Count()}, none {by[SteamAppInfo.None].Count()}");
}
}