16 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.7 7bd2bf9df0 chore(release): bump to v1.2.0
Logging-overhaul release. Turns the v1.1 logging surface — working but
thin — into a diagnostic tool developers and end-users can rely on when
something misbehaves. No capture-engine changes, no breaking config
changes; Velopack publish on the existing `win` channel.

Highlights:
  - Runtime log-level picker in Settings (Debug / Info / Warn / Error)
  - Log viewer min-level filter + "Open folder" button
  - Caller context (File:Line:Member) on every entry, via
    CallerAwareLoggerExtensions
  - Global exception handlers for AppDomain / TaskScheduler /
    Avalonia dispatcher
  - Expanded coverage across WGC, hotkey, Velopack, tray,
    localization
  - 4 previously silent catches now log
  - settings.json schema bumped v1→v2 with auto migration
  - Window widened to 1200×720 with animated log drawer (480 px,
    200 ms fade + slide)
  - Scroll bars hidden on About + Settings (wheel scrolling still works)

Default minimum log level is now Information (was Debug) — flip back
to Debug via Settings → Logging if you were relying on verbose output.

Tests: 156 green (was 123). New suites cover InMemorySink,
SerilogLogLevelSwitcher, CallerAwareLoggerExtensions, LogViewer
filter / hydration / live-tail, and v1→v2 settings migration with
write-back.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:40:33 +07:00
poli0981andClaude Opus 4.7 7cd59eac36 feat(v1.2-M7): widen window, animate log drawer, hide main-view scrollbars
UX polish on top of the M1–M5 logging work:

- **Window 1200×720** (was 960×600) with **log drawer at 480 px**
  (was 400 px). Content area visible while the drawer is open goes
  from ~340 px to ~500 px — the cramped "half your app is behind a
  drawer" feeling is gone.
- **Log drawer slides in with a 200 ms fade + translate-X easing.**
  The drawer is now kept in the visual tree permanently so
  transitions fire on every toggle. Classes.visible is bound to
  IsLogViewerVisible; IsHitTestVisible is bound to the same flag so
  the drawer stays click-through while hidden. DoubleTransition
  (Opacity, 180 ms) + TransformOperationsTransition (translateX,
  220 ms) with CircularEaseOut.
- **Scroll bars hidden on About + Settings** (Horizontal=Disabled,
  Vertical=Hidden). Mouse-wheel scrolling still works; the track
  just isn't drawn. Update log + Log viewer drawer keep their bars
  since those are diagnostic surfaces where users want to scrub.

Dashboard has no ScrollViewer so it wasn't touched. UpdateView's
inner log ScrollViewer is left alone for the same reason as the log
drawer: it's a diagnostic surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:39:57 +07:00
poli0981andClaude Opus 4.7 f82b300d25 test(v1.2-M5): unit coverage for logging stack + v1→v2 settings migration
New test suites:
  - InMemorySinkTests (7 cases): ring-buffer eviction at MaxCapacity,
    pause suppresses Emitted but still buffers, Snapshot returns a
    defensive copy, Clear empties, caller properties round-trip when
    present on the LogEvent and stay null when absent
  - SerilogLogLevelSwitcherTests (13 cases): canonical + alias names
    (info/warn/ERROR/empty) map correctly, unknown/null falls back
    to Information, CurrentLevel reports canonical capitalisation
  - CallerAwareLoggerExtensionsTests (4 cases): LogXAt extensions
    attach Member/File/Line as scope state, Path.GetFileName strips
    absolute build-machine paths, exception overloads forward both
    exception and caller context, template args pass through
  - LogViewerViewModelTests (6 cases): hydration copies snapshot
    (idempotent), live tail appends, filter rebuild keeps only ≥
    selected level, filter never touches the underlying buffer, live
    tail below filter is suppressed

Extended JsonSettingsStoreTests:
  - V1File_MigratesToV2AndWritesBack: v1 document without LogLevel is
    upgraded in memory AND the canonical v2 form is written back to
    disk
  - V2File_PreservesLogLevelField: existing LogLevel value round-trips

Also tightened JsonSettingsStore migration: STJ source-gen does NOT
honour record init defaults when a property is absent from JSON, so
we set LogLevel explicitly in the v1→v2 branch and add a defensive
"v2 file with null LogLevel" fill-in (possible via hand-edits).

Totals: 156 tests (was 123), all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:24:00 +07:00
poli0981andClaude Opus 4.7 e6ba7b4dfa feat(v1.2-M4): runtime log-level switch + viewer filter + reveal folder
User-facing logging controls:

Settings → Logging group adds a "Minimum log level" picker bound to a new
AppSettings.LogLevel field (schema v1→v2, additive). Changing the picker
updates a Serilog LoggingLevelSwitch live — no restart — and persists to
settings.json through the debounced writer. Default is "Information";
legacy v1 users migrate in place and keep their existing values
(LogLevel defaults when deserialised). Hand-edited or unknown values
fall back to Information with a log line at startup.

LogViewer gets two new controls in the header:
  - Min-level filter dropdown (view-side only — sink keeps everything,
    so Export always carries the full history regardless of filter)
  - "Open folder" button that launches Explorer at
    %LocalAppData%\CaptureImage\logs, with a Toast on failure

Plumbing:
  - LoggingSetup.Initialize now returns (InMemorySink, LoggingLevelSwitch);
    Program wires the switch to settings.Current.LogLevel after LoadAsync.
    Boot floor stays at Debug so early-startup lines always reach the
    rolling file.
  - CompositionRoot adds LoggingLevelSwitch singleton + the new
    ILogLevelSwitcher abstraction (Core) backed by SerilogLogLevelSwitcher
    (Infrastructure). Keeps VMs free of a Serilog dependency.
  - MEL minimum level goes to Trace so filtering stays with the Serilog
    switch.
  - LogPaths.GetLogsDirectory (new Core helper) — single source of truth
    for %LocalAppData%\CaptureImage\logs, used by both LoggingSetup and
    LogViewerViewModel's Reveal command.
  - JsonSettingsStore: v1→v2 migration stamps the new version and writes
    back on load so existing users don't need to touch settings.json.
  - SettingsJsonContext needs no change — LogLevel is a string.

Localization: new keys Settings_Logging, Settings_LogLevel,
Settings_LogLevelHint, Log_Filter, Log_RevealFolder added in EN / VI / AR.
Arabic / Vietnamese remain machine-assisted per existing disclaimer.

Tests updated: JsonSettingsStoreTests now expect Version=2 and assert the
new LogLevel default.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:19:51 +07:00
poli0981andClaude Opus 4.7 3ae8fdddfe feat(v1.2-M3): expand logging coverage across capture/hotkey/update/tray/localization
Fill in log call sites that were either silent or shallow:

- WindowsGraphicsCaptureEngine: Info on session start (HWND + size), Debug on
  first frame arrival and session dispose, Warning on CreateForWindow
  COMException with explicit HRESULT formatting, Warning on frame timeout
  with configured deadline, dedicated COMException path on outer catch
- HotkeyConflictSniffer: Win32 error codes now decode to names
  (ERROR_HOTKEY_ALREADY_REGISTERED / ERROR_INVALID_PARAMETER / etc.) so
  debug output reads without Googling 1409
- SharpHookHotkeyService: Info when TaskPoolGlobalHook actually starts
  (previously only logged on Stop + binding change)
- VelopackUpdateService: Info before ApplyUpdatesAndRestart with target
  version + Error if the call throws (it used to fail silently into the
  relaunch)
- AvaloniaTrayIconHost: wrap BuildRuntimeIcon (SkiaSharp) in a guarded
  helper so a native-asset blow-up falls back to Avalonia's default glyph
  instead of crashing startup; Info when the tray is initialized and
  disposed
- ResxLocalizationService: inject ILogger and dedup-log Warning on the
  first time a resource key is missing per (culture, key) pair — catches
  resx typos without flooding the file on every refresh
- Program.cs: startup banner now includes Version / OS / Culture / Args
  so support sessions can pick the build up from a glance

Also extend CallerAwareLoggerExtensions with LogWarningAt<T0>,
LogWarningAt<T0,T1> exception overloads and LogErrorAt<T0,T1> to cover
the new WGC call sites. Update ResxLocalizationServiceTests to pass
NullLogger through the new required ctor parameter.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:04:53 +07:00
poli0981andClaude Opus 4.7 2367082aab feat(v1.2-M2): caller-aware logger extensions with file:line context
Add LogXAt extensions on ILogger that capture [CallerMemberName],
[CallerFilePath], [CallerLineNumber] and attach them as Serilog properties
(Member / File / Line) via MEL BeginScope, which the Serilog MEL bridge
forwards as LogEvent properties. Path.GetFileName strips build-machine
paths so we don't leak E:\capture\captureimg\... into shipped logs.

Pipeline plumbed end-to-end:
  - LogEntry gains File / Line / Member init-only properties + FileLineText
    computed helper for the viewer
  - InMemorySink.MapToEntry reads the three scalar properties
  - CallerPropertyDefaultsEnricher injects empty defaults so the rolling-
    file template renders cleanly on legacy call sites
  - Rolling-file outputTemplate gains ({File}:{Line}) between level and
    message
  - LogViewer gets a subdued File:Line column; Export file format matches
    the rolling file

Overloads cover 0-3 template args for Info/Debug/Warning, plus Error
variants that take an Exception. Existing ILogger<T>.LogX call sites keep
working unchanged (no caller context, rendered as legacy defaults).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 08:59:26 +07:00
poli0981andClaude Opus 4.7 b72d9d9e22 fix(v1.2-M1): global exception handlers + unswallow silent catches
Register AppDomain.UnhandledException, TaskScheduler.UnobservedTaskException,
and Avalonia Dispatcher.UnhandledException handlers in Program.cs so background-
thread and UI-dispatcher crashes reach the rolling log instead of silently
tearing down the process. Structured log on each path with IsTerminating flag,
SetObserved() on unobserved tasks, Handled=true on dispatcher exceptions.

Unswallow four silent catches that hid real failures:
  - SharpHookHotkeyService.Stop/Dispose: log at Warning when hook dispose throws
  - WmiProcessWatcher.DisposeWatchers_NoLock: log at Debug on teardown failures
  - JsonSettingsStore.Deserialize: log JsonException with line/byte position
    before returning null (caller still falls back to defaults)
  - JsonSettingsStore.TryDelete: log at Debug when temp-file cleanup fails

Also add shutdown marker in finally (Reason=Normal|StartupCrash) so logs
bracket every session.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 08:54:03 +07:00
poli0981andClaude Opus 4.7 3224ad65c2 chore(release): bump to v1.1.2
M5 of the v1.1.2 localization hotfix. Closes the cycle: adds regression
tests for the two most foundational pieces of the fix, bumps the dev
version so fresh builds report v1.1.2, and writes the release notes.

- New `tests/CaptureImage.UI.Tests/` project covering
  `ResxLocalizationService`: SetCulture thread-culture propagation
  (CurrentUICulture / CurrentCulture / DefaultThreadCurrent* all
  follow), FlowDirection mapping for ar-SA, event count per switch
  (Item[] once + CurrentCulture + CurrentFlowDirection + CultureChanged),
  no-op when target culture equals current, indexer fallback for
  missing and empty keys, real resx lookup for known keys in en + vi,
  SupportedCultures surface. 12 tests.
- New `tests/CaptureImage.ViewModels.Tests/Preview/PreviewViewModelTests.cs`
  covering the M1 regression guard: VM forwards Item[] and
  CurrentCulture notifications as PropertyChanged("Localization"),
  ignores other notifications, and detaches its subscription on
  Dispose. 4 tests.
- `CaptureImage.App.csproj` version bumped to 1.1.2 so dev builds
  report the right string in the About tab; release.yml still
  overrides via `/p:Version=<git-tag>` on tag-driven builds.
- `CHANGELOG.md` adds a [1.1.2] section grouping the 13 original
  audit items + 3 user-reported bugs from smoke testing into
  Fixed / Changed / Removed / Known limitations / Tests, with
  cross-references to the affected VMs and services.

Test totals: 123 passing across four projects (Core 58 + VM 16 +
Infrastructure 37 + UI 12), up from 107 before M5. Build: 0 warnings,
0 errors.

Next step after this commit: tag v1.1.2 and run the Velopack release
pipeline on the `win` channel (same as v1.1.1) so the delta chain
stays intact.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 23:22:52 +07:00
poli0981andClaude Opus 4.7 eaf34e5543 fix(v1.1.2): live-refresh Log button + SettingsView + HotkeyRecorder, init settings.json on first run
M4a of the v1.1.2 localization hotfix — three bugs discovered during
smoke testing after M4:

A. Log drawer toggle button (MainWindow nav rail) did not retranslate
   when the user switched language — a restart was needed. Root cause:
   `{Binding Localization[Nav_LogViewer]}` and `[Dashboard_LogToggle]`
   are compiled indexer bindings through an intermediate `Localization`
   property on MainWindowViewModel. Avalonia does not reliably
   reevaluate these when the intermediate reference is unchanged, so
   the v1.1.1 `OnPropertyChanged(nameof(Localization))` signal does
   not wake them. Fix: expose `LogToggleLabel` and `LogToggleTooltip`
   as plain computed properties reading through the indexer, raise them
   on culture change, and bind the XAML to those properties instead.

B. SettingsView did not retranslate live when the user switched
   language from the Settings tab itself (where the language picker
   lives) — they had to navigate to another tab and back to see the
   new culture. The other tabs "appeared" to work only because the
   DataTemplate re-instantiated them on navigation. Same compiled
   indexer binding limitation as (A). Fix: add 18 plain computed
   properties on SettingsViewModel (TitleLabel, LanguageLabel,
   HotkeyLabel, …) and 6 on HotkeyBindingViewModel
   (RecordLabel, CancelLabel, ResetLabel, RecorderPromptText,
   ConflictWarningText, HotkeyFieldAutomationName). Raise all on
   culture change and rewrite SettingsView.axaml +
   HotkeyRecorder.axaml bindings to target the new properties.

   Scope is deliberately limited to the two views the user is active
   in when switching language (Settings + HotkeyRecorder) plus the
   always-visible MainWindow Log button. Dashboard / About / Update /
   Preview / LogViewer may have the same latent bug but are not user-
   reported, and their indexer bindings refresh on re-navigation since
   the views are destroyed / recreated via DataTemplate.

C. `settings.json` was never written to disk on first run. Previously
   `JsonSettingsStore.LoadAsync` created a fresh `AppSettings()` in
   memory when the file was missing but only persisted on the first
   `Update()` — users who launched the app without changing anything
   never saw a settings file they could edit. Partial / malformed /
   version-too-new files fell back to defaults in memory but left the
   on-disk file skewed. Fix: set a `needsWriteBack` flag for four
   paths (file missing, parse failure, future version, canonical
   form differs from raw JSON) and call `WriteAsync` directly after
   `SetCurrent`. Write failure is logged but non-fatal so a read-only
   disk does not break Load.

Build: 0 warnings, 0 errors. Tests: 107 passing (Core 58 + VM 12 +
Infrastructure 37, includes the existing `JsonSettingsStoreTests`
which still pass since they only assert `store.Current.*` state, not
file absence).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 23:07:49 +07:00
poli0981andClaude Opus 4.7 4d358028d0 chore(v1.1.2): thread-culture hardening, startup validation, dead key cleanup
M4 of the v1.1.2 localization hotfix. Three platform-level cleanups:

- ResxLocalizationService.SetCulture used to set only
  DefaultThreadCurrentUICulture, which is the baseline for threads
  that haven't overridden their culture. The UI thread keeps its
  OS-inherited culture, so any implicit .ToString() on DateTime,
  numbers, or currency stayed in the OS locale even after the user
  switched language. Align CurrentUICulture + CurrentCulture on the
  calling thread and DefaultThreadCurrentCulture for new background
  threads, so date/number formatting follows the chosen language
  wherever implicit formatting lands. Resx lookup was already correct
  (indexer passes _currentCulture explicitly to ResourceManager).
- Program.cs used to accept any culture name that CultureInfo.
  GetCultureInfo could resolve. A hand-edited settings.json with
  Culture=fr-FR would flip the app to fr, fall through to neutral
  English resx, and leave Settings showing "English" selected —
  coherent but misleading. Validate against SupportedCultures before
  calling SetCulture; unsupported cultures log a warning and stay on
  the en-US default, matching what Settings displays.
- Remove four unused resx keys (Settings_Theme, Tray_Arm, Tray_Disarm,
  Log_Export) in lockstep across en/vi/ar. No UI wires these — theme
  picker, tray arm/disarm, and log-export button aren't built yet.
  A future v1.2+ can re-add the keys when the UI actually needs them.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 22:35:50 +07:00
poli0981andClaude Opus 4.7 5ac99712b0 refactor(v1.1.2): named localization handlers + IDisposable on Settings/LogViewer VMs
M3 of the v1.1.2 localization hotfix. Cleans up handler hygiene across
the localization subscribers:

- AvaloniaTrayIconHost used to rebuild the tray menu three times per
  culture switch because it reacted to every PropertyChanged
  (Item[], CurrentCulture, CurrentFlowDirection — the service fires
  all three on SetCulture). Filter to "Item[]" so it rebuilds once.
  Also unsubscribe in Dispose.
- DashboardViewModel, AboutViewModel, LogViewerViewModel, and
  SettingsViewModel had their Localization.PropertyChanged handlers
  as anonymous lambdas that could not be detached. Extract each to a
  named OnLocalizationChanged method so they can be unsubscribed.
  DashboardViewModel also gains a _disposed guard mirroring the other
  IDisposable VMs.
- SettingsViewModel's _settings.Changed subscription was likewise a
  lambda (`(_, _) => Hydrate()`); extract to OnSettingsStoreChanged
  so both subscriptions can be torn down together.
- LogViewerViewModel and SettingsViewModel now implement IDisposable
  and unsubscribe both of their event sources. DI container disposes
  singletons on shutdown, so runtime behavior is unchanged — the
  value is the consistency with the Dashboard/Update/HotkeyBinding
  pattern and the future-proofing against lifetime changes.
- AboutViewModel keeps its no-IDisposable status intentionally: it's a
  DI singleton owned by the nav shell for the whole process, so the
  leak is theoretical. The extraction to a named handler still lands
  for consistency.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 22:30:03 +07:00
poli0981andClaude Opus 4.7 5b6c2ddf01 feat(v1.1.2): localize About disclaimer bodies (vi/ar)
M2 of the v1.1.2 localization hotfix. The About tab already localized
the three disclaimer section headings (Translations / Capture support /
No warranty) but the body paragraphs stayed hardcoded English — an
inconsistency that looked half-translated to vi/ar users.

- Add About_TranslationDisclaimerBody, About_CaptureLimitationDisclaimerBody,
  About_LiabilityDisclaimerBody to all three resx files (en/vi/ar) in
  lockstep. vi + ar translations are machine-assisted, matching the
  existing Translations disclaimer that warns users about this.
- Swap AboutViewModel's three disclaimer properties from hardcoded
  strings to Localization[...] indexer reads. AiAssistanceNotice stays
  English by design (dev-process disclosure, not user-facing functionality).
- AboutView.axaml binds each disclaimer by property name, not through
  the Localization indexer, so the v1.1.1 Item[] refresh alone won't
  wake those bindings. Raise PropertyChanged explicitly for each
  disclaimer property on culture switch so the bound TextBlocks
  retranslate in place.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 22:17:07 +07:00
poli0981andClaude Opus 4.7 d3e9b7df5c fix(v1.1.2): live localize picker titles, toast error, preview window + status message
M1 of v1.1.2 localization hotfix — 6 fixes the user sees directly when
switching languages at runtime:

- PreviewWindow now binds Title + FlowDirection to Localization, so the
  modal's title and mirrored layout track the current culture (Arabic
  RTL used to stay LTR, English title used to stay "Preview").
- PreviewViewModel is IDisposable and subscribes to Localization.
  PropertyChanged with a named handler, matching the v1.1.1 pattern the
  other VMs use. AvaloniaPreviewPresenter Dispose()s it after each
  modal so the subscription doesn't leak into the singleton service.
- Settings file picker titles ("Import settings" / "Export settings")
  and the generic error-toast title ("Error") now come from resx
  (Settings_ImportTitle, Settings_ExportTitle, Toast_Error), with
  vi-VN + ar-SA translations added in lockstep.
- Dashboard StatusMessage retranslates on culture change — previously
  it was an [ObservableProperty] stored field, so the PropertyChanged
  notification handed the UI the same stale string. Call
  UpdateStatusForState() instead to rederive it from the state machine
  under the new culture.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 22:11:36 +07:00
