Files
frameledger/tests/FrameLedger.App.Tests/CoverStoreTests.cs
poli0981andClaude Opus 5.5 fb0ee60fa0 feat(app): a game's page shows its artwork - your own image, else what the Steam or GOG GALAXY app keeps on this PC - in a band coloured from it (beta.23 PR-3) (#310)
The owner asked for a game's cover and hero art on its page, its colour optionally
carried into the page (2026-10-14), and chose: images already on the PC only, a banner
with a portrait cover, the colour on by default.

D60 - where the artwork comes from:
- The image the user chooses in Edit... > Choose image..., copied only once the dialog
  closed with Save (Cancel leaves nothing) as a PNG no larger than 1200 px a side, to
  the data folder's covers\game-<id>-<unix ms>.png - a new name for each choice, so a
  shown file is never written over - and named in games.cover_path relative to the data
  folder. A cover_path is followed only when it is one of those names, in that folder
  and never through a junction or a symbolic link: a viewer's copy of a ledger may come
  from anywhere, and a rooted, share (\\host\...) or .. path is never opened. "Use the
  store's image" deletes the copy, as removing a game with its sessions does; at start
  the App deletes the copies no row names (its own folder only, never a viewer's).
- Else what the store's app keeps: Steam's appcache\librarycache\<appid>\ (flat, or in
  hash-named folders - library_600x900[_2x], library_capsule, library_hero, header,
  library_header; the newest copy wins) and GOG GALAXY's webcache\<user>\gog\<id>\
  (WebP). Which store installed the game is asked of the stores' own records as Play
  asks (StoreRecords.Owning over Steam's and GOG's, kept two minutes), never of the
  row's platform alone; store ids are digits only. Epic's and itch's apps keep no image
  files.
- Found, decoded (no larger than the page needs, frozen, the twelve latest kept) and
  coloured on the thread pool: the page's text is there first. Nothing is downloaded; privacy.online_metadata
  stays reserved.

D61 - the band's colour: the artwork's dominant colour (a hue histogram of a 48 px copy,
greys and near-black or near-white skipped) over the card's fill, at the strongest
opacity - at most 30 % on the dark theme, 22 % on the light - at which every text the
header shows still reads: primary and secondary 4.5:1, tertiary 3:1, the pills' and the
warning's text 4.5:1 on their fills. Controls/ArtTint follows a theme switch through a
resource reference on the band (ApplicationThemeManager.Changed is raised by Apply
alone); no tint in high contrast; no text is ever drawn on a picture.

Settings > Games: "Show game artwork" (ui.game_art) and "Colour the game page from its
artwork" (ui.game_art_tint), both on. Strings in en, vi and ja (ja marked for review).

Caught in a render of the page before this commit: the cover's own Style was not based
on WPF UI's DefaultImageStyle, so the ui:Image had no template and drew nothing beside a
banner that drew. PagesLoadTests.TheGamePagesArtworkIsDrawn and
AccessibilityTests.NoStyleOfAWpfUiControlLeavesOutItsTemplate both ran red first;
16_WPFUI_SYNTAX's Gotchas list has it.

Docs: Privacy Policy 2.11 (section 1: the images you choose; section 4: the store apps'
images, and their records read when a game's page opens) with legal-drift-history,
TRADEMARKS, THIRD_PARTY_NOTICES, LIMITATIONS (Game artwork), 08_UI, 16_WPFUI_SYNTAX,
06_DATA_MODEL, 01_ARCHITECTURE, 02_SPEC FR-1.3, 05_DETECTION, 12_BUILD,
20_OPEN_QUESTIONS (Cover art closed), guide 05/07/08, wiki App-UI-development, CHANGELOG.

Tests: StoreArtCachesTests (both Steam layouts, the better cover and the newest copy,
ids of another shape, nothing there, several GOG users), ColorMathTests (agrees with the
tests' own WCAG; the hardest colours keep every pair readable in both themes),
GameArtTests (source order, a missing own image, the D59 owning rule, off in Settings
reads nothing, a cover_path not ours, a damaged file, records read once),
CoverStoreTests (a new name each choice, a non-image leaves nothing, tidying keeps a
removed row's image, deleting follows our names only, a covers junction is never
followed), EditGameViewModelTests, GameDetailViewModelTests, PagesLoadTests (the band
readable in both themes and through a switch; the edit dialog's image row; the artwork
drawn).
Local gate: ALL GATES PASSED in 282 s; the artwork classes 20 times green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 00:08:58 +07:00

150 lines
7.2 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Diagnostics;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.Application.Persistence;
namespace FrameLedger.App.Tests;
/// <summary>
/// beta.23 (owner decision D60): the images users choose for their games — a re-encoded copy in the data folder's
/// <c>covers</c>, a new name for each choice — and the tidying that deletes the ones no row names any more.
/// </summary>
public sealed class CoverStoreTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-covers-" + Guid.NewGuid().ToString("N"));
public CoverStoreTests() => Directory.CreateDirectory(_dir);
public void Dispose()
{
// A junction a test made goes on its own first: met inside a recursive delete, it is unmounted as a volume would be,
// which Windows refuses without elevation (UnauthorizedAccessException) — though the link itself is then removed.
var covers = new DirectoryInfo(Path.Combine(Data, "covers"));
if (covers.Exists && covers.LinkTarget is not null)
{
covers.Delete();
}
Directory.Delete(_dir, recursive: true);
}
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private string Data => Path.Combine(_dir, "data");
[Fact]
public async Task APickedImageIsCopiedAsAPngNoLargerThan1200PixelsUnderANewName()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var store = new CoverStore(new UiMode(false, Data), s.Games);
string picked = TestImages.Write(Path.Combine(_dir, "mine.png"), TestImages.Png(1600, 2400, Color.FromRgb(10, 120, 200)));
string first = (await store.ImportAsync(7, picked, Ct))!;
string second = (await store.ImportAsync(7, picked, Ct))!;
first.Should().MatchRegex(@"^covers\\game-7-\d+\.png$");
second.Should().NotBe(first, "each choice is a new file, so a shown image is never written over");
string full = CoverStore.Resolve(Data, first)!;
BitmapFrame copy = BitmapDecoder.Create(new Uri(full), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0];
copy.PixelHeight.Should().Be(1200);
copy.PixelWidth.Should().Be(800);
Directory.EnumerateFiles(Path.Combine(Data, "covers"), "*.tmp").Should().BeEmpty();
File.Exists(picked).Should().BeTrue("the user's own file is read, never moved");
}
[Fact]
public async Task AFileThatIsNotAnImageIsRefusedAndLeavesNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var store = new CoverStore(new UiMode(false, Data), s.Games);
string notAnImage = TestImages.Write(Path.Combine(_dir, "notes.png"), "not an image"u8.ToArray());
(await store.ImportAsync(7, notAnImage, Ct)).Should().BeNull();
(Directory.Exists(Path.Combine(Data, "covers")) ? Directory.EnumerateFiles(Path.Combine(Data, "covers")) : []).Should().BeEmpty();
}
[Fact]
public async Task TidyingDeletesWhatNoRowNamesAndKeepsWhatARemovedRowStillOwns()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow kept = await s.GameAsync("Kept");
GameRow removed = await s.GameAsync("Removed");
string covers = Path.Combine(Data, "covers");
string keptFile = "game-" + kept.Id + "-100.png";
string removedFile = "game-" + removed.Id + "-100.png";
foreach (string name in new[] { keptFile, removedFile, "game-" + kept.Id + "-99.png", "game-999999-1.png", "readme.txt" })
{
_ = TestImages.Write(Path.Combine(covers, name), [1]);
}
string stale = TestImages.Write(Path.Combine(covers, "game-" + kept.Id + "-98.png.tmp"), [1]);
File.SetLastWriteTimeUtc(stale, DateTime.UtcNow.AddHours(-2));
string fresh = TestImages.Write(Path.Combine(covers, "game-" + kept.Id + "-101.png.tmp"), [1]);
await s.Games.UpdateMetadataAsync(kept.Id, GameMetadata.Of(kept) with { CoverPath = "covers\\" + keptFile }, Ct);
await s.Games.UpdateMetadataAsync(removed.Id, GameMetadata.Of(removed) with { CoverPath = "covers\\" + removedFile }, Ct);
(await s.Games.RemoveAsync(removed.Id, keepSessions: true, Ct)).Should().BeTrue();
int deleted = await new CoverStore(new UiMode(false, Data), s.Games).PruneAsync(Ct);
deleted.Should().Be(3, "the replaced image, the deleted game's, and the copy half-written two hours ago");
Directory.EnumerateFiles(covers).Select(Path.GetFileName).Should().BeEquivalentTo([keptFile, removedFile, "readme.txt", Path.GetFileName(fresh)],
"a row removed with its sessions kept comes back with its image; another file's name is not ours to touch");
}
[Fact]
public async Task DeletingFollowsOnlyOurOwnNames()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var store = new CoverStore(new UiMode(false, Data), s.Games);
string outside = TestImages.Write(Path.Combine(_dir, "precious.png"), [1]);
string ours = TestImages.Write(Path.Combine(Data, "covers", "game-3-4.png"), [1]);
store.Delete("covers\\..\\..\\precious.png");
store.Delete(outside);
store.Delete("covers\\game-3-4.png");
File.Exists(outside).Should().BeTrue();
File.Exists(ours).Should().BeFalse();
}
/// <summary>A <c>covers</c> folder that is a junction leads to another place: nothing behind it is shown, deleted, written or tidied.</summary>
[Fact]
public async Task ACoversFolderThatIsALinkIsNeverFollowed()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
string elsewhere = Path.Combine(_dir, "elsewhere");
string there = TestImages.Write(Path.Combine(elsewhere, "game-" + game.Id + "-1.png"), TestImages.Png(4, 4, Color.FromRgb(200, 30, 30)));
_ = Directory.CreateDirectory(Data);
Junction(Path.Combine(Data, "covers"), elsewhere);
var store = new CoverStore(new UiMode(false, Data), s.Games);
string picked = TestImages.Write(Path.Combine(_dir, "mine.png"), TestImages.Png(4, 4, Color.FromRgb(10, 120, 200)));
CoverStore.Resolve(Data, "covers\\" + Path.GetFileName(there)).Should().BeNull("the folder is a link");
store.Delete("covers\\" + Path.GetFileName(there));
(await store.ImportAsync(game.Id, picked, Ct)).Should().BeNull("no image is written through a link");
(await store.PruneAsync(Ct)).Should().Be(0);
Directory.EnumerateFiles(elsewhere).Should().BeEquivalentTo([there], "nothing behind the link was deleted or written");
}
private static void Junction(string link, string target)
{
var start = new ProcessStartInfo("cmd.exe") { CreateNoWindow = true, UseShellExecute = false };
foreach (string arg in new[] { "/c", "mklink", "/J", link, target })
{
start.ArgumentList.Add(arg);
}
using Process mklink = Process.Start(start)!;
mklink.WaitForExit();
mklink.ExitCode.Should().Be(0, "a junction needs no privilege");
}
}