* refactor(core)!: v2 capture model, settings v3, profiles, coordinator
- remove the WinUI projects (replaced by WPF in this branch); resx files and
ResxLocalizationService move to ViewModels so they stay framework-agnostic
- capture model: CaptureMode (Window/Region/Monitor), CaptureSource,
CaptureOptions, MonitorInfo/HdrInfo, PixelRect; frames carry a pixel format
(BGRA8 or scRGB FP16) so HDR captures flow through the pipeline
- HdrToneMapper (scRGB -> sRGB with a C1-continuous highlight shoulder),
FrameOperations (crop, force opaque)
- AppSettings v3: one hotkey per mode, HDR/PNG/cursor/window-frame options,
start-with-Windows, arm-on-startup, game profiles; unknown fields round-trip
via JsonExtensionData; SettingsMigrator moves v1/v2 files forward
- GameProfile + ProfileResolver (exe path > exe name > Steam AppId)
- FileNameStrategy: fixed Windows-invalid set, strips bidi/zero-width
characters, guards CON/NUL/COM1..., caps length, working {counter}, {Mode}
- CaptureFileWriter: encode off-thread to .tmp, move without overwrite, retry on
name races, optional JPEG XR HDR sidecar
- CaptureCoordinator replaces the Stateless state machine and the duplicated
save pipeline in DashboardViewModel: one capture at a time (busy requests are
ignored instead of throwing), cancellable countdown/selection/preview,
frozen-snapshot region capture across monitors, profile auto-arm
- interfaces for the WinEvent watcher, RegisterHotKey service, display/HDR
info, region selector, library, shell, sound, autostart, diagnostics
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(infra)!: RegisterHotKey, WinEvent watcher, WGC monitor/HDR capture, WIC
- hotkeys: Win32 RegisterHotKey on a dedicated message-loop thread (no global
keyboard *and mouse* hook any more), MOD_NOREPEAT, real conflict detection,
temporary keys for the region overlay; SharpHook and HotkeyConflictSniffer gone
- window list: SetWinEventHook (create/destroy/show/hide/rename/minimize/
foreground) replaces WMI polling every 2 s; TargetCatalog runs off the UI thread,
skips cloaked windows and reads exe paths with QueryFullProcessImageName (works
for elevated games); bounded LRU icon cache
- DisplayService: monitors in physical pixels with DPI, HDR state per output via
IDXGIOutput6 on every adapter, SDR white level via DisplayConfig
- WgcCaptureEngine: window and monitor sources, BGRA8 or FP16 HDR, client-area /
ContentSize crop on the GPU, cancellable timeout, late frames disposed, device
lost -> recreate and retry once, no RCW leaks (vtable interop), safe readback
- encoders: SkiaSharp (PNG with selectable zlib level, JPEG 4:4:4 at q>=90, WebP)
without extra copies or premultiplied-alpha transparency; WIC for TIFF and the
JPEG XR HDR sidecar
- JsonSettingsStore v3: real atomic replace, serialized writes, backups of
corrupt/older/newer files, v1 file adopted from the install folder, validated
import that rejects UNC output folders
- CaptureLibraryService (index + WIC thumbnails + Recycle Bin), ShellService,
SoundService, PerformanceModeService (EcoQoS), AutostartService,
DiagnosticsExporter, OCR from BGRA frames with cached engines, Velopack 1.2
WaitExitThenApplyUpdates, log path redaction, VDF depth limit
- packages: + Microsoft.Windows.CsWin32 (build-time), Vortice.Direct2D1 (WIC);
- SharpHook, Stateless, System.Management, System.IO.Abstractions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(viewmodels)!: v2 view models for the WPF shell
Rewrite the view-model layer against the v2 Core abstractions, with no
framework or OS calls inside view models:
- Shell (tray tooltip, arm/disarm, capture per mode, exit through
IAppLifetime), Dashboard (in-place window list refreshed by WinEvent
notifications only while visible, target lock, per-hotkey status),
Library (lazy thumbnails, filters, copy/OCR/pin/delete to Recycle Bin),
Profiles (editor, create from a Dashboard window), Settings (write-
through, per-mode hotkey recorder with conflict checks, import/export,
reset, diagnostics), Logs (batched, paused, filtered), Update (localized
status, cancellable check/download, apply on exit), About, Preview.
- Coordinator gains SuspendHotkeys() so the recorder receives combinations
that are currently registered.
- IImageDecoder + WIC implementation for library copy/OCR/pin.
- Localization service uses source-generated logging, narrows its catch
and can match the OS language to a shipped culture.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(ui)!: WPF + WPF UI shell, tray, overlays and 11-language strings
Replace the WinUI 3 front end with WPF on .NET 10 and WPF UI 4.3:
- CaptureImage.UI: FluentWindow + NavigationView (Dashboard, Library,
Profiles, Settings, Logs, Update, About) with pages resolved from DI,
{loc:Tr} live localization, RTL + per-window language, WPF UI themes
(System/Light/Dark/High contrast), snackbar in the window and
non-activating, capture-excluded toast pop-ups when it isn't in front.
- Region selection: one frozen overlay per monitor placed in physical
pixels at the monitor's DPI; Esc/Enter also registered as temporary
hotkeys so they work while a game holds the keyboard.
- Preview window, pinned thumbnails, clipboard (bitmap + PNG), dialogs,
hotkey recorder (Alt combos, Print Screen key-up).
- Tray icon (H.NotifyIcon.Wpf) with an armed indicator; re-added after
Explorer restarts.
- CaptureImage.App: Velopack hooks first, per-user single instance over a
CurrentUserOnly pipe, Serilog (async file + in-memory, user paths
redacted), validated container, --data-dir / --instance-id /
--minimized / --smoke-test / --screenshots, PerMonitorV2 + long paths
manifest, multi-size app icon, commit recorded for "2.0.0 (abc1234)".
- Strings: 306 keys translated into all 11 languages; tests compare key
sets per culture without fallback, check placeholders and that every
key the code uses exists and every key is used.
- Settings records keep unknown JSON fields with a settable
ExtensionData (the source generator can't bind init-only ones).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(ui)!: view-model and FlaUI suites, WPF publish smoke, stricter analyzers
- 135 view-model tests (settings write-through and reload, hotkey recorder
with suspension, conflicts and validation, in-place window list,
profiles, library filters and delete, log viewer batching, update flow,
shell tray state, About links and third-party coverage, preview/OCR).
- CaptureImage.App.UiTests: FlaUI end-to-end tests against the real exe
with a temporary data folder and instance id (navigation, arming,
language switch, Arabic RTL, hotkey recorder, hide to tray + second
launch). They skip unless CAPTUREIMAGE_UI_TESTS=1; new `ui-tests` job.
- CI publish-smoke publishes framework-dependent, runs --smoke-test with
page screenshots (uploaded as an artifact) and checks the payload;
deadcode now covers the UI and App projects.
- Release: framework-dependent publish + smoke test, vpk --framework
net10-x64-desktop and --icon. Package .pdb/.xml stay out of the
installer (publish 143 MB -> 51 MB, Setup ~28 MB).
- src/ builds with AnalysisMode=Recommended (warnings are errors);
CA1716/CA1873 off with reasons, CA1822 off for bound view models.
- Test projects moved to the "tests" solution folder; Dependabot groups
and the license ignore list follow the new dependencies.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: redundant casts and an unused P/Invoke result found by InspectCode
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(ui): hide and exit after Closing returns; let sign-out close the app
Hiding or shutting down from inside Window.Closing can throw ("while a
Window is closing"), and tray Exit / Windows sign-out went through
Application.Shutdown without allowing the main window to close. Defer the
hide/exit, route IAppLifetime through App.RequestExit and allow close on
SessionEnding.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(changelog): v2.0 notes under Unreleased
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(logging): render enums without JSON quotes in the log file and viewer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(app): give the startup and shutdown log lines a source context
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(ui): drop the sleep-and-retry temp cleanup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(ui): keep running when the tray icon can't be created
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(infra): extract window icons with Win32 and WIC instead of System.Drawing
IconExtractor now takes the executable's own 48 px icon with SHDefExtractIcon
(falling back to the shell icon from SHGetFileInfo) and encodes it to PNG with
the WIC factory the app already uses. That removes the last System.Drawing.Common
reference and its central pin, which NuGet's package pruning resolved differently
on Linux than on Windows and broke the locked restore of the audit and license jobs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(ui): expose pages to UI Automation as named panes
WPF creates no automation peer for Page, so the pages' automation ids and titles
never reached UI Automation: screen readers had no region to announce and the UI
tests could not find a page. Each page now creates a pane peer named after its
localized title.
The language UI test also waits for the debounced settings write instead of
reading settings.json once, which raced on the CI runner.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(core): v2 Core test suite
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* ci: run the audit and license checks on Windows runners
NuGet prunes the WPF projects' Windows Desktop packages (System.Drawing.Common,
System.Diagnostics.EventLog, ...) only when restoring on Windows, so a locked
restore on Linux could never match the lock files. Both jobs now restore exactly
like the build job. The license job's restore is split so a failed package
restore can't be masked by the tool restore that follows it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs: v2 README, contributor guides, legal texts and contacts
- README, ARCHITECTURE, RELEASING, dev_env and pc_spec (+ Vietnamese) describe the WPF app,
per-mode hotkeys, library, profiles, HDR, the framework-dependent installer and the new data
folder; new screenshots rendered from seeded demo data (no personal windows or paths).
- PRIVACY, TERMS, DISCLAIMER, THIRD_PARTY_NOTICES and NOTICE match what v2 does and ships
(clipboard, OCR, WinEvent hook, named pipe, library index, autostart, diagnostics export).
- New CONTRIBUTING, CODE_OF_CONDUCT, SUPPORT and CODEOWNERS; issue and PR templates updated.
- Contacts: contact@poli0981.dev and https://poli0981.dev/links, plus the role aliases
(security@, privacy@, legal@, copyright@, dmca@, takedown@, code@, sponsor@, games@, collab@,
press@) where each one belongs.
- CLAUDE.md covers the v2 layout, required checks, release steps, the Windows-only restore and
how README screenshots are made.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(infra): v2 Infrastructure test suite
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: address the SonarCloud findings on the v2 branch
- S2190: LocalizationSource.FlowDirection shared its name with the FlowDirection enum it
returns, which reads as a recursive property; it is now CurrentFlowDirection.
- S8949: the coordinator's hotkey and auto-arm paths pass CancellationToken.None explicitly
(a hotkey capture has no caller to cancel it; CancelCurrent() still stops it).
- S6640: unsafe code is how the Infrastructure assembly talks to Win32, Direct3D and WinRT; the
rule is acknowledged once for that assembly with a justification instead of per call site.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
442 lines
15 KiB
C#
442 lines
15 KiB
C#
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
// Copyright (c) CaptureImage Contributors
|
|
|
|
using System.Globalization;
|
|
using System.Text;
|
|
using AwesomeAssertions;
|
|
using CaptureImage.Core.Capture;
|
|
using CaptureImage.Core.Models;
|
|
using CaptureImage.Core.Pipeline;
|
|
using CaptureImage.Core.Tests.TestSupport;
|
|
using Xunit;
|
|
|
|
namespace CaptureImage.Core.Tests.Pipeline;
|
|
|
|
public class FileNameStrategyTests
|
|
{
|
|
private const string Template = "{Game}_{yyyy}-{MM}-{dd}_{HH}-{mm}-{ss}";
|
|
private const string ExpectedStem = "Notepad_2026-04-15_19-30-45";
|
|
|
|
private static readonly DateTimeOffset FixedTime = new(2026, 4, 15, 19, 30, 45, TimeSpan.Zero);
|
|
|
|
/// <summary>Never touched on disk: every test injects its own existence check.</summary>
|
|
private static readonly string OutputDir = Path.Combine("out", "captures");
|
|
|
|
private static GameTarget Notepad(string title = "Notepad", string process = "notepad") =>
|
|
TestTargets.Game(title: title, processName: process, executablePath: @"C:\Windows\System32\notepad.exe");
|
|
|
|
private static string Expected(string fileName) => Path.Combine(OutputDir, fileName);
|
|
|
|
// ---- ExpandTokens ---------------------------------------------------------------------
|
|
|
|
[Fact]
|
|
public void ExpandTokens_ReplacesEveryToken()
|
|
{
|
|
var result = FileNameStrategy.ExpandTokens(
|
|
"{Game}|{Process}|{Mode}|{yyyy}|{MM}|{dd}|{HH}|{mm}|{ss}|{counter}",
|
|
Notepad(title: "Super Mario", process: "mario"),
|
|
CaptureMode.Region,
|
|
FixedTime,
|
|
"_7");
|
|
|
|
result.Should().Be("Super Mario|mario|Region|2026|04|15|19|30|45|_7");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("{Game}", "Super Mario")]
|
|
[InlineData("{Process}", "mario")]
|
|
[InlineData("{Mode}", "Monitor")]
|
|
[InlineData("{yyyy}", "0999")]
|
|
[InlineData("{MM}", "01")]
|
|
[InlineData("{dd}", "02")]
|
|
[InlineData("{HH}", "03")]
|
|
[InlineData("{mm}", "04")]
|
|
[InlineData("{ss}", "05")]
|
|
[InlineData("{counter}", "_3")]
|
|
public void ExpandTokens_EachTokenIsZeroPaddedAndInvariant(string template, string expected)
|
|
{
|
|
var time = new DateTimeOffset(999, 1, 2, 3, 4, 5, TimeSpan.Zero);
|
|
|
|
FileNameStrategy.ExpandTokens(template, Notepad("Super Mario", "mario"), CaptureMode.Monitor, time, "_3")
|
|
.Should().Be(expected);
|
|
}
|
|
|
|
[Fact]
|
|
public void ExpandTokens_UsesTheCaptureTimeAsGiven()
|
|
{
|
|
// The coordinator passes local time; the name must show that wall clock, not UTC.
|
|
var local = new DateTimeOffset(2026, 4, 15, 23, 30, 45, TimeSpan.FromHours(7));
|
|
|
|
FileNameStrategy.ExpandTokens("{dd} {HH}", null, CaptureMode.Window, local, string.Empty).Should().Be("15 23");
|
|
}
|
|
|
|
[Fact]
|
|
public void ExpandTokens_WithoutTarget_UsesTheModeName()
|
|
{
|
|
FileNameStrategy.ExpandTokens("{Game}-{Process}", null, CaptureMode.Monitor, FixedTime, string.Empty)
|
|
.Should().Be("Monitor-Monitor");
|
|
}
|
|
|
|
[Fact]
|
|
public void ExpandTokens_UntitledWindow_UsesTheProcessName()
|
|
{
|
|
FileNameStrategy.ExpandTokens("{Game}", Notepad(title: " "), CaptureMode.Window, FixedTime, string.Empty)
|
|
.Should().Be("notepad");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("{Game}_{unknown}_suffix", "Notepad_{unknown}_suffix")]
|
|
[InlineData("{GAME}{game}{ Game }", "{GAME}{game}{ Game }")]
|
|
[InlineData("{Game", "{Game")]
|
|
[InlineData("Game}", "Game}")]
|
|
[InlineData("{}", "{}")]
|
|
[InlineData("{{Game}}", "{Notepad}")]
|
|
[InlineData("{Game}{", "Notepad{")]
|
|
[InlineData("{Game}{counter}", "Notepad")]
|
|
[InlineData("no tokens", "no tokens")]
|
|
public void ExpandTokens_UnknownOrMalformedTokensStayVerbatim(string template, string expected)
|
|
{
|
|
FileNameStrategy.ExpandTokens(template, Notepad(), CaptureMode.Window, FixedTime, string.Empty).Should().Be(expected);
|
|
}
|
|
|
|
// ---- Sanitize ---------------------------------------------------------------------------
|
|
|
|
[Theory]
|
|
[InlineData("a<b")]
|
|
[InlineData("a>b")]
|
|
[InlineData("a:b")]
|
|
[InlineData("a\"b")]
|
|
[InlineData("a/b")]
|
|
[InlineData("a\\b")]
|
|
[InlineData("a|b")]
|
|
[InlineData("a?b")]
|
|
[InlineData("a*b")]
|
|
public void Sanitize_InvalidCharacter_BecomesUnderscore(string raw)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be("a_b");
|
|
}
|
|
|
|
[Fact]
|
|
public void Sanitize_RunOfInvalidCharacters_BecomesOneUnderscore()
|
|
{
|
|
FileNameStrategy.Sanitize(@"My<Game>:""/\|?*Name").Should().Be("My_Game_Name");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("a\u0000b")]
|
|
[InlineData("a\u0001b")]
|
|
[InlineData("a\u001Fb")]
|
|
[InlineData("a\u007Fb")]
|
|
[InlineData("a\u0080b")]
|
|
[InlineData("a\u009Fb")]
|
|
public void Sanitize_ControlCharacter_BecomesUnderscore(string raw)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be("a_b");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("a\u202Eb")] // RIGHT-TO-LEFT OVERRIDE
|
|
[InlineData("a\u202Db")] // LEFT-TO-RIGHT OVERRIDE
|
|
[InlineData("a\u2066b")] // LEFT-TO-RIGHT ISOLATE
|
|
[InlineData("a\u200Bb")] // ZERO WIDTH SPACE
|
|
[InlineData("a\u200Db")] // ZERO WIDTH JOINER
|
|
[InlineData("a\u200Eb")] // LEFT-TO-RIGHT MARK
|
|
[InlineData("a\uFEFFb")] // ZERO WIDTH NO-BREAK SPACE (BOM)
|
|
[InlineData("a\u00ADb")] // SOFT HYPHEN
|
|
public void Sanitize_InvisibleFormattingCharacter_BecomesUnderscore(string raw)
|
|
{
|
|
CharUnicodeInfo.GetUnicodeCategory(raw[1]).Should().Be(UnicodeCategory.Format);
|
|
|
|
FileNameStrategy.Sanitize(raw).Should().Be("a_b");
|
|
}
|
|
|
|
[Fact]
|
|
public void Sanitize_BidiOverride_CannotDisguiseTheName()
|
|
{
|
|
// "photo<RLO>gnp.exe" renders as "photoexe.png" in Explorer.
|
|
var result = FileNameStrategy.Sanitize("photo\u202Egnp.exe");
|
|
|
|
result.Should().Be("photo_gnp.exe");
|
|
result.Should().NotContain("\u202E");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("A B\t\tC", "A B C")]
|
|
[InlineData("A \t\r\n B", "A B")]
|
|
[InlineData(" Elden Ring ", "Elden Ring")]
|
|
[InlineData("A\u00A0\u3000B", "A B")] // no-break space, ideographic space
|
|
[InlineData("A\u0085B", "A B")] // NEXT LINE is whitespace, not a control to escape
|
|
public void Sanitize_WhitespaceRunsCollapseToOneSpace(string raw, string expected)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be(expected);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("A <B", "A B")]
|
|
[InlineData("A< B", "A_B")]
|
|
[InlineData("A <> B", "A B")]
|
|
public void Sanitize_SpacesAndReplacementsShareOneSeparator(string raw, string expected)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be(expected);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("..name..", "name")]
|
|
[InlineData("__name__", "name")]
|
|
[InlineData(" _.name._ ", "name")]
|
|
[InlineData("name.", "name")]
|
|
[InlineData("<name>", "name")]
|
|
public void Sanitize_TrimsSpacesUnderscoresAndDotsAtTheEnds(string raw, string expected)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be(expected);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("Ōkami — 大神")]
|
|
[InlineData("GG 🎮")]
|
|
[InlineData("Half-Life 2 (2004) [v1.0]")]
|
|
public void Sanitize_KeepsOrdinaryUnicode(string raw)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be(raw);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("CON", "CON_")]
|
|
[InlineData("con", "con_")]
|
|
[InlineData("Nul", "Nul_")]
|
|
[InlineData("PRN", "PRN_")]
|
|
[InlineData("AUX", "AUX_")]
|
|
[InlineData("COM0", "COM0_")]
|
|
[InlineData("COM1", "COM1_")]
|
|
[InlineData("com9", "com9_")]
|
|
[InlineData("LPT1", "LPT1_")]
|
|
[InlineData("LPT9", "LPT9_")]
|
|
[InlineData("COM¹", "COM¹_")]
|
|
[InlineData("COM³", "COM³_")]
|
|
[InlineData("LPT¹", "LPT¹_")]
|
|
[InlineData("LPT²", "LPT²_")]
|
|
[InlineData("NUL ", "NUL_")]
|
|
[InlineData("nul.txt", "nul.txt_")]
|
|
[InlineData("con.tar.gz", "con.tar.gz_")]
|
|
[InlineData("AUX .png", "AUX .png_")]
|
|
public void Sanitize_ReservedDeviceName_GetsASuffix(string raw, string expected)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be(expected);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("CONSOLE")]
|
|
[InlineData("COM10")]
|
|
[InlineData("LPT")]
|
|
[InlineData("Con Air")]
|
|
[InlineData("xNUL")]
|
|
[InlineData("NULL")]
|
|
public void Sanitize_NamesThatOnlyResembleDevices_AreUnchanged(string raw)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be(raw);
|
|
}
|
|
|
|
[Fact]
|
|
public void Sanitize_CapsTheLength()
|
|
{
|
|
FileNameStrategy.Sanitize(new string('a', 200)).Should().Be(new string('a', FileNameStrategy.MaxNameLength));
|
|
FileNameStrategy.Sanitize(new string('b', 120)).Should().HaveLength(120);
|
|
FileNameStrategy.MaxNameLength.Should().Be(120);
|
|
}
|
|
|
|
[Fact]
|
|
public void Sanitize_TrimsSeparatorsLeftAtTheCut()
|
|
{
|
|
var raw = new string('a', 119) + " tail";
|
|
|
|
FileNameStrategy.Sanitize(raw).Should().Be(new string('a', 119));
|
|
}
|
|
|
|
[Fact]
|
|
public void Sanitize_NeverSplitsASurrogatePairAtTheCut()
|
|
{
|
|
// The emoji's high surrogate is character 120; the cap must drop the whole pair.
|
|
var raw = new string('a', 119) + "😀b";
|
|
|
|
var result = FileNameStrategy.Sanitize(raw);
|
|
|
|
result.Should().Be(new string('a', 119));
|
|
IsWellFormedUtf16(result).Should().BeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public void Sanitize_KeepsASurrogatePairThatFitsExactly()
|
|
{
|
|
var raw = new string('a', 118) + "😀bb";
|
|
|
|
var result = FileNameStrategy.Sanitize(raw);
|
|
|
|
result.Should().Be(new string('a', 118) + "😀");
|
|
result.Should().HaveLength(120);
|
|
IsWellFormedUtf16(result).Should().BeTrue();
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("")]
|
|
[InlineData(" ")]
|
|
[InlineData("\t\r\n")]
|
|
[InlineData("<<<>>>")]
|
|
[InlineData("...")]
|
|
[InlineData("___")]
|
|
[InlineData("\u202E\u200B")]
|
|
public void Sanitize_NothingLeft_FallsBackToCapture(string raw)
|
|
{
|
|
FileNameStrategy.Sanitize(raw).Should().Be("capture");
|
|
}
|
|
|
|
// ---- BuildFilePath ------------------------------------------------------------------------
|
|
|
|
[Fact]
|
|
public void BuildFilePath_NoCollision_UsesTheSanitizedTemplate()
|
|
{
|
|
var probed = new List<string>();
|
|
var strategy = new FileNameStrategy(path =>
|
|
{
|
|
probed.Add(path);
|
|
return false;
|
|
});
|
|
|
|
var path = strategy.BuildFilePath(OutputDir, Template, Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
path.Should().Be(Expected(ExpectedStem + ".png"));
|
|
probed.Should().Equal(path);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("")]
|
|
[InlineData(" ")]
|
|
public void BuildFilePath_BlankTemplate_UsesTheDefaultTemplate(string template)
|
|
{
|
|
var strategy = new FileNameStrategy(_ => false);
|
|
|
|
var path = strategy.BuildFilePath(OutputDir, template, Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
FileNameStrategy.DefaultTemplate.Should().Be(Template);
|
|
path.Should().Be(Expected(ExpectedStem + ".png"));
|
|
}
|
|
|
|
[Fact]
|
|
public void BuildFilePath_WithoutTarget_NamesTheFileAfterTheMode()
|
|
{
|
|
var strategy = new FileNameStrategy(_ => false);
|
|
|
|
var path = strategy.BuildFilePath(OutputDir, Template, null, CaptureMode.Region, FixedTime, ImageFormat.Png);
|
|
|
|
path.Should().Be(Expected("Region_2026-04-15_19-30-45.png"));
|
|
}
|
|
|
|
[Fact]
|
|
public void BuildFilePath_OneCollision_AppendsCounter1()
|
|
{
|
|
var existing = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Expected(ExpectedStem + ".png") };
|
|
var strategy = new FileNameStrategy(existing.Contains);
|
|
|
|
var path = strategy.BuildFilePath(OutputDir, Template, Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
path.Should().Be(Expected(ExpectedStem + "_1.png"));
|
|
}
|
|
|
|
[Fact]
|
|
public void BuildFilePath_ManyCollisions_CountsUpToTheFirstFreeName()
|
|
{
|
|
var existing = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
Expected(ExpectedStem + ".png"),
|
|
Expected(ExpectedStem + "_1.png"),
|
|
Expected(ExpectedStem + "_2.png"),
|
|
Expected(ExpectedStem + "_3.png"),
|
|
};
|
|
var strategy = new FileNameStrategy(existing.Contains);
|
|
|
|
var path = strategy.BuildFilePath(OutputDir, Template, Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
path.Should().Be(Expected(ExpectedStem + "_4.png"));
|
|
}
|
|
|
|
[Fact]
|
|
public void BuildFilePath_CollisionInAnotherFormat_IsNotACollision()
|
|
{
|
|
var existing = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Expected(ExpectedStem + ".jpg") };
|
|
var strategy = new FileNameStrategy(existing.Contains);
|
|
|
|
var path = strategy.BuildFilePath(OutputDir, Template, Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
path.Should().Be(Expected(ExpectedStem + ".png"));
|
|
}
|
|
|
|
[Fact]
|
|
public void BuildFilePath_CounterToken_PlacesTheSuffixInsteadOfAppendingIt()
|
|
{
|
|
var existing = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
Expected("Notepad shot.png"),
|
|
Expected("Notepad_1 shot.png"),
|
|
};
|
|
var strategy = new FileNameStrategy(existing.Contains);
|
|
|
|
var first = new FileNameStrategy(_ => false)
|
|
.BuildFilePath(OutputDir, "{Game}{counter} shot", Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
var third = strategy.BuildFilePath(OutputDir, "{Game}{counter} shot", Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
first.Should().Be(Expected("Notepad shot.png"));
|
|
third.Should().Be(Expected("Notepad_2 shot.png"));
|
|
}
|
|
|
|
[Fact]
|
|
public void BuildFilePath_DirectoryPackedWithNames_FallsBackToAMillisecondTimestamp()
|
|
{
|
|
var strategy = new FileNameStrategy(_ => true);
|
|
|
|
var path = strategy.BuildFilePath(OutputDir, Template, Notepad(), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
var millis = FixedTime.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
|
|
path.Should().Be(Expected($"{ExpectedStem}_{millis}.png"));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(ImageFormat.Png, ".png")]
|
|
[InlineData(ImageFormat.Jpeg, ".jpg")]
|
|
[InlineData(ImageFormat.Webp, ".webp")]
|
|
[InlineData(ImageFormat.Tiff, ".tiff")]
|
|
[InlineData(ImageFormat.Jxr, ".jxr")]
|
|
public void BuildFilePath_UsesTheFormatsExtension(ImageFormat format, string extension)
|
|
{
|
|
var path = new FileNameStrategy(_ => false)
|
|
.BuildFilePath(OutputDir, "{Game}", Notepad(), CaptureMode.Window, FixedTime, format);
|
|
|
|
path.Should().Be(Expected("Notepad" + extension));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("Doom/Eternal: Part <2>", "Doom_Eternal_Part 2.png")]
|
|
[InlineData(@"..\..\Windows\evil", "Windows_evil.png")]
|
|
[InlineData("CON", "CON_.png")]
|
|
[InlineData("<<>>", "capture.png")]
|
|
public void BuildFilePath_HostileTitles_StayInsideTheDirectory(string title, string expectedFileName)
|
|
{
|
|
var path = new FileNameStrategy(_ => false)
|
|
.BuildFilePath(OutputDir, "{Game}", Notepad(title: title), CaptureMode.Window, FixedTime, ImageFormat.Png);
|
|
|
|
path.Should().Be(Expected(expectedFileName));
|
|
Path.GetDirectoryName(path).Should().Be(OutputDir);
|
|
}
|
|
|
|
private static bool IsWellFormedUtf16(string value)
|
|
{
|
|
try
|
|
{
|
|
_ = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetByteCount(value);
|
|
return true;
|
|
}
|
|
catch (EncoderFallbackException)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|