poli0981 3da2fcc65d remove unused 'using' in code 2026-04-20 20:48:46 +07:00
poli0981 395728142b Merge pull request #12 from poli0981/fix/v1.1.1-hotfix
fix(v1.1.1): in-app updates, live localization, folder picker
2026-04-20 20:24:40 +07:00
poli0981andClaude Opus 4.7 35d5fd47bd fix(v1.1.1): in-app updates, live localization, folder picker
Hotfix on top of v1.1.0 — three bugs surfaced during the post-release
install smoke plus a CI gap that prevented the very update path from
working.

Fixed:

- **In-app update from v1.0.0 → v1.1.0 failed**. release.yml only
  published a full .nupkg + the legacy RELEASES manifest, but Velopack
  clients ≥ 0.0.900 poll for releases.win.json and prefer a
  *-delta.nupkg. Workflow now runs `vpk download github --channel win`
  ahead of `vpk pack` so pack sees the previous release, emits a delta
  + the JSON manifest; upload pattern picks up `releases.*.json` too.
  `vpk pack` also gains `--channel win --delta BestSize` explicitly.

- **Settings did not re-localize live**. `{Binding Localization[Key]}`
  indexer bindings through an intermediate property don't always pick
  up the service's own `PropertyChanged("Item[]")` in Avalonia's
  compiled binding path. Every VM exposing a `Localization` property
  now raises `OnPropertyChanged(nameof(Localization))` on culture
  switch — new listeners on SettingsViewModel, MainWindowViewModel,
  UpdateViewModel, AboutViewModel; existing listeners on Dashboard /
  LogViewer / HotkeyBinding extended with the same line. This matches
  the pattern NavItemViewModel has always used for its `Label`
  computed property.

- **Log drawer toggle label on the nav rail required app restart** to
  pick up a new language. Same root cause; MainWindowViewModel's new
  listener fixes it.

Added:

- **Output folder picker** in Settings. Click **Browse…** next to the
  Output folder TextBox to open the native folder picker instead of
  typing a path by hand. Seeds at the current value when set; falls
  back to the picker default otherwise. New resx keys `Settings_Browse`,
  `Settings_BrowseTitle`, `Settings_BrowseTooltip` in EN / VI / AR.

Build: 0/0, tests 107 pass on net9.0 + net9.0-windows10.0.22621.0.
Tag v1.1.1 follows this merge — release workflow will publish the
first incremental-update-capable set of artifacts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 20:21:34 +07:00
97 changed files with 2655 additions and 286 deletions

No files matched your search

