Files
frameledger/src/FrameLedger.App/ViewModels/GameDetailViewModel.cs
T
poli0981andClaude Opus 5.5 c9b0aab862 feat: DLSS 5 is named where the game ran its neural rendering (schema 0022, rules 2026.11.2, Privacy 2.14); Streamline headers re-vendored at v2.14.16 (D84) (beta.34 PR-3) (#358)
The owner, 2026-11-06: Hogwarts Legacy with Neural Rendering on loaded DLSS 5's runtime
(nvngx_dlssnr.dll 310.9.16.0, from the game's folder) and the session could say only "DLSS 5
runtime loaded". Then: check what changed in recent Streamline versions, fix it if needed.

- Streamline: the vendored closure was v2.12.0 byte for byte; v2.14.16 changes three of its
  eleven files (kFeatureDLSS_NR = 1004, the uplift buffer types 70-72, kStructVersion7, the
  version). Re-vendored byte for byte; README provenance, THIRD_PARTY_NOTICES row.
- Overlay (hook path): the slEvaluateFeature detour decodes kFeatureDLSS_NR into its own bit;
  RecordPresent sets FL_FEAT_SL_NEURAL_RENDERING (feature byte bit 7, an enumerator - no layout
  change) under the condition every Streamline fact shares; the evaluate row's family also claims
  FL_HOOK_SL_NEURAL_RENDERING (bit 12), published with the detour. Overhead: decode unchanged
  within noise (4.7 ns a call), +0.14..0.19 ns a present.
- Agent: Domain.Metrics.NeuralRendering.SharePct; sessions.dlss_nr_pct (schema 0022) only from a
  writer that published the family - an older Overlay's silence is never a measured 0 %.
  CensusNames records sl.dlss_nr.dll.
- Rules 2026.11.2: capability dlss_nr -> "Supports DLSS 5 Neural Rendering".
- App (D84): DLSS 5 heads the DLSS line where it ran ("DLSS 5 (neural rendering on 97.3% of
  rendered frames)"); its library listed with version and source; measured 0 -> "runtime loaded,
  not seen running"; nothing to tell -> "runtime loaded" as before. CSV basis/pct.
- CaptureHost dev census: a kFeatureDLSS_NR bucket.
- Privacy Policy 2.14 (neural-rendering libraries); the accuracy block's DLSS 5 sentence.
- Tests: native guard_test (the new harness mode through an injected Overlay; 0xF00D lights no NR
  fact; the token case's exact mask gains the family), NeuralRenderingTests, SessionAggregatorTests,
  DlssGenerationTests, DlssTextTests (a row shaped from session 132), LedgerDatabaseTests (0022),
  the repository round trip, the rules fixture, RuntimeModuleSourcesTests, SlCensusTests.
- Docs: 05_DETECTION, 06_DATA_MODEL, 17_HOOK_ENGINE, LIMITATIONS, guide/03, guide/10, the accuracy
  block, spike-notes 26 (+ owner-only item 30(a)'s decision table), HANDOFF (D84), CHANGELOG.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 08:39:42 +00:00

1467 lines
64 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FrameLedger.App.Charts;
using FrameLedger.App.Pages;
using FrameLedger.App.Services;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Settings;
using FrameLedger.Application.TriState;
using FrameLedger.Domain.Detection;
using FrameLedger.Domain.Sessions;
using FrameLedger.Infrastructure.Io;
using FrameLedger.Shared.Ipc;
using Wpf.Ui.Controls;
namespace FrameLedger.App.ViewModels;
/// <summary>
/// The game page (<c>08_UI</c> §Games › Game detail): header, the two clearly separated rows (Supports vs Last
/// session measured), the hooking control over <see cref="HookingConsent"/> (FR-2.1/2.2/2.5), the Sessions tab.
/// A refusal or a mismatch is a persistent notice on this page, never a toast (§Notifications policy).
/// </summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime")]
public sealed partial class GameDetailViewModel : ObservableObject
{
private readonly GameLibrary _library;
private readonly HookingConsent _consent;
private readonly IPageNavigator _navigator;
private readonly IConfirmations _confirmations;
private readonly IEditGamePrompt _edit;
private readonly IGamePicker _picker;
private readonly IMessageStrip _strip;
private readonly GamePlayer? _player;
private readonly ISessionSummaryOpener _summaries;
private readonly SessionSeriesLoader _loader;
private readonly IAgentLink? _agent;
private readonly UiMode _mode;
private readonly UiThread _ui = new();
private bool _attached;
private readonly IHardwareSnapshotRepository _hardware;
private readonly SessionSelection _selection;
private readonly RegisteredSettings? _settings;
private readonly AntiCheatExceptions? _exceptions;
private readonly SessionDeletion? _deletion;
private readonly Func<string, bool> _exists;
private readonly GameArt? _art;
private readonly CoverStore? _covers;
private readonly IImagePicker? _images;
private readonly long? _gameId;
// ui.hide_anticheat_hooking (2026-09-25), read at each load; on until the settings say otherwise, as its default is.
private bool _hideAntiCheatHooking = true;
// hooking.usermode_ac_exceptions (D33, 2026-09-26), read at each load; off until the settings say otherwise.
private bool _exceptionsOn;
private GameDetail? _detail;
[ObservableProperty]
private string _name = string.Empty;
[ObservableProperty]
private string _subtitle = string.Empty;
/// <summary>The executable the row is about: what the watcher matches and what consent is keyed on, so a wrong import guess is visible.</summary>
[ObservableProperty]
private string _executableText = string.Empty;
/// <summary>
/// The row's executable is not where the row says (2026-09-22). Read when the page loads; the Agent moves the row
/// itself when the file is under another drive letter, so this clears on the next visit once it has.
/// </summary>
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(PlayCommand))]
private bool _executableMissing;
/// <summary>
/// The missing executable's bar (beta.8): the page's sentence, then whether the DRIVE is not connected or the file is gone
/// from its path — the two need different things of the user. Worked out with the check, off the UI thread (beta.23): it
/// asked the drive from this property's getter, on the UI thread, at every read.
/// </summary>
[ObservableProperty]
private string _executableMissingMessage = ExecutableMissingText;
// Why the executable is missing, from the last load's check (beta.23); null while it was found.
private string? _executableMissingWhy;
/// <summary>
/// beta.23 (D60): the game's artwork — the image the user chose, else the store's own cover, else its landscape header;
/// null with none. Shown in the header band beside the name.
/// </summary>
[ObservableProperty]
private ImageSource? _artCover;
/// <summary>The cover slot holds the store's landscape header (no portrait cover): drawn wider and shorter.</summary>
[ObservableProperty]
private bool _artCoverIsLandscape;
/// <summary>The cover slot holds an Xbox game's square logo (beta.33): drawn square, never cropped to a portrait.</summary>
[ObservableProperty]
private bool _artCoverIsSquare;
/// <summary>The store's wide banner, above the header band; null without one.</summary>
[ObservableProperty]
private ImageSource? _artHero;
/// <summary>D61: the colour the header band takes from the artwork; null leaves it the card's own fill.</summary>
[ObservableProperty]
private Color? _artTint;
/// <summary>The page shows artwork: the band, the cover, the banner.</summary>
[ObservableProperty]
private bool _hasArt;
/// <summary>Where the artwork came from, for its tooltip.</summary>
[ObservableProperty]
private string? _artSource;
// What the edit dialog needs: whether the cover is the user's own, and the store's own cover to go back to.
private bool _artCoverIsOwn;
private ImageSource? _artStoreCover;
/// <summary>What Play will do, in the mode Settings ▸ Games has now (beta.21, D59).</summary>
[ObservableProperty]
private string _playToolTip = Strings.Play_ToolTip_Store;
[ObservableProperty]
private string _lastSessionText = string.Empty;
[ObservableProperty]
private FpsReadoutModel _lifetime = FpsReadoutModel.Unavailable;
[ObservableProperty]
private bool _supportsEmpty = true;
/// <summary>
/// What the Supports card says when it lists nothing (beta.21): "not scanned yet" until the Agent's sweep has read the
/// executable, then that none of the files the rules name was found. It said "not scanned yet" for every game that
/// ships none of them — a scanned RPG Maker game's page contradicted its own Details card.
/// </summary>
[ObservableProperty]
private string _supportsEmptyText = Strings.GameDetail_Supports_Empty;
[ObservableProperty]
private string _measuredEmptyText = string.Empty;
/// <summary>The entry's recording switch (schema 0009, 2026-09-23): off, FrameLedger does not watch for the program.</summary>
[ObservableProperty]
private bool _recordSessions = true;
[ObservableProperty]
private string _recordingStatusText = string.Empty;
[ObservableProperty]
private bool _hookEnabled;
[ObservableProperty]
private bool _hookToggleEnabled;
[ObservableProperty]
private string _hookStatusText = string.Empty;
[ObservableProperty]
private string? _blockedText;
/// <summary>
/// The compact finding shown IN PLACE of the Hooking card when anti-cheat was found and the user keeps such cards hidden
/// (beta.8); null otherwise. The finding itself is always on the page (FR-2.2) — here, or as the card's blocked text.
/// </summary>
[ObservableProperty]
private string? _antiCheatText;
/// <summary>Whether the Hooking card and its lines show: false only for an anti-cheat game while they are hidden.</summary>
[ObservableProperty]
private bool _hookingSectionVisible = true;
/// <summary>
/// D33: the user-mode exception's card on a blocked game — shown while the option is on, and for an exception kept while
/// it is off; its state is the Agent's (<see cref="ExceptionView"/>).
/// </summary>
[ObservableProperty]
private bool _exceptionCardVisible;
[ObservableProperty]
private string? _exceptionText;
/// <summary>D33: what an exception in force means, on the page it applies to; null otherwise.</summary>
[ObservableProperty]
private string? _exceptionInForceText;
[ObservableProperty]
private string? _exceptionSuspendedText;
[ObservableProperty]
private string? _exceptionLapseText;
[ObservableProperty]
private bool _canGrantException;
[ObservableProperty]
private bool _canWithdrawException;
/// <summary>
/// Why the switch cannot be turned on when the executable cannot run as x64 (beta.8, <c>exe_machine</c>); null otherwise.
/// A switch that is on for such a game can still be turned off.
/// </summary>
[ObservableProperty]
private string? _notX64Text;
[ObservableProperty]
private string? _autoDisabledText;
[ObservableProperty]
private string? _unverifiedText;
[ObservableProperty]
private string? _noticeText;
[ObservableProperty]
private InfoBarSeverity _noticeSeverity = InfoBarSeverity.Warning;
[ObservableProperty]
private bool _busy;
[ObservableProperty]
private bool _notFound;
[ObservableProperty]
private bool _sessionsEmpty = true;
[ObservableProperty]
private SessionItemViewModel? _selectedSession;
[ObservableProperty]
private string _selectedNote = Strings.Tabs_SelectASession;
[ObservableProperty]
private bool _selectedHasSeries;
/// <summary>The Sensors tab's note: why nothing is drawn there, or empty.</summary>
[ObservableProperty]
private string _sensorsNote = Strings.Tabs_SelectASession;
[ObservableProperty]
private bool _selectedHasSensors;
[ObservableProperty]
private string _latencyText = string.Empty;
[ObservableProperty]
private bool _hasLatency;
/// <summary>
/// beta.14: any of the game's sessions measured PC latency, so the Latency tab is shown. Nothing measures Reflex today
/// (<c>sessions.reflex_active</c> is null on every row), and a tab that can only ever say "no data" was noise.
/// </summary>
[ObservableProperty]
private bool _anyLatency;
[ObservableProperty]
private TrendMetric _trendMetric = TrendMetric.PresentedFps;
[ObservableProperty]
private bool _includeMidSession;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(TrendChangesVisible))]
private bool _trendEmpty = true;
/// <summary>
/// FR-6.3 since beta.30 (owner decision D70): one marker per day that changed, numbered oldest first — the badges on both
/// charts and the lists under them, so a number means the same day everywhere on the page.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasChangeMarkers), nameof(TrendChangesVisible))]
private IReadOnlyList<ChangeMarker> _changeMarkers = [];
/// <summary>beta.11 (D39): whether the Sessions tab's overview has anything to draw.</summary>
[ObservableProperty]
private bool _overviewVisible;
[ObservableProperty]
private string _trendExcludedText = string.Empty;
public GameDetailViewModel(GameLibrary library, GameSelection selection, HookingConsent consent, IPageNavigator navigator,
IConfirmations confirmations, IEditGamePrompt edit, IMessageStrip strip, ISessionSummaryOpener summaries,
SessionSeriesLoader loader, IHardwareSnapshotRepository hardware, SessionSelection sessionSelection, IGamePicker picker,
RegisteredSettings? settings = null, IAgentLink? agent = null, AntiCheatExceptions? exceptions = null, SessionDeletion? deletion = null,
UiMode? mode = null, GamePlayer? player = null, Func<string, bool>? executableExists = null, GameArt? art = null, CoverStore? covers = null,
IImagePicker? images = null)
{
_art = art;
_covers = covers;
_images = images;
// beta.23: whether the executable is on disk is a question for its drive, which can take seconds to answer (the
// owner's games are on a USB drive), so it is asked off the UI thread, as the library page has asked since beta.19.
_exists = executableExists ?? GameLibrary.ExecutableExists;
// beta.15 (D52): a viewer over a copy has no Agent to ask; a composition without a mode (a test) is the profile's App.
_player = player;
_mode = mode ?? UiMode.Profile;
_deletion = deletion;
_exceptions = exceptions;
_settings = settings;
_agent = agent;
_picker = picker ?? throw new ArgumentNullException(nameof(picker));
_selection = sessionSelection ?? throw new ArgumentNullException(nameof(sessionSelection));
_library = library ?? throw new ArgumentNullException(nameof(library));
ArgumentNullException.ThrowIfNull(selection);
_consent = consent ?? throw new ArgumentNullException(nameof(consent));
_navigator = navigator ?? throw new ArgumentNullException(nameof(navigator));
_confirmations = confirmations ?? throw new ArgumentNullException(nameof(confirmations));
_edit = edit ?? throw new ArgumentNullException(nameof(edit));
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
_summaries = summaries ?? throw new ArgumentNullException(nameof(summaries));
_loader = loader ?? throw new ArgumentNullException(nameof(loader));
_hardware = hardware ?? throw new ArgumentNullException(nameof(hardware));
_gameId = selection.GameId;
Pending = LoadAsync();
}
public static string BackText => Strings.GameDetail_Back;
/// <summary>
/// beta.15 (D52): what asks the Agent — hooking, the exception's grant and withdrawal, re-enabling, Delete all sessions —
/// is live everywhere but in a viewer over a copy, which has none to ask.
/// </summary>
public bool ActsOnThisPc => _mode.ActsOnThisPc;
public static string ExceptionHeader => Strings.GameDetail_Exception_Header;
public static string GrantExceptionText => Strings.GameDetail_Exception_Grant;
public static string WithdrawExceptionText => Strings.GameDetail_Exception_Withdraw;
public static string EditText => Strings.GameDetail_Edit;
public static string PlayText => Strings.Play_Button;
public static string RemoveText => Strings.GameDetail_Remove;
public static string ChangeExecutableText => Strings.GameDetail_ChangeExe;
public static string ExecutableMissingText => Strings.GameDetail_ExeMissing;
public static string LifetimeLabel => Strings.GameDetail_LifetimeAvg;
public static string SupportsHeader => Strings.GameDetail_Supports_Header;
public static string MeasuredHeader => Strings.GameDetail_Measured_Header;
public static string RecordingHeader => Strings.GameDetail_Recording_Header;
public static string RecordingBody => Strings.GameDetail_Recording_Body;
public static string HookingHeader => Strings.GameDetail_Hooking_Header;
public static string AntiCheatHeader => Strings.GameDetail_AntiCheat_Header;
public static string DetailsHeader => Strings.GameDetail_Details_Header;
/// <summary>What the game's files and its store say about it (beta.8): what it runs as, its versions, what it ships.</summary>
public ObservableCollection<GameDetailRow> Details { get; } = [];
public static string HookingBody => Strings.GameDetail_Hooking_Body;
public static string ReEnableText => Strings.GameDetail_Hooking_ReEnable;
public static string BusyText => Strings.GameDetail_Hooking_Busy;
public static string SessionsEmptyText => Strings.GameDetail_Sessions_Empty;
public static string NotFoundText => Strings.GameDetail_NotFound;
public static string TabSessions => Strings.GameDetail_Tab_Sessions;
public static string TabFrametime => Strings.GameDetail_Tab_Frametime;
public static string TabDistribution => Strings.GameDetail_Tab_Distribution;
public static string TabTrend => Strings.GameDetail_Tab_Trend;
public static string TabSensors => Strings.GameDetail_Tab_Sensors;
public static string TabLatency => Strings.GameDetail_Tab_Latency;
public static string TrendMetricLabel => Strings.Trend_Metric_Label;
public static string IncludeMidSessionText => Strings.Trend_IncludeMidSession;
public static string TrendEmptyText => Strings.Trend_Empty;
public static string TrendAverageNote => Strings.Trend_Average_Note;
public static string TrendPartialNote => Strings.Trend_Partial_Note;
/// <summary>Why the trend is empty FOR THIS METRIC (beta.8): "no hooked session yet" was wrong for a game whose sessions simply lack it.</summary>
[ObservableProperty]
private string _trendEmptyMessage = Strings.Trend_Empty;
public static string LatencyHeader => Strings.Latency_Header;
public static string LatencyEmptyText => Strings.Latency_Empty;
public static string SensorsEmptyText => Strings.Sensors_Empty;
/// <summary>
/// The selector's entries, built for each page in the language it opens in (beta.8: a static list kept the language the
/// App started in).
/// </summary>
public IReadOnlyList<Choice<TrendMetric>> TrendMetrics { get; } =
[
new(TrendMetric.PresentedFps, Strings.Trend_Metric_PresentedFps),
new(TrendMetric.NativeFps, Strings.Trend_Metric_NativeFps),
new(TrendMetric.Displayed, Strings.Trend_Metric_Displayed),
new(TrendMetric.P1Low, Strings.Trend_Metric_P1Low),
new(TrendMetric.P01Low, Strings.Trend_Metric_P01Low),
new(TrendMetric.MaxGpuTemp, Strings.Trend_Metric_MaxGpuTemp),
new(TrendMetric.AvgGpuLoad, Strings.Trend_Metric_AvgGpuLoad),
new(TrendMetric.AvgGpuPower, Strings.Trend_Metric_AvgGpuPower),
new(TrendMetric.AvgCpuLoad, Strings.Trend_Metric_AvgCpuLoad),
new(TrendMetric.MaxCpuTemp, Strings.Trend_Metric_MaxCpuTemp),
new(TrendMetric.GameVramMedian, Strings.Trend_Metric_GameVramMedian),
new(TrendMetric.GameVramPeak, Strings.Trend_Metric_GameVramPeak),
new(TrendMetric.GameRamMedian, Strings.Trend_Metric_GameRamMedian),
new(TrendMetric.GameRamPeak, Strings.Trend_Metric_GameRamPeak),
new(TrendMetric.AvgRam, Strings.Trend_Metric_AvgRam),
new(TrendMetric.FgFactor, Strings.Trend_Metric_FgFactor),
new(TrendMetric.DisplayExclusiveShare, Strings.Trend_Metric_DisplayExclusive),
new(TrendMetric.DisplayBorderlessShare, Strings.Trend_Metric_DisplayBorderless),
new(TrendMetric.DisplayWindowedShare, Strings.Trend_Metric_DisplayWindowed),
new(TrendMetric.TimeBelow60, Strings.Trend_Metric_TimeBelow60),
new(TrendMetric.TimeBelowRefresh, Strings.Trend_Metric_TimeBelowRefresh),
new(TrendMetric.FrameToFrame, Strings.Trend_Metric_FrameToFrame),
new(TrendMetric.RenderScale, Strings.Trend_Metric_RenderScale),
new(TrendMetric.VsyncShare, Strings.Trend_Metric_VsyncShare),
new(TrendMetric.GpuCoreClock, Strings.Trend_Metric_GpuCoreClock),
new(TrendMetric.MaxGpuMemTemp, Strings.Trend_Metric_MaxGpuMemTemp),
new(TrendMetric.PowerLimitShare, Strings.Trend_Metric_PowerLimitShare),
new(TrendMetric.Efficiency, Strings.Trend_Metric_Efficiency),
];
/// <summary>The selected session's decoded series (null: none selected, Tier 2, or swept).</summary>
public SessionSeries? SelectedSeries { get; private set; }
/// <summary>
/// What the Sensors tab draws: the selected session's series, or — for a session that was not hooked — its sensors alone
/// (beta.8: a Tier-2 row has kept them since 2026-09-22, and the tab said "not hooked" over them).
/// </summary>
public SessionSeries? SelectedSensors { get; private set; }
public IReadOnlyList<TrendPoint> TrendPoints { get; private set; } = [];
/// <summary>
/// beta.11 (D39): what the Trend draws — the selected metric, then every metric ticked beside it. One line alone keeps
/// its own name on the axis, as before; several are labelled by unit, a second unit on the right.
/// </summary>
public IReadOnlyList<TrendLine> TrendLines { get; private set; } = [];
/// <summary>beta.11 (D39): the metrics that can be drawn beside the selected one, ticked by the user.</summary>
public ObservableCollection<TrendMetricOptionViewModel> TrendExtras { get; } = [];
/// <summary>beta.11 (D39): the Sessions tab's overview — every hooked session's rate and lows (<see cref="TrendSeriesBuilder.Overview"/>).</summary>
public IReadOnlyList<TrendLine> OverviewLines { get; private set; } = [];
public static string TrendExtrasLabel => Strings.Trend_Extras_Label;
public static string TrendExtrasNote => Strings.Trend_Extras_Note;
public static string OverviewHeader => Strings.GameDetail_Overview_Header;
public static string OverviewNote => Strings.GameDetail_Overview_Note;
public static string DeleteAllSessionsText => Strings.GameDetail_DeleteSessions;
public IReadOnlyList<HardwareChange> HardwareChanges { get; private set; } = [];
public bool HasChangeMarkers => ChangeMarkers.Count > 0;
/// <summary>The Trend tab's list stands with its chart: no point drawn, no chart, no badge to number.</summary>
public bool TrendChangesVisible => HasChangeMarkers && !TrendEmpty;
public string TrendMetricText => TrendMetrics.First(c => c.Value == TrendMetric).Label;
/// <summary>Raised when the selected session's series (re)loaded — the Frametime, Distribution, Sensors and Latency tabs redraw.</summary>
public event EventHandler? SelectionPresented;
/// <summary>Raised when the trend was rebuilt.</summary>
public event EventHandler? TrendPresented;
public GameRow? Game { get; private set; }
public ObservableCollection<TriStateChipModel> Chips { get; } = [];
public ObservableCollection<string> Supports { get; } = [];
public ObservableCollection<string> Measured { get; } = [];
public ObservableCollection<SessionItemViewModel> Sessions { get; } = [];
public bool NoticeVisible => NoticeText is not null;
/// <summary>The load or the action in flight, for a test to await.</summary>
public Task Pending { get; private set; }
public async Task LoadAsync(CancellationToken ct = default)
{
GameDetail? detail = _gameId is long id ? await _library.LoadAsync(id, ct: ct).ConfigureAwait(true) : null;
if (detail is null)
{
NotFound = true;
Game = null;
return;
}
string exePath = detail.Row.Fingerprint.ExePath;
Func<string, bool> exists = _exists;
_executableMissingWhy = await Task.Run(() => exists(exePath) ? null : Formats.ExecutableMissingText(exePath), ct).ConfigureAwait(true);
Game = detail.Row;
_detail = detail;
NotFound = false;
if (_player is not null)
{
PlayToolTip = await _player.IsDirectAsync(ct).ConfigureAwait(true) ? Strings.Play_ToolTip_Direct : Strings.Play_ToolTip_Store;
}
if (_settings is not null)
{
_hideAntiCheatHooking = await _settings.GetBooleanAsync(SettingsRegistry.UiHideAntiCheatHooking, ct).ConfigureAwait(true);
_exceptionsOn = await _settings.GetBooleanAsync(SettingsRegistry.HookingUserModeExceptions, ct).ConfigureAwait(true);
}
Present(detail);
AnyLatency = detail.Sessions.Any(static s => s.ReflexActive == true);
ChooseDefaultMetric(detail);
// beta.23 (D60): the artwork is looked for and decoded on the thread pool while the trend is drawn; the page's text is
// already there, and a reload keeps the picture it has until the new one is ready.
Task<GameArtView?> art = _art?.ForAsync(detail.Row, ct) ?? Task.FromResult<GameArtView?>(null);
await RebuildTrendAsync(ct).ConfigureAwait(true);
PresentArt(await art.ConfigureAwait(true));
}
private void PresentArt(GameArtView? view)
{
ArtCover = view?.Cover;
ArtCoverIsLandscape = view?.CoverIsLandscape ?? false;
ArtCoverIsSquare = view?.CoverIsSquare ?? false;
ArtHero = view?.Hero;
ArtTint = view?.Tint;
ArtSource = view?.Source;
_artCoverIsOwn = view?.CoverIsOwn ?? false;
_artStoreCover = view?.StoreCover;
HasArt = view is not null;
}
partial void OnSelectedSessionChanged(SessionItemViewModel? value)
{
_selection.Set(value?.Id); // File ▸ Export acts on this (P4 PR-3)
Pending = LoadSelectedAsync(value);
}
partial void OnTrendMetricChanged(TrendMetric value)
{
_trendMetricChosen |= !_choosingDefaultMetric;
RebuildTrendPoints();
}
private bool _trendMetricChosen;
private bool _choosingDefaultMetric;
/// <summary>
/// The first metric a game's trend opens on (beta.8): Presented FPS, unless the game's newest measured session counted
/// generated frames — then Native FPS, the rate such sessions have. Kept once the user picks one.
/// </summary>
private void ChooseDefaultMetric(GameDetail detail)
{
if (_trendMetricChosen)
{
return;
}
SessionRow? newest = detail.Sessions.FirstOrDefault(static s => s.Tier == CaptureTier.Hooked && s.FrameCount > 0);
_choosingDefaultMetric = true;
TrendMetric = newest is not null && FpsPresentation.FromRow(newest).Kind == FpsReadoutKind.Generated ? TrendMetric.NativeFps : TrendMetric.PresentedFps;
_choosingDefaultMetric = false;
}
partial void OnIncludeMidSessionChanged(bool value) => RebuildTrendPoints();
/// <summary>
/// Listens to the Agent while the page is on screen (beta.8): a session of this game that finishes reloads the page, so
/// its sessions, trend and header include it — they were the ones the page opened with until it was left and reopened.
/// The page calls it on Loaded and <see cref="Detach"/> on Unloaded; the link is a singleton and must not hold the page.
/// </summary>
public void Attach()
{
if (_agent is not null && !_attached)
{
_agent.EventReceived += OnAgentEvent;
_attached = true;
}
}
public void Detach()
{
if (_agent is not null && _attached)
{
_agent.EventReceived -= OnAgentEvent;
_attached = false;
}
}
private void OnAgentEvent(object? sender, AgentEventArgs e) => _ui.Post(() =>
{
if (string.Equals(e.Envelope.Type, IpcMessageType.SessionCompleted, StringComparison.Ordinal)
&& IpcCodec.Payload<SessionCompletedEvent>(e.Envelope) is { SessionId: not null } completed
&& completed.GameId is long game && game == _gameId)
{
Pending = LoadAsync();
}
else if (string.Equals(e.Envelope.Type, IpcMessageType.GameRemoved, StringComparison.Ordinal)
&& IpcCodec.Payload<GameRemovedEvent>(e.Envelope) is { } removed && removed.GameId == _gameId)
{
// D55 (beta.19): this very entry was removed by the Agent — the page reloads into its not-found state and says why.
_strip.Info(Strings.Games_Removed_Title, string.Format(CultureInfo.CurrentCulture, Strings.Games_Removed_Format, removed.GameName ?? removed.ExePath));
Pending = LoadAsync();
}
});
private async Task LoadSelectedAsync(SessionItemViewModel? session)
{
SelectedSeries = null;
SelectedSensors = null;
HasLatency = false;
LatencyText = string.Empty;
if (session is null)
{
SelectedNote = Strings.Tabs_SelectASession;
}
else if (!session.IsHooked)
{
SelectedNote = Strings.Tabs_SelectedNotHooked;
IReadOnlyList<SensorSeries> sensors = await _loader.LoadSensorsAsync(session.Id).ConfigureAwait(true);
SelectedSensors = sensors.Count > 0 ? SessionSeries.SensorsOnly(sensors) : null;
}
else
{
SelectedSeries = await _loader.LoadAsync(session.Id).ConfigureAwait(true);
SelectedNote = SelectedSeries is null ? Strings.Tabs_SelectedNoFrames : string.Empty;
SelectedSensors = SelectedSeries;
HasLatency = SelectedSeries?.LatencyUs is { Length: > 0 } && session.Row.ReflexActive == true;
LatencyText = HasLatency && session.Row.LatencyAvgUs is long avg && session.Row.LatencyP95Us is long p95
? string.Format(CultureInfo.CurrentCulture, Strings.Latency_Stats_Format, avg / 1000.0, p95 / 1000.0)
: string.Empty;
}
SelectedHasSeries = SelectedSeries is not null;
SelectedHasSensors = SelectedSensors is { Sensors.Count: > 0 };
SensorsNote = session is null ? Strings.Tabs_SelectASession
: SelectedHasSensors ? string.Empty
: session.IsHooked && SelectedSeries is null ? Strings.Tabs_SelectedNoFrames
: Strings.Sensors_Empty;
SelectionPresented?.Invoke(this, EventArgs.Empty);
}
/// <summary>FR-6.3: the snapshots of this game's sessions, then the markers between consecutive ones that differ.</summary>
private async Task RebuildTrendAsync(CancellationToken ct)
{
if (_detail is null)
{
return;
}
var snapshots = new Dictionary<long, HardwareSnapshot?>();
foreach (long id in _detail.Sessions.Select(static s => s.SnapshotId).Distinct())
{
snapshots[id] = await _hardware.FindAsync(id, ct).ConfigureAwait(true);
}
HardwareChanges = TrendSeriesBuilder.Changes(_detail.Sessions, id => snapshots.GetValueOrDefault(id));
ChangeMarkers = TrendSeriesBuilder.Markers(HardwareChanges);
RebuildTrendPoints();
}
private void RebuildTrendPoints()
{
if (_detail is null)
{
return;
}
TrendPoints = TrendSeriesBuilder.Points(_detail.Sessions, TrendMetric, IncludeMidSession);
int excluded = IncludeMidSession ? 0 : TrendSeriesBuilder.ExcludedCount(_detail.Sessions, TrendMetric);
TrendExcludedText = excluded > 0 ? string.Format(CultureInfo.CurrentCulture, Strings.Trend_Excluded_Format, excluded) : string.Empty;
TrendLines = BuildTrendLines();
TrendEmpty = TrendLines.All(static l => l.Points.Count == 0);
TrendEmptyMessage = string.Format(CultureInfo.CurrentCulture, Strings.Trend_Empty_Format, TrendMetricText);
OverviewLines = TrendSeriesBuilder.Overview(_detail.Sessions);
OverviewVisible = OverviewLines.Count > 0;
OnPropertyChanged(nameof(TrendMetricText));
TrendPresented?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// beta.11 (D39): the selected metric's line, then each ticked metric's — and the options' state: the selected metric
/// is not offered beside itself, and once two units are on the chart a metric in a third cannot be ticked. A metric
/// ticked in a third unit — the selected one changed to a unit neither ticked unit shares — is unticked: the chart
/// draws two units, and a box left ticked would name a line that is not there.
/// </summary>
private List<TrendLine> BuildTrendLines()
{
if (TrendExtras.Count == 0)
{
foreach (Choice<TrendMetric> choice in TrendMetrics)
{
var option = new TrendMetricOptionViewModel(choice.Value, choice.Label, TrendSeriesBuilder.UnitOf(choice.Value));
option.PropertyChanged += OnTrendExtraChanged;
TrendExtras.Add(option);
}
}
_rebuildingExtras = true;
try
{
string primaryUnit = TrendSeriesBuilder.UnitOf(TrendMetric);
string? secondUnit = null;
foreach (TrendMetricOptionViewModel option in TrendExtras.Where(o => o.IsSelected))
{
if (option.Metric == TrendMetric)
{
option.IsSelected = false;
}
else if (!string.Equals(option.Unit, primaryUnit, StringComparison.Ordinal))
{
secondUnit ??= option.Unit;
option.IsSelected = string.Equals(option.Unit, secondUnit, StringComparison.Ordinal);
}
}
TrendMetricOptionViewModel[] ticked = [.. TrendExtras.Where(static o => o.IsSelected)];
HashSet<string> units = new([primaryUnit, .. ticked.Select(static o => o.Unit)], StringComparer.Ordinal);
foreach (TrendMetricOptionViewModel option in TrendExtras)
{
option.IsEnabled = option.Metric != TrendMetric && (option.IsSelected || units.Count < 2 || units.Contains(option.Unit));
}
if (ticked.Length == 0)
{
return [new TrendLine(TrendMetricText, TrendMetricText, TrendPoints)];
}
List<TrendLine> lines = [new TrendLine(TrendMetricText, primaryUnit, TrendPoints)];
lines.AddRange(ticked.Select(o => new TrendLine(o.Label, o.Unit, TrendSeriesBuilder.Points(_detail!.Sessions, o.Metric, IncludeMidSession))));
return lines;
}
finally
{
_rebuildingExtras = false;
}
}
private bool _rebuildingExtras;
private void OnTrendExtraChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (!_rebuildingExtras && string.Equals(e.PropertyName, nameof(TrendMetricOptionViewModel.IsSelected), StringComparison.Ordinal))
{
RebuildTrendPoints();
}
}
/// <summary>beta.11 (D39): a click on the Sessions tab's overview selects that session in the grid.</summary>
public void SelectSession(long sessionId)
{
if (Sessions.FirstOrDefault(s => s.Row.Id == sessionId) is { } session)
{
SelectedSession = session;
}
}
[RelayCommand]
private void Back() => _navigator.Navigate<GamesPage>();
/// <summary>A session row opens its summary window (08_UI §Games: "Row → Session summary").</summary>
[RelayCommand]
private void OpenSession(SessionItemViewModel? session)
{
if (session is not null)
{
_summaries.Open(session.Id);
}
}
[RelayCommand]
private Task ToggleHookingAsync() => RunAsync(() => ThenShowStoredAsync(HookEnabled ? DisableAsync : EnableAsync, nameof(HookEnabled)));
[RelayCommand]
private Task ToggleRecordingAsync() => RunAsync(() => ThenShowStoredAsync(ToggleRecordingCoreAsync, nameof(RecordSessions)));
/// <summary>D33: the exception's disclosure, then the request; the Agent gathers the facts and grants or refuses.</summary>
[RelayCommand]
private Task GrantExceptionAsync() => RunAsync(GrantExceptionCoreAsync);
[RelayCommand]
private Task WithdrawExceptionAsync() => RunAsync(WithdrawExceptionCoreAsync);
[RelayCommand]
private Task ReEnableHookingAsync() => RunAsync(EnableAsync);
/// <summary>
/// beta.21 (owner decision D59): Play — through the store that installed the game, or started by the capture agent
/// (Settings ▸ Games); <see cref="GamePlayer"/> says what each does. A game whose executable is not there has none.
/// </summary>
[RelayCommand(CanExecute = nameof(CanPlay))]
private Task PlayAsync() => RunAsync(PlayCoreAsync);
[RelayCommand]
private Task EditAsync() => RunAsync(EditCoreAsync);
[RelayCommand]
private Task RemoveAsync() => RunAsync(RemoveCoreAsync);
/// <summary>beta.11 (D40): every session of this game, after the confirmation; the game, its settings and its consent stay.</summary>
[RelayCommand]
private Task DeleteAllSessionsAsync() => RunAsync(DeleteAllSessionsCoreAsync);
[RelayCommand]
private Task ChangeExecutableAsync() => RunAsync(ChangeExecutableCoreAsync);
private bool CanPlay() => _player is not null && !ExecutableMissing;
private async Task PlayCoreAsync()
{
if (_player is null || Game is not { } game)
{
return;
}
PlayResult result = await _player.PlayAsync(game).ConfigureAwait(true);
(string message, bool warning) = GamePlayer.Describe(result, game.Name);
if (warning)
{
_strip.Warn(Strings.Play_Title, message);
}
else
{
_strip.Info(Strings.Play_Title, message);
}
}
/// <summary>One action at a time, and the one in flight is <see cref="Pending"/> for a test to await.</summary>
private async Task RunAsync(Func<Task> work)
{
Task running = work();
Pending = running;
await running.ConfigureAwait(true);
}
/// <summary>
/// A switch's command, then the switch's property raised whatever happened (beta.30, the owner's report). The switch's
/// <c>IsChecked</c> is OneWay from the row, and the click has already flipped it through <c>SetCurrentValue</c>; when the
/// command leaves the row as it was — a declined dialog, a refusal, no Agent — the property is set to the value it
/// already held and raises nothing, so the switch went on showing the click: on while the text beside it said off, and
/// the next click asked to enable again. Raised unchanged, the binding reads the row again and drops the click's value.
/// </summary>
private async Task ThenShowStoredAsync(Func<Task> work, string property)
{
try
{
await work().ConfigureAwait(true);
}
finally
{
OnPropertyChanged(property);
}
}
private async Task EnableAsync()
{
if (Game is null)
{
return;
}
Busy = true;
try
{
HookingConsentResult result = await _consent.EnableAsync(Game.Id, Game.Name).ConfigureAwait(true);
Notice(result);
}
finally
{
Busy = false;
}
await LoadAsync().ConfigureAwait(true);
}
private async Task DisableAsync()
{
if (Game is null)
{
return;
}
Busy = true;
try
{
HookingConsentResult result = await _consent.DisableAsync(Game.Id).ConfigureAwait(true);
Notice(result, turningOff: true);
}
finally
{
Busy = false;
}
await LoadAsync().ConfigureAwait(true);
}
/// <summary>
/// Flips the entry's recording switch (2026-09-23). No confirmation: it deletes nothing — sessions already recorded stay,
/// and turning it back on is the same click.
/// </summary>
private async Task ToggleRecordingCoreAsync()
{
if (Game is null)
{
return;
}
await _library.SetRecordingAsync(Game.Id, !Game.RecordSessions).ConfigureAwait(true);
await LoadAsync().ConfigureAwait(true);
}
private async Task EditCoreAsync()
{
if (Game is null)
{
return;
}
// beta.23 (D60): the dialog's image row, when this page has artwork to show and somewhere to keep a chosen image.
GameArt? art = _art;
EditImage? image = art is not null && _covers is not null && _images is not null
? new EditImage(ArtCover, _artCoverIsOwn, _artStoreCover, _images, async path => await art.PreviewAsync(path, 192).ConfigureAwait(true))
: null;
GameEdit? edit = await _edit.EditAsync(GameMetadata.Of(Game), Game.FieldProvenanceJson, image).ConfigureAwait(true);
if (edit is null)
{
return;
}
GameMetadata edited = edit.Metadata;
string? before = Game.CoverPath;
if (edit.PickedImage is { } picked && _covers is not null)
{
// Copied only now that the dialog closed with Save; a file that cannot be used leaves the image the game had.
if (await _covers.ImportAsync(Game.Id, picked).ConfigureAwait(true) is { } copied)
{
edited = edited with { CoverPath = copied };
}
else
{
edited = edited with { CoverPath = before };
_strip.Warn(Strings.EditGame_Title, Strings.Art_ImportFailed);
}
}
await _library.UpdateMetadataAsync(Game.Id, edited).ConfigureAwait(true);
if (before is not null && !string.Equals(before, edited.CoverPath, StringComparison.OrdinalIgnoreCase))
{
_covers?.Delete(before);
}
_strip.Success(Strings.EditGame_Title, Strings.EditGame_Saved);
await LoadAsync().ConfigureAwait(true);
}
/// <summary>
/// A store import guesses the executable (Steam names none), and everything downstream is keyed on it: a wrong guess
/// is a game that can never be matched. The pick is the user's own; the row comes back hooking-off and unconsented,
/// exactly as a new game would, and consent is revoked over the pipe first, as removal does. The dialog opens in the
/// game's own folder (beta.19, <see cref="GameFolder"/>), asked off the UI thread.
/// </summary>
private async Task ChangeExecutableCoreAsync()
{
if (Game is null)
{
return;
}
string current = Game.Fingerprint.ExePath;
string? folder = await Task.Run(() => GameFolder.StartFolder(current)).ConfigureAwait(true);
string? path = _picker.PickExecutable(folder);
if (path is null || string.Equals(ExecutableIdentity.Normalise(path), Game.Fingerprint.ExePath, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (Game.HookEnabled)
{
await _consent.DisableAsync(Game.Id).ConfigureAwait(true);
}
bool? changed = await _library.ChangeExecutableAsync(Game.Id, path).ConfigureAwait(true);
string file = Path.GetFileName(path);
switch (changed)
{
case null:
_strip.Warn(Strings.GameDetail_ChangeExe, string.Format(CultureInfo.CurrentCulture, Strings.ChangeExe_Unreadable_Format, file));
break;
case false:
_strip.Warn(Strings.GameDetail_ChangeExe, string.Format(CultureInfo.CurrentCulture, Strings.ChangeExe_Taken_Format, file));
break;
default:
_strip.Success(Strings.GameDetail_ChangeExe, string.Format(CultureInfo.CurrentCulture, Strings.ChangeExe_Done_Format, Game.Name, file));
break;
}
await LoadAsync().ConfigureAwait(true);
}
private async Task DeleteAllSessionsCoreAsync()
{
if (Game is null || Sessions.Count == 0 || !await _confirmations.DeleteSessionsAsync(Game.Name, Sessions.Count).ConfigureAwait(true))
{
return;
}
SessionDeletionResult result = _deletion is null
? new(SessionDeletionOutcome.AgentUnavailable)
: await _deletion.DeleteAsync(Game.Id).ConfigureAwait(true);
if (!result.Succeeded)
{
_strip.Warn(Game.Name, result.Message);
if (result.Outcome == SessionDeletionOutcome.Unanswered)
{
// beta.22: the delete may have run — the page shows what is stored, not what it held before the ask.
await LoadAsync().ConfigureAwait(true);
}
return;
}
// SessionDeletion has let go of File ▸ Export's selection and the summary windows of what is gone (ids are reused).
_strip.Success(Game.Name, result.Message);
await LoadAsync().ConfigureAwait(true);
}
private async Task RemoveCoreAsync()
{
if (Game is null)
{
return;
}
RemoveGameChoice choice = await _confirmations.RemoveGameAsync(Game.Name).ConfigureAwait(true);
if (choice == RemoveGameChoice.Cancel)
{
return;
}
// Consent is revoked over the pipe first (never through the table): the row may stay, hooking must not.
if (Game.HookEnabled)
{
await _consent.DisableAsync(Game.Id).ConfigureAwait(true);
}
string name = Game.Name;
string? cover = Game.CoverPath;
bool keepSessions = choice == RemoveGameChoice.KeepSessions;
bool removed = await _library.RemoveAsync(Game.Id, keepSessions).ConfigureAwait(true);
// beta.23 (D60): a game removed with its sessions is gone, and its own image with it; one removed with its sessions
// kept comes back with them when it is added again, and keeps its image.
if (removed && !keepSessions)
{
_covers?.Delete(cover);
}
_strip.Info(Strings.Games_Header, string.Format(CultureInfo.CurrentCulture, Strings.RemoveGame_Removed_Format, name));
_navigator.Navigate<GamesPage>();
}
private async Task GrantExceptionCoreAsync()
{
if (Game is null || ExceptionView.Of(Game) is not { CanGrant: true } view)
{
return;
}
Busy = true;
try
{
AntiCheatExceptionResult result = _exceptions is null
? AntiCheatExceptionResult.Of(AntiCheatExceptionOutcome.AgentUnavailable)
: await _exceptions.GrantAsync(Game.Id, new AntiCheatExceptionFacts(Game.Name, view.Family ?? string.Empty, view.Signal ?? string.Empty))
.ConfigureAwait(true);
Notice(result, Game.Name);
}
finally
{
Busy = false;
}
await LoadAsync().ConfigureAwait(true);
}
private async Task WithdrawExceptionCoreAsync()
{
if (Game is null)
{
return;
}
Busy = true;
try
{
AntiCheatExceptionResult result = _exceptions is null
? AntiCheatExceptionResult.Of(AntiCheatExceptionOutcome.AgentUnavailable)
: await _exceptions.WithdrawAsync(Game.Id).ConfigureAwait(true);
Notice(result, Game.Name);
}
finally
{
Busy = false;
}
await LoadAsync().ConfigureAwait(true);
}
/// <summary>D33: an exception's outcome as this page's notice — a success is said, not only shown by the card changing.</summary>
private void Notice(AntiCheatExceptionResult result, string gameName)
{
NoticeText = result.MessageFor(gameName);
NoticeSeverity = result.Succeeded ? InfoBarSeverity.Success : InfoBarSeverity.Warning;
OnPropertyChanged(nameof(NoticeVisible));
}
/// <summary>
/// A refusal, a mismatch or a failure is a persistent notice on the page; a success clears it. With no Agent, turning
/// hooking off changed nothing — not "Nothing was enabled.", the enable path's words, which it said until beta.18.
/// </summary>
private void Notice(HookingConsentResult result, bool turningOff = false)
{
(NoticeText, NoticeSeverity) = result.Outcome switch
{
HookingConsentOutcome.Refused => (result.RefusalText(), InfoBarSeverity.Error),
HookingConsentOutcome.VersionMismatch => (Shared.Strings.Safety_Consent_VersionMismatch, InfoBarSeverity.Warning),
HookingConsentOutcome.AgentUnavailable => (turningOff ? Strings.Agent_NotConnected_NothingChanged : Shared.Strings.Safety_Consent_AgentUnavailable, InfoBarSeverity.Warning),
// beta.22: the page reads what is stored after every ask, so whether hooking changed is shown beside this.
HookingConsentOutcome.Unanswered => (Strings.Agent_Unanswered, InfoBarSeverity.Warning),
// The Agent could not read the executable (beta.8): say whether its drive or the file is missing, not the IPC code.
HookingConsentOutcome.Failed when string.Equals(result.Detail, Shared.Ipc.IpcErrorCode.ExecutableUnreadable, StringComparison.Ordinal) && Game is not null
=> (_executableMissingWhy ?? Formats.ExecutableMissingText(Game.Fingerprint.ExePath), InfoBarSeverity.Warning),
HookingConsentOutcome.Failed => (result.Detail ?? Strings.Common_NotAvailable, InfoBarSeverity.Warning),
_ => (null, InfoBarSeverity.Informational),
};
OnPropertyChanged(nameof(NoticeVisible));
}
private void Present(GameDetail detail)
{
GameRow row = detail.Row;
Name = row.Name;
// A store's version is said as one ("Steam build 20374416", beta.8), and then names the store itself.
bool storeVersion = EditGameViewModel.IsDetectedField(row.FieldProvenanceJson, "game_version") && row.Platform is "steam" or "gog" or "epic" or "xbox";
string?[] subtitle = storeVersion
? [row.Publisher, Formats.StoreVersion(row.Platform, row.GameVersion, detected: true) ?? Formats.Platform(row.Platform), EngineText(row)]
: [row.Publisher, row.GameVersion, Formats.Platform(row.Platform), EngineText(row)];
Subtitle = string.Join(" · ", subtitle.Where(static s => !string.IsNullOrWhiteSpace(s)));
ExecutableText = row.Fingerprint.ExePath;
ExecutableMissing = _executableMissingWhy is not null;
ExecutableMissingMessage = _executableMissingWhy is { } why ? ExecutableMissingText + " " + why : ExecutableMissingText;
SessionRow? last = detail.Sessions.Count > 0 ? detail.Sessions[0] : null;
SessionRow? lastHooked = detail.Sessions.FirstOrDefault(static s => s.Tier == CaptureTier.Hooked && s.FrameCount > 0);
LastSessionText = last is null ? string.Empty : string.Format(CultureInfo.CurrentCulture, Strings.GameDetail_LastSession_Format, Formats.Date(last.StartedAt), Formats.Api(last.Api));
Lifetime = lastHooked is null ? FpsReadoutModel.Unavailable : FpsPresentation.FromRow(lastHooked);
PresentChips(detail, lastHooked);
PresentSupports(row);
PresentDetails(detail);
PresentMeasured(last, lastHooked);
PresentRecording(row);
PresentHooking(row);
PresentSessions(detail);
}
private void PresentRecording(GameRow row)
{
RecordSessions = row.RecordSessions;
RecordingStatusText = row.RecordSessions ? Strings.GameDetail_Recording_On : Strings.GameDetail_Recording_Off;
}
private void PresentChips(GameDetail detail, SessionRow? lastHooked)
{
Chips.Clear();
foreach (TriStateKind kind in new[] { TriStateKind.RayTracing, TriStateKind.PathTracing, TriStateKind.RayReconstruction })
{
ResolvedTriState resolved = lastHooked is null
? TriStateResolution.Resolve(null, Domain.Metrics.Tri.NotApplicable, DefaultOf(detail.Row, kind))
: TriStateResolution.Resolve(kind, lastHooked, detail.Annotations.GetValueOrDefault(lastHooked.Id), detail.Row);
Chips.Add(TriStateChipModel.Of(kind, resolved));
}
}
private void PresentSupports(GameRow row)
{
Supports.Clear();
foreach (string capability in CapabilityNames(row.CapabilityFlagsJson))
{
Supports.Add(string.Format(CultureInfo.CurrentCulture, Strings.GameDetail_Supports_Format, capability));
}
SupportsEmpty = Supports.Count == 0;
// The Details card's own test: a row the sweep has read carries the executable's machine.
SupportsEmptyText = row.ExeMachine is null ? Strings.GameDetail_Supports_Empty : Strings.GameDetail_Supports_None;
}
private void PresentDetails(GameDetail detail)
{
GameRow row = detail.Row;
Details.Clear();
if (row.ExeMachine is null)
{
// Written by the Agent's detection sweep: a row it has not read under this build yet.
Details.Add(new GameDetailRow(Strings.GameDetail_Details_Architecture, Strings.GameDetail_Details_NotRead));
}
else
{
Details.Add(new GameDetailRow(Strings.GameDetail_Details_Architecture, Formats.Architecture(row.ExeMachine)));
AddDetail(Strings.GameDetail_Details_FileVersion, row.ExeFileVersion);
AddDetail(Strings.GameDetail_Details_ProductVersion, row.ExeProductVersion);
}
bool detected = EditGameViewModel.IsDetectedField(row.FieldProvenanceJson, "game_version");
AddDetail(detected ? Strings.GameDetail_Details_Store : Strings.GameDetail_Details_Version, Formats.StoreVersion(row.Platform, row.GameVersion, detected));
AddDetail(Strings.GameDetail_Details_Engine, EngineText(row));
AddDetail(Strings.GameDetail_Details_EngineVersion, EngineVersionSourceText(row));
if (row.ExeMachine is not null)
{
Details.Add(new GameDetailRow(Strings.GameDetail_Details_Libraries, row.Libraries.Count == 0
? Strings.GameDetail_Details_NoLibraries
: string.Join(Environment.NewLine, row.Libraries.Select(LibraryText))));
}
// beta.8: the NVIDIA App's overrides, as the driver profile stood at the newest session that read one (sessions
// come newest first). Nothing is shown where no session could ask — a machine without an NVIDIA driver.
if (detail.Sessions.Select(static s => Application.Recording.DriverProfileRecord.Parse(s.DriverProfileJson))
.FirstOrDefault(static p => p is not null && NvidiaOverrides.IsRead(p)) is { } profile)
{
Details.Add(new GameDetailRow(Strings.GameDetail_Details_NvidiaOverride, NvidiaOverrides.OverridesText(profile)));
}
}
private void AddDetail(string label, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
Details.Add(new GameDetailRow(label, value));
}
}
/// <summary>"DLSS: nvngx_dlss.dll 3.7.10.0" — the product the rule names, the file, and what the file says it is.</summary>
private static string LibraryText(LibraryFile library)
{
string product = CapabilityName(library.CapabilityId) is { Length: > 0 } name ? name : library.CapabilityId;
return library.FileVersion is { } version
? string.Format(CultureInfo.CurrentCulture, Strings.GameDetail_Details_Library_Format, product, library.FileName, version)
: string.Format(CultureInfo.CurrentCulture, Strings.GameDetail_Details_LibraryNoVersion_Format, product, library.FileName);
}
private void PresentMeasured(SessionRow? last, SessionRow? lastHooked)
{
Measured.Clear();
if (lastHooked is null)
{
MeasuredEmptyText = last is null ? Strings.GameDetail_Measured_Empty : Strings.GameDetail_Measured_NotHooked;
return;
}
MeasuredEmptyText = string.Empty;
string upscaler = Formats.UpscalerOf(lastHooked);
Measured.Add(upscaler + " · " + Formats.Resolution(lastHooked.RenderW, lastHooked.RenderH, lastHooked.OutputW, lastHooked.OutputH));
if (DlssText.Label(lastHooked) is { } dlss)
{
// beta.24 (D64): a DLSS generation only where the session showed one, with what it rests on.
Measured.Add(dlss);
}
Measured.Add(FpsPresentation.FrameGenerationLabel(FpsPresentation.FromRow(lastHooked), lastHooked.FgMode));
foreach (TriStateChipModel chip in Chips.Where(static c => !c.IsNotApplicable))
{
Measured.Add(chip.Text);
}
// beta.10: how that session was shown — the mode that lasted longest and the window's size.
if (DisplayText.Of(lastHooked) is { } display)
{
string window = DisplayText.Window(display);
string headline = DisplayText.Headline(display);
Measured.Add(string.Format(CultureInfo.CurrentCulture, Strings.Display_Line_Format,
string.Equals(window, Strings.Common_NotAvailable, StringComparison.Ordinal) ? headline : headline + " · " + window));
}
}
private void PresentHooking(GameRow row)
{
HookEnabled = row.HookEnabled;
bool blocked = row.BlockedByGuard;
// A blocked row's toggle is disabled because enabling it could only be refused (19_SAFETY §What a finding does
// to the game): the finding is on the page, and there is no switch that overrules it (2026-09-22).
// An executable that cannot run as x64 (beta.8): turning hooking ON could only be refused; a switch that is on
// (enabled before this build read the file) can still be turned off.
bool notX64 = ExecutableArchitecture.IsKnownNotHookable(row.ExeMachine);
// D33: a blocked game whose user-mode exception is in force (the option on, a grant on the row) may be switched on —
// through FR-2.1's dialog as ever, and the Agent's pre-scan names the family; the finding stays on the page.
ExceptionView? exception = ExceptionView.Of(row);
bool exceptionInForce = _exceptionsOn && exception is { Kind: ExceptionViewKind.Granted };
HookToggleEnabled = ActsOnThisPc && (!blocked || exceptionInForce) && !Busy && (row.HookEnabled || !notX64);
NotX64Text = notX64 && !blocked
? string.Format(CultureInfo.CurrentCulture, Strings.Hooking_NotX64_Format, Formats.Architecture(row.ExeMachine))
: null;
HookStatusText = row.HookEnabled ? Strings.GameDetail_Hooking_On : Strings.GameDetail_Hooking_Off;
string? found = blocked ? BlockedReasonText.Describe(row.HookBlockedReason ?? row.HookPrescanState) : null;
BlockedText = found is null
? null
: string.Format(CultureInfo.CurrentCulture, Shared.Strings.Safety_Blocked_Toggle_Format, found);
// beta.8 (owner request 2026-09-25): for an anti-cheat game the card is a switch that can never be turned on, so
// by default it gives way to the finding alone. The setting off keeps the card, with the finding under it.
HookingSectionVisible = !(blocked && _hideAntiCheatHooking) || exceptionInForce;
PresentException(exception, exceptionInForce);
// 2026-10-03: "cannot be turned on" beside a usable "Make exception…" contradicted itself; an eligible game's card
// says what would turn it on.
AntiCheatText = found is not null && !HookingSectionVisible
? string.Format(CultureInfo.CurrentCulture,
_exceptionsOn && exception is { Kind: ExceptionViewKind.Eligible } ? Strings.GameDetail_AntiCheat_Exceptionable_Format : Strings.GameDetail_AntiCheat_Format,
found)
: null;
// Its "Turn hooking back on" could only be refused once anti-cheat was found, or for an executable that cannot run
// as x64, so neither row offers it.
AutoDisabledText = !blocked && !notX64 && row.HookAutoDisabledReason is { Length: > 0 } reason && !row.HookEnabled
? string.Format(CultureInfo.CurrentCulture, Shared.Strings.Safety_AutoDisabled_Format, reason)
: null;
UnverifiedText = string.Equals(row.HookPrescanState, "unverified", StringComparison.Ordinal) ? Strings.GameDetail_Hooking_Unverified : null;
}
/// <summary>D33: the exception card — its state from the Agent's columns, and the one action that state allows.</summary>
private void PresentException(ExceptionView? view, bool inForce)
{
ExceptionCardVisible = view is not null && (_exceptionsOn || view.Kind == ExceptionViewKind.Granted);
ExceptionText = view?.Text;
ExceptionLapseText = view?.LapseText;
ExceptionInForceText = inForce && view?.Family is { } family
? string.Format(CultureInfo.CurrentCulture, Strings.GameDetail_Exception_Granted_Format, family)
: null;
ExceptionSuspendedText = view is { Kind: ExceptionViewKind.Granted } && !_exceptionsOn ? Strings.GameDetail_Exception_Suspended : null;
CanGrantException = _exceptionsOn && view is { CanGrant: true } && !Busy;
CanWithdrawException = view is { CanWithdraw: true } && !Busy;
}
private void PresentSessions(GameDetail detail)
{
Sessions.Clear();
foreach (SessionRow row in detail.Sessions)
{
Sessions.Add(new SessionItemViewModel(row, detail.Annotations.GetValueOrDefault(row.Id), detail.Row));
}
SessionsEmpty = Sessions.Count == 0;
}
private static string EngineText(GameRow row) => Formats.EngineWithVersion(row.Engine, row.EngineVersion, row.EngineVersionSource);
/// <summary>
/// Which witness an engine version rests on (beta.10 for Unreal, schema 0015; beta.19 for Unity, Godot and RPG Maker) —
/// said, because each witness can be wrong or short in its own way (<c>05_DETECTION</c> §Engine version). A title of
/// these engines whose files name no version says so once the sweep has read it; other engines add no line.
/// </summary>
internal static string? EngineVersionSourceText(GameRow row)
{
ArgumentNullException.ThrowIfNull(row);
return row.EngineVersionSource switch
{
EngineVersionSource.UnrealBranchAndFile => Strings.GameDetail_EngineVersion_BranchAndFile,
EngineVersionSource.UnrealBranch => Strings.GameDetail_EngineVersion_Branch,
EngineVersionSource.UnrealFileVersion => Strings.GameDetail_EngineVersion_FileVersion,
EngineVersionSource.UnityPlayer => Strings.GameDetail_EngineVersion_UnityPlayer,
EngineVersionSource.UnityData => Strings.GameDetail_EngineVersion_UnityData,
EngineVersionSource.UnityPlayerFile => Strings.GameDetail_EngineVersion_UnityPlayerFile,
EngineVersionSource.GodotPack => Strings.GameDetail_EngineVersion_GodotPack,
EngineVersionSource.GodotPackEmbedded => Strings.GameDetail_EngineVersion_GodotPackEmbedded,
EngineVersionSource.GodotExe => Strings.GameDetail_EngineVersion_GodotExe,
EngineVersionSource.RpgMakerMzCore => string.Format(CultureInfo.CurrentCulture, Strings.GameDetail_EngineVersion_CoreScript_Format, "js/rmmz_core.js"),
EngineVersionSource.RpgMakerMvCore => string.Format(CultureInfo.CurrentCulture, Strings.GameDetail_EngineVersion_CoreScript_Format, "rpg_core.js"),
EngineVersionSource.Rgss1Library or EngineVersionSource.Rgss2Library or EngineVersionSource.Rgss3Library => Strings.GameDetail_EngineVersion_Rgss,
EngineVersionSource.RenPyVcVersion => Strings.GameDetail_EngineVersion_RenPyVcVersion,
null when string.Equals(row.Engine, "unreal", StringComparison.Ordinal) && row.EngineVersion is null && row.ExeMachine is not null
=> Strings.GameDetail_EngineVersion_NotFound,
null when row.Engine is "unity" or "godot" or "rpgmaker_mv" or "rpgmaker_rgss" or "renpy" && row.EngineVersion is null && row.ExeMachine is not null
=> Strings.GameDetail_EngineVersion_NotFoundInFiles,
_ => null,
};
}
private static Domain.Metrics.Tri DefaultOf(GameRow row, TriStateKind kind) => kind switch
{
TriStateKind.RayTracing => row.RtDefault,
TriStateKind.PathTracing => row.PtDefault,
_ => row.RrDefault,
};
/// <summary>
/// <c>capability_flags</c> (<c>05_DETECTION</c> §Capability hints): an array of the rule ids the Agent's detection sweep
/// writes (P4 PR-1 — <c>dlss</c>, <c>dlss_g</c>, <c>dlss_rr</c>, <c>streamline</c>, <c>fsr</c>, <c>xess</c>, <c>xefg</c>), or
/// an object of flags in the older spelling, → product names. An unreadable value is no chips.
/// </summary>
internal static IReadOnlyList<string> CapabilityNames(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
IEnumerable<string> tokens = json.AsSpan().TrimStart().StartsWith('[')
? JsonSerializer.Deserialize(json, AppJsonContext.Default.StringArray) ?? []
: (JsonSerializer.Deserialize(json, AppJsonContext.Default.DictionaryStringBoolean) ?? new Dictionary<string, bool>(StringComparer.Ordinal)).Where(static kv => kv.Value).Select(static kv => kv.Key);
return [.. tokens.Select(CapabilityName).Where(static n => n.Length > 0)];
}
catch (JsonException)
{
return [];
}
}
internal static string CapabilityName(string token) => token switch
{
"dlss" => "DLSS",
"dlssg" or "dlss_g" => "DLSS-G",
"dlssd" or "dlss_rr" => "DLSS Ray Reconstruction",
"dlss_nr" => "DLSS 5 Neural Rendering",
"streamline" => "Streamline",
"vulkan" => "Vulkan",
"fsr" => "FSR",
"fsrfg" => "FSR Frame Generation",
"xess" => "XeSS",
"xefg" => "XeFG",
"reflex" => "Reflex",
_ => string.Empty,
};
}