+18
View File
@@ -88,7 +88,22 @@ jobs:
shell: pwsh
run: echo "$env:USERPROFILE\.dotnet\tools" | Out-File -FilePath $env:GITHUB_PATH -Append
- name: Download previous release (for delta generation)
# Velopack only emits a *-delta.nupkg when it finds a previous full package
# in --outputDir. Fetching the last GitHub release before pack gives the
# Update tab a working incremental path from n-1 → n. Safe to continue-on-error:
# a first-ever release has nothing to download and we just publish full.
shell: pwsh
continue-on-error: true
run: |
New-Item -ItemType Directory -Force -Path ./releases | Out-Null
vpk download github --repoUrl https://github.com/${{ github.repository }} --outputDir ./releases --channel win
- name: Velopack pack
# --channel win produces the modern releases.win.json manifest alongside the
# legacy RELEASES file, which is what Velopack clients >= 0.0.900 poll for.
# --delta BestSize keeps the hotfix payload small (typical v1.1.0 → v1.1.1
# delta is a few MB vs the ~55 MB full).
run: >
vpk pack
--packId ${{ env.PACK_ID }}
@@ -96,6 +111,8 @@ jobs:
--packDir ./publish
--mainExe ${{ env.MAIN_EXE }}
--outputDir ./releases
--channel win
--delta BestSize
- name: Compute SHA256 sums
shell: pwsh
@@ -127,6 +144,7 @@ jobs:
./releases/*.exe
./releases/*.nupkg
./releases/RELEASES
./releases/releases.*.json
./releases/SHA256SUMS.txt
body: |
## CaptureImage v${{ steps.version.outputs.version }}
+251
View File
@@ -7,6 +7,257 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.2.0] - 2026-04-21
Logging overhaul. Turns a working-but-thin diagnostic surface into one you
can actually rely on when things go wrong — developer and end-user alike.
No capture-engine changes; Velopack release on the existing `win` channel
so the delta chain from v1.1.2 stays intact.
### Added
- **Runtime log-level control.** New Settings → Logging group with a
minimum-level picker (Debug / Information / Warning / Error).
Persisted in `AppSettings.LogLevel` (new field, schema bump v1 → v2,
additive) and pushed into Serilog's `LoggingLevelSwitch` live — no
restart required.
- **Log viewer min-level filter.** Dropdown in the log drawer header
narrows what's shown without touching the sink buffer, so Export
still carries the full history regardless of the filter.
- **"Open folder" button in the log drawer.** Launches Explorer at
`%LocalAppData%\CaptureImage\logs` for support-session copy-paste.
Guarded with a Toast on failure.
- **Caller context on every log entry** — each line carries `File`,
`Line`, and `Member` structured properties, captured via new
`LogInformationAt` / `LogWarningAt` / `LogErrorAt` / `LogDebugAt`
extension methods on `ILogger`. Rolling-file template now prints
`(File.cs:42)`; log viewer shows a subdued `File:Line` column; Export
includes the same. Absolute build-machine paths are stripped via
`Path.GetFileName` so shipped logs stay clean.
- **Global exception handlers.** `AppDomain.UnhandledException`,
`TaskScheduler.UnobservedTaskException`, and
`Dispatcher.UIThread.UnhandledException` all now reach Serilog before
the process dies or the UI resumes. `SetObserved()` on unobserved
task exceptions keeps the default-crash policy from ending the app on
background-thread throws.
- **Startup + shutdown banner** — Program.Main logs
`Version` / `OS` / `Culture` / `Args` on start and a
`Reason=Normal|StartupCrash` line on exit, so support sessions can
tell which build produced the log at a glance.
- **Expanded coverage** — `Windows.Graphics.Capture` engine emits Info
on session start, Debug on first frame + session dispose, Warning on
frame timeout, Error with explicit `HRESULT=0x…` on `COMException`;
`HotkeyConflictSniffer` decodes Win32 error codes by name
(`ERROR_HOTKEY_ALREADY_REGISTERED` / `ERROR_INVALID_PARAMETER` / …);
`SharpHookHotkeyService` logs when `TaskPoolGlobalHook` boots;
`VelopackUpdateService` logs before + after
`ApplyUpdatesAndRestart`; `AvaloniaTrayIconHost` logs tray
init/dispose and guards the runtime SkiaSharp icon render so a
native-asset blow-up falls back to the platform default instead of
crashing startup; `ResxLocalizationService` warns once per
`(culture, key)` pair when a resource key is missing (dedup
prevents flooding on every refresh).
### Changed
- **Window widened to 1200×720** (was 960×600) and **log drawer
widened to 480 px** (was 400 px). The drawer now slides in with a
200 ms fade + 48 px translate-X easing (`CircularEaseOut`) instead
of snapping in and out. Content area visible while the drawer is
open is now ~500 px (was ~340 px).
- **Scroll bars hidden on About + Settings tabs.** Mouse-wheel
scrolling still works; the track is just no longer drawn, so the
view reads cleanly on the fixed-size window. Horizontal scrolling
on those tabs is disabled entirely. Diagnostic surfaces (Update
log, Log viewer drawer) keep their visible bars.
- **Default minimum log level is now `Information`** (was `Debug`).
v1 users are migrated in place: `settings.json` is stamped
Version=2 on first v1.2 launch and the LogLevel field defaults to
`Information`. Flip back to Debug via Settings → Logging if you
were relying on verbose output.
- Four previously-silent `catch { /* ignore */ }` blocks now log
their exceptions: `SharpHookHotkeyService.Stop/Dispose` (Warning),
`WmiProcessWatcher.DisposeWatchers_NoLock` (Debug),
`JsonSettingsStore.Deserialize` (Warning with JSON line / byte
position), `JsonSettingsStore.TryDelete` (Debug).
### Migration
- **`settings.json` schema v1 → v2.** Automatic on first v1.2 run —
the file is re-written in canonical v2 form with `LogLevel =
"Information"` and existing values preserved. Hand-edited files
with `logLevel` already present keep their value.
### Tests
- 33 new unit tests (total 156, up from 123). Covers the
`InMemorySink` ring buffer / pause / clear / snapshot-copy
semantics, `SerilogLogLevelSwitcher` string mapping + fallback,
`CallerAwareLoggerExtensions` scope + path-stripping behaviour,
`LogViewerViewModel` hydration / filter / live-tail paths, and the
v1 → v2 settings migration with write-back.
## [1.1.2] - 2026-04-20
Localization hotfix on top of v1.1.1 — closes 13 bugs and gaps found in
a post-v1.1.1 audit plus three bugs reported during smoke testing of
the hotfix itself. No new features; no capture-engine changes. Velopack
release on the same `win` channel as v1.1.1 to keep the delta chain
intact.
### Fixed
- **Dashboard status line stale on culture switch.** `StatusMessage`
is an `[ObservableProperty]` stored backing field, so the v1.1.1
`OnPropertyChanged(nameof(Localization))` signal re-read the same
stored string. Redrive via `UpdateStatusForState()` on culture
change so the new culture's template wins.
- **Preview window hardcoded English.** `PreviewWindow.axaml` had
`Title="Preview"` and no `FlowDirection` binding, so the modal stayed
in English and rendered LTR under Arabic. Title now binds to
`Localization[Preview_Title]`; `FlowDirection` binds to
`Localization.CurrentFlowDirection`.
- **`PreviewViewModel` did not listen for culture changes.** If the
user switched language while the preview modal was open, the four
indexer bindings (`Preview_Title`, `Preview_Prompt`, `Preview_Save`,
`Preview_Discard`) stayed in the old culture. VM now implements
`IDisposable`, subscribes with a named `OnLocalizationChanged`, and
`AvaloniaPreviewPresenter` `using`-disposes it after the modal so
the subscription doesn't leak into the singleton service.
- **File picker titles hardcoded English.** `Import settings` /
`Export settings` now come from new resx keys
`Settings_ImportTitle` / `Settings_ExportTitle` (en + vi + ar).
- **Settings toast error title hardcoded English.**
`_toasts.ShowError("Error", …)` in three places now reads through
`Localization["Toast_Error"]` (new resx key).
- **About tab disclaimer body paragraphs hardcoded English.** The
three disclaimer headings were already localized; the body
paragraphs were not, leaving the tab half-translated for vi / ar
users. Added `About_TranslationDisclaimerBody`,
`About_CaptureLimitationDisclaimerBody`, and
`About_LiabilityDisclaimerBody` in all three resx files (machine-
assisted translation, matching the existing Translations
disclaimer). `AiAssistanceNotice` intentionally stays English — it
describes the development process, not the user-facing product.
- **Tray menu rebuilt 3× per culture switch.**
`AvaloniaTrayIconHost`'s `PropertyChanged` handler fired for every
notification the service raises (`Item[]` + `CurrentCulture` +
`CurrentFlowDirection`). Named handler now filters `"Item[]"` only,
and the subscription is torn down in `Dispose`.
- **`ResxLocalizationService.SetCulture` set only
`DefaultThreadCurrentUICulture`.** Date / number / currency
formatting on the UI thread kept the OS locale. The service now
also sets `CultureInfo.CurrentUICulture`, `CurrentCulture`, and
`DefaultThreadCurrentCulture` so implicit `.ToString()` follows
the chosen language.
- **Startup accepted any resolvable culture.** A hand-edited
`settings.json` with `Culture=fr-FR` would flip the app to fr and
fall through to neutral English resx while Settings still showed
"English" selected. `Program.cs` now validates the persisted
culture against `SupportedCultures` before calling `SetCulture`.
- **Log drawer toggle button did not retranslate live.** Same
compiled-indexer-binding limitation as the next item — the v1.1.1
`OnPropertyChanged(nameof(Localization))` signal does not wake
Avalonia compiled indexer bindings through an intermediate
property. Fix: expose `LogToggleLabel` and `LogToggleTooltip` as
plain computed properties on `MainWindowViewModel` and bind
MainWindow.axaml to those instead of the indexer path.
- **SettingsView did not retranslate live when the user switched
language from the Settings tab itself.** The view only refreshed
on re-navigation (DataTemplate re-instantiation). Added 18 plain
computed properties on `SettingsViewModel` and 6 on
`HotkeyBindingViewModel`, rewrote the bindings in
`SettingsView.axaml` and `HotkeyRecorder.axaml` to target them.
- **`settings.json` was never written on first run.**
`JsonSettingsStore.LoadAsync` created a fresh `AppSettings()` in
memory when the file was missing but only persisted on the first
user-triggered `Update()`. Partial / malformed / future-version
files left the on-disk form out of sync with the in-memory form.
`LoadAsync` now writes back when the file is missing, unparseable,
version-too-new, or when the canonical re-serialized form differs
from the raw JSON. Write failure is logged but non-fatal so a
read-only disk does not break Load.
### Changed
- **Handler hygiene across localization subscribers.** Anonymous
lambda subscriptions on `Localization.PropertyChanged` extracted
to named methods so they can be unsubscribed
(`DashboardViewModel`, `AboutViewModel`, `LogViewerViewModel`,
`SettingsViewModel`, `AvaloniaTrayIconHost`). `LogViewerViewModel`
and `SettingsViewModel` now implement `IDisposable` and
unsubscribe both of their event sources; runtime behavior is
unchanged because the DI container disposes singletons on
shutdown.
### Removed
- Four unused resx keys (`Settings_Theme`, `Tray_Arm`, `Tray_Disarm`,
`Log_Export`) in lockstep across en / vi / ar. None were wired to
UI; a future v1.2+ can re-add them when a theme picker, tray
arm/disarm, or log export button actually ships.
### Known limitations
- Toast title / message snapshot the localized string at the time
`ToastService.Show` is called; switching culture while a toast is
still fading out does not retranslate it. Fixing this requires
threading resx keys through `ToastService` instead of strings —
deferred to v1.2+ to keep this hotfix focused.
- `Dashboard` / `About` / `Update` / `LogViewer` tabs still use
`{Binding Localization[Key]}` indexer bindings in their
respective views. They refresh because navigation re-instantiates
them via `DataTemplate`; if a future change pins the active tab
through a culture switch, the same computed-property refactor may
be needed.
### Tests
- New `tests/CaptureImage.UI.Tests/` project covering
`ResxLocalizationService` (SetCulture thread-culture propagation,
FlowDirection mapping for ar-SA, event counts, indexer fallback
for missing keys, localized lookup for known keys, SupportedCultures
surface).
- New `tests/CaptureImage.ViewModels.Tests/Preview/PreviewViewModelTests.cs`
covering the v1.1.2 M1 fix: Localization PropertyChanged forwarding
+ Dispose detachment.
## [1.1.1] - 2026-04-20
Hotfix on top of v1.1.0 — closes three bugs reported after the v1.1.0
smoke install, and closes the CI gap that prevented in-app updates from
working.
### Fixed
- **In-app update from v1.0.0 → v1.1.0 failed** because `release.yml`
packaged only a full `.nupkg` with the legacy `RELEASES` manifest —
Velopack clients ≥ 0.0.900 poll for `releases.win.json` and prefer an
incremental `*-delta.nupkg`. The workflow now runs
`vpk download github --channel win` ahead of `vpk pack` so Velopack
sees the previous release, emits a delta + the JSON manifest, and the
GitHub Release upload pattern picks up `releases.*.json`.
- **Settings tab did not re-localize live when the language dropdown
was used**. The `{Binding Localization[Settings_*]}` indexer bindings
relied on the service's own `PropertyChanged("Item[]")` notification,
which Avalonia's compiled indexer bindings through an intermediate
property don't always pick up. Every ViewModel that exposes a
`Localization` property now raises
`OnPropertyChanged(nameof(Localization))` on culture change
(`SettingsViewModel`, `MainWindowViewModel`, `UpdateViewModel`,
`AboutViewModel`, and the existing listeners on
`DashboardViewModel`, `LogViewerViewModel`, `HotkeyBindingViewModel`).
- **Log drawer toggle label on the nav rail required an app restart to
switch language** — same root cause as the Settings bug, same fix.
### Added
- **Output folder picker** in Settings. Click **Browse…** next to the
Output folder field to open the native folder picker instead of
typing a path by hand. The picker seeds from the current value when
set. New resx keys `Settings_Browse`, `Settings_BrowseTitle`,
`Settings_BrowseTooltip` in EN / VI / AR.
## [1.1.0] - 2026-04-20
Second release. Polish + configurability pass on top of v1.0.0 — ships a
+17
View File
@@ -21,6 +21,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.Infrastructure
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.ViewModels.Tests", "tests\CaptureImage.ViewModels.Tests\CaptureImage.ViewModels.Tests.csproj", "{65E8FCC7-53C0-4793-925F-3AB562EFC562}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.UI.Tests", "tests\CaptureImage.UI.Tests\CaptureImage.UI.Tests.csproj", "{C4E037B1-D055-4C6C-AAAF-3D814665D077}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -127,6 +131,18 @@ Global
{65E8FCC7-53C0-4793-925F-3AB562EFC562}.Release|x64.Build.0 = Release|Any CPU
{65E8FCC7-53C0-4793-925F-3AB562EFC562}.Release|x86.ActiveCfg = Release|Any CPU
{65E8FCC7-53C0-4793-925F-3AB562EFC562}.Release|x86.Build.0 = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x64.ActiveCfg = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x64.Build.0 = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x86.ActiveCfg = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x86.Build.0 = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|Any CPU.Build.0 = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x64.ActiveCfg = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x64.Build.0 = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x86.ActiveCfg = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -140,5 +156,6 @@ Global
{41DC8750-7186-494E-80BC-845C5071DF8F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{679C3869-EE49-4A76-ADF2-431430B781E1} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{65E8FCC7-53C0-4793-925F-3AB562EFC562} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{C4E037B1-D055-4C6C-AAAF-3D814665D077} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
EndGlobal
+2 -2
View File
@@ -10,9 +10,9 @@
<UseWpf>false</UseWpf>
<!-- App icon + manifest are added in M4 -->
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<!-- Release value for v1.1.0; release.yml still overrides via /p:Version=<git-tag>
<!-- Release value for v1.2.0; release.yml still overrides via /p:Version=<git-tag>
for tag-driven builds. Bump to the next -dev suffix after the release lands. -->
<Version>1.1.0</Version>
<Version>1.2.0</Version>
</PropertyGroup>
<ItemGroup>
+10 -4
View File
@@ -1,4 +1,3 @@
using System;
using System.IO.Abstractions;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Pipeline;
@@ -22,6 +21,7 @@ using CaptureImage.ViewModels.Update;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Extensions.Logging;
namespace CaptureImage.App;
@@ -31,7 +31,7 @@ namespace CaptureImage.App;
/// </summary>
internal static class CompositionRoot
{
public static IServiceProvider BuildServices(InMemorySink inMemorySink)
public static IServiceProvider BuildServices(InMemorySink inMemorySink, LoggingLevelSwitch loggingLevelSwitch)
{
var services = new ServiceCollection();
@@ -40,13 +40,19 @@ internal static class CompositionRoot
{
builder.ClearProviders();
builder.AddProvider(new SerilogLoggerProvider(Log.Logger, dispose: false));
builder.SetMinimumLevel(LogLevel.Debug);
// MEL's minimum level needs to sit at Trace/Debug so it never filters events
// before they reach Serilog — the real gating happens in the LoggingLevelSwitch.
builder.SetMinimumLevel(LogLevel.Trace);
});
// The same InMemorySink instance is both the Serilog sink AND the log buffer source
// used by the log viewer VM.
services.AddSingleton(inMemorySink);
services.AddSingleton<ILogBufferSource>(inMemorySink);
// Expose the Serilog level switch so Settings can mutate it live. Wrap it in the
// ILogLevelSwitcher abstraction so ViewModels don't take a Serilog dependency.
services.AddSingleton(loggingLevelSwitch);
services.AddSingleton<ILogLevelSwitcher, SerilogLogLevelSwitcher>();
// --- Cross-cutting -----------------------------------------------------
services.AddSingleton<IFileSystem, FileSystem>();
@@ -73,7 +79,7 @@ internal static class CompositionRoot
services.AddSingleton<IImageEncoder, SkiaImageEncoder>();
services.AddSingleton<IImageEncoder, ImageSharpTiffEncoder>();
services.AddSingleton<FileNameStrategy>(_ =>
new FileNameStrategy(System.IO.File.Exists));
new FileNameStrategy(File.Exists));
services.AddSingleton<CaptureOrchestrator>();
// --- Hotkeys -----------------------------------------------------------
+38 -14
View File
@@ -1,7 +1,7 @@
using System;
using System.IO;
using CaptureImage.Core.Logging;
using CaptureImage.Infrastructure.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.App;
@@ -24,26 +24,30 @@ internal static class LoggingSetup
return dir;
}
public static string GetLogsDir()
{
var dir = Path.Combine(GetAppDataDir(), "logs");
Directory.CreateDirectory(dir);
return dir;
}
public static string GetLogsDir() => LogPaths.GetLogsDirectory();
/// <summary>
/// Build the Serilog root logger together with the in-memory sink, and assign it to
/// <see cref="Log.Logger"/>. Returns the sink so the DI container can register it.
/// Build the Serilog root logger together with the in-memory sink and the runtime
/// level switch, and assign the logger to <see cref="Log.Logger"/>. Both are returned
/// so the DI container can register them — the sink drives the log viewer, the switch
/// drives the Settings → Log Level picker.
/// </summary>
public static InMemorySink Initialize()
/// <remarks>
/// The switch boots at <see cref="LogEventLevel.Debug"/> so early-startup telemetry is
/// always captured; <c>Program.Main</c> narrows it to the user's configured value once
/// <c>ISettingsStore.LoadAsync</c> has finished.
/// </remarks>
public static (InMemorySink Sink, LoggingLevelSwitch LevelSwitch) Initialize()
{
var logPath = Path.Combine(GetLogsDir(), "captureimg-.log");
var sink = new InMemorySink();
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Debug);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.ControlledBy(levelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.WithProperty("App", "CaptureImage")
.Enrich.With(new CallerPropertyDefaultsEnricher())
.WriteTo.Console()
.WriteTo.Sink(sink)
.WriteTo.Async(a => a.File(
@@ -53,9 +57,29 @@ internal static class LoggingSetup
fileSizeLimitBytes: 10L * 1024 * 1024,
rollOnFileSizeLimit: true,
shared: false,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"))
// {File}:{Line} shows caller context injected by CallerAwareLoggerExtensions.
// Missing on legacy call sites — Serilog prints a bare ":" then, so keep the
// template consistent and accept that one cosmetic artifact until those are
// migrated. {Properties:j} still JSON-dumps every non-templated property.
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] ({File}:{Line}) {Message:lj} {Properties:j}{NewLine}{Exception}"))
.CreateLogger();
return sink;
return (sink, levelSwitch);
}
/// <summary>
/// Map the persisted <c>LogLevel</c> string (one of <c>Debug</c> / <c>Information</c> /
/// <c>Warning</c> / <c>Error</c>) to a <see cref="LogEventLevel"/>. Unknown strings
/// fall back to <see cref="LogEventLevel.Information"/>.
/// </summary>
public static LogEventLevel ParseLevel(string? value) => value?.Trim().ToLowerInvariant() switch
{
"debug" => LogEventLevel.Debug,
"information" => LogEventLevel.Information,
"info" => LogEventLevel.Information,
"warning" => LogEventLevel.Warning,
"warn" => LogEventLevel.Warning,
"error" => LogEventLevel.Error,
_ => LogEventLevel.Information,
};
}
+91 -7
View File
@@ -1,6 +1,7 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Threading;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
@@ -27,29 +28,71 @@ internal static class Program
// when the launch is a normal one.
VelopackApp.Build().Run();
// Bootstrap Serilog early (and keep the in-memory sink reference for DI).
var inMemorySink = LoggingSetup.Initialize();
// Bootstrap Serilog early (keep the in-memory sink + runtime level switch for DI).
var (inMemorySink, loggingLevelSwitch) = LoggingSetup.Initialize();
// Catch anything that escapes try/catch on any thread. Register before we stand up DI
// or UI so background-thread crashes during startup still reach the rolling file.
RegisterGlobalExceptionHandlers();
var shutdownReason = "Normal";
try
{
Log.Information("CaptureImage starting. Args: {Args}", args);
Log.Information(
"CaptureImage starting. Version={Version} OS={OS} Culture={Culture} Args={Args}",
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0-dev",
System.Runtime.InteropServices.RuntimeInformation.OSDescription,
System.Globalization.CultureInfo.CurrentUICulture.Name,
args);
var services = CompositionRoot.BuildServices(inMemorySink);
var services = CompositionRoot.BuildServices(inMemorySink, loggingLevelSwitch);
UI.App.Services = services;
// Load persisted settings before the UI binds to them.
var settingsStore = services.GetRequiredService<ISettingsStore>();
settingsStore.LoadAsync().GetAwaiter().GetResult();
// Narrow Serilog's minimum level from the boot default (Debug) down to whatever
// the user chose via Settings last run. This happens after LoadAsync so that
// early-startup lines — "CaptureImage starting", "Settings loaded …" — always
// land in the file regardless of the configured floor.
var configuredLevel = LoggingSetup.ParseLevel(settingsStore.Current.LogLevel);
loggingLevelSwitch.MinimumLevel = configuredLevel;
Log.Information("Log level set to {Level} from settings.", configuredLevel);
// Apply persisted culture before the first window is constructed so nav labels etc.
// render in the right language from frame zero.
// render in the right language from frame zero. Only accept cultures the app
// actually ships translations for — a hand-edited settings.json with, say,
// Culture=fr-FR used to flip the app to fr and then fall through to neutral
// en strings with Settings showing "English" selected; refuse at startup
// instead so the default en-US stays coherent.
var localization = services.GetRequiredService<ILocalizationService>();
var cultureName = settingsStore.Current.Culture;
if (!string.IsNullOrWhiteSpace(cultureName))
{
try
{
localization.SetCulture(System.Globalization.CultureInfo.GetCultureInfo(cultureName));
var culture = System.Globalization.CultureInfo.GetCultureInfo(cultureName);
var supported = false;
foreach (var shipped in localization.SupportedCultures)
{
if (shipped.Name.Equals(culture.Name, StringComparison.OrdinalIgnoreCase))
{
supported = true;
break;
}
}
if (supported)
{
localization.SetCulture(culture);
}
else
{
Log.Warning(
"Persisted culture {Culture} is not a shipped language; falling back to default.",
cultureName);
}
}
catch (System.Globalization.CultureNotFoundException)
{
@@ -62,6 +105,7 @@ internal static class Program
}
catch (Exception ex)
{
shutdownReason = "StartupCrash";
Log.Fatal(ex, "CaptureImage crashed during startup.");
return -1;
}
@@ -83,6 +127,7 @@ internal static class Program
{
Log.Warning(ex, "Failed to flush settings on shutdown.");
}
Log.Information("CaptureImage shutting down. Reason={Reason}", shutdownReason);
Log.CloseAndFlush();
}
}
@@ -94,5 +139,44 @@ internal static class Program
=> AppBuilder.Configure<UI.App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace();
.LogToTrace()
.AfterSetup(_ =>
{
// Hook the Avalonia UI-thread dispatcher so exceptions raised by command
// handlers, bindings, and tick callbacks don't silently kill the UI.
Dispatcher.UIThread.UnhandledException += OnDispatcherUnhandledException;
});
private static void RegisterGlobalExceptionHandlers()
{
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
var ex = e.ExceptionObject as Exception;
Log.Fatal(
ex,
"Unhandled AppDomain exception. IsTerminating={IsTerminating}",
e.IsTerminating);
if (e.IsTerminating)
{
// Last-ditch flush — CLR is about to pull the rug.
Log.CloseAndFlush();
}
};
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error(e.Exception, "Unobserved task exception.");
// Claim the exception so the default .NET policy doesn't terminate the process
// on the next GC — structured log is enough signal for us to investigate.
e.SetObserved();
};
}
private static void OnDispatcherUnhandledException(object? sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "Unhandled exception on UI dispatcher.");
// Don't let a single bad command tear down the window — swallow after logging so the
// user can keep using the app (and notice the Toast / LogViewer will surface it).
e.Handled = true;
}
}
@@ -1,5 +1,3 @@
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,4 +1,3 @@
using System;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,6 +1,3 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,5 +1,3 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
@@ -1,5 +1,3 @@
using System;
using System.Collections.Generic;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -0,0 +1,21 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Live control over the Serilog minimum-level floor. The Settings view mutates this
/// when the user picks a new log level, and the wrapper — implemented in
/// <c>CaptureImage.Infrastructure.Logging</c> — pushes the value through to Serilog's
/// <c>LoggingLevelSwitch</c> so new events are filtered immediately.
/// </summary>
/// <remarks>
/// Level strings accepted by <see cref="SetLevel"/>: <c>Debug</c>, <c>Information</c>,
/// <c>Warning</c>, <c>Error</c> (case-insensitive, aliases <c>info</c> / <c>warn</c>
/// accepted). Unknown strings fall back to <c>Information</c>.
/// </remarks>
public interface ILogLevelSwitcher
{
/// <summary>Set the minimum log level from a canonical string.</summary>
void SetLevel(string level);
/// <summary>Canonical name of the currently active minimum level.</summary>
string CurrentLevel { get; }
}
@@ -1,5 +1,3 @@
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,6 +1,3 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,4 +1,3 @@
using System;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,6 +1,3 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,4 +1,3 @@
using System.Collections.Generic;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,4 +1,3 @@
using System;
using System.Collections.ObjectModel;
using CaptureImage.Core.Models;
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Abstractions;
/// <summary>
@@ -1,6 +1,3 @@
using System;
using System.Threading.Tasks;
namespace CaptureImage.Core.Abstractions;
/// <summary>
@@ -1,6 +1,3 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Errors;
/// <summary>
@@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
namespace CaptureImage.Core.Logging;
/// <summary>
/// Extension methods that inject <c>[CallerMemberName]</c>, <c>[CallerFilePath]</c>, and
/// <c>[CallerLineNumber]</c> as Serilog structured properties (<c>Member</c>, <c>File</c>,
/// <c>Line</c>) so every entry the log viewer shows — and every line the rolling file
/// receives — carries a cheap jump-to-source anchor.
/// </summary>
/// <remarks>
/// <para>
/// The properties are attached via <see cref="ILogger.BeginScope{TState}"/>. The
/// <c>Serilog.Extensions.Logging</c> provider forwards MEL scope state as
/// <see cref="Serilog.Events.LogEvent"/> properties, so the output template
/// <c>{File}:{Line}</c> and the <see cref="Models.LogEntry"/> mapper both see them.
/// </para>
/// <para>
/// <c>Path.GetFileName</c> strips the build-machine absolute path so we don't leak
/// <c>E:\capture\captureimg\…</c> into shipped binaries and user log exports.
/// </para>
/// <para>
/// Overloads are provided for 0–3 template arguments — that covers the vast majority of
/// call sites. For more arguments, fall back to <see cref="ILogger.BeginScope{TState}"/>
/// with a manual scope and regular <c>LogInformation</c>/<c>LogError</c>/etc.
/// </para>
/// </remarks>
public static class CallerAwareLoggerExtensions
{
// --- Information --------------------------------------------------------
public static void LogInformationAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(message);
}
}
public static void LogInformationAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0);
}
}
public static void LogInformationAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0, arg1);
}
}
public static void LogInformationAt<T0, T1, T2>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
T2 arg2,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0, arg1, arg2);
}
}
// --- Debug --------------------------------------------------------------
public static void LogDebugAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(message);
}
}
public static void LogDebugAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(messageTemplate, arg0);
}
}
public static void LogDebugAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(messageTemplate, arg0, arg1);
}
}
// --- Warning ------------------------------------------------------------
public static void LogWarningAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(message);
}
}
public static void LogWarningAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(messageTemplate, arg0);
}
}
public static void LogWarningAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(messageTemplate, arg0, arg1);
}
}
public static void LogWarningAt(
this ILogger logger,
Exception exception,
string messageTemplate,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate);
}
}
public static void LogWarningAt<T0>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate, arg0);
}
}
public static void LogWarningAt<T0, T1>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate, arg0, arg1);
}
}
// --- Error --------------------------------------------------------------
public static void LogErrorAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(message);
}
}
public static void LogErrorAt(
this ILogger logger,
Exception exception,
string messageTemplate,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate);
}
}
public static void LogErrorAt<T0>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate, arg0);
}
}
public static void LogErrorAt<T0, T1>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate, arg0, arg1);
}
}
// --- Shared scope builder -----------------------------------------------
private static Dictionary<string, object> CallerScope(string member, string filePath, int line)
=> new(3)
{
["Member"] = member ?? string.Empty,
// Path.GetFileName tolerates forward and back slashes, returns the input if the
// string doesn't look like a path — so empty / odd CallerFilePath values degrade
// gracefully.
["File"] = string.IsNullOrEmpty(filePath) ? string.Empty : Path.GetFileName(filePath),
["Line"] = line,
};
}
+27
View File
@@ -0,0 +1,27 @@
using System;
using System.IO;
namespace CaptureImage.Core.Logging;
/// <summary>
/// Canonical on-disk locations for log files. Shared between <c>LoggingSetup</c> (which
/// configures Serilog's rolling-file sink) and <c>LogViewerViewModel</c> (which opens the
/// folder when the user clicks "Reveal logs folder") so both agree on the path.
/// </summary>
public static class LogPaths
{
/// <summary>
/// Returns <c>%LocalAppData%\CaptureImage\logs</c>, creating the directory tree if
/// missing. Uses <see cref="Environment.SpecialFolder.LocalApplicationData"/> so the
/// path is per-user and roams with the profile.
/// </summary>
public static string GetLogsDirectory()
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CaptureImage",
"logs");
Directory.CreateDirectory(dir);
return dir;
}
}
+14 -1
View File
@@ -19,7 +19,7 @@ namespace CaptureImage.Core.Models;
public sealed record AppSettings
{
/// <summary>Schema version. Bump when adding migration steps.</summary>
public int Version { get; init; } = 1;
public int Version { get; init; } = 2;
/// <summary>
/// IETF BCP-47 culture code for UI (e.g. <c>en-US</c>, <c>vi-VN</c>, <c>ar-SA</c>).
@@ -34,6 +34,19 @@ public sealed record AppSettings
public CaptureSettings Capture { get; init; } = new();
public UiSettings UI { get; init; } = new();
/// <summary>
/// Minimum log level retained in the rolling file and in-memory buffer.
/// One of <c>Debug</c>, <c>Information</c>, <c>Warning</c>, <c>Error</c> — case-insensitive
/// on parse. Unknown values fall back to <c>Information</c>.
/// </summary>
/// <remarks>
/// Stored as a string rather than an enum so hand-edited <c>settings.json</c> files stay
/// readable and so the persistence layer doesn't take a dependency on MEL's enum identity.
/// v1 files load with this defaulted to <c>Information</c>; legacy behaviour was
/// <c>Debug</c>, so users who relied on it get a note in CHANGELOG to flip it back.
/// </remarks>
public string LogLevel { get; init; } = "Information";
}
/// <summary>Capture-specific persisted options.</summary>
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -1,7 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CaptureImage.Core.Validation;
namespace CaptureImage.Core.Models;
+27 -3
View File
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -11,12 +9,38 @@ namespace CaptureImage.Core.Models;
/// <param name="SourceContext">Fully-qualified logger name if present, else empty.</param>
/// <param name="Message">Rendered message text (format tokens already applied).</param>
/// <param name="Exception">Exception stringification if any, else null.</param>
/// <remarks>
/// The <see cref="File"/>, <see cref="Line"/>, and <see cref="Member"/> init-only properties are
/// populated when the call site used the <c>LogXAt</c> helpers from
/// <c>CaptureImage.Core.Logging.CallerAwareLoggerExtensions</c>; they stay null for legacy
/// call sites that still log via <c>ILogger&lt;T&gt;.LogInformation</c> or the static
/// <c>Serilog.Log</c> API.
/// </remarks>
public sealed record LogEntry(
DateTimeOffset Timestamp,
LogLevel Level,
string SourceContext,
string Message,
string? Exception);
string? Exception)
{
/// <summary>Source file name (e.g. <c>WindowsGraphicsCaptureEngine.cs</c>) — no directory.</summary>
public string? File { get; init; }
/// <summary>Line number in <see cref="File"/> where the log was emitted.</summary>
public int? Line { get; init; }
/// <summary>Method or property name that emitted the log.</summary>
public string? Member { get; init; }
/// <summary>
/// Convenience string for the log viewer — <c>"File.cs:42"</c> when both are present,
/// else empty. Computed; never participates in record equality.
/// </summary>
public string FileLineText =>
!string.IsNullOrEmpty(File) && Line is > 0
? $"{File}:{Line}"
: string.Empty;
}
/// <summary>Levels the log viewer filters on. Mapped from Serilog's LogEventLevel.</summary>
public enum LogLevel
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Errors;
using CaptureImage.Core.Models;
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using CaptureImage.Core.Models;
@@ -1,4 +1,3 @@
using System;
using Stateless;
namespace CaptureImage.Core.StateMachine;
@@ -1,5 +1,3 @@
using System.Collections.Generic;
using System.Linq;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Validation;
@@ -1,4 +1,3 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Windows.Graphics.Capture;
@@ -1,4 +1,3 @@
using System;
using System.Runtime.Versioning;
using Vortice.Direct3D;
using Vortice.Direct3D11;
@@ -1,4 +1,3 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Vortice.Direct3D11;
@@ -1,4 +1,3 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using CaptureImage.Core.Errors;
@@ -1,9 +1,8 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Errors;
using CaptureImage.Core.Logging;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
using Vortice.Direct3D11;
@@ -72,14 +71,29 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
{
item = CaptureItemInterop.CreateForWindow(target.WindowHandle);
}
catch (COMException comEx)
{
_logger.LogWarningAt(
comEx,
"CreateForWindow failed for HWND=0x{Hwnd:X8} HRESULT=0x{HResult:X8}.",
target.WindowHandle,
comEx.HResult);
throw new CaptureException(CaptureError.TargetGone,
$"CreateForWindow failed for HWND 0x{target.WindowHandle:X} (HRESULT 0x{comEx.HResult:X8}).", comEx);
}
catch (Exception ex)
{
_logger.LogWarningAt(
ex,
"CreateForWindow threw for HWND=0x{Hwnd:X8}.",
target.WindowHandle);
throw new CaptureException(CaptureError.TargetGone,
$"CreateForWindow failed for HWND 0x{target.WindowHandle:X}.", ex);
}
if (item is null)
{
_logger.LogWarningAt("GraphicsCaptureItem was null for HWND=0x{Hwnd:X8}.", target.WindowHandle);
throw new CaptureException(CaptureError.TargetGone, "GraphicsCaptureItem was null.");
}
@@ -103,6 +117,12 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
session.IsBorderRequired = false;
session.IsCursorCaptureEnabled = false;
_logger.LogInformationAt(
"WGC session started for HWND=0x{Hwnd:X8} size={Width}x{Height}.",
target.WindowHandle,
item.Size.Width,
item.Size.Height);
var tcs = new TaskCompletionSource<Direct3D11CaptureFrame>(
TaskCreationOptions.RunContinuationsAsynchronously);
@@ -132,11 +152,16 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
if (completed != tcs.Task)
{
cancellationToken.ThrowIfCancellationRequested();
_logger.LogWarningAt(
"WGC frame timeout after {Seconds:F1}s for HWND=0x{Hwnd:X8}.",
FrameTimeout.TotalSeconds,
target.WindowHandle);
throw new CaptureException(
CaptureError.NoFrameArrived,
$"No frame arrived within {FrameTimeout.TotalSeconds:F1}s.");
}
frame = await tcs.Task.ConfigureAwait(false);
_logger.LogDebugAt("WGC first frame received for HWND=0x{Hwnd:X8}.", target.WindowHandle);
}
finally
{
@@ -160,15 +185,26 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
{
throw new CaptureException(CaptureError.Cancelled, "Capture was cancelled.");
}
catch (COMException comEx)
{
_logger.LogErrorAt(
comEx,
"WGC capture COM failure for HWND=0x{Hwnd:X8} HRESULT=0x{HResult:X8}.",
target.WindowHandle,
comEx.HResult);
throw new CaptureException(CaptureError.Unknown,
$"WGC capture failed (HRESULT 0x{comEx.HResult:X8}): {comEx.Message}", comEx);
}
catch (Exception ex)
{
_logger.LogError(ex, "WGC capture failed for HWND 0x{Hwnd:X}.", target.WindowHandle);
_logger.LogErrorAt(ex, "WGC capture failed for HWND=0x{Hwnd:X8}.", target.WindowHandle);
throw new CaptureException(CaptureError.Unknown, "WGC capture failed: " + ex.Message, ex);
}
finally
{
session?.Dispose();
framePool?.Dispose();
_logger.LogDebugAt("WGC session disposed for HWND=0x{Hwnd:X8}.", target.WindowHandle);
// Note: `item` and `winrtDevice` are WinRT projections — they release automatically
// when the RCW is collected. Explicit dispose is optional but not required here.
}
@@ -1,7 +1,5 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
@@ -55,11 +53,30 @@ public sealed partial class HotkeyConflictSniffer : IHotkeyConflictSniffer
var err = Marshal.GetLastWin32Error();
_logger.LogDebug(
"RegisterHotKey sniff failed for {Binding} (win32 error {Err}); treating as conflicted.",
binding, err);
"RegisterHotKey sniff failed for {Binding}; treating as conflicted. ({ErrCode}: {ErrText})",
binding,
err,
DescribeWin32Error(err));
return true;
}
/// <summary>
/// Map the handful of Win32 errors <c>RegisterHotKey</c> can realistically produce back
/// to human-readable names. Unknown codes fall through to <c>"UNKNOWN"</c> — the
/// numeric value is always logged alongside so diagnosis isn't blocked on the map
/// having complete coverage.
/// </summary>
private static string DescribeWin32Error(int code) => code switch
{
0 => "ERROR_SUCCESS",
5 => "ERROR_ACCESS_DENIED",
87 => "ERROR_INVALID_PARAMETER",
1400 => "ERROR_INVALID_WINDOW_HANDLE",
1409 => "ERROR_HOTKEY_ALREADY_REGISTERED",
1419 => "ERROR_HOTKEY_NOT_REGISTERED",
_ => "UNKNOWN",
};
[LibraryImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
@@ -1,4 +1,3 @@
using System;
using System.Runtime.Versioning;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
@@ -60,7 +59,14 @@ public sealed class SharpHookHotkeyService : IHotkeyService
_binding = null;
if (_hook is not null)
{
try { _hook.Dispose(); } catch { /* ignore */ }
try
{
_hook.Dispose();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to dispose SharpHook on Stop.");
}
_hook = null;
_logger.LogInformation("Hotkey service stopped.");
}
@@ -73,7 +79,14 @@ public sealed class SharpHookHotkeyService : IHotkeyService
{
if (_disposed) return;
_disposed = true;
try { _hook?.Dispose(); } catch { /* ignore */ }
try
{
_hook?.Dispose();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to dispose SharpHook on Dispose.");
}
_hook = null;
}
}
@@ -85,6 +98,7 @@ public sealed class SharpHookHotkeyService : IHotkeyService
_hook = new TaskPoolGlobalHook();
_hook.KeyPressed += OnKeyPressed;
_hook.RunAsync();
_logger.LogInformation("SharpHook TaskPoolGlobalHook started.");
}
private void OnKeyPressed(object? sender, KeyboardHookEventArgs e)
@@ -1,6 +1,3 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Errors;
using CaptureImage.Core.Models;
@@ -1,8 +1,4 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Errors;
using CaptureImage.Core.Models;
@@ -0,0 +1,34 @@
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.Infrastructure.Logging;
/// <summary>
/// Serilog <see cref="ILogEventEnricher"/> that fills empty defaults for the caller-info
/// properties (<c>File</c>, <c>Line</c>, <c>Member</c>) on every log event where the call
/// site didn't populate them via <c>CallerAwareLoggerExtensions</c>.
/// </summary>
/// <remarks>
/// Without this, the rolling-file output template <c>({File}:{Line})</c> would render as
/// the literal <c>({File}:{Line})</c> tokens on legacy call sites. With it, those call
/// sites produce <c>(:)</c> — ugly but honest ("no caller context here"), and visually
/// easy to filter out when grepping a log.
/// </remarks>
public sealed class CallerPropertyDefaultsEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (!logEvent.Properties.ContainsKey("File"))
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("File", string.Empty));
}
if (!logEvent.Properties.ContainsKey("Line"))
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Line", 0));
}
if (!logEvent.Properties.ContainsKey("Member"))
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Member", string.Empty));
}
}
}
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.IO;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using Serilog.Core;
@@ -96,7 +93,36 @@ public sealed class InMemorySink : ILogEventSink, ILogBufferSource
Level: MapLevel(ev.Level),
SourceContext: sourceContext ?? string.Empty,
Message: writer.ToString(),
Exception: ev.Exception?.ToString());
Exception: ev.Exception?.ToString())
{
// Caller-info is injected by CallerAwareLoggerExtensions via MEL scope; absent
// on legacy call sites that still use Log.X or bare ILogger.LogInformation.
File = ReadStringProperty(ev, "File"),
Line = ReadInt32Property(ev, "Line"),
Member = ReadStringProperty(ev, "Member"),
};
}
private static string? ReadStringProperty(LogEvent ev, string name)
{
if (ev.Properties.TryGetValue(name, out var value) &&
value is ScalarValue { Value: string s } &&
!string.IsNullOrEmpty(s))
{
return s;
}
return null;
}
private static int? ReadInt32Property(LogEvent ev, string name)
{
if (ev.Properties.TryGetValue(name, out var value) &&
value is ScalarValue { Value: int i } &&
i > 0)
{
return i;
}
return null;
}
private static LogLevel MapLevel(LogEventLevel level) => level switch
@@ -0,0 +1,43 @@
using CaptureImage.Core.Abstractions;
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.Infrastructure.Logging;
/// <summary>
/// <see cref="ILogLevelSwitcher"/> backed by Serilog's <see cref="LoggingLevelSwitch"/>.
/// </summary>
public sealed class SerilogLogLevelSwitcher : ILogLevelSwitcher
{
private readonly LoggingLevelSwitch _levelSwitch;
public SerilogLogLevelSwitcher(LoggingLevelSwitch levelSwitch)
{
_levelSwitch = levelSwitch;
}
public string CurrentLevel => _levelSwitch.MinimumLevel switch
{
LogEventLevel.Verbose => "Debug",
LogEventLevel.Debug => "Debug",
LogEventLevel.Information => "Information",
LogEventLevel.Warning => "Warning",
LogEventLevel.Error => "Error",
LogEventLevel.Fatal => "Error",
_ => "Information",
};
public void SetLevel(string level)
{
_levelSwitch.MinimumLevel = level?.Trim().ToLowerInvariant() switch
{
"debug" => LogEventLevel.Debug,
"information" => LogEventLevel.Information,
"info" => LogEventLevel.Information,
"warning" => LogEventLevel.Warning,
"warn" => LogEventLevel.Warning,
"error" => LogEventLevel.Error,
_ => LogEventLevel.Information,
};
}
}
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
@@ -1,8 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.Versioning;
using Microsoft.Extensions.Logging;
@@ -1,4 +1,3 @@
using System;
using System.Runtime.InteropServices;
namespace CaptureImage.Infrastructure.Processes.Interop;
@@ -1,4 +1,3 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
@@ -1,5 +1,3 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using CaptureImage.Infrastructure.Processes.Interop;
@@ -1,4 +1,3 @@
using System;
using System.Management;
using System.Runtime.Versioning;
using CaptureImage.Core.Abstractions;
@@ -109,8 +108,10 @@ public sealed class WmiProcessWatcher : IProcessWatcher
private void DisposeWatchers_NoLock()
{
try { _startWatcher?.Stop(); } catch { /* ignore */ }
try { _stopWatcher?.Stop(); } catch { /* ignore */ }
try { _startWatcher?.Stop(); }
catch (Exception ex) { _logger.LogDebug(ex, "Failed to stop WMI creation watcher during teardown."); }
try { _stopWatcher?.Stop(); }
catch (Exception ex) { _logger.LogDebug(ex, "Failed to stop WMI deletion watcher during teardown."); }
_startWatcher?.Dispose();
_stopWatcher?.Dispose();
_startWatcher = null;
@@ -1,9 +1,5 @@
using System;
using System.IO;
using System.IO.Abstractions;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
@@ -22,7 +18,7 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
private static readonly TimeSpan WriteDebounce = TimeSpan.FromMilliseconds(300);
/// <summary>Highest schema version this binary understands.</summary>
private const int SupportedVersion = 1;
private const int SupportedVersion = 2;
private readonly IFileSystem _fs;
private readonly ILogger<JsonSettingsStore> _logger;
@@ -56,35 +52,114 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
public async Task LoadAsync(CancellationToken cancellationToken = default)
{
AppSettings loaded;
// Ensure settings.json exists on disk after a successful load. Four paths trigger
// a write-back:
// (1) file missing — first run, we want the user to see defaults they can edit;
// (2) parse failure — bad/corrupt JSON, replace with defaults so next run is clean;
// (3) version newer than we support — fall back to defaults;
// (4) partial/missing/extra fields — `System.Text.Json` fills init defaults for
// absent properties on deserialize, but on-disk file stays skewed; normalize
// by comparing re-serialized form with the raw JSON.
var needsWriteBack = false;
try
{
if (!_fs.File.Exists(_filePath))
{
_logger.LogInformation("Settings file not found; using defaults at {Path}.", _filePath);
_logger.LogInformation(
"Settings file not found at {Path}; initialising with defaults.", _filePath);
loaded = new AppSettings();
needsWriteBack = true;
}
else
{
var json = await _fs.File.ReadAllTextAsync(_filePath, cancellationToken).ConfigureAwait(false);
loaded = Deserialize(json) ?? new AppSettings();
if (loaded.Version > SupportedVersion)
var parsed = Deserialize(json);
if (parsed is null)
{
_logger.LogWarning(
"Settings file {Path} could not be parsed; replacing with defaults.", _filePath);
loaded = new AppSettings();
needsWriteBack = true;
}
else if (parsed.Version > SupportedVersion)
{
_logger.LogWarning(
"Settings file version {Found} is newer than supported {Supported}; using defaults.",
loaded.Version, SupportedVersion);
parsed.Version, SupportedVersion);
loaded = new AppSettings();
needsWriteBack = true;
}
else
{
// v1 → v2 migration: earlier builds only tracked fields up to UI.
// System.Text.Json's source-gen deserializer leaves absent init-only
// strings at null instead of the record's init default, so explicitly
// set LogLevel here; then stamp Version=2 and trigger a write-back
// so the canonical on-disk form matches the current schema.
if (parsed.Version < SupportedVersion)
{
_logger.LogInformation(
"Migrating settings file {Path} from version {From} to {To}.",
_filePath, parsed.Version, SupportedVersion);
parsed = parsed with
{
Version = SupportedVersion,
LogLevel = string.IsNullOrWhiteSpace(parsed.LogLevel)
? "Information"
: parsed.LogLevel,
};
needsWriteBack = true;
}
// Defensive: even a v2-stamped file can arrive with LogLevel=null if it
// was hand-edited or produced by an older preview binary. Fill in the
// default so downstream code never sees null.
if (string.IsNullOrWhiteSpace(parsed.LogLevel))
{
parsed = parsed with { LogLevel = "Information" };
needsWriteBack = true;
}
loaded = parsed;
// Partial/missing/extra fields — re-serializing fills init defaults, so
// if the canonical form differs from the raw JSON, write back to
// normalize the on-disk file.
var canonical = Serialize(loaded);
if (!string.Equals(json.Trim(), canonical.Trim(), StringComparison.Ordinal))
{
_logger.LogInformation(
"Settings file {Path} differs from canonical form; normalizing.", _filePath);
needsWriteBack = true;
}
_logger.LogInformation(
"Settings loaded from {Path} (version {Version}, log level {LogLevel}).",
_filePath, loaded.Version, loaded.LogLevel);
}
_logger.LogInformation("Settings loaded from {Path} (version {Version}).",
_filePath, loaded.Version);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to load settings from {Path}; reverting to defaults.", _filePath);
loaded = new AppSettings();
needsWriteBack = true;
}
SetCurrent(loaded, persistImmediately: false);
if (needsWriteBack)
{
try
{
await WriteAsync(loaded, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// Best-effort: Load must succeed even if the disk is read-only. A subsequent
// Update() will retry via the debounced write path.
_logger.LogWarning(
ex, "Could not write initial/normalized settings file to {Path}.", _filePath);
}
}
}
public void Update(Func<AppSettings, AppSettings> mutator)
@@ -224,21 +299,37 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
private void TryDelete(string path)
{
try { if (_fs.File.Exists(path)) _fs.File.Delete(path); }
catch { /* best-effort */ }
try
{
if (_fs.File.Exists(path)) _fs.File.Delete(path);
}
catch (Exception ex)
{
// Best-effort cleanup — if the temp file can't be removed, a subsequent write
// will overwrite it via the rename-into-place path. Log at Debug so we can still
// correlate if it compounds into a real failure later.
_logger.LogDebug(ex, "Failed to delete {Path}.", path);
}
}
private static string Serialize(AppSettings settings) =>
JsonSerializer.Serialize(settings, SettingsJsonContext.Default.AppSettings);
private static AppSettings? Deserialize(string json)
private AppSettings? Deserialize(string json)
{
try
{
return JsonSerializer.Deserialize(json, SettingsJsonContext.Default.AppSettings);
}
catch (JsonException)
catch (JsonException ex)
{
// The caller turns a null return into "replace with defaults". Surface the root
// cause here so the log explains why, not just that parsing failed.
_logger.LogWarning(
ex,
"Malformed settings JSON ({LineNumber}:{BytePositionInLine}); reverting to defaults.",
ex.LineNumber,
ex.BytePositionInLine);
return null;
}
}
@@ -1,4 +1,3 @@
using System;
using System.IO.Abstractions;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.Logging;
@@ -1,5 +1,3 @@
using System;
using System.Collections.Generic;
using System.IO.Abstractions;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
namespace CaptureImage.Infrastructure.Steam;
/// <summary>
@@ -1,5 +1,3 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CaptureImage.Infrastructure.Steam;
@@ -1,6 +1,3 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
@@ -147,12 +144,28 @@ public sealed class VelopackUpdateService : IUpdateService
{
if (_manager is null || _pendingUpdate is null)
{
_logger.LogWarning(
"ApplyAndRestart invoked with no pending update (manager={HasManager}, pending={HasPending}).",
_manager is not null,
_pendingUpdate is not null);
throw new InvalidOperationException(
"No pending update to install. Call CheckAsync + DownloadAsync first.");
}
_logger.LogInformation(
"Applying update {Version} and restarting.",
_pendingUpdate.TargetFullRelease.Version);
EmitLog("Applying update and restarting…");
_manager.ApplyUpdatesAndRestart(_pendingUpdate.TargetFullRelease);
try
{
_manager.ApplyUpdatesAndRestart(_pendingUpdate.TargetFullRelease);
}
catch (Exception ex)
{
_logger.LogError(ex, "ApplyUpdatesAndRestart failed.");
EmitLog($"Apply failed: {ex.Message}");
throw;
}
}
private void EmitLog(string line)
@@ -34,14 +34,14 @@
BorderBrush="{DynamicResource SystemControlForegroundBaseMediumLowBrush}"
Background="{DynamicResource SystemControlBackgroundChromeMediumLowBrush}"
VerticalAlignment="Center"
AutomationProperties.Name="{Binding Localization[Settings_Hotkey]}"
AutomationProperties.HelpText="{Binding Localization[Settings_HotkeyRecorderPrompt]}">
AutomationProperties.Name="{Binding HotkeyFieldAutomationName}"
AutomationProperties.HelpText="{Binding RecorderPromptText}">
<Grid>
<TextBlock Text="{Binding DisplayText}"
FontFamily="Consolas, Courier New, monospace"
VerticalAlignment="Center"
IsVisible="{Binding !IsRecording}" />
<TextBlock Text="{Binding Localization[Settings_HotkeyRecorderPrompt]}"
<TextBlock Text="{Binding RecorderPromptText}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
FontStyle="Italic"
VerticalAlignment="Center"
@@ -50,18 +50,18 @@
</Border>
<Button Grid.Column="2"
Content="{Binding Localization[Settings_HotkeyRecord]}"
Content="{Binding RecordLabel}"
Command="{Binding StartRecordingCommand}"
IsVisible="{Binding !IsRecording}"
MinWidth="80" />
<Button Grid.Column="2"
Content="{Binding Localization[Settings_HotkeyCancel]}"
Content="{Binding CancelLabel}"
Command="{Binding CancelRecordingCommand}"
IsVisible="{Binding IsRecording}"
MinWidth="80" />
<Button Grid.Column="4"
Content="{Binding Localization[Settings_HotkeyReset]}"
Content="{Binding ResetLabel}"
Command="{Binding ResetToDefaultCommand}"
IsVisible="{Binding !IsRecording}"
MinWidth="80" />
@@ -75,7 +75,7 @@
IsVisible="{Binding HasError}" />
<!-- Conflict warning — non-blocking, binding already persisted. -->
<TextBlock Text="{Binding Localization[Settings_HotkeyConflictWarning]}"
<TextBlock Text="{Binding ConflictWarningText}"
Foreground="#C19C00"
FontSize="11"
TextWrapping="Wrap"
@@ -1,4 +1,3 @@
using System;
using System.ComponentModel;
using Avalonia.Controls;
using Avalonia.Input;
@@ -1,6 +1,4 @@
using System;
using System.Globalization;
using System.IO;
using Avalonia.Data.Converters;
using Avalonia.Media.Imaging;
@@ -1,4 +1,3 @@
using System;
using System.Globalization;
using Avalonia.Data.Converters;
using CaptureImage.Core.Abstractions;
@@ -1,4 +1,3 @@
using System;
using System.Globalization;
using Avalonia.Data.Converters;
using Avalonia.Media;
@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Globalization;
using System.Resources;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.Logging;
namespace CaptureImage.UI.Localization;
@@ -24,12 +24,22 @@ public sealed class ResxLocalizationService : ILocalizationService
};
private readonly ResourceManager _resourceManager;
private readonly ILogger<ResxLocalizationService> _logger;
/// <summary>
/// Tracks <c>(culture, key)</c> pairs we've already logged a "missing string" warning for.
/// Missing keys are usually the same handful repeated on every refresh; logging once per
/// pair per process keeps the signal without flooding the rolling file.
/// </summary>
private readonly ConcurrentDictionary<string, byte> _loggedMissingKeys = new();
private CultureInfo _currentCulture;
public ResxLocalizationService()
public ResxLocalizationService(ILogger<ResxLocalizationService> logger)
{
_resourceManager = new ResourceManager(ResourceBaseName, typeof(ResxLocalizationService).Assembly);
_currentCulture = CultureInfo.GetCultureInfo("en-US");
_logger = logger;
}
public event PropertyChangedEventHandler? PropertyChanged;
@@ -53,15 +63,42 @@ public sealed class ResxLocalizationService : ILocalizationService
if (string.IsNullOrEmpty(key)) return string.Empty;
try
{
return _resourceManager.GetString(key, _currentCulture) ?? $"[{key}]";
var value = _resourceManager.GetString(key, _currentCulture);
if (value is null)
{
LogMissingKeyOnce(key);
return $"[{key}]";
}
return value;
}
catch
catch (Exception ex)
{
LogMissingKeyOnce(key, ex);
return $"[{key}]";
}
}
}
private void LogMissingKeyOnce(string key, Exception? exception = null)
{
var dedupKey = $"{_currentCulture.Name}|{key}";
if (!_loggedMissingKeys.TryAdd(dedupKey, 0)) return;
if (exception is null)
{
_logger.LogWarning(
"Localization key '{Key}' missing for culture {Culture}; falling back to bracketed key.",
key, _currentCulture.Name);
}
else
{
_logger.LogWarning(
exception,
"Localization lookup threw for key '{Key}' culture {Culture}; falling back to bracketed key.",
key, _currentCulture.Name);
}
}
public void SetCulture(CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(culture);
@@ -71,7 +108,18 @@ public sealed class ResxLocalizationService : ILocalizationService
}
_currentCulture = culture;
// The indexer passes _currentCulture explicitly to ResourceManager so resx lookup
// is correct regardless of thread culture — but date/number/currency formatting
// elsewhere in the app uses the ambient CurrentCulture. Align both so a vi-VN
// user sees Vietnamese dates and an ar-SA user sees Arabic-Indic digits wherever
// implicit .ToString() lands. DefaultThread* sets the baseline for threads that
// haven't overridden their own culture (e.g. background threads the user hasn't
// touched yet); the UI thread gets both explicit assignments.
CultureInfo.CurrentUICulture = culture;
CultureInfo.CurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
CultureInfo.DefaultThreadCurrentCulture = culture;
// "Item[]" is the magic property name that tells Avalonia to refresh every indexer binding.
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
@@ -60,7 +60,6 @@
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>الإعدادات</value></data>
<data name="Settings_Language" xml:space="preserve"><value>اللغة</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>المظهر</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>مفتاح اختصار الالتقاط</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>انقر تسجيل ثم اضغط على مجموعة مفاتيح. Esc للإلغاء. إعادة التعيين تستعيد Ctrl+Shift+F12.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>تسجيل…</value></data>
@@ -77,13 +76,21 @@
<data name="Settings_WebpQuality" xml:space="preserve"><value>جودة WebP</value></data>
<data name="Settings_OutputFolder" xml:space="preserve"><value>مجلد الإخراج</value></data>
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(افتراضي: Pictures\CaptureImage)</value></data>
<data name="Settings_Browse" xml:space="preserve"><value>استعراض…</value></data>
<data name="Settings_BrowseTitle" xml:space="preserve"><value>اختر مجلد الإخراج</value></data>
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>اختر مجلدًا بدلاً من كتابة المسار.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>قالب اسم الملف</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>معاينة كل التقاط قبل الحفظ</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>زر الإغلاق يصغر إلى علبة النظام</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>تشغيل صوت الالتقاط</value></data>
<data name="Settings_Import" xml:space="preserve"><value>استيراد…</value></data>
<data name="Settings_Export" xml:space="preserve"><value>تصدير…</value></data>
<data name="Settings_ImportTitle" xml:space="preserve"><value>استيراد الإعدادات</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>تصدير الإعدادات</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>فتح ملف الإعدادات</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>السجلات</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>الحد الأدنى لمستوى السجل</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>يُصفّي ملف السجل المتدوّر وعارض السجل. اختر Debug للتشخيص، Information للاستخدام اليومي، Warning أو Error لتقليل الضوضاء.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>تحديث</value></data>
@@ -105,8 +112,11 @@
<data name="About_AiSection" xml:space="preserve"><value>التطوير بمساعدة الذكاء الاصطناعي</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>إخلاءات المسؤولية</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>الترجمات</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>حزم اللغة العربية والفيتنامية مترجمة بمساعدة الآلة. قد لا تتطابق المصطلحات مع العرف المحلي، وبعض الكلمات التقنية (hotkey، toast، frame، إلخ) تُركت بالإنجليزية عمداً. نرحب بمتحدثي اللغة الأم الراغبين في المراجعة لإرسال طلبات سحب على ملفات .resx في src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>دعم الالتقاط</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>يمكن لـ CaptureImage التقاط معظم الألعاب النافذية وعديمة الحدود عبر Windows.Graphics.Capture، لكن ليست كل لعبة تعمل. الأسطح المحمية بـ DRM، وألعاب Direct3D 9 بالشاشة الكاملة الحصرية، والألعاب ذات خطافات anti-cheat قد تعيد إطارات سوداء أو ترفض الالتقاط. تُجرَّب آلية احتياطية GDI PrintWindow للتطبيقات القديمة. راجع docs/legal/DISCLAIMER.md §2 للقائمة الكاملة.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>بدون ضمان</value></data>
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>يُوزَّع CaptureImage بموجب GPL-3.0-or-later كما هو، دون أي ضمان من أي نوع. المؤلفون غير مسؤولين عن لقطات الشاشة المفقودة أو تعطل الألعاب أو عقوبات anti-cheat أو فقد البيانات. الاستخدام على مسؤوليتك الخاصة. راجع docs/legal/DISCLAIMER.md للنص الكامل.</value></data>
<data name="About_LegalSection" xml:space="preserve"><value>المستندات القانونية</value></data>
<data name="About_ThirdPartySection" xml:space="preserve"><value>مكونات الطرف الثالث</value></data>
<data name="About_ThirdPartyHint" xml:space="preserve"><value>انقر على "Third-party notices" أعلاه للحصول على القائمة الكاملة مع عناوين URL.</value></data>
@@ -122,9 +132,10 @@
<data name="Log_Pause" xml:space="preserve"><value>إيقاف مؤقت</value></data>
<data name="Log_Resume" xml:space="preserve"><value>استئناف</value></data>
<data name="Log_Clear" xml:space="preserve"><value>مسح</value></data>
<data name="Log_Export" xml:space="preserve"><value>تصدير…</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} حدث</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>لا توجد أحداث سجل بعد. ستظهر الأحداث المباشرة من محرك الالتقاط هنا.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>الحد الأدنى:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>فتح المجلد</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>معاينة</value></data>
@@ -137,11 +148,10 @@
<data name="Toast_CaptureFailed" xml:space="preserve"><value>فشل الالتقاط</value></data>
<data name="Toast_SettingsImported" xml:space="preserve"><value>تم استيراد الإعدادات</value></data>
<data name="Toast_SettingsExported" xml:space="preserve"><value>تم تصدير الإعدادات</value></data>
<data name="Toast_Error" xml:space="preserve"><value>خطأ</value></data>
<!-- Tray menu -->
<data name="Tray_ShowWindow" xml:space="preserve"><value>عرض CaptureImage</value></data>
<data name="Tray_Arm" xml:space="preserve"><value>تفعيل الالتقاط</value></data>
<data name="Tray_Disarm" xml:space="preserve"><value>إلغاء تفعيل الالتقاط</value></data>
<data name="Tray_OpenFolder" xml:space="preserve"><value>فتح مجلد اللقطات</value></data>
<data name="Tray_Exit" xml:space="preserve"><value>خروج</value></data>
@@ -60,7 +60,6 @@
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>Settings</value></data>
<data name="Settings_Language" xml:space="preserve"><value>Language</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>Theme</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>Capture hotkey</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Click Record and press a combination. Esc cancels. Reset restores Ctrl+Shift+F12.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>Record…</value></data>
@@ -77,13 +76,21 @@
<data name="Settings_WebpQuality" xml:space="preserve"><value>WebP quality</value></data>
<data name="Settings_OutputFolder" xml:space="preserve"><value>Output folder</value></data>
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(default: Pictures\CaptureImage)</value></data>
<data name="Settings_Browse" xml:space="preserve"><value>Browse…</value></data>
<data name="Settings_BrowseTitle" xml:space="preserve"><value>Choose output folder</value></data>
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>Pick a folder instead of typing the path.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>File name template</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>Preview each capture before saving</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>Close button minimizes to tray</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>Play capture sound</value></data>
<data name="Settings_Import" xml:space="preserve"><value>Import…</value></data>
<data name="Settings_Export" xml:space="preserve"><value>Export…</value></data>
<data name="Settings_ImportTitle" xml:space="preserve"><value>Import settings</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>Export settings</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>Open settings file</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>Logging</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>Minimum log level</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>Filters the rolling log file and viewer. Pick Debug for support diagnostics, Information for day-to-day, Warning or Error to keep logs quiet.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>Update</value></data>
@@ -105,8 +112,11 @@
<data name="About_AiSection" xml:space="preserve"><value>AI-assisted development</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>Disclaimers</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>Translations</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Vietnamese and Arabic language packs are machine-assisted. Terminology may not match native conventions, and some technical words (hotkey, toast, frame, etc.) are kept in English on purpose. Native speakers willing to proofread are warmly invited to submit pull requests against the .resx files in src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>Capture support</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage can capture most windowed and borderless games via Windows.Graphics.Capture, but not every title works. DRM-protected surfaces, exclusive-fullscreen Direct3D 9 games, and titles with anti-cheat hooks may return black frames or refuse capture. A GDI PrintWindow fallback is attempted for legacy apps. See docs/legal/DISCLAIMER.md §2 for the full list.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>No warranty</value></data>
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage is distributed under GPL-3.0-or-later AS IS, without warranty of any kind. The authors are not liable for lost screenshots, game crashes, anti-cheat sanctions, or data loss. Use at your own risk. See docs/legal/DISCLAIMER.md for the full text.</value></data>
<data name="About_LegalSection" xml:space="preserve"><value>Legal documents</value></data>
<data name="About_ThirdPartySection" xml:space="preserve"><value>Third-party components</value></data>
<data name="About_ThirdPartyHint" xml:space="preserve"><value>Click "Third-party notices" above for the full list with upstream URLs.</value></data>
@@ -122,9 +132,10 @@
<data name="Log_Pause" xml:space="preserve"><value>Pause</value></data>
<data name="Log_Resume" xml:space="preserve"><value>Resume</value></data>
<data name="Log_Clear" xml:space="preserve"><value>Clear</value></data>
<data name="Log_Export" xml:space="preserve"><value>Export…</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} events</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>No log events yet. Live events from the capture engine will appear here.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>Min level:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>Open folder</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>Preview</value></data>
@@ -137,11 +148,10 @@
<data name="Toast_CaptureFailed" xml:space="preserve"><value>Capture failed</value></data>
<data name="Toast_SettingsImported" xml:space="preserve"><value>Settings imported</value></data>
<data name="Toast_SettingsExported" xml:space="preserve"><value>Settings exported</value></data>
<data name="Toast_Error" xml:space="preserve"><value>Error</value></data>
<!-- Tray menu -->
<data name="Tray_ShowWindow" xml:space="preserve"><value>Show CaptureImage</value></data>
<data name="Tray_Arm" xml:space="preserve"><value>Arm capture</value></data>
<data name="Tray_Disarm" xml:space="preserve"><value>Disarm capture</value></data>
<data name="Tray_OpenFolder" xml:space="preserve"><value>Open captures folder</value></data>
<data name="Tray_Exit" xml:space="preserve"><value>Exit</value></data>
@@ -60,7 +60,6 @@
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>Cài đặt</value></data>
<data name="Settings_Language" xml:space="preserve"><value>Ngôn ngữ</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>Giao diện</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>Hotkey chụp</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Nhấn Ghi rồi nhấn tổ hợp phím. Esc để huỷ. Đặt lại sẽ khôi phục Ctrl+Shift+F12.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>Ghi…</value></data>
@@ -77,13 +76,21 @@
<data name="Settings_WebpQuality" xml:space="preserve"><value>Chất lượng WebP</value></data>
<data name="Settings_OutputFolder" xml:space="preserve"><value>Thư mục lưu</value></data>
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(mặc định: Pictures\CaptureImage)</value></data>
<data name="Settings_Browse" xml:space="preserve"><value>Duyệt…</value></data>
<data name="Settings_BrowseTitle" xml:space="preserve"><value>Chọn thư mục lưu</value></data>
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>Chọn thư mục thay vì phải gõ đường dẫn.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>Mẫu tên tệp</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>Xem trước từng ảnh chụp trước khi lưu</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>Nút đóng sẽ thu nhỏ xuống tray</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>Phát âm thanh khi chụp</value></data>
<data name="Settings_Import" xml:space="preserve"><value>Nhập…</value></data>
<data name="Settings_Export" xml:space="preserve"><value>Xuất…</value></data>
<data name="Settings_ImportTitle" xml:space="preserve"><value>Nhập cài đặt</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>Xuất cài đặt</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>Mở tệp cài đặt</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>Ghi log</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>Mức log tối thiểu</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>Lọc cả file log xoay vòng và cửa sổ Log. Chọn Debug khi gỡ lỗi, Information cho vận hành hằng ngày, Warning hoặc Error để giữ log gọn.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>Cập nhật</value></data>
@@ -105,8 +112,11 @@
<data name="About_AiSection" xml:space="preserve"><value>Phát triển có hỗ trợ AI</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>Tuyên bố miễn trừ</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>Bản dịch</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Gói ngôn ngữ tiếng Việt và tiếng Ả Rập đang dùng bản dịch máy. Thuật ngữ có thể không khớp với quy ước bản ngữ, và một số từ kỹ thuật (hotkey, toast, frame, v.v.) được giữ tiếng Anh có chủ đích. Người bản ngữ sẵn lòng hiệu đính xin gửi pull request vào các tệp .resx trong src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>Khả năng chụp</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage có thể chụp hầu hết game cửa sổ và borderless qua Windows.Graphics.Capture, nhưng không phải game nào cũng hoạt động. Bề mặt có DRM, game Direct3D 9 exclusive-fullscreen, và game có hook anti-cheat có thể trả khung đen hoặc từ chối chụp. Cơ chế dự phòng GDI PrintWindow được thử cho ứng dụng cũ. Xem docs/legal/DISCLAIMER.md §2 để biết danh sách đầy đủ.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>Không bảo hành</value></data>
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage được phân phối theo GPL-3.0-or-later NGUYÊN TRẠNG, không kèm bảo đảm dưới bất kỳ hình thức nào. Các tác giả không chịu trách nhiệm về ảnh chụp bị mất, game crash, chế tài từ anti-cheat, hay mất dữ liệu. Dùng với rủi ro của chính bạn. Xem docs/legal/DISCLAIMER.md để biết toàn văn.</value></data>
<data name="About_LegalSection" xml:space="preserve"><value>Tài liệu pháp lý</value></data>
<data name="About_ThirdPartySection" xml:space="preserve"><value>Thành phần third-party</value></data>
<data name="About_ThirdPartyHint" xml:space="preserve"><value>Bấm "Third-party notices" phía trên để xem danh sách đầy đủ kèm URL upstream.</value></data>
@@ -122,9 +132,10 @@
<data name="Log_Pause" xml:space="preserve"><value>Tạm dừng</value></data>
<data name="Log_Resume" xml:space="preserve"><value>Tiếp tục</value></data>
<data name="Log_Clear" xml:space="preserve"><value>Xoá</value></data>
<data name="Log_Export" xml:space="preserve"><value>Xuất…</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} sự kiện</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>Chưa có sự kiện nhật ký nào. Sự kiện thời gian thực từ capture engine sẽ xuất hiện ở đây.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>Mức tối thiểu:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>Mở thư mục</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>Xem trước</value></data>
@@ -137,11 +148,10 @@
<data name="Toast_CaptureFailed" xml:space="preserve"><value>Chụp thất bại</value></data>
<data name="Toast_SettingsImported" xml:space="preserve"><value>Đã nhập cài đặt</value></data>
<data name="Toast_SettingsExported" xml:space="preserve"><value>Đã xuất cài đặt</value></data>
<data name="Toast_Error" xml:space="preserve"><value>Lỗi</value></data>
<!-- Tray menu -->
<data name="Tray_ShowWindow" xml:space="preserve"><value>Hiện CaptureImage</value></data>
<data name="Tray_Arm" xml:space="preserve"><value>Sẵn sàng chụp</value></data>
<data name="Tray_Disarm" xml:space="preserve"><value>Ngừng chụp</value></data>
<data name="Tray_OpenFolder" xml:space="preserve"><value>Mở thư mục ảnh</value></data>
<data name="Tray_Exit" xml:space="preserve"><value>Thoát</value></data>
@@ -1,7 +1,3 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using CaptureImage.Core.Abstractions;
@@ -43,7 +39,10 @@ public sealed class AvaloniaPreviewPresenter : IPreviewPresenter
{
try
{
var vm = new PreviewViewModel(_localization);
// `using` so the VM's Localization.PropertyChanged subscription is detached
// after the modal closes — otherwise every preview leaks one handler into
// the singleton localization service.
using var vm = new PreviewViewModel(_localization);
vm.SetFrame(frame, target, pngBytes);
var window = new PreviewWindow
@@ -1,7 +1,5 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
@@ -44,7 +42,7 @@ public sealed class AvaloniaTrayIconHost : ITrayIconHost
_trayIcon = new TrayIcon
{
Icon = BuildRuntimeIcon(),
Icon = BuildRuntimeIconSafely(),
ToolTipText = "CaptureImage",
IsVisible = true,
Menu = BuildMenu(),
@@ -56,15 +54,43 @@ public sealed class AvaloniaTrayIconHost : ITrayIconHost
TrayIcon.SetIcons(Application.Current!, icons);
_mainWindow.Closing += OnMainWindowClosing;
_localization.PropertyChanged += (_, _) => RefreshMenuLabels();
_localization.PropertyChanged += OnLocalizationChanged;
_logger.LogInformation("Tray icon initialized.");
_logger.LogInformation("Tray icon initialized and visible.");
}
private WindowIcon? BuildRuntimeIconSafely()
{
try
{
return BuildRuntimeIcon();
}
catch (Exception ex)
{
// A SkiaSharp / native-asset failure here used to take the whole startup down.
// Fall back to a null icon (Avalonia renders a default glyph) and log — the
// user still gets a tray entry, just one without our branding.
_logger.LogWarning(ex, "Failed to render runtime tray icon via SkiaSharp; falling back to default.");
return null;
}
}
private void OnLocalizationChanged(object? sender, PropertyChangedEventArgs e)
{
// `ResxLocalizationService.SetCulture` raises three events per switch
// (Item[], CurrentCulture, CurrentFlowDirection). Rebuild the menu once, not
// three times — Item[] is the canonical "all lookups may have changed" signal.
if (e.PropertyName == "Item[]")
{
RefreshMenuLabels();
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_localization.PropertyChanged -= OnLocalizationChanged;
if (_mainWindow is not null)
{
_mainWindow.Closing -= OnMainWindowClosing;
@@ -75,6 +101,7 @@ public sealed class AvaloniaTrayIconHost : ITrayIconHost
_trayIcon.Dispose();
_trayIcon = null;
}
_logger.LogInformation("Tray icon disposed.");
}
// -- menu ----------------------------------------------------------------
@@ -1,5 +1,3 @@
using System;
using System.Threading.Tasks;
using Avalonia.Threading;
using CaptureImage.Core.Abstractions;
@@ -1,6 +1,4 @@
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Avalonia.Threading;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
+5 -1
View File
@@ -7,7 +7,11 @@
x:Class="CaptureImage.UI.Views.AboutView"
x:DataType="vm:AboutViewModel">
<ScrollViewer>
<!-- HorizontalScrollBarVisibility=Disabled prevents the horizontal bar from ever
appearing; Vertical=Hidden lets mouse-wheel scrolling keep working but hides
the track so the view reads cleanly on a fixed window. -->
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16,24,24" Spacing="18" MaxWidth="640">
<!-- Header -->
+29 -5
View File
@@ -16,21 +16,37 @@
<Grid RowDefinitions="Auto,*">
<!-- Header + controls -->
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto,Auto" Margin="0,0,0,8">
<Grid Grid.Row="0"
ColumnDefinitions="*,Auto,Auto,Auto,Auto,Auto,Auto"
Margin="0,0,0,8">
<TextBlock Grid.Column="0"
Text="{Binding Localization[Log_Title]}"
FontSize="14"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<Button Grid.Column="1"
<TextBlock Grid.Column="1"
Text="{Binding FilterLabel}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
VerticalAlignment="Center"
Margin="0,0,6,0" />
<ComboBox Grid.Column="2"
ItemsSource="{Binding FilterLevels}"
SelectedItem="{Binding SelectedFilterLevel, Mode=TwoWay}"
MinWidth="110"
Margin="0,0,8,0" />
<Button Grid.Column="3"
Command="{Binding TogglePauseCommand}"
Content="{Binding TogglePauseLabel}"
Margin="0,0,8,0" />
<Button Grid.Column="2"
<Button Grid.Column="4"
Command="{Binding ClearCommand}"
Content="{Binding Localization[Log_Clear]}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="3"
<Button Grid.Column="5"
Command="{Binding RevealLogsFolderCommand}"
Content="{Binding RevealFolderLabel}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="6"
Text="{Binding EventsCountText}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
VerticalAlignment="Center" />
@@ -44,7 +60,7 @@
<ItemsControl ItemsSource="{Binding Entries}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="models:LogEntry">
<Grid ColumnDefinitions="Auto,Auto,*" Margin="0,1">
<Grid ColumnDefinitions="Auto,Auto,Auto,*" Margin="0,1">
<TextBlock Grid.Column="0"
Text="{Binding Timestamp, StringFormat='HH:mm:ss.fff'}"
FontFamily="Consolas, Courier New, monospace"
@@ -58,6 +74,14 @@
Width="45"
Margin="0,0,8,0" />
<TextBlock Grid.Column="2"
Text="{Binding FileLineText}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
Width="170"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
TextTrimming="CharacterEllipsis"
Margin="0,0,8,0" />
<TextBlock Grid.Column="3"
Text="{Binding Message}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
+31 -9
View File
@@ -15,9 +15,9 @@
x:Class="CaptureImage.UI.Views.MainWindow"
x:DataType="vm:MainWindowViewModel"
Title="CaptureImage"
Width="960" Height="600"
MinWidth="960" MinHeight="600"
MaxWidth="960" MaxHeight="600"
Width="1200" Height="720"
MinWidth="1200" MinHeight="720"
MaxWidth="1200" MaxHeight="720"
CanResize="False"
WindowStartupLocation="CenterScreen"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={x:Static conv:FlowDirectionConverter.Instance}}">
@@ -65,14 +65,14 @@
HorizontalContentAlignment="Left"
Margin="8,4,8,16"
Padding="12,8"
AutomationProperties.Name="{Binding Localization[Dashboard_LogToggle]}"
ToolTip.Tip="{Binding Localization[Dashboard_LogToggle]}">
AutomationProperties.Name="{Binding LogToggleTooltip}"
ToolTip.Tip="{Binding LogToggleTooltip}">
<StackPanel Orientation="Horizontal" Spacing="12">
<TextBlock Text="&#xE9F9;"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets"
FontSize="16"
VerticalAlignment="Center" />
<TextBlock Text="{Binding Localization[Nav_LogViewer]}"
<TextBlock Text="{Binding LogToggleLabel}"
VerticalAlignment="Center" />
</StackPanel>
</Button>
@@ -108,11 +108,33 @@
</Grid>
<!-- Log viewer drawer — overlays the right 400px when toggled. -->
<views:LogViewerView Width="400"
<!-- Log viewer drawer — overlays the right 480px of the content grid with a
200ms slide-in + fade. Always kept in the visual tree so the transitions
fire on every toggle; IsHitTestVisible + Classes.visible let us collapse
interaction + drive the animation state from IsLogViewerVisible. -->
<views:LogViewerView x:Name="LogDrawer"
Width="480"
HorizontalAlignment="Right"
DataContext="{Binding LogViewer}"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}" />
Classes.visible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}"
IsHitTestVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}">
<views:LogViewerView.Styles>
<Style Selector="views|LogViewerView">
<Setter Property="Opacity" Value="0" />
<Setter Property="RenderTransform" Value="translateX(48px)" />
<Setter Property="Transitions">
<Transitions>
<DoubleTransition Property="Opacity" Duration="0:0:0.18" Easing="CircularEaseOut" />
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.22" Easing="CircularEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="views|LogViewerView.visible">
<Setter Property="Opacity" Value="1" />
<Setter Property="RenderTransform" Value="translateX(0)" />
</Style>
</views:LogViewerView.Styles>
</views:LogViewerView>
<!-- Toast overlay — anchored bottom-right, floats over the content grid.
Under RTL FlowDirection Avalonia automatically mirrors Right/Left edges,
@@ -7,10 +7,11 @@
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.PreviewWindow"
x:DataType="vm:PreviewViewModel"
Title="Preview"
Title="{Binding Localization[Preview_Title]}"
Width="720" Height="560"
WindowStartupLocation="CenterOwner"
CanResize="False">
CanResize="False"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={x:Static conv:FlowDirectionConverter.Instance}}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16">
@@ -1,5 +1,3 @@
using System;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
+49 -19
View File
@@ -5,19 +5,22 @@
xmlns:vm="clr-namespace:CaptureImage.ViewModels.Settings;assembly=CaptureImage.ViewModels"
xmlns:ctrl="clr-namespace:CaptureImage.UI.Controls"
xmlns:sys="clr-namespace:System.Globalization;assembly=System.Runtime"
xmlns:models="clr-namespace:CaptureImage.Core.Models;assembly=CaptureImage.Core"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.SettingsView"
x:DataType="vm:SettingsViewModel">
<ScrollViewer>
<!-- HorizontalScrollBarVisibility=Disabled prevents the horizontal bar from ever
appearing; Vertical=Hidden lets mouse-wheel scrolling keep working but hides
the track so the view reads cleanly on a fixed window. -->
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16" Spacing="18" MaxWidth="620">
<TextBlock Text="{Binding Localization[Settings_Title]}" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{Binding TitleLabel}" FontSize="22" FontWeight="SemiBold" />
<!-- Language -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[Settings_Language]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBlock Text="{Binding LanguageLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<ComboBox ItemsSource="{Binding SupportedCultures}"
SelectedItem="{Binding SelectedCulture, Mode=TwoWay}"
HorizontalAlignment="Stretch">
@@ -31,14 +34,14 @@
<!-- Hotkey -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[Settings_Hotkey]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBlock Text="{Binding HotkeyLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<ctrl:HotkeyRecorder DataContext="{Binding Hotkey}" />
<TextBlock Text="{Binding Localization[Settings_HotkeyHint]}" FontSize="11" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
<TextBlock Text="{Binding HotkeyHint}" FontSize="11" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
</StackPanel>
<!-- Default format -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[Settings_Format]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBlock Text="{Binding FormatLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<ComboBox ItemsSource="{Binding SupportedFormats}"
SelectedItem="{Binding DefaultFormat, Mode=TwoWay}"
HorizontalAlignment="Stretch" />
@@ -47,12 +50,12 @@
<!-- Quality sliders -->
<Grid ColumnDefinitions="*,16,*">
<StackPanel Grid.Column="0" Spacing="4">
<TextBlock Text="{Binding Localization[Settings_JpegQuality]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBlock Text="{Binding JpegQualityLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<Slider Minimum="1" Maximum="100" Value="{Binding JpegQuality, Mode=TwoWay}" TickFrequency="10" />
<TextBlock Text="{Binding JpegQuality}" FontSize="11" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" HorizontalAlignment="Right" />
</StackPanel>
<StackPanel Grid.Column="2" Spacing="4">
<TextBlock Text="{Binding Localization[Settings_WebpQuality]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBlock Text="{Binding WebpQualityLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<Slider Minimum="1" Maximum="100" Value="{Binding WebpQuality, Mode=TwoWay}" TickFrequency="10" />
<TextBlock Text="{Binding WebpQuality}" FontSize="11" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" HorizontalAlignment="Right" />
</StackPanel>
@@ -60,33 +63,60 @@
<!-- Output folder -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[Settings_OutputFolder]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBox Text="{Binding OutputDirectory, Mode=TwoWay}"
Watermark="{Binding Localization[Settings_OutputFolderDefault]}" />
<TextBlock Text="{Binding OutputFolderLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<Grid ColumnDefinitions="*,8,Auto">
<TextBox Grid.Column="0"
Text="{Binding OutputDirectory, Mode=TwoWay}"
Watermark="{Binding OutputFolderWatermark}" />
<Button Grid.Column="2"
Name="BrowseOutputButton"
Content="{Binding BrowseLabel}"
ToolTip.Tip="{Binding BrowseTooltip}"
MinWidth="100" />
</Grid>
</StackPanel>
<!-- File name template -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[Settings_FileNameTemplate]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBlock Text="{Binding FileNameTemplateLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBox Text="{Binding FileNameTemplate, Mode=TwoWay}"
FontFamily="Consolas, Courier New, monospace" />
</StackPanel>
<!-- Toggles -->
<StackPanel Spacing="6">
<CheckBox Content="{Binding Localization[Settings_PreviewBeforeSave]}"
<CheckBox Content="{Binding PreviewBeforeSaveLabel}"
IsChecked="{Binding PreviewBeforeSave, Mode=TwoWay}" />
<CheckBox Content="{Binding Localization[Settings_MinimizeToTray]}"
<CheckBox Content="{Binding MinimizeToTrayLabel}"
IsChecked="{Binding MinimizeToTray, Mode=TwoWay}" />
<CheckBox Content="{Binding Localization[Settings_SoundEnabled]}"
<CheckBox Content="{Binding SoundEnabledLabel}"
IsChecked="{Binding SoundEnabled, Mode=TwoWay}" />
</StackPanel>
<!-- Logging -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding LoggingLabel}"
FontSize="13"
FontWeight="SemiBold" />
<StackPanel Spacing="4">
<TextBlock Text="{Binding LogLevelLabel}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
FontSize="12" />
<ComboBox ItemsSource="{Binding SupportedLogLevels}"
SelectedItem="{Binding SelectedLogLevel, Mode=TwoWay}"
HorizontalAlignment="Stretch" />
<TextBlock Text="{Binding LogLevelHint}"
FontSize="11"
TextWrapping="Wrap"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
</StackPanel>
</StackPanel>
<!-- Import / export / open -->
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Name="ImportButton" Content="{Binding Localization[Settings_Import]}" />
<Button Name="ExportButton" Content="{Binding Localization[Settings_Export]}" />
<Button Content="{Binding Localization[Settings_OpenFile]}"
<Button Name="ImportButton" Content="{Binding ImportLabel}" />
<Button Name="ExportButton" Content="{Binding ExportLabel}" />
<Button Content="{Binding OpenFileLabel}"
Command="{Binding OpenSettingsFileCommand}" />
</StackPanel>
@@ -1,5 +1,3 @@
using System;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
@@ -15,6 +13,7 @@ public partial class SettingsView : UserControl
var importButton = this.FindControl<Button>("ImportButton");
var exportButton = this.FindControl<Button>("ExportButton");
var browseOutputButton = this.FindControl<Button>("BrowseOutputButton");
if (importButton is not null)
{
@@ -24,6 +23,51 @@ public partial class SettingsView : UserControl
{
exportButton.Click += OnExportClick;
}
if (browseOutputButton is not null)
{
browseOutputButton.Click += OnBrowseOutputClick;
}
}
private async void OnBrowseOutputClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not SettingsViewModel vm) return;
var top = TopLevel.GetTopLevel(this);
if (top is null) return;
// Seed the picker at whatever the user has configured (or the system default if
// the field is empty). Failing to resolve the suggested start is non-fatal — the
// picker falls back to its own default.
IStorageFolder? suggestedStart = null;
if (!string.IsNullOrWhiteSpace(vm.OutputDirectory))
{
try
{
suggestedStart = await top.StorageProvider.TryGetFolderFromPathAsync(vm.OutputDirectory);
}
catch
{
// Ignore — start elsewhere.
}
}
var folders = await top.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
{
Title = vm.Localization["Settings_BrowseTitle"],
AllowMultiple = false,
SuggestedStartLocation = suggestedStart,
});
if (folders.Count == 0) return;
var path = folders[0].TryGetLocalPath();
if (!string.IsNullOrEmpty(path))
{
// Two-way binding pushes back into AppSettings through the
// OnOutputDirectoryChanged partial handler in the VM.
vm.OutputDirectory = path;
}
}
private async void OnImportClick(object? sender, RoutedEventArgs e)
@@ -35,7 +79,7 @@ public partial class SettingsView : UserControl
var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "Import settings",
Title = vm.Localization["Settings_ImportTitle"],
AllowMultiple = false,
FileTypeFilter = new[]
{
@@ -61,7 +105,7 @@ public partial class SettingsView : UserControl
var file = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "Export settings",
Title = vm.Localization["Settings_ExportTitle"],
DefaultExtension = "json",
SuggestedFileName = "captureimage-settings.json",
FileTypeChoices = new[]
@@ -25,6 +25,21 @@ public sealed partial class AboutViewModel : ViewModelBase
Localization = localization;
_logger = logger;
// About view binds every label through `{Binding Localization[About_*]}`. Push an
// explicit PropertyChanged on culture switch so the compiled indexer bindings
// re-resolve their path — the Localization service's own Item[] notification
// isn't picked up through the intermediate property in every case.
//
// Disclaimer bodies are computed properties reading through Localization[...] but
// the view binds them by property name (`{Binding TranslationDisclaimer}`), so the
// indexer refresh alone won't wake those bindings — raise each disclaimer property
// explicitly so their bound TextBlocks retranslate in place.
//
// AboutViewModel is a DI singleton with process-long lifetime (nav owns it), so we
// skip IDisposable and rely on the container tearing the subscription down on app
// exit — adding IDisposable here would be cosmetic and the leak is theoretical.
Localization.PropertyChanged += OnLocalizationChanged;
var asm = typeof(AboutViewModel).Assembly;
AppVersion = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion
?? asm.GetName().Version?.ToString()
@@ -47,6 +62,17 @@ public sealed partial class AboutViewModel : ViewModelBase
};
}
private void OnLocalizationChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(Localization));
OnPropertyChanged(nameof(TranslationDisclaimer));
OnPropertyChanged(nameof(CaptureLimitationDisclaimer));
OnPropertyChanged(nameof(LiabilityDisclaimer));
}
}
public string AppName => "CaptureImage";
public string AppVersion { get; }
@@ -69,22 +95,11 @@ public sealed partial class AboutViewModel : ViewModelBase
"by the human maintainer before landing. Commits that involve meaningful AI authorship " +
"carry a Co-Authored-By trailer naming the model. See docs/CONTRIBUTORS.md for details.";
public string TranslationDisclaimer =>
"Vietnamese and Arabic language packs are machine-assisted. Terminology may not match " +
"native conventions, and some technical words (hotkey, toast, frame, etc.) are kept in " +
"English on purpose. Native speakers willing to proofread are warmly invited to submit " +
"pull requests against the .resx files in src/CaptureImage.UI/Resources/Strings/.";
public string TranslationDisclaimer => Localization["About_TranslationDisclaimerBody"];
public string CaptureLimitationDisclaimer =>
"CaptureImage can capture most windowed and borderless games via Windows.Graphics.Capture, " +
"but not every title works. DRM-protected surfaces, exclusive-fullscreen Direct3D 9 games, " +
"and titles with anti-cheat hooks may return black frames or refuse capture. A GDI PrintWindow " +
"fallback is attempted for legacy apps. See docs/legal/DISCLAIMER.md §2 for the full list.";
public string CaptureLimitationDisclaimer => Localization["About_CaptureLimitationDisclaimerBody"];
public string LiabilityDisclaimer =>
"CaptureImage is distributed under GPL-3.0-or-later AS IS, without warranty of any kind. " +
"The authors are not liable for lost screenshots, game crashes, anti-cheat sanctions, or " +
"data loss. Use at your own risk. See docs/legal/DISCLAIMER.md for the full text.";
public string LiabilityDisclaimer => Localization["About_LiabilityDisclaimerBody"];
public ObservableCollection<ThirdPartyItem> ThirdPartyItems { get; }
@@ -112,16 +112,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
_hotkeys.Triggered += OnHotkeyTriggered;
_settings.Changed += OnSettingsChanged;
Localization.PropertyChanged += (_, e) =>
{
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(StatusMessage));
OnPropertyChanged(nameof(TargetsCountText));
OnPropertyChanged(nameof(LoadingText));
OnPropertyChanged(nameof(EmptyStateText));
}
};
Localization.PropertyChanged += OnLocalizationChanged;
// TargetsCountText depends on Targets.Count — refresh whenever the collection changes.
Targets.CollectionChanged += (_, _) =>
@@ -134,6 +125,25 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
_ = RefreshAsync();
}
private void OnLocalizationChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_disposed) return;
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
// StatusMessage is a stored [ObservableProperty], not a computed getter —
// re-raising PropertyChanged alone would hand the UI the same stale string.
// Re-derive it from the state machine so the new culture's template wins.
UpdateStatusForState();
OnPropertyChanged(nameof(TargetsCountText));
OnPropertyChanged(nameof(LoadingText));
OnPropertyChanged(nameof(EmptyStateText));
// Forces `{Binding Localization[Key]}` bindings on DashboardView to
// re-resolve the indexer path in-place (Title, Subtitle, Refresh / Arm /
// Disarm button labels). See v1.1.1 hotfix notes.
OnPropertyChanged(nameof(Localization));
}
}
// HasNoTargets depends on IsLoading — refresh when the loading flag flips.
partial void OnIsLoadingChanged(bool value)
{
@@ -500,6 +510,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
_watcher.Changed -= OnProcessChanged;
_settings.Changed -= OnSettingsChanged;
_stateMachine.StateChanged -= OnStateChanged;
Localization.PropertyChanged -= OnLocalizationChanged;
_pendingRefresh?.Cancel();
_pendingRefresh?.Dispose();
}
@@ -1,20 +1,29 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Logging;
using CaptureImage.Core.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
// Disambiguate — `LogLevel` here means the one in LogEntry (Serilog-derived severity),
// not MEL's `Microsoft.Extensions.Logging.LogLevel` used by the `_logger` field.
using LogLevel = CaptureImage.Core.Models.LogLevel;
namespace CaptureImage.ViewModels.Logs;
/// <summary>
/// Live log viewer for the drawer pane. Hydrates from the ring buffer on first show,
/// appends new entries as they fire, and supports pause/resume/clear/export.
/// appends new entries as they fire, and supports pause/resume/clear/export plus a
/// view-side level filter and a button to open the rolling-file folder in Explorer.
/// </summary>
public sealed partial class LogViewerViewModel : ViewModelBase
public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
{
/// <summary>UI cap — the sink buffer holds more, but rendering 2000 rows is already
/// the budget; we don't push them all into <see cref="Entries"/>.</summary>
@@ -22,38 +31,54 @@ public sealed partial class LogViewerViewModel : ViewModelBase
private readonly ILogBufferSource _source;
private readonly IUIThreadDispatcher _dispatcher;
private readonly ILogger<LogViewerViewModel> _logger;
private readonly IToastService _toasts;
private bool _hydrated;
private bool _disposed;
public ILocalizationService Localization { get; }
public ObservableCollection<LogEntry> Entries { get; } = new();
/// <summary>Options shown in the level-filter dropdown. Order matters: lowest to highest.</summary>
public IReadOnlyList<LogLevel> FilterLevels { get; } = new[]
{
LogLevel.Verbose,
LogLevel.Debug,
LogLevel.Information,
LogLevel.Warning,
LogLevel.Error,
};
[ObservableProperty]
private bool _isPaused;
[ObservableProperty]
private bool _isVisible;
/// <summary>
/// Minimum level the viewer displays. Entries below this get hidden from
/// <see cref="Entries"/> but still live in the sink buffer, so Export always carries
/// the full history regardless of this filter.
/// </summary>
[ObservableProperty]
private LogLevel _selectedFilterLevel = LogLevel.Verbose;
public LogViewerViewModel(
ILogBufferSource source,
IUIThreadDispatcher dispatcher,
ILocalizationService localization)
ILocalizationService localization,
ILogger<LogViewerViewModel> logger,
IToastService toasts)
{
_source = source;
_dispatcher = dispatcher;
Localization = localization;
_logger = logger;
_toasts = toasts;
_source.Emitted += OnEmitted;
Localization.PropertyChanged += (_, e) =>
{
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(TogglePauseLabel));
OnPropertyChanged(nameof(EventsCountText));
OnPropertyChanged(nameof(EmptyStateText));
}
};
Localization.PropertyChanged += OnLocalizationChanged;
Entries.CollectionChanged += (_, _) =>
{
@@ -62,6 +87,31 @@ public sealed partial class LogViewerViewModel : ViewModelBase
};
}
private void OnLocalizationChanged(object? sender, PropertyChangedEventArgs e)
{
if (_disposed) return;
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(TogglePauseLabel));
OnPropertyChanged(nameof(EventsCountText));
OnPropertyChanged(nameof(EmptyStateText));
OnPropertyChanged(nameof(FilterLabel));
OnPropertyChanged(nameof(RevealFolderLabel));
// Refresh the `{Binding Localization[Log_Title]}` / `[Log_Clear]` direct
// indexer bindings in the header. v1.1.1 hotfix — the service's own
// Item[] notification alone doesn't reliably re-resolve the path.
OnPropertyChanged(nameof(Localization));
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_source.Emitted -= OnEmitted;
Localization.PropertyChanged -= OnLocalizationChanged;
}
/// <summary>
/// Label shown on the Pause/Resume button. Flips on <see cref="IsPaused"/> so one
/// button drives both states, and re-localizes on culture change.
@@ -76,6 +126,12 @@ public sealed partial class LogViewerViewModel : ViewModelBase
/// <summary>Localized hint shown inside the drawer when no log events have fired yet.</summary>
public string EmptyStateText => Localization["Log_EmptyState"];
/// <summary>Localized label for the minimum-level filter dropdown.</summary>
public string FilterLabel => Localization["Log_Filter"];
/// <summary>Localized button label that opens the rolling-file folder in Explorer.</summary>
public string RevealFolderLabel => Localization["Log_RevealFolder"];
public bool HasNoEntries => Entries.Count == 0;
partial void OnIsPausedChanged(bool value)
@@ -84,6 +140,24 @@ public sealed partial class LogViewerViewModel : ViewModelBase
OnPropertyChanged(nameof(TogglePauseLabel));
}
partial void OnSelectedFilterLevelChanged(LogLevel value)
{
// Rebuild the visible list from the sink snapshot whenever the filter moves.
// O(2000) — trivial and only runs on user input.
Entries.Clear();
var snapshot = _source.Snapshot();
var start = Math.Max(0, snapshot.Count - MaxVisibleEntries);
for (var i = start; i < snapshot.Count; i++)
{
if (PassesFilter(snapshot[i]))
{
Entries.Add(snapshot[i]);
}
}
}
private bool PassesFilter(LogEntry entry) => entry.Level >= SelectedFilterLevel;
/// <summary>
/// Called the first time the drawer is shown. Fills the ObservableCollection from the
/// sink's snapshot so the user sees historical log events too.
@@ -96,7 +170,10 @@ public sealed partial class LogViewerViewModel : ViewModelBase
var start = Math.Max(0, snapshot.Count - MaxVisibleEntries);
for (var i = start; i < snapshot.Count; i++)
{
Entries.Add(snapshot[i]);
if (PassesFilter(snapshot[i]))
{
Entries.Add(snapshot[i]);
}
}
}
@@ -110,6 +187,21 @@ public sealed partial class LogViewerViewModel : ViewModelBase
[RelayCommand]
private void TogglePause() => IsPaused = !IsPaused;
[RelayCommand]
private void RevealLogsFolder()
{
var folder = LogPaths.GetLogsDirectory();
try
{
Process.Start(new ProcessStartInfo(folder) { UseShellExecute = true });
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to open logs folder {Path}.", folder);
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
[RelayCommand]
private async Task ExportAsync(string filePath)
{
@@ -121,6 +213,11 @@ public sealed partial class LogViewerViewModel : ViewModelBase
{
sb.Append('[').Append(entry.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sb.Append(' ').Append(entry.Level.ToString().ToUpperInvariant().Substring(0, 3)).Append("] ");
var fileLine = entry.FileLineText;
if (!string.IsNullOrEmpty(fileLine))
{
sb.Append('(').Append(fileLine).Append(") ");
}
if (!string.IsNullOrEmpty(entry.SourceContext))
{
sb.Append(entry.SourceContext).Append(": ");
@@ -139,6 +236,7 @@ public sealed partial class LogViewerViewModel : ViewModelBase
// Marshal to UI thread before mutating the ObservableCollection.
_dispatcher.Post(() =>
{
if (!PassesFilter(entry)) return;
Entries.Add(entry);
while (Entries.Count > MaxVisibleEntries)
{
@@ -43,6 +43,21 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// <summary>Brand name shown in the nav rail header. Constant across cultures — brand names do not translate.</summary>
public string AppTitle => "CaptureImage";
/// <summary>
/// Localized label for the Log drawer toggle button at the bottom of the nav rail.
/// Exposed as a plain computed property (not via the Localization indexer) because
/// Avalonia's compiled indexer bindings don't reevaluate reliably when the
/// intermediate <c>Localization</c> property reference is unchanged — a plain
/// property path refresh with <c>OnPropertyChanged</c> is the reliable pattern.
/// </summary>
public string LogToggleLabel => Localization["Nav_LogViewer"];
/// <summary>
/// Localized tooltip / automation name for the Log drawer toggle button. Same
/// refresh-reliability reasoning as <see cref="LogToggleLabel"/>.
/// </summary>
public string LogToggleTooltip => Localization["Dashboard_LogToggle"];
/// <summary>
/// Short semver pulled from the entry assembly's <c>Version</c> at runtime. Release builds
/// set this via <c>/p:Version=&lt;git-tag&gt;</c> in release.yml; dev builds fall back to the
@@ -88,6 +103,22 @@ public sealed partial class MainWindowViewModel : ViewModelBase
// Activate the first item by default.
SelectedNavItem = NavItems[0];
// `{Binding Localization[Nav_LogViewer]}` on the log drawer toggle (and AppTitle /
// AppVersion / tooltip bindings) need an explicit poke at the VM level when
// culture changes — Avalonia's compiled indexer binding through an intermediate
// property doesn't always refresh on the service's own Item[] notification.
Localization.PropertyChanged += OnLocalizationChanged;
}
private void OnLocalizationChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(Localization));
OnPropertyChanged(nameof(LogToggleLabel));
OnPropertyChanged(nameof(LogToggleTooltip));
}
}
partial void OnSelectedNavItemChanged(NavItemViewModel? value)
@@ -1,3 +1,5 @@
using System;
using System.ComponentModel;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -8,8 +10,10 @@ namespace CaptureImage.ViewModels.Preview;
/// VM for the preview window. Holds the captured frame's dimensions + PNG bytes so the view
/// can render it without asking the engine to re-encode.
/// </summary>
public sealed partial class PreviewViewModel : ViewModelBase
public sealed partial class PreviewViewModel : ViewModelBase, IDisposable
{
private bool _disposed;
public ILocalizationService Localization { get; }
[ObservableProperty]
@@ -27,6 +31,28 @@ public sealed partial class PreviewViewModel : ViewModelBase
public PreviewViewModel(ILocalizationService localization)
{
Localization = localization;
// Preview window is modal and short-lived, but the user can still switch language
// from the tray menu while it is open. Raise Localization on culture change so the
// `{Binding Localization[Preview_*]}` indexer bindings in PreviewWindow.axaml
// re-resolve in place. Matches the v1.1.1 pattern used by every other VM.
Localization.PropertyChanged += OnLocalizationChanged;
}
private void OnLocalizationChanged(object? sender, PropertyChangedEventArgs e)
{
if (_disposed) return;
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(Localization));
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
Localization.PropertyChanged -= OnLocalizationChanged;
}
/// <summary>
@@ -53,6 +53,22 @@ public sealed partial class HotkeyBindingViewModel : ViewModelBase, IDisposable
_ => string.Empty,
};
// -- localized labels ---------------------------------------------------
//
// Plain computed properties exposing each Localization[key] the HotkeyRecorder
// control binds to. Compiled indexer bindings (`{Binding Localization[Settings_Foo]}`)
// don't reevaluate reliably when the intermediate `Localization` reference is
// unchanged on the live view — binding to a plain property and raising
// OnPropertyChanged on culture switch is the reliable pattern. Matches the same
// refactor applied to SettingsViewModel and MainWindowViewModel.
public string HotkeyFieldAutomationName => Localization["Settings_Hotkey"];
public string RecorderPromptText => Localization["Settings_HotkeyRecorderPrompt"];
public string RecordLabel => Localization["Settings_HotkeyRecord"];
public string CancelLabel => Localization["Settings_HotkeyCancel"];
public string ResetLabel => Localization["Settings_HotkeyReset"];
public string ConflictWarningText => Localization["Settings_HotkeyConflictWarning"];
public HotkeyBindingViewModel(
ISettingsStore settings,
IHotkeyService hotkeys,
@@ -80,6 +96,15 @@ public sealed partial class HotkeyBindingViewModel : ViewModelBase, IDisposable
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(ErrorMessage));
OnPropertyChanged(nameof(Localization));
// Plain-property refresh for every HotkeyRecorder label — indexer-path
// bindings don't wake reliably on Localization-reference ping.
OnPropertyChanged(nameof(HotkeyFieldAutomationName));
OnPropertyChanged(nameof(RecorderPromptText));
OnPropertyChanged(nameof(RecordLabel));
OnPropertyChanged(nameof(CancelLabel));
OnPropertyChanged(nameof(ResetLabel));
OnPropertyChanged(nameof(ConflictWarningText));
}
}
@@ -16,12 +16,14 @@ namespace CaptureImage.ViewModels.Settings;
/// open-settings-file. Persists every change through <see cref="ISettingsStore.Update"/> so
/// the debounced writer handles the disk.
/// </summary>
public sealed partial class SettingsViewModel : ViewModelBase
public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
{
private readonly ISettingsStore _settings;
private readonly IToastService _toasts;
private readonly ILogger<SettingsViewModel> _logger;
private readonly ILogLevelSwitcher _logLevelSwitcher;
private bool _suppressPush;
private bool _disposed;
public ILocalizationService Localization { get; }
@@ -33,6 +35,14 @@ public sealed partial class SettingsViewModel : ViewModelBase
public ObservableCollection<ImageFormat> SupportedFormats { get; } =
new(new[] { ImageFormat.Png, ImageFormat.Jpeg, ImageFormat.Webp, ImageFormat.Tiff });
/// <summary>
/// Log-level options shown in the Settings Logging picker. Order matches user
/// expectation (most-verbose first) and the strings match <see cref="AppSettings.LogLevel"/>
/// so the picker can bind directly to <see cref="SelectedLogLevel"/>.
/// </summary>
public ObservableCollection<string> SupportedLogLevels { get; } =
new(new[] { "Debug", "Information", "Warning", "Error" });
[ObservableProperty]
private CultureInfo _selectedCulture;
@@ -60,18 +70,55 @@ public sealed partial class SettingsViewModel : ViewModelBase
[ObservableProperty]
private bool _soundEnabled;
[ObservableProperty]
private string _selectedLogLevel = "Information";
public string SettingsFilePath => _settings.SettingsFilePath;
// -- localized labels ---------------------------------------------------
//
// Plain computed properties exposing each Localization[key] the Settings view binds
// to. Avalonia compiled indexer bindings (`{Binding Localization[Settings_Foo]}`)
// don't reevaluate reliably when the intermediate `Localization` reference is
// unchanged — the live SettingsView binds through an intermediate property, so the
// service's own Item[] notification doesn't bubble through. Binding to a plain VM
// property and raising OnPropertyChanged on culture switch is the reliable pattern
// (same as NavItemViewModel.Label and AboutViewModel disclaimer bodies).
public string TitleLabel => Localization["Settings_Title"];
public string LanguageLabel => Localization["Settings_Language"];
public string HotkeyLabel => Localization["Settings_Hotkey"];
public string HotkeyHint => Localization["Settings_HotkeyHint"];
public string FormatLabel => Localization["Settings_Format"];
public string JpegQualityLabel => Localization["Settings_JpegQuality"];
public string WebpQualityLabel => Localization["Settings_WebpQuality"];
public string OutputFolderLabel => Localization["Settings_OutputFolder"];
public string OutputFolderWatermark => Localization["Settings_OutputFolderDefault"];
public string BrowseLabel => Localization["Settings_Browse"];
public string BrowseTooltip => Localization["Settings_BrowseTooltip"];
public string FileNameTemplateLabel => Localization["Settings_FileNameTemplate"];
public string PreviewBeforeSaveLabel => Localization["Settings_PreviewBeforeSave"];
public string MinimizeToTrayLabel => Localization["Settings_MinimizeToTray"];
public string SoundEnabledLabel => Localization["Settings_SoundEnabled"];
public string ImportLabel => Localization["Settings_Import"];
public string ExportLabel => Localization["Settings_Export"];
public string OpenFileLabel => Localization["Settings_OpenFile"];
public string LoggingLabel => Localization["Settings_Logging"];
public string LogLevelLabel => Localization["Settings_LogLevel"];
public string LogLevelHint => Localization["Settings_LogLevelHint"];
public SettingsViewModel(
ISettingsStore settings,
ILocalizationService localization,
IToastService toasts,
HotkeyBindingViewModel hotkey,
ILogger<SettingsViewModel> logger)
ILogger<SettingsViewModel> logger,
ILogLevelSwitcher logLevelSwitcher)
{
_settings = settings;
_toasts = toasts;
_logger = logger;
_logLevelSwitcher = logLevelSwitcher;
Localization = localization;
Hotkey = hotkey;
@@ -79,7 +126,61 @@ public sealed partial class SettingsViewModel : ViewModelBase
_selectedCulture = FindCulture(settings.Current.Culture) ?? SupportedCultures[0];
Hydrate();
_settings.Changed += (_, _) => Hydrate();
_settings.Changed += OnSettingsStoreChanged;
// Raise OnPropertyChanged(nameof(Localization)) on culture switch so every
// `{Binding Localization[Key]}` in SettingsView re-resolves the full path and
// picks up the new translation in-place. The service's own "Item[]" INPC fires,
// but Avalonia's compiled indexer bindings through an intermediate property do
// not always listen to that; bumping the property name at the VM level forces
// re-evaluation and matches the pattern used by NavItemViewModel.
Localization.PropertyChanged += OnLocalizationChanged;
}
private void OnSettingsStoreChanged(object? sender, EventArgs e)
{
if (_disposed) return;
Hydrate();
}
private void OnLocalizationChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_disposed) return;
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(Localization));
// Plain-property refresh for every localized label the view binds to —
// indexer-path bindings don't wake reliably on Localization-reference ping.
OnPropertyChanged(nameof(TitleLabel));
OnPropertyChanged(nameof(LanguageLabel));
OnPropertyChanged(nameof(HotkeyLabel));
OnPropertyChanged(nameof(HotkeyHint));
OnPropertyChanged(nameof(FormatLabel));
OnPropertyChanged(nameof(JpegQualityLabel));
OnPropertyChanged(nameof(WebpQualityLabel));
OnPropertyChanged(nameof(OutputFolderLabel));
OnPropertyChanged(nameof(OutputFolderWatermark));
OnPropertyChanged(nameof(BrowseLabel));
OnPropertyChanged(nameof(BrowseTooltip));
OnPropertyChanged(nameof(FileNameTemplateLabel));
OnPropertyChanged(nameof(PreviewBeforeSaveLabel));
OnPropertyChanged(nameof(MinimizeToTrayLabel));
OnPropertyChanged(nameof(SoundEnabledLabel));
OnPropertyChanged(nameof(ImportLabel));
OnPropertyChanged(nameof(ExportLabel));
OnPropertyChanged(nameof(OpenFileLabel));
OnPropertyChanged(nameof(LoggingLabel));
OnPropertyChanged(nameof(LogLevelLabel));
OnPropertyChanged(nameof(LogLevelHint));
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_settings.Changed -= OnSettingsStoreChanged;
Localization.PropertyChanged -= OnLocalizationChanged;
}
private CultureInfo? FindCulture(string name)
@@ -109,6 +210,11 @@ public sealed partial class SettingsViewModel : ViewModelBase
PreviewBeforeSave = current.Capture.PreviewBeforeSave;
MinimizeToTray = current.UI.MinimizeToTray;
SoundEnabled = current.UI.SoundEnabled;
// Fall back to the first supported value if the persisted string doesn't match —
// that can happen after a hand-edit or a downgrade from a future schema.
SelectedLogLevel = SupportedLogLevels.Contains(current.LogLevel)
? current.LogLevel
: SupportedLogLevels[1]; // Information
}
finally
{
@@ -171,6 +277,16 @@ public sealed partial class SettingsViewModel : ViewModelBase
_settings.Update(s => s with { UI = s.UI with { SoundEnabled = value } });
}
partial void OnSelectedLogLevelChanged(string value)
{
if (_suppressPush || string.IsNullOrWhiteSpace(value)) return;
_settings.Update(s => s with { LogLevel = value });
// Flip the live Serilog minimum level immediately — no restart needed. The
// persisted value syncs via the debounced settings writer.
_logLevelSwitcher.SetLevel(value);
_logger.LogInformation("Log level changed to {Level}.", value);
}
private static int Clamp(int v) => v < 1 ? 1 : v > 100 ? 100 : v;
[RelayCommand]
@@ -183,7 +299,7 @@ public sealed partial class SettingsViewModel : ViewModelBase
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to open settings file.");
_toasts.ShowError("Error", ex.Message);
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
@@ -203,7 +319,7 @@ public sealed partial class SettingsViewModel : ViewModelBase
catch (Exception ex)
{
_logger.LogError(ex, "Settings export failed.");
_toasts.ShowError("Error", ex.Message);
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
@@ -219,7 +335,7 @@ public sealed partial class SettingsViewModel : ViewModelBase
catch (Exception ex)
{
_logger.LogError(ex, "Settings import failed.");
_toasts.ShowError("Error", ex.Message);
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
}
@@ -56,6 +56,21 @@ public sealed partial class UpdateViewModel : ViewModelBase, IDisposable
_currentVersion = _updateService.CurrentVersion;
_updateService.LogEmitted += OnLogEmitted;
// Force `{Binding Localization[Update_*]}` bindings to refresh when the user
// switches language from Settings while the Update tab is already active —
// the service's Item[] notification alone isn't reliably picked up by
// compiled indexer bindings through the intermediate Localization property.
Localization.PropertyChanged += OnLocalizationChanged;
}
private void OnLocalizationChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_disposed) return;
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(Localization));
}
}
public bool CanCheck => !IsBusy;
@@ -171,5 +186,6 @@ public sealed partial class UpdateViewModel : ViewModelBase, IDisposable
if (_disposed) return;
_disposed = true;
_updateService.LogEmitted -= OnLogEmitted;
Localization.PropertyChanged -= OnLocalizationChanged;
}
}
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.IO;
using CaptureImage.Core.Logging;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Xunit;
namespace CaptureImage.Core.Tests.Logging;
/// <summary>
/// Validates that <c>LogXAt</c> extensions attach <c>File</c> / <c>Line</c> / <c>Member</c>
/// as MEL scope state — which Serilog's MEL bridge then surfaces as structured
/// <see cref="Serilog.Events.LogEvent"/> properties at runtime.
/// </summary>
/// <remarks>
/// Rather than stand up the real Serilog pipeline, we use a tiny spy <see cref="ILogger"/>
/// that captures whatever scope state arrives. That's enough to assert the extensions
/// pass the caller context through correctly; the end-to-end "scope reaches the rolling
/// file" behaviour is covered by manual verification.
/// </remarks>
public class CallerAwareLoggerExtensionsTests
{
[Fact]
public void LogInformationAt_InjectsCallerContextIntoScope()
{
var spy = new ScopeCapturingLogger();
spy.LogInformationAt("hello");
var captured = spy.Scopes.Should().ContainSingle().Subject;
captured.Should().ContainKey("Member");
captured.Should().ContainKey("File");
captured.Should().ContainKey("Line");
captured["Member"].Should().Be(nameof(LogInformationAt_InjectsCallerContextIntoScope));
captured["File"].Should().Be("CallerAwareLoggerExtensionsTests.cs");
((int)captured["Line"]!).Should().BeGreaterThan(0);
}
[Fact]
public void LogWarningAt_WithException_ForwardsExceptionAndCaller()
{
var spy = new ScopeCapturingLogger();
var ex = new InvalidOperationException("boom");
spy.LogWarningAt(ex, "with exception");
spy.Entries.Should().ContainSingle()
.Which.Exception.Should().Be(ex);
spy.Scopes.Should().ContainSingle()
.Which.Should().ContainKey("File").WhoseValue
.Should().Be("CallerAwareLoggerExtensionsTests.cs");
}
[Fact]
public void LogErrorAt_WithTwoArgs_PassesArgsThroughToLogger()
{
var spy = new ScopeCapturingLogger();
var ex = new IOException("disk full");
spy.LogErrorAt(ex, "failed to save {Path} size={Size}", "/tmp/x", 1024);
spy.Entries.Should().ContainSingle()
.Which.State!.ToString().Should().Contain("/tmp/x").And.Contain("1024");
}
[Fact]
public void CallerScope_StripsBuildMachineAbsolutePath()
{
// Simulate [CallerFilePath] having produced an absolute path — the helper must
// strip the directory portion so we don't leak E:\build-agent\... into the log.
var spy = new ScopeCapturingLogger();
spy.LogInformationAt(
"probe",
member: "test",
filePath: @"C:\build\machine\deep\path\Module.cs",
line: 7);
var scope = spy.Scopes.Should().ContainSingle().Subject;
scope["File"].Should().Be("Module.cs");
}
// -- helpers --------------------------------------------------------------
/// <summary>Minimal spy capturing every Log call + its surrounding scope state.</summary>
private sealed class ScopeCapturingLogger : ILogger
{
public List<Dictionary<string, object?>> Scopes { get; } = new();
public List<(LogLevel Level, Exception? Exception, object? State)> Entries { get; } = new();
private readonly Stack<Dictionary<string, object?>> _currentScopes = new();
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
var dict = new Dictionary<string, object?>();
if (state is IEnumerable<KeyValuePair<string, object>> pairs)
{
foreach (var kvp in pairs)
{
dict[kvp.Key] = kvp.Value;
}
}
Scopes.Add(dict);
_currentScopes.Push(dict);
return new ScopeToken(this);
}
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
Entries.Add((logLevel, exception, state));
}
private sealed class ScopeToken : IDisposable
{
private readonly ScopeCapturingLogger _owner;
public ScopeToken(ScopeCapturingLogger owner) => _owner = owner;
public void Dispose()
{
if (_owner._currentScopes.Count > 0) _owner._currentScopes.Pop();
}
}
}
}
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.IO;
using CaptureImage.Core.Models;
using CaptureImage.Core.Pipeline;
using FluentAssertions;
@@ -1,7 +1,5 @@
using System;
using CaptureImage.Core.StateMachine;
using FluentAssertions;
using Stateless;
using Xunit;
namespace CaptureImage.Core.Tests.StateMachine;
@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using CaptureImage.Core.Models;
using CaptureImage.Infrastructure.Logging;
using FluentAssertions;
using Serilog.Events;
using Serilog.Parsing;
using Xunit;
namespace CaptureImage.Infrastructure.Tests.Logging;
/// <summary>
/// Covers the ring-buffer semantics, pause/resume behaviour, and <c>Snapshot()</c> copy
/// guarantees of <see cref="InMemorySink"/> — the real-time log viewer's event source.
/// </summary>
public class InMemorySinkTests
{
[Fact]
public void Emit_AppendsToBuffer_AndRaisesEmitted_WhenNotPaused()
{
var sink = new InMemorySink();
var raised = new List<LogEntry>();
sink.Emitted += (_, entry) => raised.Add(entry);
sink.Emit(Event("hello", LogEventLevel.Information));
sink.Snapshot().Should().HaveCount(1);
sink.Snapshot()[0].Message.Should().Be("hello");
raised.Should().HaveCount(1);
raised[0].Level.Should().Be(LogLevel.Information);
}
[Fact]
public void Emit_WhilePaused_StillBuffersButDoesNotRaiseEmitted()
{
var sink = new InMemorySink { Paused = true };
var raised = new List<LogEntry>();
sink.Emitted += (_, entry) => raised.Add(entry);
sink.Emit(Event("hidden", LogEventLevel.Warning));
sink.Snapshot().Should().HaveCount(1);
raised.Should().BeEmpty();
}
[Fact]
public void Emit_OverflowingCapacity_EvictsOldestFirst()
{
var sink = new InMemorySink();
// Fire one beyond capacity so the first event has to be dropped.
for (var i = 0; i < InMemorySink.MaxCapacity + 1; i++)
{
sink.Emit(Event($"msg-{i}", LogEventLevel.Information));
}
var snapshot = sink.Snapshot();
snapshot.Should().HaveCount(InMemorySink.MaxCapacity);
snapshot[0].Message.Should().Be("msg-1"); // index 0 evicted
snapshot[^1].Message.Should().Be($"msg-{InMemorySink.MaxCapacity}");
}
[Fact]
public void Snapshot_ReturnsCopy_MutationsDontAffectBuffer()
{
var sink = new InMemorySink();
sink.Emit(Event("a", LogEventLevel.Information));
var firstSnapshot = sink.Snapshot();
sink.Emit(Event("b", LogEventLevel.Information));
// The earlier snapshot is frozen at the moment it was taken.
firstSnapshot.Should().HaveCount(1);
firstSnapshot[0].Message.Should().Be("a");
// But the sink itself has moved on.
sink.Snapshot().Should().HaveCount(2);
}
[Fact]
public void Clear_EmptiesBuffer()
{
var sink = new InMemorySink();
sink.Emit(Event("x", LogEventLevel.Information));
sink.Emit(Event("y", LogEventLevel.Information));
sink.Clear();
sink.Snapshot().Should().BeEmpty();
}
[Fact]
public void Emit_CapturesCallerProperties_WhenPresentOnEvent()
{
var sink = new InMemorySink();
var ev = EventWithCaller("with caller", "Engine.cs", 42, "Start");
sink.Emit(ev);
var entry = sink.Snapshot()[0];
entry.File.Should().Be("Engine.cs");
entry.Line.Should().Be(42);
entry.Member.Should().Be("Start");
entry.FileLineText.Should().Be("Engine.cs:42");
}
[Fact]
public void Emit_LeavesCallerPropertiesNull_WhenAbsent()
{
var sink = new InMemorySink();
sink.Emit(Event("plain", LogEventLevel.Information));
var entry = sink.Snapshot()[0];
entry.File.Should().BeNull();
entry.Line.Should().BeNull();
entry.Member.Should().BeNull();
entry.FileLineText.Should().BeEmpty();
}
// -- helpers --------------------------------------------------------------
private static LogEvent Event(string message, LogEventLevel level)
{
var template = new MessageTemplateParser().Parse(message);
return new LogEvent(
DateTimeOffset.UtcNow,
level,
exception: null,
template,
properties: Array.Empty<LogEventProperty>());
}
private static LogEvent EventWithCaller(string message, string file, int line, string member)
{
var template = new MessageTemplateParser().Parse(message);
return new LogEvent(
DateTimeOffset.UtcNow,
LogEventLevel.Information,
exception: null,
template,
properties: new[]
{
new LogEventProperty("File", new ScalarValue(file)),
new LogEventProperty("Line", new ScalarValue(line)),
new LogEventProperty("Member", new ScalarValue(member)),
});
}
}
@@ -0,0 +1,61 @@
using CaptureImage.Infrastructure.Logging;
using FluentAssertions;
using Serilog.Core;
using Serilog.Events;
using Xunit;
namespace CaptureImage.Infrastructure.Tests.Logging;
/// <summary>
/// Verifies the canonical mapping between <see cref="AppSettings.LogLevel"/> strings and
/// Serilog's <see cref="LogEventLevel"/>. Covers the alias forms (info/warn) and the
/// unknown-value fallback.
/// </summary>
public class SerilogLogLevelSwitcherTests
{
[Theory]
[InlineData("Debug", LogEventLevel.Debug)]
[InlineData("debug", LogEventLevel.Debug)]
[InlineData("Information", LogEventLevel.Information)]
[InlineData("info", LogEventLevel.Information)]
[InlineData("Warning", LogEventLevel.Warning)]
[InlineData("warn", LogEventLevel.Warning)]
[InlineData("Error", LogEventLevel.Error)]
[InlineData("ERROR", LogEventLevel.Error)]
public void SetLevel_CanonicalAndAliasNames_MapToSerilogLevel(string input, LogEventLevel expected)
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel(input);
levelSwitch.MinimumLevel.Should().Be(expected);
}
[Theory]
[InlineData("")]
[InlineData("TRACE")]
[InlineData("Verbose")]
[InlineData(null)]
[InlineData("nonsense")]
public void SetLevel_UnknownOrNull_FallsBackToInformation(string? input)
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel(input!);
levelSwitch.MinimumLevel.Should().Be(LogEventLevel.Information);
}
[Fact]
public void CurrentLevel_ReportsCanonicalNameAfterSetLevel()
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel("debug");
switcher.CurrentLevel.Should().Be("Debug");
}
}
@@ -36,10 +36,11 @@ public class JsonSettingsStoreTests
await store.LoadAsync();
store.Current.Version.Should().Be(1);
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("en-US");
store.Current.CaptureHotkey.Should().Be(HotkeyBinding.Default);
store.Current.Capture.DefaultFormat.Should().Be(ImageFormat.Png);
store.Current.LogLevel.Should().Be("Information");
}
[Fact]
@@ -136,7 +137,7 @@ public class JsonSettingsStoreTests
await store.LoadAsync();
store.Current.Version.Should().Be(1);
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("en-US");
}
@@ -154,6 +155,46 @@ public class JsonSettingsStoreTests
store.Current.Culture.Should().Be("en-US");
}
[Fact]
public async Task LoadAsync_V1File_MigratesToV2AndWritesBack()
{
var (store, fs) = Build();
var appDataRoot = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var dir = Path.Combine(appDataRoot, "CaptureImage");
fs.Directory.CreateDirectory(dir);
// Hand-crafted v1 document — no logLevel field present. System.Text.Json fills
// it with the init default (Information), and the migration path stamps Version=2
// + triggers a write-back so the on-disk file ends up canonical.
fs.File.WriteAllText(ExpectedPath,
"{\"version\": 1, \"culture\": \"vi-VN\", \"theme\": \"System\"}");
await store.LoadAsync();
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("vi-VN");
store.Current.LogLevel.Should().Be("Information");
// Write-back normalised the file — next parse sees v2 directly.
var written = fs.File.ReadAllText(ExpectedPath);
written.Should().Contain("\"version\": 2");
written.Should().Contain("\"logLevel\": \"Information\"");
}
[Fact]
public async Task LoadAsync_V2File_PreservesLogLevelField()
{
var (store, fs) = Build();
var appDataRoot = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var dir = Path.Combine(appDataRoot, "CaptureImage");
fs.Directory.CreateDirectory(dir);
fs.File.WriteAllText(ExpectedPath,
"{\"version\": 2, \"culture\": \"en-US\", \"logLevel\": \"Debug\"}");
await store.LoadAsync();
store.Current.Version.Should().Be(2);
store.Current.LogLevel.Should().Be("Debug");
}
[Fact]
public async Task ExportAsync_WritesCurrentSettings()
{
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="FluentAssertions" />
<PackageReference Include="coverlet.collector" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\CaptureImage.Core\CaptureImage.Core.csproj" />
<ProjectReference Include="..\..\src\CaptureImage.UI\CaptureImage.UI.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using CaptureImage.Core.Abstractions;
using CaptureImage.UI.Localization;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace CaptureImage.UI.Tests.Localization;
/// <summary>
/// Covers <see cref="ResxLocalizationService"/>. Snapshots thread culture in the ctor and
/// restores in <see cref="Dispose"/> so setting <c>CultureInfo.CurrentCulture</c> from one
/// test doesn't leak into the next one running on the same test runner thread.
/// </summary>
public class ResxLocalizationServiceTests : IDisposable
{
private readonly CultureInfo _savedUICulture;
private readonly CultureInfo _savedCulture;
private readonly CultureInfo? _savedDefaultUICulture;
private readonly CultureInfo? _savedDefaultCulture;
public ResxLocalizationServiceTests()
{
_savedUICulture = CultureInfo.CurrentUICulture;
_savedCulture = CultureInfo.CurrentCulture;
_savedDefaultUICulture = CultureInfo.DefaultThreadCurrentUICulture;
_savedDefaultCulture = CultureInfo.DefaultThreadCurrentCulture;
}
public void Dispose()
{
CultureInfo.CurrentUICulture = _savedUICulture;
CultureInfo.CurrentCulture = _savedCulture;
CultureInfo.DefaultThreadCurrentUICulture = _savedDefaultUICulture;
CultureInfo.DefaultThreadCurrentCulture = _savedDefaultCulture;
}
[Fact]
public void SetCulture_Vietnamese_UpdatesCurrentCultureAndThreadCulture()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var vi = CultureInfo.GetCultureInfo("vi-VN");
svc.SetCulture(vi);
svc.CurrentCulture.Name.Should().Be("vi-VN");
CultureInfo.CurrentUICulture.Name.Should().Be("vi-VN");
CultureInfo.CurrentCulture.Name.Should().Be("vi-VN");
CultureInfo.DefaultThreadCurrentUICulture?.Name.Should().Be("vi-VN");
CultureInfo.DefaultThreadCurrentCulture?.Name.Should().Be("vi-VN");
}
[Fact]
public void SetCulture_Arabic_FlipsFlowDirectionToRightToLeft()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc.SetCulture(CultureInfo.GetCultureInfo("ar-SA"));
svc.CurrentFlowDirection.Should().Be(TextFlowDirection.RightToLeft);
}
[Fact]
public void SetCulture_English_FlowDirectionLeftToRight()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
// Default is en-US; switch elsewhere first so SetCulture actually fires.
svc.SetCulture(CultureInfo.GetCultureInfo("ar-SA"));
svc.SetCulture(CultureInfo.GetCultureInfo("en-US"));
svc.CurrentFlowDirection.Should().Be(TextFlowDirection.LeftToRight);
}
[Fact]
public void SetCulture_RaisesItemIndexer_CurrentCulture_AndFlowDirection_Once_Each()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var names = new List<string?>();
svc.PropertyChanged += (_, e) => names.Add(e.PropertyName);
svc.SetCulture(CultureInfo.GetCultureInfo("vi-VN"));
names.Should().Contain("Item[]");
names.Should().Contain(nameof(ILocalizationService.CurrentCulture));
names.Should().Contain(nameof(ILocalizationService.CurrentFlowDirection));
names.Count(n => n == "Item[]").Should().Be(1);
}
[Fact]
public void SetCulture_AlsoRaisesCultureChangedEvent()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var cultureChanged = 0;
svc.CultureChanged += (_, _) => cultureChanged++;
svc.SetCulture(CultureInfo.GetCultureInfo("vi-VN"));
cultureChanged.Should().Be(1);
}
[Fact]
public void SetCulture_SameAsCurrent_IsNoOp()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
// Constructor seeds with en-US.
var events = 0;
svc.PropertyChanged += (_, _) => events++;
var cultureChanged = 0;
svc.CultureChanged += (_, _) => cultureChanged++;
svc.SetCulture(CultureInfo.GetCultureInfo("en-US"));
events.Should().Be(0);
cultureChanged.Should().Be(0);
}
[Fact]
public void SetCulture_Null_Throws()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
Action act = () => svc.SetCulture(null!);
act.Should().Throw<ArgumentNullException>();
}
[Fact]
public void Indexer_MissingKey_ReturnsKeyInBrackets()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var result = svc["NoSuchKey_DefinitelyMissing_1234"];
result.Should().Be("[NoSuchKey_DefinitelyMissing_1234]");
}
[Fact]
public void Indexer_EmptyKey_ReturnsEmptyString()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc[""].Should().BeEmpty();
}
[Fact]
public void Indexer_KnownKey_ReturnsEnglishByDefault()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc["Nav_Dashboard"].Should().Be("Dashboard");
}
[Fact]
public void Indexer_AfterSetCulture_ReturnsLocalizedValue()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc.SetCulture(CultureInfo.GetCultureInfo("vi-VN"));
svc["Nav_Dashboard"].Should().Be("Bảng điều khiển");
}
[Fact]
public void SupportedCultures_IncludesShippedLanguages()
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var names = svc.SupportedCultures.Select(c => c.Name).ToArray();
names.Should().Contain("en-US");
names.Should().Contain("vi-VN");
names.Should().Contain("ar-SA");
}
}
@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CaptureImage.ViewModels.Logs;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Xunit;
namespace CaptureImage.ViewModels.Tests.Logs;
/// <summary>
/// Covers the view-side logic of <see cref="LogViewerViewModel"/> — hydration from the
/// buffer source, the live-tail append path, and the min-level filter that feeds the
/// viewer while leaving the underlying sink snapshot intact (so Export stays complete).
/// </summary>
public class LogViewerViewModelTests
{
[Fact]
public void EnsureHydrated_CopiesSnapshotIntoEntries()
{
var source = new FakeBuffer();
source.Feed("one", LogLevel.Information);
source.Feed("two", LogLevel.Warning);
var vm = Build(source);
vm.EnsureHydrated();
vm.Entries.Should().HaveCount(2);
vm.Entries[0].Message.Should().Be("one");
vm.Entries[1].Message.Should().Be("two");
}
[Fact]
public void EnsureHydrated_OnlySecondCallDoesNothing()
{
var source = new FakeBuffer();
source.Feed("a", LogLevel.Information);
var vm = Build(source);
vm.EnsureHydrated();
vm.EnsureHydrated(); // idempotent
vm.Entries.Should().HaveCount(1);
}
[Fact]
public void LiveTail_AppendedEntryAppearsInEntries()
{
var source = new FakeBuffer();
var vm = Build(source);
source.Emit(new LogEntry(
DateTimeOffset.UtcNow,
LogLevel.Information,
"TestCtx",
"live",
Exception: null));
vm.Entries.Should().ContainSingle()
.Which.Message.Should().Be("live");
}
[Fact]
public void FilterChange_DropsLowerLevelEntries_KeepsHigherOnes()
{
var source = new FakeBuffer();
source.Feed("dbg", LogLevel.Debug);
source.Feed("inf", LogLevel.Information);
source.Feed("wrn", LogLevel.Warning);
source.Feed("err", LogLevel.Error);
var vm = Build(source);
vm.EnsureHydrated();
vm.SelectedFilterLevel = LogLevel.Warning;
vm.Entries.Should().HaveCount(2);
vm.Entries.Should().OnlyContain(e => e.Level >= LogLevel.Warning);
}
[Fact]
public void FilterChange_DoesNotTouchUnderlyingBuffer()
{
var source = new FakeBuffer();
source.Feed("a", LogLevel.Debug);
source.Feed("b", LogLevel.Information);
var vm = Build(source);
vm.EnsureHydrated();
vm.SelectedFilterLevel = LogLevel.Error;
vm.Entries.Should().BeEmpty();
// Export path calls Snapshot directly — full set must still be there.
source.Snapshot().Should().HaveCount(2);
}
[Fact]
public void LiveTail_WhenEntryBelowFilter_Suppressed()
{
var source = new FakeBuffer();
var vm = Build(source);
vm.SelectedFilterLevel = LogLevel.Warning;
source.Emit(new LogEntry(
DateTimeOffset.UtcNow, LogLevel.Debug, "Ctx", "quiet", null));
source.Emit(new LogEntry(
DateTimeOffset.UtcNow, LogLevel.Error, "Ctx", "loud", null));
vm.Entries.Should().ContainSingle()
.Which.Message.Should().Be("loud");
}
// -- helpers --------------------------------------------------------------
private static LogViewerViewModel Build(ILogBufferSource source)
{
var dispatcher = Substitute.For<IUIThreadDispatcher>();
dispatcher.When(d => d.Post(Arg.Any<Action>()))
.Do(call => call.Arg<Action>().Invoke());
var localization = Substitute.For<ILocalizationService>();
localization["Log_Pause"].Returns("Pause");
localization["Log_Resume"].Returns("Resume");
localization["Log_EventsCount"].Returns("{0} events");
localization["Log_EmptyState"].Returns("no entries");
localization["Log_Filter"].Returns("min:");
localization["Log_RevealFolder"].Returns("open");
var toasts = Substitute.For<IToastService>();
return new LogViewerViewModel(
source,
dispatcher,
localization,
NullLogger<LogViewerViewModel>.Instance,
toasts);
}
private sealed class FakeBuffer : ILogBufferSource
{
private readonly List<LogEntry> _entries = new();
public IReadOnlyList<LogEntry> Snapshot() => new List<LogEntry>(_entries);
public event EventHandler<LogEntry>? Emitted;
public bool Paused { get; set; }
public void Clear() => _entries.Clear();
public void Feed(string message, LogLevel level)
{
_entries.Add(new LogEntry(
DateTimeOffset.UtcNow, level, "TestCtx", message, Exception: null));
}
/// <summary>Test-only: push an entry as if the live tail fired.</summary>
public void Emit(LogEntry entry)
{
_entries.Add(entry);
Emitted?.Invoke(this, entry);
}
}
}
@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using CaptureImage.Core.Abstractions;
using CaptureImage.ViewModels.Preview;
using FluentAssertions;
using Xunit;
namespace CaptureImage.ViewModels.Tests.Preview;
/// <summary>
/// Regression guard for the v1.1.2 M1 fix: <see cref="PreviewViewModel"/> implements
/// <see cref="IDisposable"/> and wires a named <c>OnLocalizationChanged</c> handler that
/// forwards <c>"Item[]"</c> and <c>CurrentCulture</c> notifications to the VM's own
/// <c>Localization</c> property so bindings in <c>PreviewWindow.axaml</c> retranslate.
/// </summary>
public class PreviewViewModelTests
{
[Fact]
public void ItemIndexerChange_RaisesLocalizationPropertyChanged()
{
var localization = new FakeLocalizationService();
using var vm = new PreviewViewModel(localization);
var raised = new List<string?>();
vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
localization.RaiseItemIndexer();
raised.Should().Contain(nameof(PreviewViewModel.Localization));
}
[Fact]
public void CurrentCultureChange_RaisesLocalizationPropertyChanged()
{
var localization = new FakeLocalizationService();
using var vm = new PreviewViewModel(localization);
var raised = new List<string?>();
vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
localization.RaiseCurrentCulture();
raised.Should().Contain(nameof(PreviewViewModel.Localization));
}
[Fact]
public void UnrelatedPropertyChange_DoesNotRaiseLocalization()
{
var localization = new FakeLocalizationService();
using var vm = new PreviewViewModel(localization);
var raised = new List<string?>();
vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
localization.RaiseOther(nameof(ILocalizationService.CurrentFlowDirection));
raised.Should().NotContain(nameof(PreviewViewModel.Localization));
}
[Fact]
public void Dispose_DetachesLocalizationHandler()
{
var localization = new FakeLocalizationService();
var vm = new PreviewViewModel(localization);
var raised = 0;
vm.PropertyChanged += (_, _) => raised++;
vm.Dispose();
localization.RaiseItemIndexer();
raised.Should().Be(0, "Dispose must detach the subscription so the singleton service "
+ "doesn't leak one handler per preview modal");
}
private sealed class FakeLocalizationService : ILocalizationService
{
public CultureInfo CurrentCulture { get; private set; } = CultureInfo.GetCultureInfo("en-US");
public TextFlowDirection CurrentFlowDirection => TextFlowDirection.LeftToRight;
public IReadOnlyList<CultureInfo> SupportedCultures { get; } = new[] { CultureInfo.GetCultureInfo("en-US") };
public string this[string key] => $"[{key}]";
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler? CultureChanged;
public void SetCulture(CultureInfo culture)
{
CurrentCulture = culture;
CultureChanged?.Invoke(this, EventArgs.Empty);
}
public void RaiseItemIndexer() =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
public void RaiseCurrentCulture() =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentCulture)));
public void RaiseOther(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}