72 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.7 394e108c22 chore(changelog): note M6 (notify filter narrow) and M7 (discussion welcome)
Two bullets added under [1.5.1]:

- Under Changed: notify workflows narrowed from workflows:["*"] to
  the specific workflows they monitor (CI, Release), stopping the
  skip-run spam in the Actions tab.

- Under Added: discussion-welcome.yml — bilingual greeting for new
  Discussion threads opened by non-maintainers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 20:36:20 +07:00
poli0981andClaude Opus 4.7 fb06950389 feat(ci): add discussion-welcome workflow
Auto-post a brief bilingual greeting (Vietnamese + English) the
first time a non-maintainer opens a Discussion thread. Directs the
poster at the right venue:

  - Bugs           -> in-app "About -> Report a bug" or the
                      bug-report issue template
  - Security       -> GitHub Security Advisories, not a public
                      discussion
  - Q&A / ideas    -> Discussions, where they already are

Skipped for OWNER / COLLABORATOR / MEMBER (the maintainer doesn't
need a venue cheat-sheet on their own threads). Uses the GraphQL
`addDiscussionComment` mutation via actions/github-script@v7, the
only scope required is `discussions: write` — everything else is
defaulted to read.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 20:35:48 +07:00
poli0981andClaude Opus 4.7 9f04b96eb6 fix(ci): narrow notify-* workflow_run filters to stop skip spam
Both notify caller workflows previously listened to
`workflows: ["*"]`, which fires the caller on every workflow
completion in the repo — every CI run, every release run, every
notify run itself. The Actions tab filled with skipped entries from
two workflows reacting to events they had no business reacting to.

- notify-ci-failure: narrowed to `workflows: ["CI"]` and gated the
  job on `github.event.workflow_run.conclusion == 'failure'`. The
  reusable still re-checks conclusion as defense-in-depth, but the
  caller now short-circuits on green builds before invoking it.

- notify-release-pipeline: narrowed to `workflows: ["Release"]`.
  Intentionally excludes "Announce Release to Discord" — that
  workflow already posts to Discord, routing it through this
  notifier too would double-post.

Effect: roughly 50% fewer notify-* runs in the Actions tab; the
remaining runs all correspond to events worth observing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 20:34:56 +07:00
poli0981andClaude Opus 4.7 4eb8f75072 chore(release): prepare v1.5.1 — README support section, version bump, changelog
Three release-prep touches:

1. README — new "Support the project" section preceding License,
   linking GitHub Sponsors, Ko-fi, Buy Me a Coffee, Patreon, and
   pointing at the in-app Report-a-bug button.

2. App.csproj — bump <Version> from 1.5.0 to 1.5.1. Picked up at
   build time and surfaced in MainWindow PaneHeader and the About
   page's "Version" row.

3. CHANGELOG — new [1.5.1] - 2026-05-11 entry following the
   Keep-a-Changelog format used for v1.5.0: Fixed (CI permissions),
   Changed (SHA pin), Added (3 About sections + FUNDING.yml +
   dev/spec docs + README section), Smoke checklist.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 20:20:46 +07:00
poli0981andClaude Opus 4.7 928badc87c feat(about): add Social Dev, Donate, Report Bug sections
About page grows three small sections between the metadata card and
the existing AI-assistance disclosure:

1. Social Dev — ItemsControl rendering 8 HyperlinkButtons (X,
   YouTube, Discord repo/game, Steam, Bluesky, Mastodon, Telegram).
   HyperlinkButton.NavigateUri opens the URL via
   Windows.System.Launcher — same shell-execute behaviour as the
   existing OpenUrl helper used by the repo link.

2. Support the project — short prose + 4 buttons (GitHub Sponsors
   accent-styled, Ko-fi, Buy Me a Coffee, Patreon). Donate URLs
   hardcoded in AboutViewModel to match the existing
   Developer/RepositoryUrl pattern. Mirror of .github/FUNDING.yml —
   keep in sync.

3. Report a bug — single low-friction button targeting the GitHub
   bug-report issue template
   (https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml).

Public-handle scope only: personal email (proton.me) and PayPal
real-name link intentionally not exposed here.

Localization adds 9 new keys per locale × 11 locales = 99 .resx
entries. EN + VI human-written; the other 9 locales follow the
existing machine-assisted convention documented in
About_TranslationDisclaimer.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 20:20:01 +07:00
poli0981andClaude Opus 4.7 d547a6da25 docs: add FUNDING.yml + pc_spec / dev_env (EN + VI mirrors)
Three additions for v1.5.1:

1. .github/FUNDING.yml — wires the GitHub repo "Sponsor" button to
   GitHub Sponsors (poli0981), Ko-fi, Buy Me a Coffee, and Patreon
   (all under handle "skullmute"). Public-handle scope only; email
   and PayPal intentionally omitted.

2. docs/pc_spec.md (+ docs/i18n/vi/pc_spec.md) — public reference
   for the maintainer's primary development hardware. Documents the
   Win11 Insider Dev Channel build, RTX 5080, JetBrains 2026.x
   lineup. Mobile test devices listed for transparency but flagged
   as not used for CaptureImage itself (Win11-only desktop).

3. docs/dev_env.md (+ docs/i18n/vi/dev_env.md) — toolchain versions
   (.NET 9, Python 3.12, Node 22+ LTS, Rust stable, Git + GPG),
   Rider plugin recommendations, Windows SDK requirement,
   build/test/run commands, release tooling. Mirrors the CI command
   in .github/workflows/ci.yml so contributors run the same locally.

VI mirrors keep tech terms (toolchain names, file paths, env vars)
in English per the repo bilingual convention; cross-links between
VI docs target VI siblings, with EN-only docs flagged explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 20:11:48 +07:00
poli0981andClaude Opus 4.7 c48dc38e92 fix(ci): add minimum permissions to ci.yml + pin reusable workflow refs
Two CI hardening changes:

1. ci.yml previously had no top-level permissions block, which Code
   Scanning flagged as "Workflow does not contain permissions." Now
   declares the minimum it actually needs: contents: read (to checkout
   the repo and run dotnet build/test). No package writes, no release
   uploads, no PR comments.

2. announce-release.yml, notify-ci-failure.yml, and
   notify-release-pipeline.yml previously referenced
   poli0981/.github/.github/workflows/*.yml@main. A push to ops-repo
   main would land in our release pipeline silently. Now pinned to
   commit SHA e973e2f15725356653ef07539016670ad2733f83. Dependabot
   already has the github-actions ecosystem rule (.github/dependabot.yml
   line 39-51); it will bump these refs weekly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 20:09:30 +07:00
poli0981 d8b5e2e436 Refactor workflows to use reusable configurations for Discord notifications 2026-05-09 01:16:18 +07:00
poli0981 4f7059e585 Add notify release pipeline workflow for Discord notifications 2026-05-08 21:12:11 +07:00
poli0981 acaee4a0a0 Enhance Discord notification helper with phase 2 commands and improved webhook handling 2026-05-08 20:10:16 +07:00
poli0981 3bb238be3f Add CI failure notification workflow for Discord
This workflow listens for CI failures and posts notifications to a Discord channel.
2026-05-08 18:47:16 +07:00
poli0981 c6e4145f5d Add GitHub Actions workflow to announce releases on Discord 2026-05-08 18:46:40 +07:00
poli0981 33d6b0c004 Add Discord notification helper script
This script helps send notifications to Discord via webhooks for release announcements and CI failure alerts. It includes configuration for colors, truncation of messages, and handles environment variables for dynamic content.
2026-05-08 18:45:49 +07:00
poli0981 419ab7a627 Merge pull request #14 from poli0981/release/v1.5.0
release: v1.5.0 — process leak fix, theme sync, +4 langs, 4 features
2026-05-07 21:48:42 +07:00
poli0981andClaude Opus 4.7 a29217a324 chore(release): bump to v1.5.0
Closes the v1.5 cycle: process-leak fix + theme-sync fix + 4 new
languages + 4 new features (countdown / clipboard / pinned thumbnail /
OCR / region capture) + single-instance guard.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 21:34:34 +07:00
poli0981andClaude Opus 4.7 72a6730c84 test(v1.5-M9): regression test for new AppSettings defaults
Locks in the v1.5 schema defaults so a future refactor can't silently
flip CountdownSeconds=3 or AutoPinAfterCapture=true and surprise
existing users on upgrade. Also smoke-tests the `with` round-trip to
guard against the STJ source-gen init-default gotcha from the v1.2
cycle ledger.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 21:33:04 +07:00
poli0981andClaude Opus 4.7 94027889d3 feat(v1.5-M8): region capture mode
A new Settings → Capture mode dropdown switches between Window mode
(default; existing Windows.Graphics.Capture pipeline) and Region mode,
which opens a full-screen overlay so the user can drag-select any
rectangle of the desktop.

Flow:
1. Region hotkey fires → service captures the primary monitor pixels
   in one GDI shot (CopyFromScreen). This locks the source image
   BEFORE the overlay appears, so the overlay never shows up inside
   the screenshot.
2. RegionSelectorOverlay shows the dimmed screenshot full-screen, with
   a Border that re-shows the image at 100% inside the user's drag
   rectangle (a "spotlight" effect that needs no clip path).
3. On pointer release, the original BGRA buffer is cropped to the
   selected rect and packaged into a CapturedFrame, which then flows
   through the existing Preview / Save / Clipboard / Pinned-thumbnail
   pipeline unchanged.
4. Esc or a micro-drag (<4 px) cancels — state machine returns to
   Armed without firing FrameCaptured.

v1.5 ships primary-monitor support only. Multi-monitor + per-monitor
DPI scaling is on the v1.6 roadmap (the codepath already accepts a
RECT in pixel coords; it just hasn't been generalised to enumerate
DisplayArea.FindAll yet).

5 new localization keys (Settings_CaptureMode, …Window, …Region,
Region_TargetName, Region_DragHint) added to all 11 packs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 21:31:48 +07:00
poli0981andClaude Opus 4.7 38b1554dc5 feat(v1.5-M7): built-in offline OCR via Windows.Media.Ocr
PreviewWindow gains an Extract Text (OCR) button that runs the OS-supplied
OCR engine on the captured frame and copies recognised text to the
clipboard. All processing is on-device — nothing leaves the machine,
which fits the local/private ethos.

- IOcrService + OcrResult abstraction in Core/Abstractions so portable VM
  code stays free of WinRT references; WindowsOcrService in Infrastructure
  wraps OcrEngine.TryCreate* with a 3-tier fallback chain (explicit lang
  tag → user profile languages → en-US → unavailable).
- IClipboardService grew a CopyText overload so the OCR result can land
  in the clipboard in plain-text form (callers already had the image
  variant).
- PreviewViewModel: ExtractTextCommand calls OCR, copies, and surfaces
  one of three toast outcomes — N words copied / no text / engine
  unavailable — all localized.
- 4 new keys (Preview_ExtractText, Toast_OcrSuccess, Toast_OcrEmpty,
  Toast_OcrUnavailable) added to all 11 packs.

Note: engine availability depends on the user's installed OCR language
packs (Settings → Time & language → Language & region → Optional
features). The fallback chain keeps things working when the requested
language pack isn't installed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 21:25:42 +07:00
poli0981andClaude Opus 4.7 f296756b0d feat(v1.5-M6): pinned floating thumbnail window
After capture, optionally spawns a small always-on-top window holding a
thumbnail of the shot — handy for comparing successive captures or
keeping a reference visible while playing/working in another app.

- PinnedThumbnailWindow: 280×220, Mica backdrop, ExtendsContentIntoTitleBar
  for a draggable header strip with Show-in-Explorer + Close buttons. The
  always-on-top behaviour comes from OverlappedPresenter.IsAlwaysOnTop —
  cleaner than SetWindowPos(HWND_TOPMOST) and reverts naturally if the
  user un-pins later.
- Theme tracking via the M3 ThemeApplicator (subscribes to ISettingsStore.
  Changed; unsubscribes on Closed) so dark-mode users don't get a Light
  flash.
- Each capture spawns a fresh window, so the user can pile up multiple
  pins to compare side-by-side.
- DashboardViewModel encodes PNG once and feeds the same buffer into both
  the clipboard service and the pin host (lazy `EnsurePngAsync` cache).

Settings: new `UISettings.AutoPinAfterCapture` toggle. Pinning from the
Preview window's Save button is deferred — the auto-pin checkbox covers
the headline use case for v1.5.

3 new localization keys (Settings_AutoPinAfterCapture, PinnedWindow_Open,
PinnedWindow_Close) added to all 11 packs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 21:20:38 +07:00
poli0981andClaude Opus 4.7 56cd1047c2 feat(v1.5-M5): countdown delay, clipboard mode, auto-open folder
Three small Settings toggles that have been frequently requested:

- **Capture countdown** (Off / 3s / 5s / 10s) — runs before the state
  machine fires HotkeyPressed, so the dashboard still reads "Armed"
  during the wait and StatusMessage shows "Capturing in N…" each tick.
  Useful for capturing tooltips and menu animations that vanish when
  you Alt-Tab back from the target.
- **Clipboard mode** (None / Copy only / Copy + Save) — the encoder
  pipeline now optionally produces PNG bytes that flow through the new
  IClipboardService into the WinRT clipboard. "Copy only" skips the
  file write entirely.
- **Open output folder after save** — toggle on UI page; reuses the
  existing UseShellExecute pattern.

The clipboard service is a thin abstraction over WinRT's DataPackage
+ InMemoryRandomAccessStream so portable VM code stays free of
Windows.* references.

12 new localization keys added to all 11 packs; SettingsViewModel
gains CountdownOption / ClipboardOption helpers (parallel of the
ThemeOption pattern) so ComboBox labels rebuild cleanly on culture
switch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 21:16:04 +07:00
poli0981andClaude Opus 4.7 933e872b49 feat(v1.5-M4): add fr-FR, de-DE, pt-BR, ru-RU language packs
Brings shipped locales to 11 (en, vi, ar, ja, zh-Hans, ko, es + new fr,
de, pt-BR, ru). Each pack carries the full 112-key load. The translation
disclaimer in every pre-existing locale was also updated to mention the
four new languages so the About page stays honest about what's machine-
assisted.

Test plumbing: LocalizationCompletenessTests' Theory matrix now spans all
11 cultures, and both ResxLocalizationServiceTests and the completeness
tests are pinned to a shared xUnit collection so they can't race on the
process-wide CultureInfo.DefaultThreadCurrent* statics — adding 4 more
cultures to the parallel pool finally tipped that pre-existing race into
a consistent failure.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 21:07:07 +07:00
poli0981andClaude Opus 4.7 cfe2b5ce69 feat(v1.5-M3): sync PreviewWindow theme with main app via ThemeApplicator
PreviewWindow used to ship with whatever theme the OS happened to be on
because it never read the persisted theme from ISettingsStore. Now it
mirrors MainWindow: applies the saved theme before Activate (no flash on
open) and re-applies on every settings.Changed (so toggling theme while
the preview is up updates it live). The Closed handler unsubscribes so
each preview doesn't leak a handler into the singleton settings store.

Extracted the string→ElementTheme switch into ThemeApplicator so future
secondary windows (pinned thumbnail, region overlay) reuse the same
mapping and can't drift.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 20:56:04 +07:00
poli0981andClaude Opus 4.7 9f5986dbac feat(v1.5-M2): single-instance guard with restore-on-relaunch
A second launch of the app no longer spawns a duplicate process — instead it
pings the existing instance over a named pipe and the original window pops to
the foreground. Mirrors the Spotify/Slack pattern.

- SingleInstanceGuard.TryAcquire holds Local\CaptureImage.SingleInstance.<user>
  scoped per OS user; abandoned mutex from a crashed prior run is treated as
  acquired so we don't lock ourselves out.
- ActivationListener runs a NamedPipeServerStream loop on a background task
  and posts the restore sequence to the UI thread on ACTIVATE — same
  AppWindow.Show + ShowWindow(SW_RESTORE) + SetForegroundWindow dance the
  tray icon already uses.
- Guard runs AFTER VelopackApp.Build().Run() so installer/uninstaller hooks
  (--squirrel-*) keep working.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 20:54:03 +07:00
poli0981andClaude Opus 4.7 585dfb3de5 fix(v1.5-M1): close dispose chain to stop process zombies on exit
DashboardViewModel.Dispose was missing _watcher.Stop() — the WMI watcher's
ManagementEventWatcher subscriptions run on non-background threads, so when
the dashboard tore down its other watchers but left the WMI one alive the
CLR couldn't unwind on exit. Combined with the fact that Program.Main
never disposed the IServiceProvider, the entire singleton graph (tray,
foreground watcher, WMI watcher) leaked across each launch — Task Manager
accumulated one zombie CaptureImage.exe per app open.

Two-line fix: stop the WMI watcher in DashboardViewModel.Dispose and
dispose App.Services in Program.Main's finally block. ServiceProvider
disposal now cascades through every IDisposable singleton.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 20:51:42 +07:00
poli0981 e5ddc4e3ac Merge pull request #13 from poli0981/release/v1.4.0
v1.4.0 — UX polish + accessibility cycle
2026-04-27 09:36:26 +07:00
poli0981andClaude Opus 4.7 81563c65f0 fix(v1.4-M3): use GetForegroundWindow inside the WinEvent callback
The original M3 implementation trusted the hwnd parameter the OS
passes to the WinEvent callback. On Win11 that's reliable for
mouse-click activations (single clean event with idObject=OBJID_WINDOW)
but breaks Alt-Tab: the modern Task View overlay fires events whose
hwnd points at a DWM-cloaked window, and the secondary event for the
real destination sometimes carries idObject != 0 (which the previous
'if (idObject != 0) return' filter dropped on the floor).

Net effect for users: enabling auto-switch only updated the selected
target on click, never on Alt-Tab.

Fix:
- Add User32.GetForegroundWindow P/Invoke.
- Inside OnRawForegroundEvent, ignore the event-supplied hwnd and
  poll GetForegroundWindow() to get the real current foreground at
  callback time. The 250 ms debounce already collapses the burst of
  events Alt-Tab fires into a single delivery.
- Drop the idObject != 0 short-circuit. WINEVENT_SKIPOWNPROCESS plus
  the explicit pid check still keep our own windows out.

Also adds a Debug-level log when the watcher fires - makes future
diagnosis easier without touching Information level for end users.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 09:30:10 +07:00
poli0981andClaude Opus 4.7 e13b9a6b56 chore(release): bump to v1.4.0
UX polish + accessibility cycle (M1-M7).

- Window fixed at 1200x720, maximize and resize disabled
- Light / Dark / System theme picker
- Auto-switch on Alt-Tab (opt-in)
- 4 new language packs: ja-JP, zh-Hans, ko-KR, es-ES (machine-assisted)
- Friendlier end-user log lines + new lifecycle events
- Tests cover 7 cultures x load-bearing keys (401 cases)

Publish smoke verified locally - .xbf + .pri custom MSBuild target
from v1.3.1 still propagates correctly, all 6 non-English satellite
assemblies materialize under bin/.../publish/{ar,es,ja,ko,vi,zh-Hans}/.

settings.json schema is unchanged (Theme stays a string, default
"System"; Capture.AutoSwitchOnAltTab is a new optional bool that
defaults false on missing). Existing v1.3.x users upgrade in place
without migration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 09:12:07 +07:00
poli0981andClaude Opus 4.7 414d145bc8 test(v1.4-M6): smoke coverage for Win32ForegroundWindowWatcher
Three lifecycle tests - new instance not running, stop-before-start
is a no-op, dispose is idempotent. The actual SetWinEventHook path
needs a UI thread with a live message pump and is exercised manually
during QA on Win11.

The localization completeness matrix already covers all 7 cultures
(401 cases) - that's M6's other tested deliverable, picked up via the
M5 commit. Manual QA matrix (7 cultures x 3 themes x auto-switch
on/off) lives outside the automated suite and runs against the M7
publish output.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 09:09:43 +07:00
poli0981andClaude Opus 4.7 1a57c07409 feat(v1.4-M5): add ja-JP, zh-Hans, ko-KR, es-ES language packs
Brings shipped culture count to 7. Translations are machine-assisted
- the About > Translations disclaimer now lists all 6 non-English
packs and invites native-speaker proofreading PRs.

- src/CaptureImage.UI/Resources/Strings/Strings.{ja,zh-Hans,ko,es}.resx
  translate all 56 keys (nav, dashboard, settings, hotkey errors,
  update, about, log viewer, preview, toasts, tray menu).
- ResxLocalizationService.ShippedCultures grows to 7 entries
  (en-US, vi-VN, ar-SA + ja-JP, zh-Hans, ko-KR, es-ES). All 4 new
  cultures are LTR so existing RTL handling for Arabic stays
  unchanged.
- LocalizationCompletenessTests.CultureMatrix iterates all 7 - 401
  test cases now assert every load-bearing key is non-bracketed and
  non-empty in every shipped culture.
- Updated About_TranslationDisclaimerBody in en/vi/ar to reference
  the full set of machine-translated packs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 09:08:12 +07:00
poli0981andClaude Opus 4.7 edf6ab93d7 feat(v1.4-M4): friendlier log messages + new lifecycle log sites
End-user-facing logs are now phrased like a person, not a stack
trace.

New log sites:
- "Picture captured: {Name} ({W}x{H}, {KB} KB) at {Path} [{Format}]"
  on success (replaces "Capture OK -> ...").
- "Picture capture cancelled by user." on OperationCanceledException
  AND CaptureException(Cancelled).
- "Picture capture failed: {Reason}" on other CaptureExceptions.
- "Language switched to {Code} ({Name})." on culture change.
- "Capture sound {State}." on sound toggle.
- "Auto-switch on Alt-Tab {State}." on toggle.

Tone shift on existing sites - "Failed to X" -> "Couldn't X" across
DashboardViewModel, SettingsViewModel, UpdateViewModel, AboutViewModel,
LogViewerViewModel. Structured properties unchanged so log queries and
diagnostics still work.

Logs remain English-only per v1.2 design (file shareability + parser
stability across cultures).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 09:00:39 +07:00
poli0981andClaude Opus 4.7 b9ec09c62e feat(v1.4-M3): auto-switch capture target when Alt-Tab
Adds an opt-in foreground watcher so the dashboard's selected
target follows whichever window has focus.

- IForegroundWindowWatcher (Core.Abstractions): contract for
  start/stop + ForegroundChanged event.
- Win32ForegroundWindowWatcher (Infrastructure.Processes):
  SetWinEventHook on EVENT_SYSTEM_FOREGROUND with
  WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS, plus a 250ms
  debounce timer so rapid Alt-Tab sequences only fire once on
  the landing window. Holds a strong reference to the delegate
  so the OS doesn't AV when the next event arrives.
- AppSettings.Capture.AutoSwitchOnAltTab (default false) — bool
  toggle. Source-gen STJ picks it up automatically.
- DashboardViewModel: subscribes to ForegroundChanged, marshals
  to UI via IUIThreadDispatcher, matches HWND against the
  Targets collection. Non-target windows keep current selection
  so users who Alt-Tab to Explorer/Settings don't lose context.
  Watcher start/stop driven by ApplyAutoSwitchSetting() called
  from the constructor and OnSettingsChanged.
- SettingsViewModel + SettingsPage: CheckBox with hint copy.
- Strings.{en,vi,ar}.resx: new keys + completeness test.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 08:56:05 +07:00
poli0981andClaude Opus 4.7 bef2e2fdc6 feat(v1.4-M2): wire Light/Dark/System theme
AppSettings.Theme was reserved in v1.3 but never applied. M2 hooks
it up:

- SettingsViewModel: SelectedTheme + SupportedThemes (rebuilt on
  culture change so labels stay localized), persists via Update().
- SettingsPage: new Theme ComboBox sandwiched between Language and
  Hotkey, ItemTemplate binds to localized DisplayLabel.
- MainWindow.ApplyTheme: maps "Light"/"Dark"/"System" to ElementTheme,
  hops via DispatcherQueue so callers don't have to.
- App.OnLaunched: applies persisted theme before Activate, then
  re-applies on every ISettingsStore.Changed.
- Strings.resx/vi/ar: 4 new keys (Settings_Theme + System/Light/Dark).
- LocalizationCompletenessTests: theme keys added to LoadBearingKeys.

XAML audit found zero hardcoded brushes - v1.3 migrate already used
ThemeResource throughout, so light/dark flips with no extra cleanup.
Mica Base re-tints with the resolved theme automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 08:48:42 +07:00
poli0981andClaude Opus 4.7 1e02f7578e feat(v1.4-M1): fix window size + disable maximize/resize
Cast AppWindow.Presenter to OverlappedPresenter and clear
IsMaximizable + IsResizable. Window stays at 1200x720; minimize
remains enabled for tray flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 08:41:22 +07:00
poli0981andClaude Opus 4.7 8baefc4a1e chore: remove unused System usings from Program.cs
Leftover cleanup from v1.3 cycle.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 08:40:49 +07:00
poli0981andClaude Opus 4.7 4c1dba2dbd fix(release): v1.3.1 hotfix — copy .xbf + .pri to publish output
v1.3.0 shipped broken. The WinUI 3 publish pipeline silently omits two
file types from the self-contained publish output:

  1. .xbf — compiled XAML binary format (MainWindow.xbf, App.xbf, plus
     every Page/UserControl in CaptureImage.UI/Controls/ +
     CaptureImage.UI/Views/). Without these,
     Application.LoadComponent throws XamlParseException at runtime on
     every ms-appx:/// XAML reference.
  2. CaptureImage.App.pri — the app's compiled Package Resource Index.
     Without it, Windows can't resolve any ms-appx:/// URI at all,
     including the WinAppSDK theme resources at
     ms-appx:///Microsoft.UI.Xaml/Themes/themeresources.xaml.

Both files are produced into bin/Release/.../win-x64/ during build but
`dotnet publish --self-contained` skips them. v1.3.0 users got an installer
+ Velopack pack that ran fine, but the new app's MainWindow constructor
threw on InitializeComponent and the UI thread caught it via App.Unhandled-
Exception — process kept running, no window ever appeared. Silent failure.

Bisect:
- Local Debug bin works (XAML compiler outputs to obj/, .NET picks them
  up via Content items at runtime).
- Local Release bin works (.xbf + .pri land in bin/.../win-x64/).
- Local Release publish FAILS (.xbf + .pri NOT propagated to publish
  output) — same failure as the GitHub Actions release.yml.

Fix: add a custom MSBuild target `CopyWinUIArtifactsToPublishDirectory`
(AfterTargets="ComputeFilesToPublish") that explicitly adds every .xbf
plus $(AssemblyName).pri from $(OutDir) to ResolvedFileToPublish,
preserving the cross-assembly subfolder structure the XAML compiler
creates. Verified: publish-fix2/ now contains all 10 expected .xbf
(App, MainWindow, 4 Pages, 2 Controls, LogViewerView, PreviewWindow,
UpdatePage) + CaptureImage.App.pri; launched .exe completes full boot
path through Tray icon initialization.

Bumps version 1.3.0 → 1.3.1. CHANGELOG [1.3.1] hotfix section explains
the bug and recovery path for users already on broken v1.3.0 (Update
tab can't reach them since their window never opens — they need to
download the new Setup.exe manually).

Tests: 320/320 pass (Core 67 + Infra 60 + VM 22 + UI 171).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 12:36:20 +07:00
poli0981andClaude Opus 4.7 0967de6ceb chore(release): bump to v1.3.0
Cut the v1.3.0 WinUI 3 / Fluent 2 release. Closes the v1.3 cycle that ran
M1 → M7b on branch feature/v1.3-winui3 from v1.2.0 baseline.

Version bump:
- src/CaptureImage.App/CaptureImage.App.csproj: <Version>1.3.0-dev</Version>
  → <Version>1.3.0</Version>. release.yml's tag-driven publish overrides
  this via /p:Version=$(steps.version.outputs.version) so the dev marker is
  cosmetic; bumping it keeps `dotnet run` builds reporting the right number.

CHANGELOG.md:
- New [1.3.0] - 2026-04-26 section with Added / Changed / Removed / Fixed /
  Deferred-to-v1.4 subsections. Headlines: WinUI 3 + Fluent 2 + Mica
  migration, sound on capture (was a v1.2 feature gap), Browse button,
  Composition slide animation, +164 tests (total 320 incl. 141-case
  3-culture localization completeness matrix).

release.yml:
- Drop /p:PublishSingleFile=true + /p:IncludeNativeLibrariesForSelfExtract=true
  + /p:EnableCompressionInSingleFile=true — WinAppSDK can't bundle into a
  single .exe; multi-file self-contained is the only option for unpackaged
  WinUI 3.
- Add /p:Platform=x64 + /p:WindowsPackageType=None for explicitness.
- Header comment updated.
- Add ./releases/*.zip to upload list (carry-over from v1.2 — Velopack's
  CaptureImage-win-Portable.zip output never reached the Release page).
- Release-body description adds the Portable.zip line.

Doc sync (Avalonia → WinUI 3 references in current-state docs; CHANGELOG
history of v1.0–v1.2 stays untouched since those releases WERE Avalonia):
- README.md: project structure description (CaptureImage.UI now hosts
  WinUI 3 Pages + UserControls).
- docs/ARCHITECTURE.md: layer rules + dependency mermaid + i18n sequence
  diagram + startup-order list now reference WinUI 3 / WinAppSDK.
  CaptureImage.UI TFM updated to net9.0-windows10.0.22621.0.
- docs/CONTRIBUTORS.md: acknowledgement updated — WindowsAppSDK / WinUI 3
  team for v1.3+, Avalonia team retained as historical credit for
  v1.0–v1.2, H.NotifyIcon team added.
- docs/legal/THIRD_PARTY_NOTICES.md: UI framework section rewritten —
  Microsoft.WindowsAppSDK + WinUI + SDK.BuildTools + H.NotifyIcon.WinUI +
  System.Drawing.Common; Avalonia.* + Inter typeface dropped.
- docs/legal/DISCLAIMER.md + TERMS.md: trademark lists swap "Avalonia"
  for "WinUI" + "Windows App SDK".

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 320/320 pass (Core 67, Infra 60, VM 22, UI 171).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 11:57:57 +07:00
poli0981 0cb119be6e remove unused using 2026-04-26 11:49:48 +07:00
poli0981andClaude Opus 4.7 319a3756ba test(v1.3-M7b): converter coverage + localization completeness matrix
Round out v1.3 test coverage. Total goes from 156 → 320 (+164 tests).

CaptureImage.Core.Tests/Models/LogEntryTests.cs (new — 5 tests):
- TimestampText (the v1.3-M5 addition that exists because WinUI 3 {Binding}
  doesn't honour StringFormat) — asserts HH:mm:ss.fff InvariantCulture format.
- FileLineText edge cases (both present, file missing, line missing, line=0).

CaptureImage.UI.Tests/Converters/ (new — 18 tests across 4 files):
- FlowDirectionConverter: LTR, RTL, null defensive default, unexpected type,
  ConvertBack throws.
- BoolToVisibilityConverter: true → Visible, false → Collapsed, null → Collapsed,
  ConvertBack roundtrip.
- InvertedBoolToVisibilityConverter: inverted mappings, ConvertBack roundtrip.
- NotNullToVisibilityConverter: null, string, empty string, object, ConvertBack
  throws.

These were the 4 v1.3-M4 / M6 converters with zero test coverage. All depend
only on Microsoft.UI.Xaml.{FlowDirection, Visibility} enums (no XAML runtime
init needed) so they run cleanly in xUnit on the net9.0-windows10.0.22621.0
TFM that UI.Tests already targets.

CaptureImage.UI.Tests/Localization/LocalizationCompletenessTests.cs (new —
3 cultures × 47 keys = 141 Theory cases):
- Asserts every load-bearing UI string (nav rail labels, page headers, dialog
  buttons, tray menu, toast headlines, preview prompt) renders to a non-empty,
  non-bracketed value in en-US / vi-VN / ar-SA. The bracketed fallback
  (e.g. "[Nav_Dashboard]") signals a missing resx entry; this matrix catches
  that early instead of during user testing.
- 47 curated keys cover what an end-user actually sees during normal flows.
  New visible labels added in v1.4+ should be appended to LoadBearingKeys
  to keep the matrix comprehensive.

Coverage of the new v1.3 services that genuinely need a UI thread (TrayIconHost,
PreviewPresenter, Win32FolderPicker, WinUIThreadDispatcher, HotkeyRecorder)
is intentionally NOT added — they require a live WinAppSDK runtime + XAML
context that xUnit can't realistically provide. Their behaviour is exercised
through the smoke runs at every milestone.

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 320/320 pass (Core 67, Infra 60, VM 22, UI 171).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 11:29:06 +07:00
poli0981andClaude Opus 4.7 8d460a5afa fix(v1.3-M7a): 2nd-pass fixes for drawer, tray menu, folder picker
User-reported regressions after the M7a 1st-pass interactive verification:
3 of 7 fixes didn't actually solve the issue. This commit re-fixes them
with the right WinUI 3 idioms.

#1 Log drawer still rendering on the leading edge (Column-based positioning
   from 1st pass didn't help):
- The bug was Composition `visual.Offset = (48, 0, 0)` OVERRIDING the
  layout-computed position rather than adding on top. So regardless of
  HorizontalAlignment / Grid.Column, the drawer rendered at absolute x=48
  on first measure. After window resize the layout pass reset Offset and
  the drawer snapped to its anchored position — matching the user's
  observation.
- Fix: switch to the WinUI 3 Translation pattern. Call
  `ElementCompositionPreview.SetIsTranslationEnabled(LogDrawer, true)`
  once on Loaded, then animate `visual.Properties["Translation"]`
  (additive on top of layout) instead of `visual.Offset` (which overrides
  it). Drawer now stays pinned to Grid.Column=1 (right 480 px) and
  Translation supplies the slide offset only. Same animation duration +
  easing as v1.2-M7.

#6 Tray right-click menu items not invoking actions (single-click +
   double-click on the icon work fine; only the popup menu items don't):
- Click event on MenuFlyoutItem doesn't route reliably when the flyout is
  hosted by H.NotifyIcon's TaskbarIcon ContextFlyout — H.NotifyIcon shows
  the popup outside the normal XAML routing chain so click events drop
  on the floor.
- Fix: switch all menu items from Click event to Command property using
  the same SimpleCommand pattern that already worked for
  LeftClickCommand / DoubleClickCommand on the TaskbarIcon. Upgraded
  click logging from Debug → Information so menu invocations now show
  in the default log level.

#3 Browse button throwing COMException 0x80004005 on PickSingleFolderAsync:
- `Windows.Storage.Pickers.FolderPicker` is unreliable in unpackaged
  WinUI 3 even with `WinRT.Interop.InitializeWithWindow` correctly set
  up — it throws E_FAIL with no recoverable detail. Known issue across
  WinAppSDK versions.
- Fix: replace with a Win32 IFileOpenDialog COM-interop helper
  (`Win32FolderPicker.PickSingleFolder`) using FOS_PICKFOLDERS +
  FOS_FORCEFILESYSTEM + FOS_NOCHANGEDIR option flags. Modern Vista+ Open
  dialog look, no package identity required, 100% reliable across SDK
  versions. ~150 lines of P/Invoke + COM declarations all kept in one
  file so the workaround is self-contained.
- SettingsPage.xaml.cs now passes the current OutputDirectory as the
  initial location so the dialog opens at the previously-chosen folder.

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 156/156 pass — same baseline.
- Smoke run: app boots through full path, no exceptions. Interactive
  re-verification of the 3 fixed paths is the user's job (drawer slide
  to right edge on click; tray menu items fire actions; Browse opens
  IFileOpenDialog and writes back to OutputDirectory).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 11:22:37 +07:00
poli0981andClaude Opus 4.7 6656e6380c fix(v1.3-M7a): sharp-edge sweep from interactive verification
Seven user-reported issues from M6 visual verification, fixed in priority
order (highest user-impact first).

#2 Title bar overlap (caption buttons obscuring nav rail / drawer / pages):
- MainWindow.xaml: split root Grid into 2 rows. Row 0 = 48 px transparent
  Border (AppTitleBar) reserved as drag region; Row 1 = body Grid. The
  Mica backdrop still covers the full window; the OS-drawn caption
  buttons land inside Row 0's reserved strip without overlapping content.
- MainWindow.xaml.cs: SetTitleBar(AppTitleBar) right after Activate so the
  drag region is registered with the windowing system.

#1 Log drawer rendering on the leading edge until window resize:
- MainWindow.xaml: body Grid now has 2 columns ("*" + "480"). LogDrawer
  pinned to Column 1 instead of relying on HorizontalAlignment="Right",
  which WinUI 3 doesn't honour reliably on first measure (drawer would
  render on the leading edge until a relayout). NavigationView spans
  both columns. Composition animation Offset.X +48/−48 still slides the
  drawer correctly under both LTR and RTL.

#6 Tray menu/click broken when minimized:
- TrayIconHost.cs ShowMainWindow(): now calls AppWindow.Show +
  ShowWindow(SW_RESTORE) + Activate + SetForegroundWindow. AppWindow.Show
  alone leaves a taskbar-minimized window minimized; ShowWindow(SW_RESTORE)
  handles that case. SetForegroundWindow forces Z-order to top even when
  another app has focus.
- TaskbarIcon.NoLeftClickDelay = true so single-click fires immediately
  instead of waiting ~500 ms for a possible double-click.
- DoubleClickCommand also wired to ShowMainWindow so either user habit
  works.
- Diagnostic logging on each menu Click handler so we can tell whether
  the click fired or the action silently failed.
- _quitting flag bypasses the MinimizeToTray hide-instead-of-close
  intercept when the user picks Exit from the tray menu — without it,
  Application.Current.Exit() would loop forever as the closing handler
  cancelled the shutdown.

#5 Auto-refresh disrupting preview decisions:
- DashboardViewModel.OnProcessChanged: skip RefreshAsync while
  _stateMachine.CurrentState is Previewing or Saving. Rebuilding Targets
  during a preview replaces the GameTargetViewModel instances and
  shuffles SelectedTarget out from under the user. The next process
  event after the preview closes triggers a fresh debounce — nothing's
  lost.

#3 Browse button no-op:
- SettingsPage.xaml.cs: wire BrowseOutputButton.Click to a FolderPicker
  flow. WinUI 3 unpackaged needs explicit HWND association via
  WinRT.Interop.InitializeWithWindow, otherwise the picker silently
  no-ops or crashes. HWND comes from the host window via a new
  WindowHostHelper static accessor (CaptureImage.UI side), set by
  App.OnLaunched after the main window is created. The picker writes
  the chosen path back through SettingsViewModel.OutputDirectory which
  already round-trips through ISettingsStore.

#4 Sound on capture (was a v1.2 feature gap):
- DashboardViewModel: hook the success path of CaptureOnceAsync to
  PlayCaptureSoundIfEnabled, gated on Settings.UI.SoundEnabled (the
  checkbox shipped in v1.0 but had no consumer). Uses Win32 PlaySound
  via P/Invoke instead of System.Media.SystemSounds — the latter ships
  in System.Windows.Extensions which only targets Windows TFMs, and
  ViewModels.csproj is intentionally TFM-portable. PlaySound("SystemAsterisk",
  IntPtr.Zero, SND_ASYNC | SND_ALIAS) works on net9.0 portable.

#7 Third-party list update:
- AboutViewModel.cs: drop "Avalonia" + "Inter typeface" entries; add
  "Windows App SDK / WinUI 3" and "H.NotifyIcon.WinUI". Other entries
  (SkiaSharp, Velopack, etc.) still ship.

Carry-overs (intentionally NOT fixed in M7a):
- Tray icon still ships with OS default glyph (real .ico round-trip
  deferred to v1.4 — see feedback_h_notifyicon_winui_quirks.md).
- Indexer-style {Binding Localization[Key]} bindings — verify in M7b
  3-culture smoke; port to computed properties only if WinUI 3 doesn't
  refresh them on culture change.

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 156/156 pass — same baseline.
- Smoke run: app boots clean through full path; no exceptions in startup.
  Interactive re-verification of each of the 7 fixes is the user's M7b job.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 11:01:40 +07:00
poli0981andClaude Opus 4.7 c7e9db3673 feat(v1.3-M6): port HotkeyRecorder + ToastHost; rewrite Tray + Preview
Sixth milestone of v1.3. Replace the M1 stubs (StubTrayIconHost,
StubPreviewPresenter) with real implementations and port the two custom
controls (HotkeyRecorder, ToastHost) that the v1.2 SettingsPage and
MainWindow shell depended on.

Directory.Packages.props:
- Rename `H.NotifyIcon.WindowsAppSDK 2.2.0` -> `H.NotifyIcon.WinUI 2.2.0`
  (the original package id from v1.2 doesn't exist on nuget.org;
  WinUI is the actual WinAppSDK-compatible variant).

CaptureImage.UI.csproj:
- Add PackageReference H.NotifyIcon.WinUI + System.Drawing.Common.

App.xaml:
- Register ToastKindToBrushConverter at Application.Resources scope.

CaptureImage.UI/Controls/HotkeyRecorder.xaml(.cs):
- WinUI 3 UserControl. ContentControl is the focusable surface (Border can't
  receive keyboard focus; ContentControl is the smallest stock element with
  IsTabStop + KeyDown). Captures key events while IsRecording, queries
  modifier state via Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread.
  VirtualKey enum values match Win32 VK codes 1:1, so persistence carries
  the integer through unchanged. ESC alone cancels; pure modifier keys
  swallow the event and wait for a real combination.

CaptureImage.UI/Controls/ToastHost.xaml(.cs):
- WinUI 3 UserControl. Drops v1.2's custom ItemsSource StyledProperty —
  inherits MainWindowVM context from the host root Grid and binds the
  inner ItemsControl directly to {Binding Toasts}. Cleaner, sufficient
  for v1.3's single host site.

CaptureImage.UI/Converters/ToastKindToBrushConverter.cs:
- Recreate the v1.2 converter against Microsoft.UI.Xaml.Media.SolidColorBrush.
  Same accent colors as v1.2 (Tailwind sky-500/green-500/amber-500/red-500).

CaptureImage.UI/Services/TrayIconHost.cs (new, replaces StubTrayIconHost):
- H.NotifyIcon.WinUI's TaskbarIcon backed by a MenuFlyout context menu.
  Show / Open Folder / Exit items, each rebuilt on culture change.
- close-to-tray: AppWindow.Closing intercept (Window.Closed has no Cancel
  hook in WinUI 3). Cancel + AppWindow.Hide() when MinimizeToTray is on.
- Show from tray: AppWindow.Show + Window.Activate.
- Quit: Application.Current.Exit.
- Icon: SkiaSharp PNG draw is preserved + exercised, but TaskbarIcon.IconSource
  isn't set yet — H.NotifyIcon's IconSource pipeline ends in
  System.Drawing.Icon which only accepts .ico file streams; real .ico round-
  trip via HICON needs P/Invoke cleanup that's out of scope for M6. OS
  default glyph in the meantime; M7 polish ships the real .ico.

CaptureImage.UI/Services/PreviewPresenter.cs (new, replaces StubPreviewPresenter):
- Encodes the captured frame to PNG bytes (port of v1.2 SkiaSharp pixel-
  install path), opens a non-modal PreviewWindow on the UI thread, awaits
  PreviewWindow.ResultAsync. Disposes the per-call PreviewViewModel after
  the window closes so the singleton localization service doesn't leak
  PropertyChanged subscribers.

CaptureImage.UI/Views/PreviewWindow.xaml(.cs) (new):
- 720x560 modal-style child window with Mica backdrop + extended title
  bar. Save / Discard buttons + X-to-close all resolve ResultAsync to the
  appropriate bool. FlowDirection bound via the App.xaml-scoped converter.

CompositionRoot.cs:
- Swap StubTrayIconHost -> TrayIconHost, StubPreviewPresenter -> PreviewPresenter.
- Drop the CaptureImage.UI.Services.Stubs using.

MainWindow.xaml:
- Add xmlns:controls. Embed <controls:ToastHost/> as the last overlay child
  of the root Grid (anchored bottom-right, RTL mirrors to bottom-left).

SettingsPage.xaml:
- Replace the M4 placeholder TextBox in the Hotkey section with the real
  <controls:HotkeyRecorder DataContext="{Binding Hotkey}" />.

Removed: src/CaptureImage.UI/Services/Stubs/{StubTrayIconHost,StubPreviewPresenter}.cs
— no longer referenced after the swap.

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 156/156 pass.
- Smoke run: tray initialized + visible, no exceptions on boot, all 4
  Pages still resolve, log shows full happy path through OnLaunched.
  Interactive verification of tray menu / hotkey capture / preview modal /
  toasts is left to the user — animations + window activation only show
  on a real display.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:16:03 +07:00
poli0981andClaude Opus 4.7 d0ebf6548d feat(v1.3-M5): port LogViewer + Composition-API animated drawer
Fifth milestone of v1.3. Port the slide-in log drawer that PaneFooter's
button toggles. Animation re-implementation uses the WinUI 3 Composition
API (ElementCompositionPreview + Visual.StartAnimation) instead of the
v1.2 Avalonia Style + Transitions pattern.

LogEntry (Core/Models):
- Add TimestampText computed property formatting Timestamp as
  "HH:mm:ss.fff" (InvariantCulture). WinUI 3 {Binding} doesn't honour
  StringFormat the way Avalonia/WPF do; baking the format into the model
  keeps view XAML free of one-off converters.

LogViewerView (UI/Views/, new):
- UserControl, presentation-only — animation is the host MainWindow's job
  so this stays composable + future overlays can reuse the pattern.
- Border with chrome background (LayerFillColorAltBrush), top-left rounded
  corner only (matches v1.2's right-anchored drawer aesthetic).
- Header: Title + filter label + level ComboBox + Pause/Clear/Reveal
  buttons + EventsCountText.
- Body: ScrollViewer + ItemsControl with 4-col DataTemplate (Timestamp,
  Level, FileLineText, Message) all in monospace; empty-state TextBlock
  overlays via converters.

MainWindow.xaml:
- LogViewerView added as the last child of the root Grid (overlays the
  NavigationView). Width=480, HorizontalAlignment=Right, DataContext bound
  to MainWindowVM.LogViewer. Stays in the visual tree always — never
  toggle Visibility, only Opacity + Offset, so Composition has something
  to animate every time.
- xmlns:views added.

MainWindow.xaml.cs:
- Hook Root.Loaded to push the drawer to its initial collapsed state via
  Composition: Offset.X = +48 (or -48 under RTL), Opacity = 0,
  IsHitTestVisible = false.
- Subscribe to vm.PropertyChanged in SetViewModel; when IsLogViewerVisible
  flips, fire AnimateDrawer with target offset/opacity.
- AnimateDrawer uses CubicBezier(0.4, 0, 0.2, 1) easing (Material/Fluent
  decelerate) which is visually indistinguishable from v1.2's
  CircularEaseOut for sub-300ms motion. SlideDuration=220ms,
  FadeDuration=180ms — same numbers as v1.2-M7.
- GetCollapsedOffsetX() reads Root.FlowDirection so the drawer slides
  toward the correct edge under RTL (M7 will smoke-test ar-SA).

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 156/156 pass — same baseline; LogEntry property addition
  is purely additive and doesn't break any existing test.
- Smoke run: app boots cleanly; OnRootLoaded fires (drawer collapses
  silently), no exception. Interactive verification of the actual slide
  animation is left to the user — Composition smoothness only shows on a
  real display.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:58:02 +07:00
poli0981andClaude Opus 4.7 c477dfe144 feat(v1.3-M4): port Dashboard, Update, Settings, About to WinUI 3 Pages
Fourth milestone of v1.3. Replace the M3 placeholder Pages with the four
real views, ported one-for-one from the v1.2 Avalonia UserControls but
re-authored against WinUI 3 Page semantics + Fluent 2 brushes + the
design tokens established in M2.

New converters (UI/Converters/):
- BytesToBitmapConverter: byte[] -> BitmapImage via MemoryStream.AsRandomAccessStream.
  Used by DashboardPage's per-target icon column.
- BoolToVisibilityConverter / InvertedBoolToVisibilityConverter: replace
  Avalonia's IsVisible="{Binding X}" / "{Binding !X}" patterns.
- NotNullToVisibilityConverter: replaces Avalonia's
  ObjectConverters.IsNotNull check (used on UpdatePage AvailableVersion).

App.xaml registers all 4 converters at Application.Resources scope (per
feedback_winui3_resource_scope.md — local Page.Resources hits forward-
reference issues).

MainWindow.xaml.cs:
- ContentFrame.Navigate(pageType, App.Services) — passes the DI provider as
  the navigation parameter so each Page can resolve its own VM in
  OnNavigatedTo without taking a project reference back to CaptureImage.App.
  CaptureImage.UI does not depend on CaptureImage.App; this keeps the
  layering clean.

Per-page code-behind pattern (all 4 Pages):
- Empty constructor (just InitializeComponent).
- Override OnNavigatedTo, cast e.Parameter to IServiceProvider, resolve the
  VM, set DataContext.

DashboardPage.xaml:
- Header (Title + Subtitle + Refresh/Arm/Disarm buttons with visibility
  driven by IsArmed). Arm uses AccentButtonStyle.
- Targets ListView with per-target template (icon via BytesToBitmap, name
  + process name stack, Steam pill badge with #FF6B35 fill).
- Empty-state TextBlock overlays when HasNoTargets.
- Status indicator: 3 stacked Border dots (gray idle / green armed /
  orange capturing) with Visibility converters; StatusMessage to the right.
- Footer: TargetsCountText + LoadingText.

UpdatePage.xaml:
- Header (Title + CurrentVersion run).
- Available-version Border (NotNullToVisibility on AvailableVersion) with
  release notes.
- Three buttons (Check/Download/Install) — Download/Install use
  AccentButtonStyle.
- ProgressBar + status line (BoolToVisibility on IsBusy).
- Log-lines ItemsControl in a bordered ScrollViewer, monospace font.

SettingsPage.xaml:
- 18 form fields binding to the existing computed-property labels on
  SettingsViewModel (TitleLabel, LanguageLabel, …, LogLevelHint).
- Language ComboBox (CultureInfo.DisplayName).
- Hotkey is a read-only TextBox showing Hotkey.DisplayText with a
  PlaceholderText pointing at v1.3-M6 — the real HotkeyRecorder control
  lands then.
- Format ComboBox, paired JPEG/WebP quality sliders side-by-side, output
  folder TextBox + Browse, file-name template (mono font), 3 toggles,
  log-level picker + hint, Import/Export/OpenFile buttons,
  SettingsFilePath display.

AboutPage.xaml:
- Header (Title + Tagline).
- Metadata card (5 rows: AppName, AppVersion, License, Developer,
  RepositoryUrl as HyperlinkButton).
- AI assistance disclosure.
- 3 disclaimers (Translation / CaptureLimitation / Liability).
- 6 legal-doc buttons in a horizontal StackPanel (no WrapPanel in WinUI 3
  by default; 6 buttons fit at 1200 px — M7 polish if needed).
- Third-party items list inside a bordered ItemsControl.

Avalonia -> WinUI 3 mapping notes:
- IsVisible="{Binding X}" -> Visibility="{Binding X, Converter=...}"
- TextBox Watermark -> PlaceholderText
- Classes="accent" -> Style="{StaticResource AccentButtonStyle}"
- ListBox -> ListView
- ToolTip.Tip -> ToolTipService.ToolTip
- DynamicResource SystemControlBackgroundChromeMediumLowBrush ->
  ThemeResource CardBackgroundFillColorDefaultBrush (Fluent 2 naming)

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 156/156 pass — same baseline.
- Smoke run: app boots, DashboardPage's OnNavigatedTo fires before
  Activate() (WMI watcher + Steam scan logs land at the right moment),
  user navigates through Update / Settings / About — each Page's
  OnNavigatedTo resolves its VM and sets DataContext; "Navigated to X"
  lines from NavigationService confirm the dual-flow (NavigationView
  routes Frame, MainWindowVM independently routes via NavigationService).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:45:14 +07:00
poli0981andClaude Opus 4.7 a85dfa8ec0 feat(v1.3-M3): MainWindow shell — NavigationView + Frame + FlowDirection
Third milestone of v1.3. Replace the M2 placeholder content with the real
shell: NavigationView nav rail (220 px open), data-bound MenuItems from
MainWindowViewModel.NavItems, Fluent FontIcon glyphs, log-toggle button in
PaneFooter, and a Frame content host that routes through 4 placeholder
Pages. RTL FlowDirection is wired through the existing FlowDirectionConverter.

App.xaml:
- Move FlowDirectionConverter to Application.Resources scope. Local
  Grid.Resources hits a forward-reference issue because the Grid evaluates
  its FlowDirection property before the inner Resources element is
  processed — Application.Resources is always available first.

MainWindow.xaml:
- Root Grid bound to FlowDirection via {StaticResource FlowDirectionConverter}.
- NavigationView with PaneDisplayMode=Left, OpenPaneLength=220, MenuItems
  data-bound (BindingMode=TwoWay on SelectedItem), back button + Settings
  hidden (we have our own Settings nav item, no back nav semantic).
- PaneHeader: AppTitle + AppVersion using design tokens from M2.
- MenuItemTemplate: NavigationViewItem with FontIcon (Segoe Fluent Icons)
  + bound Label / IconGlyph.
- PaneFooter: log-toggle button bound to ToggleLogViewerCommand. Drawer
  itself lands in M5; the button just fires the command.
- ContentFrame fills the rest. Pages live in CaptureImage.UI.Views.

MainWindow.xaml.cs:
- New SetViewModel(vm) public method called from App.OnLaunched. Window has
  no DataContext property in WinUI 3 — content elements (the root Grid)
  carry it instead.
- SelectionChanged handler maps NavItemViewModel.Key -> Page Type and
  navigates the Frame. Initial nav is fired from SetViewModel so the Frame
  isn't blank when the window first shows.

App.xaml.cs OnLaunched:
- Resolve MainWindowViewModel from DI, hand to SetViewModel(vm) before
  Activate(). Tray init unchanged.

CaptureImage.UI/Views/{Dashboard,Update,Settings,About}Page (new):
- Minimal placeholder Pages with a centered TextBlock. M4 swaps the content
  + wires the existing per-tab ViewModels via DataContext.

Verification:
- dotnet build: 0 errors, 0 warnings.
- dotnet test: 156/156 pass — same baseline.
- Smoke run: log records full path through DI -> initial NavigateToNavItem
  -> Frame.Navigate(DashboardPage) -> WMI/Steam scan kicks off (DashboardVM
  resolved) -> tray stub -> user clicks all 4 nav items -> Velopack +
  SettingsVM + AboutVM all resolve, "Navigated to X" lines fire for each.
  No XamlParseException.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:30:34 +07:00
poli0981andClaude Opus 4.7 241bad20be feat(v1.3-M2): Fluent 2 theme baseline — Mica backdrop + design tokens
Second milestone of v1.3. Move the placeholder shell onto the Win11 native
look-and-feel: Mica backdrop, Segoe UI Variable, integrated title bar, and
the design-token resource set the rest of the v1.3 ports will reuse.

App.xaml:
- Add design-token resources to Application.Resources, mirroring the v1.2
  Avalonia comment block (4/8/12/16/24 spacing, 4/8 corner radius, 11/12/13/
  14/16/22 font sizes). Drop Inter; Fluent 2's Segoe UI Variable Display is
  the explicit BodyFontFamily — keeps the look native to Win11.
- Keep XamlControlsResources merged dict from M1.

MainWindow.xaml.cs:
- SystemBackdrop = MicaBackdrop { Kind = MicaKind.Base } — picks up the
  Win11 desktop wallpaper tint, falls back gracefully on RDP / Win10 builds.
- ExtendsContentIntoTitleBar = true for the Fluent 2 borderless look.
- AppWindow.Resize(1200x720) carries over the v1.2-M7 dimensions; DPI-aware
  refinement is M3's job when the real shell lands.

MainWindow.xaml:
- Root Grid intentionally has no Background so MicaBackdrop shines through.
- Placeholder text uses the new resource keys (BodyFontFamily, FontSizeTitle,
  SpacingSmall) so the design tokens get exercised end-to-end.
- Secondary text uses ThemeResource TextFillColorSecondaryBrush — keeps WCAG
  AA contrast on both light and dark variants without hardcoded opacity.

Verification:
- dotnet build: 0 errors, 0 warnings.
- Smoke run: app launches, log records full happy path through App.OnLaunched
  + MainWindow init (Mica/AppWindow/title bar APIs all succeed without
  exception). Visible verification of Mica blur is left to the user.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:22:16 +07:00
poli0981andClaude Opus 4.7 310708483e feat(v1.3-M1): bootstrap WinUI 3 app shell, gut Avalonia from UI/App
First milestone of the v1.3 cycle: replace the Avalonia 11 UI stack with
WinUI 3 (Windows App SDK 1.8.x, self-contained x64). Logic layers
(Core, Infrastructure, ViewModels) untouched — they survive the swap as
designed.

Removed (Avalonia):
- Directory.Packages.props: 5 Avalonia.* package versions
- App.csproj + UI.csproj: all Avalonia.* PackageReferences
- 25 source files: App.axaml(.cs), 7 view .axaml(.cs), 2 control
  .axaml(.cs), AvaloniaUIDispatcher, AvaloniaTrayIconHost,
  AvaloniaPreviewPresenter, BytesToBitmapConverter, ToastKindToBrushConverter
- UI.csproj TFM: net9.0 -> net9.0-windows10.0.22621.0
- UI.Tests TFM: net9.0 -> net9.0-windows10.0.22621.0

Added (WinUI 3):
- Directory.Packages.props: Microsoft.WindowsAppSDK family + WinUI subpkg
- App.csproj: <UseWinUI>true</UseWinUI>, <WindowsPackageType>None</WindowsPackageType>,
  <WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>,
  <Platforms>x64</Platforms>, <RuntimeIdentifier>win-x64</RuntimeIdentifier>,
  DISABLE_XAML_GENERATED_MAIN define
- App.xaml + App.xaml.cs in App project (was in UI project before — moved to
  follow WinUI 3 idiom). App.OnLaunched binds the WinUI dispatcher and
  shows MainWindow.
- MainWindow.xaml + .cs (placeholder TextBlock; M3 ports the real shell).
- WinUIThreadDispatcher: IUIThreadDispatcher impl wrapping
  Microsoft.UI.Dispatching.DispatcherQueue. Bound from App.OnLaunched.
- StubTrayIconHost + StubPreviewPresenter: keep DI happy until M6 wires the
  real H.NotifyIcon.WindowsAppSDK + WinUI 3 modal implementations.
- FlowDirectionConverter rewritten against Microsoft.UI.Xaml.

Modified:
- Program.cs: Velopack init + logging + settings + culture untouched. Only
  the lifetime call swaps from BuildAvaloniaApp().StartWithClassicDesktopLifetime
  to Microsoft.UI.Xaml.Application.Start(...) with an explicit
  DispatcherQueueSynchronizationContext.
- CompositionRoot: register WinUIThreadDispatcher (concrete + interface),
  StubTrayIconHost, StubPreviewPresenter.
- ToastService: drop now-unused using Avalonia.Threading.

Verification:
- dotnet build: 0 errors, 0 warnings on full solution.
- dotnet test: 156/156 pass (Core 62, Infra 60, VM 22, UI 12) — same as v1.2 baseline.
- Smoke run: app launches, log records full happy path through
  App.OnLaunched, tray stub initializes (proves MainWindow.Activate() ran).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:17:11 +07:00
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
poli0981 0f7985a644 Merge pull request #11 from poli0981/chore/v1.1.0-release
chore(release): bump to v1.1.0
2026-04-20 19:52:05 +07:00
poli0981andClaude Opus 4.7 5f19835ce6 chore(release): bump to v1.1.0
Version bump for the v1.1.0 release cut:

- CaptureImage.App.csproj <Version> 1.1.0-dev → 1.1.0. release.yml still
  overrides via /p:Version=<git-tag> for tag-driven builds; this change
  only affects local `dotnet run` + `dotnet publish` invocations.
- CHANGELOG.md restructured per Keep a Changelog convention:
    • [Unreleased] placeholder for future work (empty)
    • [1.1.0] - 2026-04-20 with M1 (hotkey rebinder + conflict sniff),
      M2 (dependabot + Node 24 runners), M3 (architecture docs +
      dogfood screenshots), M4 (UI/UX polish) entries
    • [1.0.0] - 2026-04-16 (retroactive header; the existing
      Unreleased block was actually the v1.0.0 content)

Ship-ready: dotnet build -c Release 0/0, dotnet test -c Release 107
pass on net9.0 + net9.0-windows10.0.22621.0. Tag v1.1.0 follows this
commit — release workflow auto-packages Velopack Setup.exe + .nupkg +
SHA256SUMS.txt to a GitHub Release.

Closes v1.1-M5. Concludes the v1.1 cycle.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 19:49:31 +07:00
poli0981 16dcfb71dc Merge pull request #10 from poli0981/feat/v1.1-m4-polish
feat(v1.1-m4): UI/UX polish — live-localization fixes + 2025 modernization
2026-04-20 11:28:10 +07:00
poli0981andClaude Opus 4.7 5f5e878e0b feat(v1.1-m4): UI/UX polish — live-localization fixes + 2025 modernization
Part A — 7 live-localization / refresh bugs (user-flagged + audit-found):

- Dashboard title, subtitle, Refresh / Arm / Disarm buttons, target count
  line, and loading hint were all hardcoded English; now bound through
  `{Binding Localization[Dashboard_*]}` so they track the culture switch.
- `DashboardViewModel` expands its culture listener to refresh every
  computed string (TargetsCountText, LoadingText, EmptyStateText). The
  new `TargetsCountText` property formats via `Dashboard_TargetsCount`
  so the "N target(s) visible" line picks up plural wording per culture.
- `GameTargetViewModel.SteamBadgeTooltip` was a hardcoded mixed
  English/Vietnamese string; now reads through `ILocalizationService`,
  subscribes to `PropertyChanged`, and formats via
  `Dashboard_SteamBadgeTooltip` (keys {0}=app name, {1}=app id). The
  VM is now IDisposable, and the dashboard disposes rows on reconcile
  so the live listener doesn't pin dead targets.
- LogViewer Pause/Resume button was pinned to `Localization[Log_Pause]`
  and didn't flip on state change. Added `TogglePauseLabel` computed
  property that switches between `Log_Pause` / `Log_Resume` on
  IsPaused, plus a culture listener that also refreshes the events
  count and empty-state text.
- `HotkeyBindingViewModel.ErrorMessage` is an indexer-backed computed
  property; added a culture listener that raises PropertyChanged so
  the Settings error text re-localizes live.
- MainWindow hardcoded `"CaptureImage"` + `"v0.1.0 — M3 UX polish"`
  (stale!) in the nav-rail header. `MainWindowViewModel` now exposes
  `AppTitle` + `AppVersion` (pulled from
  `AssemblyInformationalVersion` / assembly metadata). App.csproj adds
  `<Version>1.1.0-dev</Version>` so dev builds render meaningfully;
  release.yml still overrides via `/p:Version=<git-tag>`.

Part B — 2025/26 visual-system modernization:

- App.axaml grows a small style sheet: global Inter font stack for
  TextBlock / TextBox / Button / ComboBox / CheckBox (Avalonia.Fonts.Inter
  was in the package graph but never referenced); a keyboard focus ring
  on ListBoxItem via :focus-visible + accent brush + 2 px border; plus
  a header comment documenting the visual conventions (fonts, radii,
  spacing, contrast) for future contributors.
- Corner-radius unified to 8 px on cards/borders (Dashboard list,
  status card, About metadata card + third-party card, Update cards,
  Preview image, LogViewer drawer, Toast). 4 px kept only on the inline
  Steam badge pill per the design contract.
- Secondary text sweep: every `Opacity="0.4"`-`"0.7"` on labels and
  hints swapped for `Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"`
  so contrast meets WCAG AA on both light and dark theme variants.
- HotkeyRecorder BindingField grows a `:focus` selector that flips
  the border to accent colour so "waiting for your key" is visually
  obvious; also gains `AutomationProperties.Name` + HelpText for
  screen readers.
- MainWindow log-drawer toggle button gets `AutomationProperties.Name`
  + tooltip via a new `Dashboard_LogToggle` key (EN/VI/AR).
- Dashboard status card gets `AutomationProperties.Name` bound to
  `StatusMessage` so narrators read the current capture state.
- Empty states added: Dashboard ("No visible windows to capture —
  launch your game or app, then click Refresh.") and LogViewer ("No
  log events yet..."). New keys `Dashboard_EmptyState` + `Log_EmptyState`
  + `Log_EventsCount` in all three .resx files.
- FontSize outliers snapped to the 11/12/13/14/16/22 scale (page titles
  24→22, preview dialog 20→22, Steam badge 10→11, nav icon 18→16).

Scope out:
- Mica window effect (needs Win11 composition hooks, not stock Avalonia).
- Dark-mode theme picker (Fluent honours OS setting already).
- 44×44 touch-target resize (desktop app; 32 is sufficient here).

Verification: `dotnet build -c Release` 0/0; `dotnet test -c Release`
107 pass. Manual culture-switch smoke on dev machine confirmed every
fixed surface re-localizes live — Dashboard title/subtitle/buttons,
target count, Steam badge tooltip, LogViewer title + Pause/Resume
label, Hotkey error text, nav labels, tray menu, MainWindow header —
and the RTL mirror still behaves under `ar-SA`.

Closes v1.1-M4. Next: v1.1-M5 release cut.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 11:24:30 +07:00
poli0981 a44b65d86c Merge pull request #9 from poli0981/feat/v1.1-m3-docs
docs(v1.1-m3): architecture tour + dogfood screenshots
2026-04-19 23:44:17 +07:00
poli0981andClaude Opus 4.7 8e374a024e docs(v1.1-m3): architecture tour + dogfood screenshots
Add docs/ARCHITECTURE.md as the one-page-per-layer reference for
contributors, auditors, and future maintainers. Five Mermaid diagrams
that GitHub renders inline:

- Layer rules (Core → ViewModels → UI; Infrastructure → Core; App =
  composition root)
- Capture state machine (stateDiagram-v2) pulled from
  CaptureStateMachine.Configure()
- WGC capture pipeline sequence (sequenceDiagram) matching
  WindowsGraphicsCaptureEngine.CaptureAsync step-for-step
- DI composition sketch (graph LR) matching CompositionRoot.BuildServices
- i18n + RTL flow (sequenceDiagram) — culture switch → "Item[]" refresh
- Velopack update flow (sequenceDiagram) — check / download / install

README changes:

- Screenshots section now shows six real app screenshots in a 2×3 table
  (dashboard / settings / about / update / logviewer / rtl-dashboard).
  Dashboard, Settings, About and RTL were dogfooded via CaptureImage
  itself; Update and LogViewer were snipped because they render on top
  of the capture surface. Replaces the "coming with the first tagged
  release" placeholder.
- New Architecture section that links to docs/ARCHITECTURE.md.

Screenshots land under docs/screenshots/ (~540 KB for six PNGs).

Closes v1.1-M3.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:40:27 +07:00
poli0981 cb3ec44693 Merge pull request #7 from poli0981/feat/v1.1-m2-dependabot
chore(v1.1-m2): bump GH Actions + test tooling, Node 24 runners
2026-04-19 23:25:20 +07:00
poli0981andClaude Opus 4.7 d5706f2dee chore(v1.1-m2): bump GH Actions + test tooling, Node 24 runners
Close out dependabot backlog ahead of the Node 20 deprecation deadline
(2026-09-16) by landing every open version bump in a single, reviewed
change rather than five separate PRs.

Workflow action bumps (all Node 20 → Node 24 runtime updates; no API
changes, windows-latest already supports the newer runner):

- actions/checkout            4 → 6   (ci.yml, release.yml)
- actions/setup-dotnet        4 → 5   (ci.yml, release.yml)
- actions/upload-artifact     4 → 7   (ci.yml, release.yml)
- softprops/action-gh-release 2 → 3   (release.yml)

Release.yml audit: upload-artifact v5/v6/v7 kept the `name`, `path`,
`retention-days` surface intact — the `overwrite` default did NOT flip
as the v1.1 plan had speculated, the only v7 addition is an optional
`archive: false` flag for direct file uploads. No yaml option changes
needed.

Test tooling (dependabot #5):

- xunit                       2.9.2 → 2.9.3   (patch)
- coverlet.collector          6.0.2 → 8.0.1   (major — now requires .NET 8 LTS floor, we target net9.0)

Verification: restore, build (0/0), 107 tests pass on net9.0 +
net9.0-windows10.0.22621.0.

Closes v1.1-M2. Supersedes dependabot PRs #1 #2 #3 #4 #5.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:21:19 +07:00
poli0981 64164b4690 Merge pull request #6 from poli0981/feat/v1.1-m1-hotkey
feat(v1.1-m1): hotkey rebinder + conflict sniff
2026-04-19 23:09:16 +07:00
poli0981andClaude Opus 4.7 0482f718cb feat(v1.1-m1): hotkey rebinder + conflict sniff
Settings → Hotkey previously showed a hardcoded "Ctrl+Shift+F12" placeholder.
This milestone lands the full rebinder UX:

- HotkeyRecorder Avalonia control listens for key combos (Esc cancels)
- HotkeyBindingViewModel bridges the recorder to persistence and calls
  IHotkeyService.SetBinding live so an armed capture picks up the new
  combo without disarm/re-arm
- ReservedHotkeys catalogues Windows shell combos (Win+L, Alt+Tab,
  Ctrl+Shift+Esc, …); HotkeyBinding.Validate() rejects those plus
  modifier-only / naked-letter bindings before persistence
- HotkeyConflictSniffer does a RegisterHotKey/UnregisterHotKey probe on
  HWND=NULL so a binding already claimed by another process surfaces as
  a non-blocking warning — the user still saves it so they keep control
- i18n strings added to EN / VI / AR for every recorder surface

Tests: +24 Core validation (ReservedHotkeys + HotkeyBinding.Validate),
+12 ViewModel flow via NSubstitute fakes. Total 107 pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:07:47 +07:00
203 changed files with 12385 additions and 1717 deletions

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
# Wires the "Sponsor" button on the repo header to the maintainer's
# funding destinations. GitHub renders one button per non-empty entry.
#
# Email + PayPal intentionally omitted — see commit log for v1.5.1 and
# the v1.5.1 hotfix plan: public handles only, no personal identifiers.
github: [poli0981]
ko_fi: skullmute
buy_me_a_coffee: skullmute
patreon: skullmute
+658
View File
@@ -0,0 +1,658 @@
"""
Discord webhook notification helper — phase 2.
Extends phase 1 with four new commands:
python discord_notify.py release # phase 1: release announcement
python discord_notify.py failure # phase 1: generic CI failure
python discord_notify.py deploy # phase 2: deploy success/fail
python discord_notify.py release-build # phase 2: release pipeline build status
python discord_notify.py dependabot-summary # phase 2: org-wide dependabot digest
python discord_notify.py weekly-digest # phase 2: org-wide weekly activity
Stdlib-only. Drop into .github/scripts/ in any repo.
"""
from __future__ import annotations
import json
import os
import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# ---------- Embed colors ----------
COLOR_RELEASE = 0x57F287 # green
COLOR_FAILURE = 0xED4245 # red
COLOR_PRERELEASE = 0xFEE75C # yellow
COLOR_DEPLOY_OK = 0x3BA55D # darker green (distinct from release)
COLOR_DEPLOY_FAIL = 0xE74C3C # darker red
COLOR_BUILD_OK = 0x5865F2 # blurple — neutral build success
COLOR_BUILD_FAIL = 0xED4245
COLOR_DEPENDABOT = 0xFAA61A # orange
COLOR_DIGEST = 0x9B59B6 # purple
# ---------- Truncation limits ----------
MAX_NOTES_CHARS = 1500
MAX_FIELD_VALUE = 1000
MAX_ASSETS_LISTED = 5
MAX_DIGEST_REPOS_PER_FIELD = 8
# ---------- Helpers ----------
def _post_webhook(url: str, payload: dict) -> bool:
"""POST a JSON payload to a Discord webhook. Returns True on 2xx."""
if not url:
print("[SKIP] No webhook URL provided.")
return False
url = url.replace("https://discordapp.com/", "https://discord.com/")
if "/webhooks/" in url and "/api/webhooks/" not in url:
url = url.replace("/webhooks/", "/api/webhooks/")
url = url.rstrip("/")
body = json.dumps(payload).encode("utf-8")
req = Request(
url,
data=body,
headers={
"Content-Type": "application/json",
"User-Agent": "poli0981-cicd/2.0 (+https://github.com/poli0981)",
},
)
try:
with urlopen(req, timeout=30) as resp:
print(f"[OK] Discord webhook posted (HTTP {resp.status}).")
return True
except HTTPError as e:
body_text = e.read().decode("utf-8", errors="replace")
print(f"[ERROR] Discord webhook: {e.code} — {body_text}")
return False
except URLError as e:
print(f"[ERROR] Discord webhook: {e}")
return False
def _gh_api(path: str, token: str, method: str = "GET", params: dict | None = None) -> dict | list:
"""Call GitHub REST API. Returns parsed JSON."""
base = "https://api.github.com"
url = f"{base}{path}"
if params:
url += "?" + urlencode(params)
req = Request(
url,
method=method,
headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "poli0981-cicd/2.0",
},
)
try:
with urlopen(req, timeout=30) as resp:
return json.loads(resp.read())
except HTTPError as e:
print(f"[ERROR] GitHub API {method} {path}: {e.code} — {e.read().decode('utf-8', errors='replace')}")
raise
except URLError as e:
print(f"[ERROR] GitHub API {method} {path}: {e}")
raise
def _gh_search(query: str, token: str, kind: str = "issues") -> list:
"""Run a GitHub search. Returns the items list (paginated, capped at 100)."""
result = _gh_api(f"/search/{kind}", token, params={"q": query, "per_page": 100})
if isinstance(result, dict):
return result.get("items", [])
return []
def _truncate(text: str, limit: int, suffix: str = "…") -> str:
if not text or len(text) <= limit:
return text or ""
cut = text[: limit - len(suffix)]
last_break = max(cut.rfind("\n"), cut.rfind(". "))
if last_break > limit * 0.6:
cut = cut[:last_break]
return cut.rstrip() + suffix
def _env(name: str, default: str = "") -> str:
return os.environ.get(name, default).strip()
def _required(name: str) -> str:
v = _env(name)
if not v:
print(f"[ERROR] Required env var not set: {name}")
sys.exit(1)
return v
# ---------- Phase 1: Release announcement ----------
def build_release_embed() -> dict:
repo = _required("GITHUB_REPOSITORY")
repo_name = repo.split("/", 1)[1]
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
tag = _required("RELEASE_TAG")
name = _env("RELEASE_NAME") or tag
body = _env("RELEASE_BODY")
html_url = _env("RELEASE_URL") or f"{server_url}/{repo}/releases/tag/{tag}"
is_prerelease = _env("RELEASE_PRERELEASE", "false").lower() == "true"
assets_raw = _env("RELEASE_ASSETS_JSON", "[]")
try:
assets = json.loads(assets_raw) if assets_raw else []
except json.JSONDecodeError:
assets = []
color = COLOR_PRERELEASE if is_prerelease else COLOR_RELEASE
badge = " (pre-release)" if is_prerelease else ""
description = _truncate(body, MAX_NOTES_CHARS) if body else "*No release notes provided.*"
fields = []
if assets:
priority_order = (".msi", ".exe", ".dmg", ".AppImage", ".deb", ".rpm", ".zip")
def asset_priority(a: dict) -> int:
n = a.get("name", "").lower()
for i, ext in enumerate(priority_order):
if n.endswith(ext.lower()):
return i
return len(priority_order)
sorted_assets = sorted(assets, key=asset_priority)[:MAX_ASSETS_LISTED]
asset_lines = []
for a in sorted_assets:
n = a.get("name", "asset")
u = a.get("browser_download_url") or a.get("url", "")
size_mb = a.get("size", 0) / (1024 * 1024) if a.get("size") else 0
size_str = f" ({size_mb:.1f} MB)" if size_mb > 0.1 else ""
asset_lines.append(f"• [{n}]({u}){size_str}")
if len(assets) > MAX_ASSETS_LISTED:
asset_lines.append(f"• … +{len(assets) - MAX_ASSETS_LISTED} more on the release page")
fields.append({
"name": "📥 Downloads",
"value": _truncate("\n".join(asset_lines), MAX_FIELD_VALUE),
"inline": False,
})
embed = {
"title": f"🚀 {repo_name} {tag}{badge}",
"url": html_url,
"description": description,
"color": color,
"fields": fields,
"footer": {"text": f"{repo} • {name}" if name != tag else repo},
"timestamp": _env("RELEASE_PUBLISHED_AT") or None,
}
return {k: v for k, v in embed.items() if v}
def post_release() -> int:
embed = build_release_embed()
repo = _required("GITHUB_REPOSITORY")
tag = _required("RELEASE_TAG")
webhooks = [w.strip() for w in _required("DISCORD_WEBHOOKS").split(",") if w.strip()]
payload = {"username": "Release Bot", "embeds": [embed]}
if _env("DISCORD_CONTENT"):
payload["content"] = _env("DISCORD_CONTENT")
print(f"[INFO] Announcing {repo}@{tag} to {len(webhooks)} webhook(s).")
failures = sum(1 for url in webhooks if not _post_webhook(url, payload))
if failures == len(webhooks):
return 1
return 0
# ---------- Phase 1: Generic CI failure ----------
def build_failure_embed() -> dict:
repo = _required("GITHUB_REPOSITORY")
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
workflow_name = _env("WORKFLOW_NAME", "Unknown workflow")
run_id = _required("RUN_ID")
run_number = _env("RUN_NUMBER", "?")
run_attempt = _env("RUN_ATTEMPT", "1")
branch = _env("BRANCH", "")
commit_sha = _env("COMMIT_SHA", "")
commit_short = commit_sha[:7] if commit_sha else "?"
commit_msg = _env("COMMIT_MESSAGE", "").splitlines()[0] if _env("COMMIT_MESSAGE") else ""
actor = _env("ACTOR", "")
event = _env("EVENT_NAME", "")
run_url = f"{server_url}/{repo}/actions/runs/{run_id}"
commit_url = f"{server_url}/{repo}/commit/{commit_sha}" if commit_sha else None
fields = [{"name": "Workflow", "value": f"`{workflow_name}` (run #{run_number}, attempt {run_attempt})", "inline": False}]
if branch:
fields.append({"name": "Branch", "value": f"`{branch}`", "inline": True})
if event:
fields.append({"name": "Trigger", "value": f"`{event}`", "inline": True})
if actor:
fields.append({"name": "Actor", "value": f"@{actor}", "inline": True})
if commit_sha:
commit_line = f"[`{commit_short}`]({commit_url})"
if commit_msg:
commit_line += f" — {_truncate(commit_msg, 100)}"
fields.append({"name": "Commit", "value": commit_line, "inline": False})
return {
"title": f"❌ CI failed: {repo}",
"url": run_url,
"description": f"**[View run logs →]({run_url})**",
"color": COLOR_FAILURE,
"fields": fields,
"footer": {"text": repo},
}
def post_failure() -> int:
embed = build_failure_embed()
webhook = _required("DISCORD_CI_WEBHOOK")
return 0 if _post_webhook(webhook, {"username": "CI Bot", "embeds": [embed]}) else 1
# ---------- Phase 2: Deploy alert ----------
def post_deploy() -> int:
"""
Post a deploy success/fail alert.
Distinct from generic CI failure: includes the deployed URL when known,
and uses 🌐 / 🚫 icons so the channel scan reads as deploys, not random builds.
Env:
DISCORD_CI_WEBHOOK — same channel as failure alerts (per user choice)
DEPLOY_STATUS — 'success' | 'failure'
DEPLOY_TARGET — e.g. 'GitHub Pages', 'Cloudflare Pages'
DEPLOY_URL — optional; live site URL when status=success
WORKFLOW_NAME, RUN_ID, BRANCH, COMMIT_SHA, COMMIT_MESSAGE, ACTOR — context
"""
repo = _required("GITHUB_REPOSITORY")
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
status = _env("DEPLOY_STATUS", "failure").lower()
target = _env("DEPLOY_TARGET", "deploy")
deploy_url = _env("DEPLOY_URL", "")
workflow_name = _env("WORKFLOW_NAME", "?")
run_id = _required("RUN_ID")
run_number = _env("RUN_NUMBER", "?")
branch = _env("BRANCH", "")
commit_sha = _env("COMMIT_SHA", "")
commit_short = commit_sha[:7] if commit_sha else "?"
commit_msg = _env("COMMIT_MESSAGE", "").splitlines()[0] if _env("COMMIT_MESSAGE") else ""
actor = _env("ACTOR", "")
run_url = f"{server_url}/{repo}/actions/runs/{run_id}"
commit_url = f"{server_url}/{repo}/commit/{commit_sha}" if commit_sha else None
if status == "success":
icon, color, verb = "🌐", COLOR_DEPLOY_OK, "deployed"
title = f"{icon} {target} deploy OK: {repo}"
else:
icon, color, verb = "🚫", COLOR_DEPLOY_FAIL, "deploy failed"
title = f"{icon} {target} deploy FAILED: {repo}"
description = f"**[View run logs →]({run_url})**"
if status == "success" and deploy_url:
description = f"**[Open live site →]({deploy_url})** • [run logs]({run_url})"
fields = [{"name": "Workflow", "value": f"`{workflow_name}` (run #{run_number})", "inline": False}]
if branch:
fields.append({"name": "Branch", "value": f"`{branch}`", "inline": True})
if actor:
fields.append({"name": "Actor", "value": f"@{actor}", "inline": True})
if commit_sha:
commit_line = f"[`{commit_short}`]({commit_url})"
if commit_msg:
commit_line += f" — {_truncate(commit_msg, 100)}"
fields.append({"name": "Commit", "value": commit_line, "inline": False})
embed = {
"title": title,
"url": run_url,
"description": description,
"color": color,
"fields": fields,
"footer": {"text": repo},
}
webhook = _required("DISCORD_CI_WEBHOOK")
return 0 if _post_webhook(webhook, {"username": "Deploy Bot", "embeds": [embed]}) else 1
# ---------- Phase 2: Release pipeline build status ----------
def post_release_build() -> int:
"""
Post a release-pipeline build status (Velopack / Tauri matrix etc.).
Both success and failure post — channel is #release-pipeline (low-volume,
only fires during release tag pushes).
Env:
DISCORD_RELEASE_PIPELINE_WEBHOOK — webhook for #release-pipeline
BUILD_STATUS — 'success' | 'failure' | 'cancelled'
BUILD_PLATFORM — e.g. 'win-x64', 'macos-14', 'ubuntu-latest'
BUILD_PACKAGER — optional; e.g. 'Velopack', 'Tauri'
RELEASE_TAG — the tag that triggered the build
WORKFLOW_NAME, RUN_ID, BRANCH, ACTOR
"""
repo = _required("GITHUB_REPOSITORY")
repo_name = repo.split("/", 1)[1]
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
status = _env("BUILD_STATUS", "failure").lower()
platform = _env("BUILD_PLATFORM", "?")
packager = _env("BUILD_PACKAGER", "")
tag = _env("RELEASE_TAG", "")
workflow_name = _env("WORKFLOW_NAME", "?")
run_id = _required("RUN_ID")
run_url = f"{server_url}/{repo}/actions/runs/{run_id}"
if status == "success":
icon, color = "✅", COLOR_BUILD_OK
verb = "OK"
elif status == "cancelled":
icon, color = "⚠️", COLOR_PRERELEASE
verb = "cancelled"
else:
icon, color = "❌", COLOR_BUILD_FAIL
verb = "FAILED"
packager_str = f" {packager}" if packager else ""
title_tag = f" {tag}" if tag else ""
title = f"{icon} {repo_name}{title_tag} —{packager_str} {platform} {verb}"
fields = [{"name": "Workflow", "value": f"`{workflow_name}`", "inline": False}]
if tag:
fields.append({"name": "Tag", "value": f"`{tag}`", "inline": True})
fields.append({"name": "Platform", "value": f"`{platform}`", "inline": True})
if packager:
fields.append({"name": "Packager", "value": packager, "inline": True})
embed = {
"title": title,
"url": run_url,
"description": f"**[View build logs →]({run_url})**",
"color": color,
"fields": fields,
"footer": {"text": repo},
}
webhook = _required("DISCORD_RELEASE_PIPELINE_WEBHOOK")
return 0 if _post_webhook(webhook, {"username": "Build Bot", "embeds": [embed]}) else 1
# ---------- Phase 2: Dependabot consolidator ----------
def _list_org_repos(owner: str, token: str) -> list[dict]:
"""List all repos owned by `owner` (user or org). Paginated, capped at 200."""
repos: list[dict] = []
for page in range(1, 3): # 100 per page × 2 pages = 200 max
# `/users/{owner}/repos` works for users; for orgs use `/orgs/{owner}/repos`.
# Try user endpoint first, fall back to org if 404.
try:
page_repos = _gh_api(f"/users/{owner}/repos", token, params={"per_page": 100, "page": page, "type": "owner"})
except HTTPError:
page_repos = _gh_api(f"/orgs/{owner}/repos", token, params={"per_page": 100, "page": page})
if not isinstance(page_repos, list) or not page_repos:
break
repos.extend(page_repos)
if len(page_repos) < 100:
break
return repos
def post_dependabot_summary() -> int:
"""
Daily Dependabot summary across all repos.
Lists open PRs authored by 'dependabot[bot]', grouped by repo. If zero PRs,
posts a quiet 'all clean' message (configurable).
Env:
DISCORD_DEPENDABOT_WEBHOOK — webhook for #dependabot
OPS_GH_TOKEN — PAT with `repo` scope (or fine-grained read across all repos)
GH_OWNER — GitHub username (e.g. 'poli0981')
QUIET_WHEN_EMPTY — 'true' to skip posting when zero PRs (default: false)
"""
webhook = _required("DISCORD_DEPENDABOT_WEBHOOK")
token = _required("OPS_GH_TOKEN")
owner = _required("GH_OWNER")
quiet_when_empty = _env("QUIET_WHEN_EMPTY", "false").lower() == "true"
# Use search API to find all open dependabot PRs across owner's repos in one call.
# Search is rate-limited at 30 req/min for authenticated users — well under that.
query = f"is:open is:pr author:app/dependabot user:{owner}"
print(f"[INFO] Searching: {query}")
items = _gh_search(query, token)
print(f"[INFO] Found {len(items)} open Dependabot PR(s).")
if not items and quiet_when_empty:
print("[INFO] No PRs and QUIET_WHEN_EMPTY=true; skipping post.")
return 0
# Group by repo
by_repo: dict[str, list[dict]] = defaultdict(list)
for item in items:
# repository_url is "https://api.github.com/repos/{owner}/{name}"
repo_url = item.get("repository_url", "")
repo_full = repo_url.rsplit("/repos/", 1)[-1] if "/repos/" in repo_url else "unknown"
by_repo[repo_full].append(item)
fields = []
for repo_full in sorted(by_repo.keys()):
prs = by_repo[repo_full]
# Sort: oldest first within a repo, so stale ones are visible
prs.sort(key=lambda p: p.get("created_at", ""))
lines = []
for pr in prs[:5]: # cap per repo to keep field under 1024
title = _truncate(pr.get("title", ""), 80)
number = pr.get("number", "?")
url = pr.get("html_url", "")
created = pr.get("created_at", "")
try:
age_days = (datetime.now(timezone.utc) - datetime.fromisoformat(created.replace("Z", "+00:00"))).days
age_str = f" ({age_days}d)" if age_days >= 1 else " (today)"
except (ValueError, AttributeError):
age_str = ""
lines.append(f"• [#{number}]({url}) {title}{age_str}")
if len(prs) > 5:
lines.append(f"• … +{len(prs) - 5} more")
fields.append({
"name": f"{repo_full} ({len(prs)})",
"value": _truncate("\n".join(lines), MAX_FIELD_VALUE),
"inline": False,
})
# Discord caps embeds at 25 fields; truncate gracefully
if len(fields) >= 24 and len(by_repo) > 24:
remaining_repos = len(by_repo) - 24
remaining_prs = sum(len(by_repo[r]) for r in sorted(by_repo.keys())[24:])
fields.append({
"name": "…and more",
"value": f"+{remaining_prs} PR(s) in {remaining_repos} other repo(s)",
"inline": False,
})
break
if items:
title = f"🤖 Dependabot: {len(items)} open PR(s) across {len(by_repo)} repo(s)"
description = "Daily summary of open dependency-update PRs."
else:
title = "🤖 Dependabot: all clean"
description = "No open dependency-update PRs across any repo. ✨"
embed = {
"title": title,
"description": description,
"color": COLOR_DEPENDABOT,
"fields": fields,
"footer": {"text": f"{owner} • daily summary"},
"timestamp": datetime.now(timezone.utc).isoformat(),
}
return 0 if _post_webhook(webhook, {"username": "Dependabot Digest", "embeds": [embed]}) else 1
# ---------- Phase 2: Weekly digest ----------
def post_weekly_digest() -> int:
"""
Weekly activity digest. Aggregates last 7 days of:
- merged PRs
- closed issues
- releases published
- commits to default branches
Posted to #announcements (configurable).
Env:
DISCORD_DIGEST_WEBHOOK — webhook for #announcements
OPS_GH_TOKEN — PAT with read access
GH_OWNER — owner username
"""
webhook = _required("DISCORD_DIGEST_WEBHOOK")
token = _required("OPS_GH_TOKEN")
owner = _required("GH_OWNER")
since = (datetime.now(timezone.utc) - timedelta(days=7)).strftime("%Y-%m-%d")
print(f"[INFO] Aggregating activity since {since} for {owner}")
# Use search for merged PRs and closed issues — fastest cross-repo aggregation
merged_prs = _gh_search(f"user:{owner} is:pr is:merged merged:>={since}", token)
closed_issues = _gh_search(f"user:{owner} is:issue is:closed closed:>={since}", token)
# Releases: list per repo via the repos endpoint, filter by published_at locally.
# GitHub search doesn't index releases, so this is unavoidable.
repos = _list_org_repos(owner, token)
releases_by_repo: dict[str, list[dict]] = defaultdict(list)
since_dt = datetime.now(timezone.utc) - timedelta(days=7)
for repo in repos:
repo_full = repo.get("full_name", "")
if repo.get("archived") or repo.get("disabled"):
continue
try:
rels = _gh_api(f"/repos/{repo_full}/releases", token, params={"per_page": 10})
if isinstance(rels, list):
for r in rels:
pub = r.get("published_at")
if not pub:
continue
try:
pub_dt = datetime.fromisoformat(pub.replace("Z", "+00:00"))
except ValueError:
continue
if pub_dt >= since_dt:
releases_by_repo[repo_full].append(r)
except HTTPError:
continue # skip repos we can't read
# Top-active repos (by PR + issue count)
repo_activity: dict[str, int] = defaultdict(int)
for pr in merged_prs:
repo_full = pr.get("repository_url", "").rsplit("/repos/", 1)[-1]
repo_activity[repo_full] += 1
for iss in closed_issues:
repo_full = iss.get("repository_url", "").rsplit("/repos/", 1)[-1]
repo_activity[repo_full] += 1
fields = []
# Summary numbers
total_releases = sum(len(rs) for rs in releases_by_repo.values())
summary_lines = [
f"• **{len(merged_prs)}** PR(s) merged",
f"• **{len(closed_issues)}** issue(s) closed",
f"• **{total_releases}** release(s) published",
f"• Activity in **{len(repo_activity)}** repo(s)",
]
fields.append({
"name": "📊 Last 7 days",
"value": "\n".join(summary_lines),
"inline": False,
})
# Releases list
if releases_by_repo:
rel_lines = []
for repo_full in sorted(releases_by_repo.keys()):
for r in releases_by_repo[repo_full]:
tag = r.get("tag_name", "?")
url = r.get("html_url", "")
rel_lines.append(f"• [{repo_full} {tag}]({url})")
fields.append({
"name": f"🚀 Releases ({total_releases})",
"value": _truncate("\n".join(rel_lines), MAX_FIELD_VALUE),
"inline": False,
})
# Top active repos
if repo_activity:
top_repos = sorted(repo_activity.items(), key=lambda x: x[1], reverse=True)[:MAX_DIGEST_REPOS_PER_FIELD]
repo_lines = [f"• **{repo}**: {count} change(s)" for repo, count in top_repos]
fields.append({
"name": "🔥 Most active",
"value": _truncate("\n".join(repo_lines), MAX_FIELD_VALUE),
"inline": False,
})
embed = {
"title": f"📅 Weekly digest — week of {since}",
"description": f"Activity across @{owner}'s repos.",
"color": COLOR_DIGEST,
"fields": fields,
"footer": {"text": f"{owner} • weekly"},
"timestamp": datetime.now(timezone.utc).isoformat(),
}
return 0 if _post_webhook(webhook, {"username": "Weekly Digest", "embeds": [embed]}) else 1
# ---------- Entry point ----------
def main() -> int:
if len(sys.argv) < 2:
print("Usage: discord_notify.py <release|failure|deploy|release-build|dependabot-summary|weekly-digest>")
return 2
cmd = sys.argv[1].lower()
handlers = {
"release": post_release,
"failure": post_failure,
"deploy": post_deploy,
"release-build": post_release_build,
"dependabot-summary": post_dependabot_summary,
"weekly-digest": post_weekly_digest,
}
handler = handlers.get(cmd)
if not handler:
print(f"[ERROR] Unknown command: {cmd}")
return 2
return handler()
if __name__ == "__main__":
sys.exit(main())
+27
View File
@@ -0,0 +1,27 @@
name: Announce Release to Discord
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: "Existing release tag to re-announce"
required: true
type: string
# Reusable announce-release.yml only needs `contents: read` to fetch
# release metadata via the gh CLI.
permissions:
contents: read
jobs:
announce:
# Pinned to commit SHA instead of @main — guards against a malicious or
# accidental push to poli0981/.github landing in our release pipeline
# silently. Dependabot bumps this weekly via the github-actions ecosystem
# rule in .github/dependabot.yml.
uses: poli0981/.github/.github/workflows/announce-release.yml@e973e2f15725356653ef07539016670ad2733f83
with:
tag_override: ${{ inputs.tag || '' }}
secrets: inherit
+8 -3
View File
@@ -5,6 +5,11 @@ name: CI
# net9.0-windows10.0.22621.0 and the WGC integration tests require a real
# desktop session with Windows 11 22H2 SDK.
# Minimum permissions required to checkout the repo and run dotnet
# build/test. No package writes, no release uploads, no PR comments.
permissions:
contents: read
on:
push:
branches: [ main ]
@@ -24,12 +29,12 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 0 # full history so MinVer / git describe works later
- name: Setup .NET
uses: actions/setup-dotnet@v4
uses: actions/setup-dotnet@v5
with:
# Honor global.json; avoids drift between local + CI.
global-json-file: global.json
@@ -48,7 +53,7 @@ jobs:
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: test-results
path: ./TestResults/**/*.trx
+68
View File
@@ -0,0 +1,68 @@
name: Welcome new discussions
# Auto-post a brief bilingual greeting (Vietnamese + English) the first time
# a non-maintainer opens a Discussion thread. The goal is to lower triage
# burden by directing posters at the right venue up front:
# - Bugs -> the in-app "About -> Report a bug" button or the
# bug-report issue template (requires Windows build,
# GPU, log snippet — the data the solo maintainer
# actually needs to act on a report).
# - Security holes -> GitHub Security Advisories, NOT a public discussion.
# - Q&A / ideas -> stay here, you're in the right place.
on:
discussion:
types: [created]
# `discussions: write` is the only scope required to add a discussion comment
# via the GraphQL `addDiscussionComment` mutation. Default everything else to
# read so a compromised step can't push code or open releases.
permissions:
contents: read
discussions: write
jobs:
welcome:
runs-on: ubuntu-latest
# Skip greetings for OWNER / COLLABORATOR / MEMBER — the maintainer and
# any future collaborators don't need a venue cheat-sheet on their own
# threads.
if: >-
github.event.discussion.author_association != 'OWNER'
&& github.event.discussion.author_association != 'COLLABORATOR'
&& github.event.discussion.author_association != 'MEMBER'
steps:
- name: Add welcome comment
uses: actions/github-script@v7
with:
script: |
const body = [
"Cảm ơn bạn đã mở thread tại **CaptureImage Discussions** — thanks for opening a discussion!",
"",
"**Tiếng Việt**",
"",
"- Báo lỗi (crash, capture lỗi, OCR sai, hotkey không hoạt động): dùng nút **About → Report a bug** ngay trong app, hoặc mở [bug-report template](https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml). Issue tracker yêu cầu các field (Windows build, GPU, log snippet) cần để debug nhanh.",
"- Lỗi bảo mật (security vulnerability): **không** post công khai — báo riêng qua [GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new).",
"- Câu hỏi sử dụng, ý tưởng, show & tell: bạn đang ở đúng chỗ rồi.",
"",
"**English**",
"",
"- Bug reports (crash, broken capture, OCR mistakes, hotkey not firing): use the **About → Report a bug** button in-app, or open the [bug-report template](https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml). The issue tracker requires the fields (Windows build, GPU, log snippet) needed to debug.",
"- Security vulnerabilities: please **don't** post publicly — file privately via [GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new).",
"- Usage questions, ideas, show & tell: you're in the right place.",
"",
"_posted automatically by [.github/workflows/discussion-welcome.yml](https://github.com/poli0981/captureimg/blob/main/.github/workflows/discussion-welcome.yml)_"
].join("\n");
await github.graphql(
`mutation($discussionId: ID!, $body: String!) {
addDiscussionComment(input: { discussionId: $discussionId, body: $body }) {
comment { id }
}
}`,
{
discussionId: context.payload.discussion.node_id,
body
}
);
+25
View File
@@ -0,0 +1,25 @@
name: Notify CI Failures
# Previously listened to `workflows: ["*"]`, which fired this caller on every
# workflow completion in the repo — every release run, every announce run,
# every notify run itself — and the Actions tab filled with skipped entries.
# Narrowed to the single workflow this is supposed to monitor: ci.yml (name
# "CI"). The job-level `if` further skips successful CI runs so the reusable
# isn't pulled in on green builds.
on:
workflow_run:
workflows: ["CI"]
types: [completed]
# REQUIRED: declare permissions matching the reusable workflow's needs.
# Reusable needs `actions: read` to inspect workflow_run details.
permissions:
contents: read
actions: read
jobs:
notify:
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
# Pinned to commit SHA — see comment in announce-release.yml.
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@e973e2f15725356653ef07539016670ad2733f83
secrets: inherit
@@ -0,0 +1,21 @@
name: Notify Release Pipeline
# Previously listened to `workflows: ["*"]`. Narrowed to the actual release
# build workflow ("Release" — release.yml) so the Actions tab no longer fills
# with skipped runs after every CI / notify completion. announce-release.yml
# is intentionally NOT included here — it already posts to Discord on its own,
# routing it through this notifier too would double-post.
on:
workflow_run:
workflows: ["Release"]
types: [completed]
permissions:
contents: read
actions: read
jobs:
notify:
# Pinned to commit SHA — see comment in announce-release.yml.
uses: poli0981/.github/.github/workflows/notify-release-pipeline.yml@e973e2f15725356653ef07539016670ad2733f83
secrets: inherit
+36 -12
View File
@@ -1,9 +1,9 @@
name: Release
# Cut a new release when a tag of the form v1.2.3 is pushed. Packages the
# CaptureImage.App project as a single-file self-contained Win64 build,
# wraps it in a Velopack installer, and uploads the result to a GitHub
# Release matching the tag.
# Cut a new release when a tag of the form v1.2.3 is pushed. Publishes the
# CaptureImage.App project as a multi-file WinAppSDK self-contained Win64
# build (WinUI 3 can't bundle into a single .exe), wraps it in a Velopack
# installer, and uploads the result to a GitHub Release matching the tag.
#
# Code signing is NOT performed yet (SignPath application was declined).
# The installer will trigger Windows SmartScreen "Unknown publisher" until
@@ -39,7 +39,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 0
@@ -58,7 +58,7 @@ jobs:
"version=$v" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
- name: Setup .NET
uses: actions/setup-dotnet@v4
uses: actions/setup-dotnet@v5
with:
global-json-file: global.json
@@ -67,15 +67,19 @@ jobs:
dotnet restore CaptureImage.sln
dotnet test CaptureImage.sln -c Release --logger "trx;LogFileName=test-results.trx" --results-directory ./TestResults
- name: Publish CaptureImage.App (win-x64 self-contained)
- name: Publish CaptureImage.App (win-x64 self-contained, multi-file)
# WinUI 3's WindowsAppSDK runtime can't be bundled into a single .exe —
# PublishSingleFile / IncludeNativeLibrariesForSelfExtract are dropped
# in v1.3. WindowsAppSDKSelfContained=true (set in the csproj) ships
# the runtime as ~50 .dll files alongside the .exe. Velopack packages
# the whole folder.
run: >
dotnet publish src/CaptureImage.App/CaptureImage.App.csproj
-c Release
-r win-x64
--self-contained
/p:PublishSingleFile=true
/p:IncludeNativeLibrariesForSelfExtract=true
/p:EnableCompressionInSingleFile=true
/p:Platform=x64
/p:WindowsPackageType=None
/p:Version=${{ steps.version.outputs.version }}
/p:AssemblyVersion=${{ steps.version.outputs.version }}.0
/p:FileVersion=${{ steps.version.outputs.version }}.0
@@ -88,7 +92,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 +115,8 @@ jobs:
--packDir ./publish
--mainExe ${{ env.MAIN_EXE }}
--outputDir ./releases
--channel win
--delta BestSize
- name: Compute SHA256 sums
shell: pwsh
@@ -108,14 +129,14 @@ jobs:
Get-Content "$outDir\SHA256SUMS.txt"
- name: Upload release artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: captureimage-release-${{ steps.version.outputs.version }}
path: ./releases/**
retention-days: 30
- name: Create / update GitHub Release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
if: startsWith(github.ref, 'refs/tags/v')
with:
name: CaptureImage v${{ steps.version.outputs.version }}
@@ -126,7 +147,9 @@ jobs:
files: |
./releases/*.exe
./releases/*.nupkg
./releases/*.zip
./releases/RELEASES
./releases/releases.*.json
./releases/SHA256SUMS.txt
body: |
## CaptureImage v${{ steps.version.outputs.version }}
@@ -136,6 +159,7 @@ jobs:
### Downloads
- **`Setup.exe`** — Velopack installer. Windows 11 22H2+ only.
- **`*.nupkg`** — portable Velopack package for manual install / CI updates.
- **`*-Portable.zip`** — extract-and-run multi-file build, no installer.
- **`RELEASES`** — Velopack release manifest.
- **`SHA256SUMS.txt`** — checksums for manual verification.
+732
View File
@@ -7,6 +7,738 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.5.1] - 2026-05-11
Hotfix cycle. CI hardening, supply-chain pinning of reusable
workflows, and a small public-attribution surface in About + repo
root.
### Fixed
- **CI workflow missing permissions block.** Code Scanning flagged
`.github/workflows/ci.yml` as not declaring an explicit
`permissions:` block. Now declares `contents: read` — the
minimum required to checkout the repo and run `dotnet build` /
`dotnet test`. No package writes, no release uploads, no PR
comments.
### Changed
- **Reusable workflow refs pinned to commit SHA.** `announce-release`,
`notify-ci-failure`, and `notify-release-pipeline` callers now
reference `poli0981/.github` via full commit SHA instead of `@main`.
Dependabot bumps the SHA weekly via the existing `github-actions`
ecosystem rule in `.github/dependabot.yml`. Avoids the supply-chain
failure mode where a malicious or accidental push to ops-repo
`main` would land in our release pipeline silently.
- **Notify workflows no longer spam the Actions tab.**
`notify-ci-failure` previously listened to `workflows: ["*"]` and
fired on every workflow completion in the repo; now narrowed to
the single workflow it monitors (`"CI"`) with a job-level
conclusion gate so successful CI runs short-circuit before
pulling in the reusable. `notify-release-pipeline` narrowed to
`["Release"]` for the same reason. Roughly 50% fewer skipped
notify-* runs in the Actions history; the remaining runs all
correspond to events worth observing.
### Added
- **About → Connect with the developer** — 8 public-profile links
(X, YouTube, Discord repo + game, Steam, Bluesky, Mastodon,
Telegram) rendered as a vertical stack of `HyperlinkButton`s. Each
uses `NavigateUri` so click opens the URL via the system shell.
Email and PayPal are intentionally not surfaced here.
- **About → Support the project** — short prose + 4 donate buttons
(GitHub Sponsors accent-styled, Ko-fi, Buy Me a Coffee, Patreon).
URLs are hardcoded in `AboutViewModel` and mirror
`.github/FUNDING.yml`.
- **About → Report a bug** — single low-friction button targeting
the GitHub bug-report issue template
(`.github/ISSUE_TEMPLATE/bug_report.yml`).
- **`.github/FUNDING.yml`** — wires GitHub Sponsors, Ko-fi, Buy Me a
Coffee, and Patreon into the repo's "Sponsor" button.
- **`docs/pc_spec.md`** + **`docs/dev_env.md`** — public dev
reference covering primary hardware, mobile test fleet, toolchain
versions, IDE setup, Windows SDK, build/test/run commands, release
tooling. Vietnamese mirrors at `docs/i18n/vi/`.
- **README "Support the project" section** — preceding the License
section, mirroring the four donate destinations and pointing at
the in-app Report-a-bug button.
- **`discussion-welcome.yml` workflow** — auto-posts a brief
bilingual (Vietnamese + English) greeting the first time a
non-maintainer opens a Discussion thread. The greeting points
the poster at the right venue: bug reports → in-app
Report-a-bug button or the bug-report issue template, security
vulnerabilities → GitHub Security Advisories (not a public
discussion), Q&A / ideas → the discussion they just opened. Skips
OWNER / COLLABORATOR / MEMBER posts to avoid greeting the
maintainer's own threads.
### Smoke checklist
1. Launch v1.5.0 → Update → install v1.5.1 → app restarts and
shows "1.5.1" in the nav header.
2. About → click each of the 8 social links → opens in the default
browser.
3. About → click each of the 4 donate buttons → opens the correct
destination.
4. About → Report a bug → GitHub opens with the bug-report template
pre-filled.
5. Switch language en → vi → ar (RTL) → the 3 new section headers
(Connect, Support, Report) retranslate in place.
6. Repo home → the "Sponsor" button appears at top right (near
Watch / Fork).
## [1.5.0] - 2026-05-07
Bug-fix + feature cycle. Tackles a long-standing process-leak bug,
adds four feature toggles requested by users, four new language
packs, and ships a region-capture mode.
### Fixed
- **Process leak on every launch.** `DashboardViewModel.Dispose`
was missing a `_watcher.Stop()` call for the WMI watcher, and
`Program.Main` never disposed the DI container — together those
two gaps left a non-background WMI subscription thread alive
past app exit, so the CLR couldn't tear down and Task Manager
accumulated one zombie `CaptureImage.exe` per launch. Both holes
are now closed; a fresh dispose-chain regression test guards
against future regressions.
- **PreviewWindow theme drift.** The capture-preview modal used to
ignore the persisted theme and always inherit the OS default,
so Dark-mode users saw a Light flash on every preview. The new
`ThemeApplicator` helper is shared between MainWindow and
PreviewWindow and re-applies on every `ISettingsStore.Changed`,
so toggling theme while a preview is open updates it live.
### Added
- **Single-instance guard with restore-on-relaunch.** A second
launch of the app no longer spawns a duplicate process — instead
it pings the existing instance over a named pipe and the
original window pops to the foreground (Spotify/Slack pattern).
The named mutex is per-OS-user, and an abandoned mutex from a
crashed prior run is treated as acquired so the app can never
lock itself out.
- **Capture countdown** (Off / 3s / 5s / 10s) — useful for
capturing tooltips and menu animations that vanish when you
Alt-Tab back to the target.
- **Clipboard mode** (None / Copy only / Copy + Save) — captures
optionally land in the clipboard as a bitmap, with or without
also writing a file. Pastes correctly into Paint, Word, Slack.
- **Open output folder after save** — opt-in toggle that fires
Explorer at the saved file's directory.
- **Pinned floating thumbnail window.** Optional opt-in: every
capture spawns a small always-on-top window with a thumbnail of
the shot, handy for comparing successive captures or keeping a
reference visible while playing/working in another app. Each
capture spawns a fresh window so users can pile up several pins.
- **Built-in offline OCR** via `Windows.Media.Ocr`. The Preview
window grew an "Extract text (OCR)" button that runs the
OS-supplied recognizer on the captured frame and copies the
recognised text to the clipboard. All processing is on-device —
nothing leaves the machine. Falls back gracefully when the
user's installed OCR language packs don't cover the requested
language.
- **Region capture mode.** New Settings → Capture mode dropdown
switches between Window mode (default; existing
`Windows.Graphics.Capture` flow) and Region mode, which opens a
full-screen overlay where the user drags a rectangle. The
selection feeds into the existing Preview / Save / Clipboard /
Pinned-thumbnail pipeline unchanged. v1.5 supports the primary
monitor only — multi-monitor + per-monitor DPI lands in v1.6.
- **Four new language packs**: French (fr-FR), German (de-DE),
Brazilian Portuguese (pt-BR), Russian (ru-RU). Brings shipped
locales to 11. The About → Translations disclaimer lists every
machine-assisted pack and invites native-speaker proofreading
PRs against `src/CaptureImage.UI/Resources/Strings/`.
### Changed
- The `string`→`ElementTheme` switch lives in the new
`ThemeApplicator` helper instead of being duplicated between
windows. `MainWindow.ApplyTheme` now delegates to it.
- `IClipboardService` grew a `CopyText` overload (used by OCR);
the existing `CopyImageAsync` path is unchanged.
- Localization completeness tests now span all 11 cultures, and
both culture test classes share a serialised xUnit collection
so they can't race on the process-wide
`CultureInfo.DefaultThreadCurrent*` statics.
### Smoke checklist
When validating a v1.5 build manually:
1. Open and close the app five times in a row → Task Manager
Background processes shows zero `CaptureImage.exe` after each
close.
2. Double-click the shortcut twice in succession → only one
instance runs; the second launch flashes the existing window
to the foreground.
3. Settings → Theme → toggle Light/Dark while a Preview window
is open → the preview retints in lock-step.
4. Switch language to fr-FR / de-DE / pt-BR / ru-RU → no
`[Settings_Foo]` bracket fallbacks anywhere in the UI; tray
menu refreshes.
5. Settings → Capture countdown → 5s, then trigger the hotkey →
countdown ticks 5/4/3/2/1 in the dashboard status before the
shot fires.
6. Settings → Clipboard mode → Copy + Save, capture, paste into
Paint → image matches the saved file.
7. Settings → Open output folder after save → on, capture →
Explorer pops with the file directory.
8. Settings → Pin a floating thumbnail after each capture → on,
capture → small always-on-top window appears with the shot.
9. Preview window → Extract text (OCR) on a capture with text →
word-count toast, paste into Notepad confirms text.
10. Settings → Capture mode → Region, trigger hotkey → full-screen
dim overlay; drag a rectangle → Preview opens with the cropped
region. Esc on the overlay cancels cleanly.
## [1.4.0] - 2026-04-27
UX polish + accessibility cycle. No breaking changes; settings.json
schema unchanged.
### Added
- **Light / Dark / System theme** picker on the Settings tab. The
preference was already reserved in `AppSettings.Theme` since v1.3
but had no consumer; v1.4 wires it through to
`FrameworkElement.RequestedTheme` and re-applies on every
`ISettingsStore.Changed`. Mica retints automatically with the
resolved theme.
- **Auto-switch on Alt-Tab** (opt-in, default off). When enabled,
the dashboard's selected target follows the OS foreground window
via a `SetWinEventHook(EVENT_SYSTEM_FOREGROUND)` watcher with a
250 ms debounce. Apps not in the target list keep your current
selection. Toggle lives next to the existing capture toggles.
- **Four new language packs**: Japanese (ja-JP), Simplified Chinese
(zh-Hans), Korean (ko-KR), Spanish (es-ES). All machine-assisted —
the About → Translations disclaimer lists every machine-assisted
pack and invites native-speaker proofreading PRs.
- **Friendlier log lines** for end-user lifecycle events: `Picture
captured: {Name} ({W}×{H}, {KB} KB) at {Path} [{Format}]`,
`Picture capture cancelled by user.`, `Language switched to
{Code} ({Name}).`, `Theme switched to {Theme}.`, `Capture sound
{State}.`, `Auto-switch on Alt-Tab {State}.` Logs remain
English-only by design (file shareability + parser stability
across cultures).
### Changed
- **Window is now fixed-size** at 1200×720. Both maximize and
resize are disabled via `OverlappedPresenter.IsMaximizable` /
`IsResizable`; minimize remains enabled for the tray flow.
- **Tone shift on existing log call sites**: "Failed to X" →
"Couldn't X" across `DashboardViewModel`, `SettingsViewModel`,
`UpdateViewModel`, `AboutViewModel`, `LogViewerViewModel`.
Structured properties are unchanged so log queries and external
diagnostics still work.
## [1.3.1] - 2026-04-26
**Critical hotfix.** v1.3.0 shipped broken — the WinUI 3 publish pipeline
omitted `.xbf` (compiled XAML binary) and `CaptureImage.App.pri` (resource
manifest) files from the self-contained publish output, so the installed
app silently failed at MainWindow.InitializeComponent on every launch
(the process stayed alive zombie-style; no window ever appeared). v1.2.x
auto-update users hit this on the first launch after Velopack restart.
### Fixed
- Add a `CopyWinUIArtifactsToPublishDirectory` MSBuild target to
`CaptureImage.App.csproj` that propagates every `.xbf` and the
`CaptureImage.App.pri` from `bin/.../win-x64/` into the publish
output, preserving the cross-assembly XAML resolution subfolders
(`CaptureImage.UI/Controls/`, `CaptureImage.UI/Views/`). `dotnet
publish` for unpackaged WinUI 3 self-contained apps doesn't include
these by default — known WinAppSDK gap.
### Recovery for v1.3.0 users
If you already updated to broken v1.3.0:
- The Update tab can't help (the app's window doesn't open).
- Download `CaptureImage-win-Setup.exe` from the v1.3.1 GitHub Release
and run it — the installer detects the existing install and replaces
it cleanly. Your `settings.json` and capture folder are untouched.
## [1.3.0] - 2026-04-26
UI framework migration from Avalonia 11 to **WinUI 3 (Windows App SDK 1.8.x)**
with Fluent 2 design — Mica backdrop, Segoe UI Variable, integrated title bar,
Composition-API animations. Logic layers (Core / Infrastructure / ViewModels)
were intentionally left untouched: the entire ~5,000-line domain + capture +
hotkey + settings + logging stack carries forward unchanged. Velopack ships
on the existing `win` channel so v1.2.x users auto-update; multi-file
WindowsAppSDK self-contained payload is ~80–120 MB (vs the v1.2 single-file
~30 MB) — accepted trade for stack-Microsoft-native parity on Windows-only.
### Added
- **Sound on capture success** (`UI.SoundEnabled` setting now has a consumer
for the first time since v1.0). Plays Windows `SystemAsterisk` via Win32
`PlaySound` P/Invoke, gated on the existing checkbox.
- **Browse button** on Settings → Output folder. Opens the modern
`IFileOpenDialog` (Vista+ folder picker) seeded at the current
OutputDirectory. Win32 COM-interop fallback because
`Windows.Storage.Pickers.FolderPicker` is unreliable in unpackaged
WinUI 3.
- **Mica backdrop** on the main window — translucent Win11 wallpaper tint.
- **Borderless title bar** integrated with the Fluent 2 chrome; caption
buttons sit in a 48 px reserved drag region.
- **Composition slide animation** on the log drawer — 220 ms slide + 180 ms
fade with CubicBezier(0.4, 0, 0.2, 1) decelerate. Mirrors the v1.2
Avalonia drawer at the visual layer; uses `UIElement.Translation` (additive
on layout) instead of `Visual.Offset` (overrides layout) so the drawer
stays anchored to its Grid column under all window sizes.
- **+164 tests, total 320** (up from 156). New coverage:
- 18 converter tests (FlowDirection / BoolToVisibility / InvertedBoolToVisibility / NotNullToVisibility).
- 5 LogEntry tests (TimestampText format, FileLineText edge cases).
- 141 Theory cases for localization completeness — 47 load-bearing keys
× 3 cultures (en-US / vi-VN / ar-SA) — every shipping label asserted
non-empty + non-bracketed.
### Changed
- **UI framework**: Avalonia 11.2.3 → WinUI 3 (Windows App SDK
1.8.260416003) self-contained x64. ViewModels project still
TFM-portable (`net9.0`); UI + UI.Tests TFM bumped to
`net9.0-windows10.0.22621.0` to link WinAppSDK assemblies.
- **Tray icon**: `H.NotifyIcon.WindowsAppSDK` → `H.NotifyIcon.WinUI` (the
actual nuget.org package id; the WindowsAppSDK suffix never existed on
nuget). Tray ships with OS default glyph for v1.3.0 — proper .ico
round-trip via `System.Drawing.Bitmap.GetHicon` + `Icon.Save` deferred
to v1.4.
- **Folder picker**: Win32 `IFileOpenDialog` COM interop replaces the
unreliable `Windows.Storage.Pickers.FolderPicker` in
`CaptureImage.UI.Services.Win32FolderPicker`.
- **Tray menu commands** wired through `MenuFlyoutItem.Command` (not
`Click` event) — the latter doesn't fire reliably from H.NotifyIcon's
out-of-tree popup.
- **Sound playback** uses Win32 `PlaySound` P/Invoke instead of
`System.Media.SystemSounds` (the latter ships in
`System.Windows.Extensions` which only targets Windows TFMs, too
restrictive for the portable ViewModels project).
- **Tray-restore from minimize** uses `AppWindow.Show` +
`User32.ShowWindow(SW_RESTORE)` + `Window.Activate` +
`User32.SetForegroundWindow` — `Show` alone leaves taskbar-minimized
windows minimized + behind whatever has foreground focus.
- **Auto-refresh suppression** while a preview modal is up — Dashboard's
WMI-driven Targets refresh used to clobber the in-flight
`SelectedTarget` and disrupt the preview decision; now skipped when
state is Previewing or Saving.
- **3rd-party list** in About: drop Avalonia + Inter typeface, add
Windows App SDK / WinUI 3 + H.NotifyIcon.WinUI.
### Removed
- `Avalonia.*` packages (Avalonia, Avalonia.Desktop, Avalonia.Themes.Fluent,
Avalonia.Fonts.Inter, Avalonia.Diagnostics) and 25 .axaml files / Avalonia
service implementations (`AvaloniaTrayIconHost`, `AvaloniaPreviewPresenter`,
`AvaloniaUIDispatcher`, `BytesToBitmapConverter` for Avalonia.Bitmap,
`ToastKindToBrushConverter` for Avalonia.IBrush). All replaced with WinUI 3
equivalents.
- Inter typeface — Fluent 2's Segoe UI Variable is the explicit body font now.
- `PublishSingleFile` from the release workflow — WinAppSDK can't be
bundled into a single .exe, ships as multi-file folder packaged by
Velopack.
### Fixed
- (in v1.3 from v1.2 carry-overs) Title-bar caption buttons no longer
overlap nav rail / Page content — 48 px drag region reserved at top
via `Window.SetTitleBar(AppTitleBar)`.
### Deferred to v1.4
- Real .ico tray icon via `System.Drawing.Bitmap.GetHicon` round-trip
(currently OS default glyph). H.NotifyIcon.WinUI's IconSource pipeline
ends in `System.Drawing.Icon` which only accepts .ico file streams.
- `release.yml` upload of `CaptureImage-win-Portable.zip` (carry-over
from v1.2 — added in v1.3 release cut).
- DPI-aware initial window sizing (`AppWindow.Resize` takes physical
pixels; v1.3 hardcodes 1200×720).
## [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
real hotkey rebinder, live localization fixes across every tab, an
architecture overview for contributors, and a visual refresh aligned
with 2025/26 Windows 11 conventions. No capture-engine changes; no new
backends.
### M4 — UI/UX polish: live-localization fixes + 2025 modernization
Polish pass closing seven localization / live-refresh bugs and modernizing
the visual system to match 2025/26 Windows 11 conventions. Commit
[`5f5e878`](https://github.com/poli0981/captureimg/commit/5f5e878).
- **Dashboard localization**: title, subtitle, Refresh / Arm / Disarm
buttons, "N target(s) visible" line, and the loading hint were all
hardcoded English; now bound through `{Binding Localization[Dashboard_*]}`
and refresh live on culture switch. `DashboardViewModel` grows
`TargetsCountText`, `LoadingText`, `EmptyStateText`, `HasNoTargets` and
expands its culture listener to refresh all of them.
- **Steam badge tooltip**: `GameTargetViewModel.SteamBadgeTooltip` was a
hardcoded mixed EN/VI string; now formats via
`Dashboard_SteamBadgeTooltip` with a culture listener. The VM is now
`IDisposable` and the dashboard disposes rows on reconcile so the
listener doesn't pin dead targets.
- **LogViewer Pause/Resume**: the button was pinned to `Log_Pause` and
didn't flip on state change. New `TogglePauseLabel` switches between
`Log_Pause` / `Log_Resume` on `IsPaused` + culture change. A new
culture listener on `LogViewerViewModel` also refreshes
`EventsCountText` + `EmptyStateText`.
- **Hotkey error message**: `HotkeyBindingViewModel.ErrorMessage` is an
indexer-backed computed property; added a culture listener that raises
`PropertyChanged` so the Settings error text re-localizes live.
- **MainWindow header**: hardcoded `"CaptureImage"` + stale
`"v0.1.0 — M3 UX polish"` replaced with `AppTitle` + `AppVersion`
pulled from `AssemblyInformationalVersion` / assembly metadata.
`App.csproj` now carries a `<Version>` element; release.yml keeps
overriding via `/p:Version=<git-tag>`.
- **Inter font stack**: `Avalonia.Fonts.Inter` was in the package graph
but never applied. `App.axaml` now declares a global Inter style for
TextBlock / TextBox / Button / ComboBox / CheckBox (monospace
overrides remain for LogViewer entries + HotkeyRecorder display).
- **Focus ring**: keyboard-focus `:focus-visible` style on
`ListBoxItem` + `Border#BindingField:focus` style on
`HotkeyRecorder` — both paint the border in the accent brush so Tab
navigation and "waiting for your key" are visually obvious.
- **Corner radius**: unified to 8 px on cards / borders across Dashboard,
About, Update, Preview, LogViewer, Toast. 4 px kept only on the inline
Steam badge pill per the design contract.
- **Text contrast**: every `Opacity="0.4"`–`"0.7"` on labels and hints
swapped for `Foreground=SystemControlForegroundBaseMediumBrush` so
secondary text meets WCAG AA on both light and dark theme variants.
- **Accessibility**: `AutomationProperties.Name` + HelpText on the log
drawer toggle, HotkeyRecorder BindingField, and Dashboard status
card — screen readers now announce meaningful names.
- **Empty states**: Dashboard and LogViewer now render a localized hint
when no targets / no log events. New keys `Dashboard_EmptyState`,
`Dashboard_LogToggle`, `Log_EmptyState`, `Log_EventsCount` added in
EN / VI / AR.
- **FontSize scale**: snapped outliers to 11/12/13/14/16/22 — page
titles 24→22, preview dialog 20→22, nav icon 18→16, Steam badge
10→11.
### M3 — Architecture tour + dogfood screenshots
Contributor-facing documentation + real README screenshots. Commit
[`8e374a0`](https://github.com/poli0981/captureimg/commit/8e374a0).
- **`docs/ARCHITECTURE.md`** (new) — one-page-per-layer reference with
five Mermaid diagrams that GitHub renders inline: project dependency
graph, capture state machine, WGC capture pipeline sequence, DI
composition sketch, i18n + RTL flow, and Velopack update flow.
- **`docs/screenshots/`** (new) — six real app screenshots
(Dashboard / Settings / About / Update / LogViewer / RTL Dashboard),
captured by dogfooding CaptureImage on itself for the passive views.
- **README refresh** — replaces the "coming with first tagged release"
placeholder with a 2×3 screenshot table, and adds an Architecture
section linking to the new doc.
### M2 — Dependabot cleanup + Node 24 runners
Close the dependabot backlog ahead of the Node 20 deprecation deadline
(2026-09-16). Commit [`d5706f2`](https://github.com/poli0981/captureimg/commit/d5706f2).
- **GitHub Actions bumps** (all Node 20 → Node 24 runtime updates; no
API changes, `windows-latest` already supports the newer runner):
`actions/checkout` 4→6, `actions/setup-dotnet` 4→5,
`actions/upload-artifact` 4→7, `softprops/action-gh-release` 2→3.
- **Test tooling bumps**: `xunit` 2.9.2→2.9.3 (patch),
`coverlet.collector` 6.0.2→8.0.1 (major — requires .NET 8 LTS floor,
which we already exceed on .NET 9).
- **Release.yml audit**: `upload-artifact` v5/v6/v7 kept `name`,
`path`, `retention-days` intact; the v1.1 plan's speculated
`overwrite` default flip never happened. No YAML option changes
required.
### M1 — Hotkey rebinder + conflict sniff
First user-facing feature addition since 1.0.0. Commit
[`0482f71`](https://github.com/poli0981/captureimg/commit/0482f71).
- **`HotkeyRecorder` control** — keyboard-driven recorder in Settings.
Click Record, press a combination, Esc cancels. The view maps
Avalonia `Key` to Win32 virtual-key codes so the persisted
`HotkeyBinding` stays round-trippable against SharpHook's RawCode.
- **`HotkeyBindingViewModel`** — bridges recorder → persistence and
calls `IHotkeyService.SetBinding` live so an armed capture picks up
the new combo without disarm/re-arm.
- **`ReservedHotkeys`** (new, `CaptureImage.Core.Validation`) —
catalogue of combinations owned by the Windows shell (Win+L,
Ctrl+Shift+Esc, Alt+Tab, Alt+F4, Win snap keys, etc.).
`HotkeyBinding.Validate()` rejects those plus modifier-only /
naked-letter bindings before persistence with a localized error.
- **`HotkeyConflictSniffer`** — `RegisterHotKey`/`UnregisterHotKey`
probe on `HWND=NULL`. If another process already owns the combo the
UI surfaces a non-blocking warning, but the user keeps control and
still saves.
- **i18n strings** for every recorder surface added in EN / VI / AR.
- **Tests**: +24 Core validation (reserved combos + `HotkeyBinding.Validate`),
+12 ViewModel flow with NSubstitute fakes. Total 107 pass.
## [1.0.0] - 2026-04-16
Initial public release. Screen-capture tool targeting Windows 11 22H2+,
built with C# .NET 9 + Avalonia 11, distributed as a Velopack installer
via GitHub Releases. Unsigned (SignPath application was declined).
### M5 — Release infrastructure (1.0.0 cut)
Everything you need to actually ship the binary. No new product features;
+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
+11 -11
View File
@@ -5,12 +5,14 @@
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
<ItemGroup Label="Avalonia">
<PackageVersion Include="Avalonia" Version="11.2.3" />
<PackageVersion Include="Avalonia.Desktop" Version="11.2.3" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<PackageVersion Include="Avalonia.Diagnostics" Version="11.2.3" />
<ItemGroup Label="WinUI 3 / Windows App SDK">
<PackageVersion Include="Microsoft.WindowsAppSDK" Version="1.8.260416003" />
<PackageVersion Include="Microsoft.WindowsAppSDK.Base" Version="1.8.251216001" />
<PackageVersion Include="Microsoft.WindowsAppSDK.Foundation" Version="1.8.260415000" />
<PackageVersion Include="Microsoft.WindowsAppSDK.Runtime" Version="1.8.260416003" />
<PackageVersion Include="Microsoft.WindowsAppSDK.WinUI" Version="1.8.260415005" />
<PackageVersion Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.28000.1721" />
<PackageVersion Include="Microsoft.Web.WebView2" Version="1.0.3912.50" />
</ItemGroup>
<ItemGroup Label="MVVM">
@@ -28,7 +30,7 @@
</ItemGroup>
<ItemGroup Label="Tray">
<PackageVersion Include="H.NotifyIcon.WindowsAppSDK" Version="2.2.0" />
<PackageVersion Include="H.NotifyIcon.WinUI" Version="2.2.0" />
<PackageVersion Include="H.NotifyIcon" Version="2.2.0" />
</ItemGroup>
@@ -63,8 +65,6 @@
</ItemGroup>
<ItemGroup Label="Imaging">
<!-- Avalonia ships SkiaSharp transitively, but Infrastructure doesn't reference Avalonia
so we pin it explicitly here. Bumping deliberately to match Avalonia's choice. -->
<PackageVersion Include="SkiaSharp" Version="3.119.2" />
<PackageVersion Include="SkiaSharp.NativeAssets.Win32" Version="3.119.2" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" />
@@ -76,12 +76,12 @@
<ItemGroup Label="Tests">
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="xunit" Version="2.9.2" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageVersion Include="FluentAssertions" Version="6.12.2" />
<PackageVersion Include="NSubstitute" Version="5.3.0" />
<PackageVersion Include="System.IO.Abstractions.TestingHelpers" Version="21.2.1" />
<PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="coverlet.collector" Version="8.0.1" />
</ItemGroup>
</Project>
+35 -6
View File
@@ -53,10 +53,15 @@ tray app, and stays out of your way until you press the hotkey.
## Screenshots
<!-- Screenshots land here once the maintainer captures them. The app
generates its own screenshots — yes, we eat our own dog food. -->
Captured with CaptureImage itself — yes, we eat our own dog food.
_(coming with the first tagged release)_
| Dashboard | Settings | About |
|:-:|:-:|:-:|
| ![Dashboard — target list with Steam badge](docs/screenshots/dashboard.png) | ![Settings — hotkey recorder + format + language](docs/screenshots/settings.png) | ![About — version, licenses, legal docs](docs/screenshots/about.png) |
| Update | Log viewer | RTL (Arabic) |
|:-:|:-:|:-:|
| ![Update — Velopack check / download / install with live log](docs/screenshots/update.png) | ![Log viewer — live Serilog ring buffer](docs/screenshots/logviewer.png) | ![RTL — dashboard mirrored for Arabic culture](docs/screenshots/rtl-dashboard.png) |
## Requirements
@@ -134,9 +139,10 @@ src/
watcher, Steam detector, hotkeys, settings, logging,
Velopack updater. net9.0-windows10.0.22621.0.
CaptureImage.ViewModels MVVM layer — reusable across UI frameworks, no
Avalonia references.
CaptureImage.UI Avalonia views, custom controls (ToastHost, etc.),
converters, resx localization.
WinUI 3 references.
CaptureImage.UI WinUI 3 Pages + UserControls (HotkeyRecorder,
ToastHost, LogViewerView, PreviewWindow),
converters, resx localization, tray host.
CaptureImage.App Entry point, DI composition root, Serilog setup,
Velopack startup hook.
tests/
@@ -155,6 +161,13 @@ docs/
THIRD_PARTY_NOTICES.md Full dependency list + licenses.
```
## Architecture
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for a one-page-per-layer
tour — layer rules, state-machine diagram, WGC capture pipeline sequence,
DI composition sketch, i18n + RTL flow, and Velopack update flow (all with
Mermaid diagrams rendered inline on GitHub).
## Contributing
See [`docs/CONTRIBUTORS.md`](docs/CONTRIBUTORS.md) for the full
@@ -187,6 +200,22 @@ meaningful AI authorship carry a `Co-Authored-By` trailer naming the
model. Full details in [`docs/CONTRIBUTORS.md`](docs/CONTRIBUTORS.md)
and [`docs/legal/DISCLAIMER.md §3`](docs/legal/DISCLAIMER.md).
## Support the project
CaptureImage is free, open source, and developed solo. If it helps
you, consider supporting development:
- [GitHub Sponsors](https://github.com/sponsors/poli0981)
- [Ko-fi](https://ko-fi.com/skullmute)
- [Buy Me a Coffee](https://buymeacoffee.com/skullmute)
- [Patreon](https://patreon.com/skullmute)
The same destinations are wired into the repo's "Sponsor" button via
[`.github/FUNDING.yml`](.github/FUNDING.yml).
Bug reports go through the in-app **About → Report a bug** button or
[directly on GitHub](https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml).
## License
CaptureImage is distributed under the **GNU General Public License
+358
View File
@@ -0,0 +1,358 @@
# Architecture
This document is a one-page-per-layer tour of CaptureImage for people who
want to contribute, audit, or port the code. It is **not** the design
intent record — that lives in the per-milestone plan files under
`.claude/plans/`. This is the shape of the code as it stands on `main`.
Diagrams are Mermaid so GitHub renders them inline. Source paths are
clickable; line numbers drift, so I link to files rather than lines.
## 1. Layer rules
Five projects, four rules:
- **`CaptureImage.Core`** (net9.0) — pure domain. Models, abstractions,
state machine, pipeline. No platform references. **Depends on nothing.**
- **`CaptureImage.Infrastructure`** (net9.0-windows10.0.22621.0) — every
Windows-specific implementation: WGC capture, D3D11 interop, WMI
process watch, `RegisterHotKey` sniff, Velopack updater, Serilog sinks,
JSON settings. **Depends on Core.**
- **`CaptureImage.ViewModels`** (net9.0) — MVVM layer using
CommunityToolkit.Mvvm source generators. Platform-agnostic — these
types exist so the UI logic is testable without WinUI 3.
**Depends on Core only.**
- **`CaptureImage.UI`** (net9.0-windows10.0.22621.0) — WinUI 3 Pages +
UserControls, converters, resx localization, tray host, picker COM
interop. **Depends on Core + ViewModels.**
- **`CaptureImage.App`** (net9.0-windows10.0.22621.0) — the composition
root. `Program.cs` + [`CompositionRoot.cs`](../src/CaptureImage.App/CompositionRoot.cs).
Single point of DI wiring. **Depends on all four projects.**
```mermaid
graph LR
App[CaptureImage.App<br/>net9.0-windows]
UI[CaptureImage.UI<br/>net9.0-windows · WinUI 3]
VM[CaptureImage.ViewModels<br/>net9.0 · MVVM]
Infra[CaptureImage.Infrastructure<br/>net9.0-windows · P/Invoke]
Core[CaptureImage.Core<br/>net9.0 · pure domain]
App --> UI
App --> Infra
App --> VM
App --> Core
UI --> VM
UI --> Core
VM --> Core
Infra --> Core
```
**Why this shape:**
- `Core` stays portable so the domain logic is trivially testable. The
Core test project runs on plain `net9.0`, no Windows 11 SDK needed.
- `ViewModels` stays off `net9.0-windows` so the type system stays
portable — VM tests run on plain `net9.0` without dragging in WinAppSDK
or WinRT projections.
- `Infrastructure` is the only project that touches `Windows.*`. If a
future milestone ports to another desktop platform, that's the project
that gets replaced.
## 2. Capture state machine
Every screenshot flows through a single
[`CaptureStateMachine`](../src/CaptureImage.Core/StateMachine/CaptureStateMachine.cs)
backed by the `Stateless` library. `DashboardViewModel` fires triggers;
the machine decides whether the preview step is visited based on a
live-checked `Func<bool> previewEnabled`.
```mermaid
stateDiagram-v2
[*] --> Idle
Idle --> TargetsSelected: SelectTargets
TargetsSelected --> Idle: ClearTargets
TargetsSelected --> Armed: Arm
Armed --> TargetsSelected: Disarm
Armed --> Idle: ClearTargets
Armed --> Capturing: HotkeyPressed
Capturing --> Previewing: FrameCaptured\n(previewEnabled=true)
Capturing --> Saving: FrameCaptured\n(previewEnabled=false)
Capturing --> Failed: ErrorOccurred
Previewing --> Saving: PreviewAccepted
Previewing --> Armed: PreviewRejected
Saving --> Complete: Saved
Saving --> Failed: ErrorOccurred
Complete --> Armed: Reset
Complete --> Idle: ClearTargets
Failed --> Armed: Reset
Failed --> Idle: ClearTargets
```
**Rules of the road:**
- Transitions are driven by explicit triggers, never by timers. The
viewmodel is the only thing allowed to call `Fire`.
- `Capturing → Saving/Previewing` uses `PermitDynamic` so the preview
toggle is consulted at transition time. Changing the toggle while
armed affects the *next* capture, not any in-flight one.
- `Failed` and `Complete` both route back to `Armed` on `Reset` so the
user can fire another shot without re-selecting a target.
- `StateChanged` fires on whatever thread drove the trigger.
`DashboardViewModel` marshals to the UI thread before touching
bindings.
Tests cover every legal transition and assert illegal ones throw —
[`CaptureStateMachineTests`](../tests/CaptureImage.Core.Tests/StateMachine/CaptureStateMachineTests.cs).
## 3. WGC capture pipeline
The primary engine is
[`WindowsGraphicsCaptureEngine`](../src/CaptureImage.Infrastructure/Capture/WindowsGraphicsCaptureEngine.cs),
an on-demand single-frame pipeline. It uses the same
`Windows.Graphics.Capture` API that OBS Studio uses for Game Capture.
Hardware-accelerated, works with DX11/DX12/Vulkan windowed and
borderless-fullscreen titles.
```mermaid
sequenceDiagram
participant VM as DashboardViewModel
participant Eng as WindowsGraphicsCaptureEngine
participant Interop as CaptureItemInterop
participant D3D as D3D11DeviceManager
participant WGC as Windows.Graphics.Capture
participant Tex as Staging Texture
VM->>Eng: CaptureAsync(target, ct)
Eng->>Interop: CreateForWindow(HWND)
Interop-->>Eng: GraphicsCaptureItem
Eng->>D3D: Get()
D3D-->>Eng: (ID3D11Device, context)
Eng->>WGC: CreateFreeThreaded(framePool)
Eng->>WGC: CreateCaptureSession(item)
Note over Eng,WGC: IsBorderRequired=false<br/>IsCursorCaptureEnabled=false
Eng->>WGC: StartCapture()
WGC-->>Eng: FrameArrived (async)
Eng->>Tex: CreateTexture2D(STAGING + CPU_READ)
Eng->>Tex: CopyResource(gpu → staging)
Eng->>Tex: Map(READ)
Eng-->>VM: CapturedFrame(w, h, stride, bytes)
Note over Eng: Dispose session<br/>Dispose framePool<br/>Dispose staging + gpu texture
```
**Invariants:**
- Exactly one frame per call. The framepool is `numberOfBuffers: 1` and
the session is disposed as soon as the first frame arrives.
- 2-second `FrameTimeout`. Games that never render (minimized, stalled)
surface as `CaptureError.NoFrameArrived`.
- BGRA8 only — pixel format is pinned so the encoder layer doesn't need
a format negotiation step. The Skia/ImageSharp wrappers accept BGRA
directly.
- Win11 22H2+ only. That's the minimum OS for the
`IsBorderRequired = false` flag to actually hide the yellow capture
frame. Older builds still work but show the frame.
**Fallback path:** if WGC itself fails (legacy GDI-only apps, some
emulators), the orchestrator retries with
[`PrintWindowFallback`](../src/CaptureImage.Infrastructure/Capture/PrintWindowFallback.cs)
which calls `PrintWindow(hwnd, hdc, PW_RENDERFULLCONTENT)`. Slower,
subject to HDCP, but wide compatibility.
## 4. DI composition
[`CompositionRoot.BuildServices`](../src/CaptureImage.App/CompositionRoot.cs)
is the only place DI registrations live. No scanning, no convention, no
assembly-level attributes — everything the runtime sees is explicit in
one file.
```mermaid
graph LR
subgraph "Cross-cutting"
Log[ILogger*]
FS[IFileSystem]
Dispatcher[IUIThreadDispatcher]
Loc[ILocalizationService]
end
subgraph "Domain services"
Settings[ISettingsStore]
Steam[ISteamDetector]
Procs[IProcessWatcher<br/>IProcessDetector]
Cap[ICaptureEngine]
Encoders[IImageEncoder × 2]
Hotkey[IHotkeyService<br/>IHotkeyConflictSniffer]
Update[IUpdateService]
Orch[CaptureOrchestrator]
end
subgraph "UI services"
Toast[IToastService]
Preview[IPreviewPresenter]
Tray[ITrayIconHost]
Nav[INavigationService]
end
subgraph "ViewModels (singletons)"
Main[MainWindowViewModel]
Dash[DashboardViewModel]
Set[SettingsViewModel]
Hk[HotkeyBindingViewModel]
About[AboutViewModel]
Upd[UpdateViewModel]
LogVM[LogViewerViewModel]
end
Dash --> Settings
Dash --> Procs
Dash --> Orch
Dash --> Hotkey
Orch --> Cap
Orch --> Encoders
Orch --> FS
Set --> Settings
Set --> Loc
Set --> Hk
Hk --> Settings
Hk --> Hotkey
```
**Lifetimes:** every service and every viewmodel is a singleton. There
is no request scope — the app is one long-running desktop process with
a single window. `validateScopes: true` is on so DI misuse fails loudly
at startup.
**Startup order:**
1. `VelopackApp.Build().Run()` — must be the first line of `Main` so
Velopack can handle `--squirrel-install`, `--squirrel-firstrun`, etc.
before WinUI 3 spins up.
2. Serilog configured (file sink + in-memory ring buffer for the log
drawer).
3. `BuildServices(inMemorySink)` — container built.
4. `ISettingsStore.LoadAsync()` — settings file read before any VM that
depends on them is resolved.
5. `Microsoft.UI.Xaml.Application.Start(...)` — installs a
`DispatcherQueueSynchronizationContext` on the freshly-minted UI
thread, then constructs the `App` instance which `OnLaunched` shows
the main window.
## 5. i18n + RTL
Resources live as three sibling `.resx` files under
[`src/CaptureImage.UI/Resources/Strings/`](../src/CaptureImage.UI/Resources/Strings):
`Strings.resx` (en-US, neutral), `Strings.vi.resx`, `Strings.ar.resx`.
MSBuild compiles them to satellite assemblies at build time. No
Designer-generated wrapper — we use `ResourceManager` directly.
```mermaid
sequenceDiagram
participant User
participant Settings as SettingsViewModel
participant Loc as ResxLocalizationService
participant RM as ResourceManager
participant XAML as WinUI 3 bindings
User->>Settings: Pick "العربية" in Language dropdown
Settings->>Loc: SetCulture(ar-SA)
Loc->>Loc: CurrentCulture = ar-SA<br/>CurrentFlowDirection = RightToLeft
Loc-->>XAML: PropertyChanged("Item[]")
XAML->>Loc: this["Settings_Hotkey"]
Loc->>RM: GetString(key, ar-SA)
RM-->>Loc: "مفتاح اختصار الالتقاط"
Loc-->>XAML: string
XAML-->>User: window mirrors + text flips
```
**Key properties:**
- `PropertyChanged("Item[]")` is the magic indexer-binding refresh
signal. WinUI 3 picks it up reliably for direct `{Binding Localization[Key]}`
paths; computed `XLabel` properties on each VM (the pattern adopted in
v1.1.2 to work around an Avalonia compiled-binding quirk) carry forward
for live culture switching.
- `MainWindow.xaml` binds `FlowDirection` on its root Grid to
`Localization.CurrentFlowDirection` via `FlowDirectionConverter` (a
static IValueConverter declared at App.xaml `Application.Resources`
scope). Arabic, Hebrew, Farsi, Urdu — any two-letter language code in
the RTL set — mirrors the whole tree.
- No app restart required. Every VM that stores localized text holds
only the key, looks up via the indexer, and refreshes on the
`PropertyChanged` broadcast.
- Translations for VI and AR are machine-assisted today — see
[`docs/legal/DISCLAIMER.md §4`](legal/DISCLAIMER.md). Native-speaker
review is the next milestone's ask.
## 6. Update flow (Velopack)
[`VelopackUpdateService`](../src/CaptureImage.Infrastructure/Update/VelopackUpdateService.cs)
wraps Velopack's `UpdateManager` pointed at the GitHub Releases source.
Everything is explicit — no background timer, no silent upgrades. The
user clicks **Check for updates**, optionally **Download**, optionally
**Install and restart**.
```mermaid
sequenceDiagram
participant Main as Program.Main
participant Velo as VelopackApp
participant User
participant UI as UpdateView
participant VM as UpdateViewModel
participant Svc as VelopackUpdateService
participant GH as GitHub Releases
participant Mgr as UpdateManager
Main->>Velo: Build().Run(args)
Note over Velo: Handles --squirrel-install,<br/>--squirrel-firstrun etc.<br/>then returns to caller
Main->>Main: Application.Start(...)
User->>UI: Click "Check for updates"
UI->>VM: CheckCommand
VM->>Svc: CheckAsync()
Svc->>Mgr: CheckForUpdatesAsync()
Mgr->>GH: GET /releases/latest
GH-->>Mgr: UpdateInfo (or null)
Mgr-->>Svc: UpdateInfo
Svc-->>VM: UpdateCheckResult
VM-->>UI: Status + version + release notes
User->>UI: Click "Download"
UI->>VM: DownloadCommand
VM->>Svc: DownloadAsync(progress)
Svc->>Mgr: DownloadUpdatesAsync(IProgress<int>)
Mgr->>GH: GET /releases/.../CaptureImage-full.nupkg
GH-->>Mgr: stream
Mgr-->>Svc: done
Svc-->>VM: Status=ReadyToInstall
User->>UI: Click "Install & restart"
UI->>VM: InstallCommand
VM->>Svc: ApplyAndRestart()
Svc->>Mgr: ApplyUpdatesAndRestart()
Note over Mgr: Velopack spawns Update.exe,<br/>kills current process,<br/>swaps files, relaunches
```
**Development-mode caveat:** when the app is launched via
`dotnet run` (not from a Velopack-installed location), `UpdateManager`
reports `IsInstalled = false` and the service returns
`UpdateStatus.Unavailable`. The update tab still renders, it just tells
you updates are disabled and why. Release builds installed via `Setup.exe`
have `IsInstalled = true` and the full flow works.
**Unsigned installer today.** Velopack can sign the installer if given a
cert; CaptureImage doesn't have one yet (SignPath application was
declined for v1.0). Users see Windows SmartScreen's "Unknown publisher"
warning on first run. Integrity is still verifiable via the
`SHA256SUMS.txt` published alongside every release.
---
## See also
- [`docs/RELEASING.md`](RELEASING.md) — how releases are cut and
published.
- [`docs/CONTRIBUTORS.md`](CONTRIBUTORS.md) — contribution flow, AI
assistance policy, translation hand-off.
- [`docs/legal/`](legal) — disclaimers, privacy, third-party notices.
- The `Co-Authored-By` commit trailers naming Claude Opus 4.7 — see
the git log for per-milestone design notes that influenced this
architecture.
+7 -2
View File
@@ -73,8 +73,13 @@ CaptureImage stands on the shoulders of several open-source projects.
See [`THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md) for the full
list with licenses. Special thanks to:
- The **Avalonia UI** team for a modern, cross-platform XAML framework
that also happens to run beautifully on Windows.
- The **Windows App SDK / WinUI 3** team at Microsoft for the modern
Win11-native XAML framework underneath the v1.3+ UI.
- The **Avalonia UI** team — v1.0 through v1.2 of CaptureImage shipped on
Avalonia, and the project owes a substantial debt to the cross-platform
XAML framework that got us off the ground.
- The **H.NotifyIcon** team for the WinUI 3 tray-icon library that fills
the gap WinAppSDK doesn't (yet) cover natively.
- The **OBS Studio** team for blazing the trail on Windows Graphics
Capture integration — their public source code was a useful reference
while wiring up `IGraphicsCaptureItemInterop`.
+74
View File
@@ -0,0 +1,74 @@
# Development environment
This document lists the toolchain versions used to build, test, and
release CaptureImage. Hardware reference: [`docs/pc_spec.md`](pc_spec.md).
Vietnamese mirror: [`docs/i18n/vi/dev_env.md`](i18n/vi/dev_env.md).
## Toolchains
| Toolchain | Version | Purpose |
|-------------|----------------------------------------|-----------------------------------------------|
| **.NET SDK**| 9.0 (exact version pinned in [`global.json`](../global.json)) | Primary build / test runtime |
| **Python** | 3.12 | Release scripting, Discord notification helper (`.github/scripts/discord_notify.py`) |
| **Node.js** | ≥ 22 LTS | Future docs site / web companion tooling |
| **Rust** | stable, via `rustup` | Reserved for future native helpers (none in v1.5.x) |
| **Git** | recent (≥ 2.40) | Source control |
| **GPG** | any version supporting Ed25519 | Commit + tag signing — `commit.gpgsign=true` is set repo-wide; tag signing required per [`docs/RELEASING.md`](RELEASING.md) |
The CI runner uses `actions/setup-dotnet@v5` with `global-json-file:
global.json`, so the local and CI .NET versions are guaranteed to
match — see [`.github/workflows/ci.yml`](../.github/workflows/ci.yml).
## IDE setup
Primary: **JetBrains Rider 2026.x** (paid lineup). Recommended Rider
plugins:
- *.NET Core User Secrets* (built in)
- *Markdown* (built in)
- *Resource Bundle Editor* — handy when editing the 11 `.resx`
locale files at once
([`src/CaptureImage.UI/Resources/Strings/`](../src/CaptureImage.UI/Resources/Strings/))
Sibling JetBrains IDEs used on adjacent projects: **PyCharm**,
**WebStorm**, **RustRover**.
Secondary: **Visual Studio Code** with the C# Dev Kit extension for
quick edits.
## Windows SDK
WinUI 3 + `Windows.Graphics.Capture` projections require the
**Windows 11 22H2 SDK** (10.0.22621). Install via the Visual Studio
Installer ("Windows 11 SDK (10.0.22621.x)") or directly from
<https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/>.
## Build / test / run
```powershell
git clone https://github.com/poli0981/captureimg.git
cd captureimg
dotnet restore
dotnet build CaptureImage.sln -c Release
dotnet test CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release
```
The CI commands are a literal mirror of the above plus
`/p:TreatWarningsAsErrors=true /p:WarningsAsErrors=nullable` — run
the same locally before opening a PR.
## Release tooling
- **Velopack** (`vpk` CLI) — packaging + delta updates.
- **`gh`** (GitHub CLI) — creating Releases, uploading artifacts,
fetching SHAs (the reusable-workflow pin lookup in
[`docs/RELEASING.md`](RELEASING.md)).
- See [`docs/RELEASING.md`](RELEASING.md) for the end-to-end cycle.
## Related documents
- [`docs/pc_spec.md`](pc_spec.md) — hardware reference.
- [`docs/ARCHITECTURE.md`](ARCHITECTURE.md) — software architecture.
- [`docs/CONTRIBUTORS.md`](CONTRIBUTORS.md) — contribution policy.
- [`README.md`](../README.md) — project overview.
+77
View File
@@ -0,0 +1,77 @@
# Môi trường phát triển
Tài liệu này liệt kê các phiên bản toolchain dùng để build, test
và release CaptureImage. Tham chiếu phần cứng:
[`pc_spec.md`](pc_spec.md). Bản tiếng Anh:
[`docs/dev_env.md`](../../dev_env.md).
## Toolchain
| Toolchain | Version | Purpose |
|-------------|----------------------------------------|-----------------------------------------------|
| **.NET SDK**| 9.0 (pin chính xác trong [`global.json`](../../../global.json)) | Build + test runtime chính |
| **Python** | 3.12 | Release scripting, Discord notification helper (`.github/scripts/discord_notify.py`) |
| **Node.js** | ≥ 22 LTS | Docs site / web companion tooling tương lai |
| **Rust** | stable, qua `rustup` | Dự phòng cho native helper tương lai (chưa có trong v1.5.x) |
| **Git** | mới (≥ 2.40) | Source control |
| **GPG** | bất kỳ phiên bản nào hỗ trợ Ed25519 | Ký commit + tag — `commit.gpgsign=true` được bật repo-wide; tag signing là bắt buộc theo [`docs/RELEASING.md`](../../RELEASING.md) |
CI runner dùng `actions/setup-dotnet@v5` với `global-json-file:
global.json`, nên phiên bản .NET local và CI đảm bảo khớp nhau —
xem [`.github/workflows/ci.yml`](../../../.github/workflows/ci.yml).
## Cấu hình IDE
Chính: **JetBrains Rider 2026.x** (paid lineup). Plugin Rider khuyến
nghị:
- *.NET Core User Secrets* (có sẵn)
- *Markdown* (có sẵn)
- *Resource Bundle Editor* — tiện khi edit 11 file `.resx` locale
cùng lúc
([`src/CaptureImage.UI/Resources/Strings/`](../../../src/CaptureImage.UI/Resources/Strings/))
JetBrains IDE anh em dùng trên các project lân cận: **PyCharm**,
**WebStorm**, **RustRover**.
Phụ: **Visual Studio Code** với extension C# Dev Kit cho các edit
nhanh.
## Windows SDK
WinUI 3 + projection của `Windows.Graphics.Capture` yêu cầu
**Windows 11 22H2 SDK** (10.0.22621). Cài qua Visual Studio
Installer ("Windows 11 SDK (10.0.22621.x)") hoặc trực tiếp từ
<https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/>.
## Build / test / run
```powershell
git clone https://github.com/poli0981/captureimg.git
cd captureimg
dotnet restore
dotnet build CaptureImage.sln -c Release
dotnet test CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release
```
Lệnh trên CI là mirror chính xác của các lệnh trên, có thêm
`/p:TreatWarningsAsErrors=true /p:WarningsAsErrors=nullable` —
chạy y hệt ở local trước khi mở PR.
## Release tooling
- **Velopack** (`vpk` CLI) — packaging + delta update.
- **`gh`** (GitHub CLI) — tạo Release, upload artifact, fetch SHA
(lookup SHA của reusable-workflow pin trong
[`docs/RELEASING.md`](../../RELEASING.md)).
- Xem [`docs/RELEASING.md`](../../RELEASING.md) cho chu trình end-to-end.
## Tài liệu liên quan
- [`pc_spec.md`](pc_spec.md) — tham chiếu phần cứng (bản VI).
- [`docs/ARCHITECTURE.md`](../../ARCHITECTURE.md) — kiến trúc phần
mềm (EN, chưa có bản VI).
- [`docs/CONTRIBUTORS.md`](../../CONTRIBUTORS.md) — chính sách đóng
góp (EN, chưa có bản VI).
- [`README.md`](../../../README.md) — tổng quan project.
+52
View File
@@ -0,0 +1,52 @@
# Cấu hình máy phát triển
Tài liệu này mô tả phần cứng tham chiếu mà CaptureImage được phát
triển và kiểm thử trên đó. Đây là snapshot của máy chính của
maintainer — **không** phải yêu cầu runtime cho end-user. Yêu cầu
cho người dùng cuối nằm trong
[README § Requirements](../../../README.md#requirements).
Bản tiếng Anh: [`docs/pc_spec.md`](../../pc_spec.md).
## Máy phát triển chính
| Component | Details |
|-------------|-------------------------------------------------------------------|
| **OS** | Windows 11 Pro 25H2 Insider Preview (Dev Channel), build 26300.8376 |
| **CPU** | Intel Core i7-14700KF |
| **GPU** | NVIDIA GeForce RTX 5080 (16 GB VRAM) |
| **RAM** | 32 GB DDR5 |
| **Storage** | 1 TB SSD |
| **IDE** | JetBrains 2026.x paid lineup (Rider cho repo này; PyCharm / WebStorm / RustRover cho các project anh em) + Visual Studio Code |
Việc dùng Windows Insider Dev Channel là có chủ đích — CaptureImage
khai thác bề mặt API mới nhất của `Windows.Graphics.Capture` và
hưởng lợi khi chạy trên build đi trước stable, nhờ vậy regression
trên các phiên bản public sắp tới được phát hiện sớm.
## Thiết bị test mobile
Một số project lân cận / tương lai sẽ ship một web companion nhỏ.
Khi phần đó được triển khai, browser test trên mobile sẽ chạy trên:
- **iPhone 14 Pro** (iOS 26.x)
- **iPhone 13 Pro Max** (iOS 26.x)
Browser test trên iOS: **Chrome**, **Brave**.
> **Ghi chú.** Bản thân CaptureImage là một desktop application
> Windows 11 (WinUI 3 / Windows App SDK), không có build iOS / web.
> Các thiết bị mobile ở trên được liệt kê để minh bạch về test fleet
> tổng thể của maintainer; không dùng để validate CaptureImage.
## Tài liệu liên quan
- [`dev_env.md`](dev_env.md) — phiên bản toolchain (Python, Node,
Rust, Git) và cấu hình IDE (bản VI).
- [`README.md` § Requirements](../../../README.md#requirements) —
yêu cầu runtime cho người dùng cuối (Windows 11 22H2+, không yêu
cầu GPU cụ thể).
- [`docs/ARCHITECTURE.md`](../../ARCHITECTURE.md) — kiến trúc phần
mềm (EN, chưa có bản VI).
- [`docs/RELEASING.md`](../../RELEASING.md) — quy trình release
(EN, chưa có bản VI).
+3 -2
View File
@@ -110,8 +110,9 @@ invited to open a pull request — see [`CONTRIBUTORS.md`](../CONTRIBUTORS.md).
## 5. Trademarks
"Steam", "Dota", "Counter-Strike", "Windows", "DirectX",
"Microsoft .NET", "Avalonia", "Velopack", "SkiaSharp", "ImageSharp",
"Serilog", "SharpHook", and any other third-party names that appear in the
"Microsoft .NET", "WinUI", "Windows App SDK", "Velopack", "SkiaSharp",
"ImageSharp", "Serilog", "SharpHook", and any other third-party names that
appear in the
source, documentation, or UI strings are trademarks or registered
trademarks of their respective owners. Their use in this project is for
identification purposes only and does not imply any affiliation with, or
+3 -2
View File
@@ -58,8 +58,9 @@ freely, subject to the GPL's attribution requirements.
Third-party trademarks that appear in the source code, documentation,
user interface, or release notes (including but not limited to Microsoft,
Windows, DirectX, Steam, Valve, Avalonia, Velopack, SkiaSharp, ImageSharp,
Serilog, SharpHook, GitHub) are property of their respective owners. They
Windows, DirectX, WinUI, Windows App SDK, Steam, Valve, Velopack,
SkiaSharp, ImageSharp, Serilog, SharpHook, GitHub) are property of their
respective owners. They
are referenced for identification and interoperability only. No
endorsement is implied.
+5 -6
View File
@@ -16,14 +16,13 @@ CaptureImage binary is distributed under.
| Package | License | Upstream |
|---|---|---|
| Avalonia | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Desktop | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Themes.Fluent | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Fonts.Inter | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Diagnostics | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Inter typeface | SIL Open Font License 1.1 | <https://github.com/rsms/inter> |
| Microsoft.WindowsAppSDK (WinUI 3) | MIT | <https://github.com/microsoft/WindowsAppSDK> |
| Microsoft.WindowsAppSDK.WinUI | MIT | <https://github.com/microsoft/WindowsAppSDK> |
| Microsoft.Windows.SDK.BuildTools | MIT | <https://github.com/microsoft/Windows.SDK.BuildTools> |
| H.NotifyIcon.WinUI | MIT | <https://github.com/HavenDV/H.NotifyIcon> |
| SkiaSharp | MIT | <https://github.com/mono/SkiaSharp> |
| SkiaSharp.NativeAssets.Win32 | MIT | <https://github.com/mono/SkiaSharp> |
| System.Drawing.Common | MIT | <https://github.com/dotnet/runtime> |
### MVVM + DI + logging
+49
View File
@@ -0,0 +1,49 @@
# Developer machine specification
This document describes the reference hardware CaptureImage is
developed and validated against. It is a snapshot of the maintainer's
primary development box — not a runtime requirement. End-user
requirements are listed in the project [README](../README.md#requirements).
A Vietnamese mirror of this document lives at
[docs/i18n/vi/pc_spec.md](i18n/vi/pc_spec.md).
## Primary development machine
| Component | Details |
|-------------|-------------------------------------------------------------------|
| **OS** | Windows 11 Pro 25H2 Insider Preview (Dev Channel), build 26300.8376 |
| **CPU** | Intel Core i7-14700KF |
| **GPU** | NVIDIA GeForce RTX 5080 (16 GB VRAM) |
| **RAM** | 32 GB DDR5 |
| **Storage** | 1 TB SSD |
| **IDE** | JetBrains 2026.x paid lineup (Rider for this repo; PyCharm / WebStorm / RustRover for sibling projects) + Visual Studio Code |
The Windows Insider Dev Channel build is intentional — CaptureImage
exercises the latest `Windows.Graphics.Capture` surface area and
benefits from running on builds ahead of stable so regressions on
upcoming public releases are caught early.
## Mobile test devices
Some adjacent / future projects ship a small web companion. When that
work lands, mobile browser testing is performed on:
- **iPhone 14 Pro** (iOS 26.x)
- **iPhone 13 Pro Max** (iOS 26.x)
Browsers under test on iOS: **Chrome**, **Brave**.
> **Note.** CaptureImage itself is a Windows 11 desktop application
> (WinUI 3 / Windows App SDK) and has no iOS / web build. The mobile
> devices above are listed for transparency about the maintainer's
> overall test fleet; they are not used to validate CaptureImage.
## Related documents
- [`docs/dev_env.md`](dev_env.md) — toolchain versions (Python, Node,
Rust, Git) and IDE configuration.
- [`README.md` § Requirements](../README.md#requirements) — end-user
runtime requirements (Windows 11 22H2+, no specific GPU needed).
- [`docs/ARCHITECTURE.md`](ARCHITECTURE.md) — software architecture.
- [`docs/RELEASING.md`](RELEASING.md) — release process.
Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Application
x:Class="CaptureImage.App.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="using:CaptureImage.UI.Converters">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
</ResourceDictionary.MergedDictionaries>
<!-- Globally-available converters. Declared at Application scope so any view's
{StaticResource X} lookup walks up the chain and finds them — local
Element.Resources scope hits a forward-reference issue when the host
element uses the converter on its own properties. See
feedback_winui3_resource_scope.md. -->
<conv:FlowDirectionConverter x:Key="FlowDirectionConverter" />
<conv:BytesToBitmapConverter x:Key="BytesToBitmapConverter" />
<conv:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<conv:InvertedBoolToVisibilityConverter x:Key="InvertedBoolToVisibilityConverter" />
<conv:NotNullToVisibilityConverter x:Key="NotNullToVisibilityConverter" />
<conv:ToastKindToBrushConverter x:Key="ToastKindToBrushConverter" />
<!-- Design tokens — port of the v1.2 Avalonia design-system comment block.
Keep the same scale (4/8/12/16/24 px spacing, 4/8 px corner radius) so the
view ports stay visually consistent with the v1.2 baseline.
FontFamily : Segoe UI Variable (Fluent 2 default — explicit for clarity).
Inter is dropped; Win11 native font carries the Fluent look.
FontSize : 11 (caption) / 12 (small) / 13 (body) / 14 (body-strong) /
16 (subtitle) / 22 (title).
CornerRadius: 8 px for cards/borders/containers, 4 px for inline pills.
Spacing : 4 / 8 / 12 / 16 / 24 px scale.
Contrast : secondary text uses TextFillColorSecondaryBrush, not
Opacity=0.6 — the theme brush keeps WCAG AA on light/dark.
-->
<FontFamily x:Key="BodyFontFamily">Segoe UI Variable Display</FontFamily>
<x:Double x:Key="FontSizeCaption">11</x:Double>
<x:Double x:Key="FontSizeSmall">12</x:Double>
<x:Double x:Key="FontSizeBody">13</x:Double>
<x:Double x:Key="FontSizeBodyStrong">14</x:Double>
<x:Double x:Key="FontSizeSubtitle">16</x:Double>
<x:Double x:Key="FontSizeTitle">22</x:Double>
<x:Double x:Key="SpacingXSmall">4</x:Double>
<x:Double x:Key="SpacingSmall">8</x:Double>
<x:Double x:Key="SpacingMedium">12</x:Double>
<x:Double x:Key="SpacingLarge">16</x:Double>
<x:Double x:Key="SpacingXLarge">24</x:Double>
<CornerRadius x:Key="PillCornerRadius">4</CornerRadius>
<CornerRadius x:Key="CardCornerRadius">8</CornerRadius>
</ResourceDictionary>
</Application.Resources>
</Application>
+81
View File
@@ -0,0 +1,81 @@
using CaptureImage.App.SingleInstance;
using CaptureImage.Core.Abstractions;
using CaptureImage.UI.Services;
using CaptureImage.UI.Views;
using CaptureImage.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Serilog;
namespace CaptureImage.App;
/// <summary>
/// WinUI 3 Application root. Holds the static <see cref="Services"/> handle so view-models
/// resolved from XAML data templates can reach the DI container; <see cref="OnLaunched"/>
/// binds the UI dispatcher and shows the first window.
/// </summary>
public partial class App : Application
{
/// <summary>
/// Service provider populated by <c>Program.Main</c> before <see cref="Application.Start"/>
/// returns. View-models and converters resolve through this.
/// </summary>
public static IServiceProvider? Services { get; set; }
private Window? _window;
private ActivationListener? _activationListener;
public App()
{
InitializeComponent();
UnhandledException += OnUnhandledException;
}
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
var services = Services
?? throw new InvalidOperationException(
"App.Services must be assigned before Application.Start runs.");
// Bind the WinUI 3 dispatcher now that we are on the UI thread.
var dispatcher = services.GetRequiredService<WinUIThreadDispatcher>();
dispatcher.Bind(DispatcherQueue.GetForCurrentThread());
var vm = services.GetRequiredService<MainWindowViewModel>();
var mainWindow = new MainWindow();
mainWindow.SetViewModel(vm);
// Stash the main window on a UI-side static accessor so Pages (which can't
// reference back into CaptureImage.App) can reach the host HWND for
// FolderPicker / FilePicker InitializeWithWindow calls.
WindowHostHelper.MainWindow = mainWindow;
_window = mainWindow;
// Apply persisted theme before first paint, then keep it in sync with settings.
var settings = services.GetRequiredService<ISettingsStore>();
mainWindow.ApplyTheme(settings.Current.Theme);
settings.Changed += (_, _) => mainWindow.ApplyTheme(settings.Current.Theme);
_window.Activate();
// Tray host attaches to the live Window. M1 ships a no-op stub; M6 wires the real
// H.NotifyIcon.WindowsAppSDK implementation.
var tray = services.GetRequiredService<ITrayIconHost>();
tray.Initialize(_window);
// Listen for ACTIVATE messages from secondary launches so a double-click on
// the shortcut restores this instance instead of orphaning a new one. The
// listener owns its own background task; disposed via the IServiceProvider
// chain at shutdown (registered just below).
_activationListener = ActivationListener.Start(
_window,
services.GetRequiredService<IUIThreadDispatcher>());
_window.Closed += (_, _) => _activationListener?.Dispose();
}
private static void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "Unhandled exception on UI dispatcher.");
e.Handled = true;
}
}
+38 -6
View File
@@ -8,17 +8,24 @@
<AssemblyName>CaptureImage.App</AssemblyName>
<UseWindowsForms>false</UseWindowsForms>
<UseWpf>false</UseWpf>
<!-- App icon + manifest are added in M4 -->
<UseWinUI>true</UseWinUI>
<EnableMsixTooling>false</EnableMsixTooling>
<WindowsPackageType>None</WindowsPackageType>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
<Platforms>x64</Platforms>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<DefineConstants>$(DefineConstants);DISABLE_XAML_GENERATED_MAIN</DefineConstants>
<Version>1.5.1</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Diagnostics" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.WindowsAppSDK" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" />
<PackageReference Include="Serilog" />
<PackageReference Include="Serilog.Extensions.Hosting" />
<PackageReference Include="Serilog.Extensions.Logging" />
@@ -34,9 +41,34 @@
<ProjectReference Include="..\CaptureImage.UI\CaptureImage.UI.csproj" />
</ItemGroup>
<!-- Ship the legal and docs files next to the binary so the About tab can open them
with Process.Start. Links to the repo-root docs/ folder so there's a single source
of truth; content is copied into bin/.../docs/... at build time. -->
<!-- HOTFIX v1.3.1: WinUI 3 publish pipeline misses two file types when building
a self-contained unpackaged app via `dotnet publish`:
1. .xbf files — compiled XAML binary format produced by the WinUI 3 XAML
compiler. Without them, Application.LoadComponent fails on every
ms-appx:/// XAML reference at runtime with XamlParseException.
2. CaptureImage.App.pri — the app's compiled resource manifest. Without it,
Windows can't resolve ms-appx:/// URIs at all (incl. WinAppSDK theme
resources like ms-appx:///Microsoft.UI.Xaml/Themes/themeresources.xaml).
Both files are produced into bin/.../win-x64/ during build but `dotnet publish`
skips them in self-contained mode. v1.3.0 shipped without either and the
window never appeared (silent UI-thread crash; process stayed alive zombie).
This target adds every .xbf and .pri from $(OutDir) to the published file set,
preserving the CaptureImage.UI/Controls and CaptureImage.UI/Views subfolders
the XAML compiler creates for cross-assembly XAML resolution. -->
<Target Name="CopyWinUIArtifactsToPublishDirectory" AfterTargets="ComputeFilesToPublish">
<ItemGroup>
<_WinUIArtifactsToPublish Include="$(OutDir)**\*.xbf" />
<_WinUIArtifactsToPublish Include="$(OutDir)$(AssemblyName).pri" />
<ResolvedFileToPublish Include="@(_WinUIArtifactsToPublish)">
<RelativePath>%(RecursiveDir)%(Filename)%(Extension)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
<ItemGroup>
<Content Include="..\..\docs\legal\DISCLAIMER.md" Link="docs\legal\DISCLAIMER.md" CopyToOutputDirectory="PreserveNewest" />
<Content Include="..\..\docs\legal\PRIVACY.md" Link="docs\legal\PRIVACY.md" CopyToOutputDirectory="PreserveNewest" />
+25 -7
View File
@@ -1,4 +1,3 @@
using System;
using System.IO.Abstractions;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Pipeline;
@@ -6,6 +5,7 @@ using CaptureImage.Infrastructure.Capture;
using CaptureImage.Infrastructure.Hotkeys;
using CaptureImage.Infrastructure.Imaging;
using CaptureImage.Infrastructure.Logging;
using CaptureImage.Infrastructure.Ocr;
using CaptureImage.Infrastructure.Processes;
using CaptureImage.Infrastructure.Settings;
using CaptureImage.Infrastructure.Steam;
@@ -22,6 +22,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 +32,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,17 +41,27 @@ 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>();
services.AddSingleton<IUIThreadDispatcher, AvaloniaUIDispatcher>();
// Concrete WinUIThreadDispatcher exposed both as itself (so App.OnLaunched can call
// Bind() with the live DispatcherQueue) and behind the portable IUIThreadDispatcher
// contract (so VMs/services keep their abstraction).
services.AddSingleton<WinUIThreadDispatcher>();
services.AddSingleton<IUIThreadDispatcher>(sp => sp.GetRequiredService<WinUIThreadDispatcher>());
services.AddSingleton<ILocalizationService, ResxLocalizationService>();
// --- Settings ----------------------------------------------------------
@@ -65,6 +76,7 @@ internal static class CompositionRoot
services.AddSingleton<IconExtractor>();
services.AddSingleton<IProcessDetector, GameDetector>();
services.AddSingleton<IProcessWatcher, WmiProcessWatcher>();
services.AddSingleton<IForegroundWindowWatcher, Win32ForegroundWindowWatcher>();
// --- Capture engine + encoders -----------------------------------------
services.AddSingleton<D3D11DeviceManager>();
@@ -73,19 +85,24 @@ 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 -----------------------------------------------------------
services.AddSingleton<IHotkeyService, SharpHookHotkeyService>();
services.AddSingleton<IHotkeyConflictSniffer, HotkeyConflictSniffer>();
// --- Updates -----------------------------------------------------------
services.AddSingleton<IUpdateService, VelopackUpdateService>();
// --- UI-side services (toasts, preview, tray) --------------------------
services.AddSingleton<IToastService, ToastService>();
services.AddSingleton<IPreviewPresenter, AvaloniaPreviewPresenter>();
services.AddSingleton<ITrayIconHost, AvaloniaTrayIconHost>();
services.AddSingleton<IPreviewPresenter, PreviewPresenter>();
services.AddSingleton<ITrayIconHost, TrayIconHost>();
services.AddSingleton<IClipboardService, WinAppSDKClipboardService>();
services.AddSingleton<IPinnedThumbnailHost, PinnedThumbnailHost>();
services.AddSingleton<IOcrService, WindowsOcrService>();
services.AddSingleton<IRegionCaptureService, WindowsRegionCaptureService>();
// --- Navigation --------------------------------------------------------
services.AddSingleton<INavigationService, NavigationService>();
@@ -94,6 +111,7 @@ internal static class CompositionRoot
services.AddSingleton<MainWindowViewModel>();
services.AddSingleton<DashboardViewModel>();
services.AddSingleton<UpdateViewModel>();
services.AddSingleton<HotkeyBindingViewModel>();
services.AddSingleton<SettingsViewModel>();
services.AddSingleton<AboutViewModel>();
services.AddSingleton<LogViewerViewModel>();
+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,
};
}
+121
View File
@@ -0,0 +1,121 @@
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="CaptureImage.App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:CaptureImage.UI.Views"
xmlns:controls="using:CaptureImage.UI.Controls"
mc:Ignorable="d">
<Grid x:Name="Root"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={StaticResource FlowDirectionConverter}}">
<Grid.RowDefinitions>
<!-- Title-bar drag region. Reserve 48 px so the OS-drawn caption buttons
(minimize / maximize / close) don't overlap the NavigationView pane
header, the LogViewer drawer, or any Page content. AppTitleBar is
marked as the window's title bar via Window.SetTitleBar in code-behind. -->
<RowDefinition Height="48" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Grid.Row="0" x:Name="AppTitleBar" Background="Transparent" />
<!-- Body grid: 2 columns so the LogViewer drawer can sit in a dedicated 480 px
column on the trailing edge instead of relying on HorizontalAlignment="Right",
which WinUI 3 doesn't honour reliably on first measure (the drawer would
render on the leading edge until a window resize forced a relayout). -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="480" />
</Grid.ColumnDefinitions>
<NavigationView
Grid.ColumnSpan="2"
x:Name="NavView"
IsBackButtonVisible="Collapsed"
IsSettingsVisible="False"
PaneDisplayMode="Left"
OpenPaneLength="220"
MenuItemsSource="{Binding NavItems}"
SelectedItem="{Binding SelectedNavItem, Mode=TwoWay}"
SelectionChanged="NavView_SelectionChanged">
<NavigationView.PaneHeader>
<StackPanel Margin="12,8,12,8">
<TextBlock
Text="{Binding AppTitle}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<TextBlock
Text="{Binding AppVersion}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Margin="0,4,0,0" />
</StackPanel>
</NavigationView.PaneHeader>
<NavigationView.MenuItemTemplate>
<DataTemplate>
<NavigationViewItem Content="{Binding Label}">
<NavigationViewItem.Icon>
<FontIcon
Glyph="{Binding IconGlyph}"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" />
</NavigationViewItem.Icon>
</NavigationViewItem>
</DataTemplate>
</NavigationView.MenuItemTemplate>
<NavigationView.PaneFooter>
<Button
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Margin="8,4,8,16"
Padding="12,8"
Background="Transparent"
BorderThickness="0"
Command="{Binding ToggleLogViewerCommand}"
ToolTipService.ToolTip="{Binding LogToggleTooltip}"
AutomationProperties.Name="{Binding LogToggleTooltip}">
<StackPanel Orientation="Horizontal" Spacing="12">
<FontIcon
Glyph="&#xE9F9;"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets"
FontSize="16" />
<TextBlock
Text="{Binding LogToggleLabel}"
FontFamily="{StaticResource BodyFontFamily}"
VerticalAlignment="Center" />
</StackPanel>
</Button>
</NavigationView.PaneFooter>
<Frame x:Name="ContentFrame" />
</NavigationView>
<!-- Log viewer drawer overlay — pinned to Column 1 (trailing edge under LTR,
leading under RTL — FlowDirection mirrors). Stays in the visual tree
always so the slide-in Composition animation has something to act on
every toggle. Initial collapsed state (Offset = ±48 px X, Opacity = 0,
IsHitTestVisible = false) is set in MainWindow.OnRootLoaded. -->
<views:LogViewerView
Grid.Column="1"
x:Name="LogDrawer"
DataContext="{Binding LogViewer}" />
<!-- Toast overlay — anchored bottom of the trailing edge column. Spans both
columns so MaxWidth + alignment can position it freely. -->
<controls:ToastHost
Grid.ColumnSpan="2"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Margin="0,0,20,20"
IsHitTestVisible="True" />
</Grid>
</Grid>
</Window>
+177
View File
@@ -0,0 +1,177 @@
using System.ComponentModel;
using System.Numerics;
using CaptureImage.UI.Theming;
using CaptureImage.UI.Views;
using CaptureImage.ViewModels;
using CaptureImage.ViewModels.Navigation;
using Microsoft.UI;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Hosting;
using Microsoft.UI.Xaml.Media;
using Windows.Graphics;
using WinRT.Interop;
namespace CaptureImage.App;
public sealed partial class MainWindow : Window
{
// Logical dimensions carried over from v1.2-M7. AppWindow.Resize takes physical
// pixels — DPI scaling refinement is deferred to v1.4 polish.
private const int InitialWidth = 1200;
private const int InitialHeight = 720;
// How far the drawer is pushed off-screen when collapsed. Matches v1.2's translateX(48px).
// The sign flips under RTL so the drawer always slides in toward its anchored edge.
private const float DrawerOffsetX = 48f;
// Show/hide timing matches v1.2-M7 (220 ms slide, 180 ms fade, CircularEaseOut-ish).
private static readonly TimeSpan SlideDuration = TimeSpan.FromMilliseconds(220);
private static readonly TimeSpan FadeDuration = TimeSpan.FromMilliseconds(180);
public MainWindow()
{
InitializeComponent();
Title = "CaptureImage";
SystemBackdrop = new MicaBackdrop { Kind = MicaKind.Base };
ExtendsContentIntoTitleBar = true;
SetTitleBar(AppTitleBar);
var hwnd = WindowNative.GetWindowHandle(this);
var windowId = Win32Interop.GetWindowIdFromWindow(hwnd);
var appWindow = AppWindow.GetFromWindowId(windowId);
appWindow.Resize(new SizeInt32(InitialWidth, InitialHeight));
if (appWindow.Presenter is OverlappedPresenter presenter)
{
presenter.IsMaximizable = false;
presenter.IsResizable = false;
}
Root.Loaded += OnRootLoaded;
}
public MainWindowViewModel? ViewModel { get; private set; }
/// <summary>
/// Apply the persisted theme preference to the window root. <c>System</c> falls back
/// to <see cref="ElementTheme.Default"/> which lets the OS theme drive everything,
/// including Mica. Called at startup and whenever <c>ISettingsStore.Changed</c> fires.
/// Safe to call from any thread — <see cref="ThemeApplicator"/> hops to the dispatcher.
/// </summary>
public void ApplyTheme(string theme) => ThemeApplicator.Apply(Content as FrameworkElement, theme);
public void SetViewModel(MainWindowViewModel vm)
{
if (ViewModel is not null)
{
ViewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
ViewModel = vm;
Root.DataContext = vm;
vm.PropertyChanged += OnViewModelPropertyChanged;
if (vm.SelectedNavItem is { } first)
{
NavigateToNavItem(first);
}
}
private void OnRootLoaded(object sender, RoutedEventArgs e)
{
// Enable the Composition `Translation` property on the drawer's visual. WITHOUT
// this, animating Translation has no effect. WITH it, Translation is added on
// top of the layout-computed position — which is what we want: the drawer stays
// pinned to Grid.Column=1 (right 480 px) while Translation supplies the slide
// offset. Setting `visual.Offset` directly (the v1.3-M5 approach) OVERRODE
// layout position and made the drawer render from x=±48 absolute, ignoring its
// Grid cell.
ElementCompositionPreview.SetIsTranslationEnabled(LogDrawer, true);
var visual = ElementCompositionPreview.GetElementVisual(LogDrawer);
// Seed Translation to the collapsed offset; subsequent toggles animate via
// visual.StartAnimation("Translation", ...).
visual.Properties.InsertVector3("Translation", new Vector3(GetCollapsedOffsetX(), 0f, 0f));
visual.Opacity = 0f;
LogDrawer.IsHitTestVisible = false;
}
private float GetCollapsedOffsetX() =>
Root.FlowDirection == FlowDirection.RightToLeft ? -DrawerOffsetX : DrawerOffsetX;
private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (args.SelectedItem is NavItemViewModel item)
{
NavigateToNavItem(item);
}
}
private void NavigateToNavItem(NavItemViewModel item)
{
var pageType = item.Key switch
{
"dashboard" => typeof(DashboardPage),
"update" => typeof(UpdatePage),
"settings" => typeof(SettingsPage),
"about" => typeof(AboutPage),
_ => null,
};
if (pageType is not null && ContentFrame.CurrentSourcePageType != pageType)
{
ContentFrame.Navigate(pageType, App.Services);
}
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (ViewModel is null) return;
if (e.PropertyName == nameof(MainWindowViewModel.IsLogViewerVisible))
{
if (ViewModel.IsLogViewerVisible) ShowLogDrawer();
else HideLogDrawer();
}
}
private void ShowLogDrawer()
{
LogDrawer.IsHitTestVisible = true;
AnimateDrawer(targetTranslationX: 0f, targetOpacity: 1f);
}
private void HideLogDrawer()
{
AnimateDrawer(targetTranslationX: GetCollapsedOffsetX(), targetOpacity: 0f);
LogDrawer.IsHitTestVisible = false;
}
private void AnimateDrawer(float targetTranslationX, float targetOpacity)
{
var visual = ElementCompositionPreview.GetElementVisual(LogDrawer);
var compositor = visual.Compositor;
// CubicBezier(0.4, 0, 0.2, 1) — Material/Fluent decelerate. Visually
// indistinguishable from v1.2's Avalonia CircularEaseOut for sub-300ms motion.
var easing = compositor.CreateCubicBezierEasingFunction(
new Vector2(0.4f, 0f), new Vector2(0.2f, 1f));
// Animate Translation (an additive transform that respects layout) instead of
// Offset (which overrides layout). Target name "Translation" routes through the
// Properties dictionary set up in OnRootLoaded.
var translationAnim = compositor.CreateVector3KeyFrameAnimation();
translationAnim.InsertKeyFrame(1f, new Vector3(targetTranslationX, 0f, 0f), easing);
translationAnim.Duration = SlideDuration;
translationAnim.Target = "Translation";
visual.StartAnimation("Translation", translationAnim);
var opacityAnim = compositor.CreateScalarKeyFrameAnimation();
opacityAnim.InsertKeyFrame(1f, targetOpacity, easing);
opacityAnim.Duration = FadeDuration;
visual.StartAnimation("Opacity", opacityAnim);
}
}
+103 -28
View File
@@ -1,8 +1,8 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using CaptureImage.App.SingleInstance;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Serilog;
using Velopack;
@@ -17,39 +17,76 @@ internal static class Program
/// <see cref="VelopackApp.Build"/> MUST be the very first thing <see cref="Main"/> does.
/// The Velopack installer passes command-line arguments like <c>--squirrel-install</c>,
/// <c>--squirrel-firstrun</c>, and <c>--squirrel-uninstall</c> on the first launch after an
/// install/update/uninstall event; these need to be handled before Avalonia boots,
/// install/update/uninstall event; these need to be handled before WinUI 3 boots,
/// otherwise the installer will hang waiting for the previous instance to exit.
/// </remarks>
[STAThread]
public static int Main(string[] args)
{
// Velopack first — runs hooks for install/firstrun/update/uninstall and returns only
// 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();
// Single-instance guard runs AFTER Velopack hooks so installer/uninstaller
// launches (--squirrel-*) aren't blocked. If another instance owns the
// mutex, we ping it via named pipe (ActivationListener restores its
// window) and exit immediately without bringing up our own UI.
if (!SingleInstanceGuard.TryAcquire(out var instanceReleaser))
{
return 0;
}
using var _instanceReleaser = instanceReleaser;
var (inMemorySink, loggingLevelSwitch) = LoggingSetup.Initialize();
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);
UI.App.Services = services;
var services = CompositionRoot.BuildServices(inMemorySink, loggingLevelSwitch);
App.Services = services;
// Load persisted settings before the UI binds to them.
var settingsStore = services.GetRequiredService<ISettingsStore>();
settingsStore.LoadAsync().GetAwaiter().GetResult();
// Apply persisted culture before the first window is constructed so nav labels etc.
// render in the right language from frame zero.
var configuredLevel = LoggingSetup.ParseLevel(settingsStore.Current.LogLevel);
loggingLevelSwitch.MinimumLevel = configuredLevel;
Log.Information("Log level set to {Level} from settings.", configuredLevel);
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)
{
@@ -57,22 +94,33 @@ internal static class Program
}
}
return BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
// WinUI 3 entry point. Application.Start blocks until the dispatcher exits. The
// callback runs once on the freshly-minted UI thread before any Window is shown
// — install a SynchronizationContext that flows back to that thread so async
// continuations land where bindings can see them.
Application.Start(p =>
{
var ctx = new DispatcherQueueSynchronizationContext(
DispatcherQueue.GetForCurrentThread());
SynchronizationContext.SetSynchronizationContext(ctx);
_ = new App();
});
return 0;
}
catch (Exception ex)
{
shutdownReason = "StartupCrash";
Log.Fatal(ex, "CaptureImage crashed during startup.");
return -1;
}
finally
{
// Flush any pending settings writes and close the logger.
try
{
if (UI.App.Services is not null)
if (App.Services is not null)
{
var store = UI.App.Services.GetService<ISettingsStore>();
var store = App.Services.GetService<ISettingsStore>();
if (store is not null)
{
store.FlushAsync().GetAwaiter().GetResult();
@@ -83,16 +131,43 @@ internal static class Program
{
Log.Warning(ex, "Failed to flush settings on shutdown.");
}
// Dispose the DI container so every IDisposable singleton runs its cleanup —
// most importantly WmiProcessWatcher (WMI subscriptions on non-background
// threads), Win32ForegroundWindowWatcher (WinEventHook), and TrayIconHost.
// Without this, the process can't fully exit and Task Manager accumulates one
// zombie CaptureImage.exe per launch.
try
{
(App.Services as IDisposable)?.Dispose();
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to dispose service provider on shutdown.");
}
Log.Information("CaptureImage shutting down. Reason={Reason}", shutdownReason);
Log.CloseAndFlush();
}
}
/// <summary>
/// Avalonia AppBuilder. Also used by the Avalonia designer — do not do expensive work here.
/// </summary>
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<UI.App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace();
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)
{
Log.CloseAndFlush();
}
};
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error(e.Exception, "Unobserved task exception.");
e.SetObserved();
};
}
}
@@ -0,0 +1,115 @@
using System.IO.Pipes;
using System.Runtime.InteropServices;
using CaptureImage.Core.Abstractions;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Serilog;
using WinRT.Interop;
namespace CaptureImage.App.SingleInstance;
/// <summary>
/// Background listener for the single-instance ACTIVATE pipe. When a secondary launch
/// fires <see cref="SingleInstanceGuard.ActivateMessage"/>, this brings the main window
/// back to the foreground — same restore sequence the tray icon uses
/// (<c>AppWindow.Show</c> + <c>ShowWindow(SW_RESTORE)</c> + <c>SetForegroundWindow</c>).
/// </summary>
internal sealed class ActivationListener : IDisposable
{
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;
private readonly Window _mainWindow;
private readonly IUIThreadDispatcher _dispatcher;
private readonly CancellationTokenSource _cts = new();
private readonly Task _loop;
private bool _disposed;
private ActivationListener(Window mainWindow, IUIThreadDispatcher dispatcher)
{
_mainWindow = mainWindow;
_dispatcher = dispatcher;
_loop = Task.Run(() => RunAsync(_cts.Token));
}
/// <summary>Start listening; returns the listener so it can be disposed on shutdown.</summary>
public static ActivationListener Start(Window mainWindow, IUIThreadDispatcher dispatcher)
=> new(mainWindow, dispatcher);
private async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(
pipeName: SingleInstanceGuard.PipeName,
direction: PipeDirection.In,
maxNumberOfServerInstances: 1,
transmissionMode: PipeTransmissionMode.Byte,
options: PipeOptions.Asynchronous);
await server.WaitForConnectionAsync(ct).ConfigureAwait(false);
using var reader = new StreamReader(server);
var line = await reader.ReadLineAsync(ct).ConfigureAwait(false);
if (string.Equals(line, SingleInstanceGuard.ActivateMessage, StringComparison.Ordinal))
{
_dispatcher.Post(RestoreWindow);
}
}
catch (OperationCanceledException)
{
// Shutdown — exit cleanly.
return;
}
catch (Exception ex)
{
Log.Warning(ex, "ActivationListener pipe iteration failed; will retry.");
// Avoid a hot loop if the pipe is in a bad state — yield briefly.
try { await Task.Delay(500, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
}
}
private void RestoreWindow()
{
try
{
var hwnd = WindowNative.GetWindowHandle(_mainWindow);
var windowId = Win32Interop.GetWindowIdFromWindow(hwnd);
var appWindow = AppWindow.GetFromWindowId(windowId);
// Mirror TrayIconHost.ShowMainWindow: AppWindow.Show un-hides if minimised
// to tray, ShowWindow(SW_RESTORE) un-minimises a taskbar-minimised window,
// and SetForegroundWindow forces Z-order to top even if another app has focus.
appWindow.Show();
ShowWindow(hwnd, SW_RESTORE);
_mainWindow.Activate();
SetForegroundWindow(hwnd);
Log.Debug("Main window restored from secondary launch ACTIVATE.");
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to restore main window on ACTIVATE.");
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { _cts.Cancel(); }
catch { /* swallow */ }
try { _loop.Wait(TimeSpan.FromSeconds(1)); }
catch { /* shutdown — best effort */ }
_cts.Dispose();
}
}
@@ -0,0 +1,99 @@
using System.IO.Pipes;
using Serilog;
namespace CaptureImage.App.SingleInstance;
/// <summary>
/// Per-user single-instance gate. The first process to call <see cref="TryAcquire"/>
/// wins the named mutex and returns a releaser to be held for the lifetime of the
/// app. Any subsequent launch fails the acquire, fires an ACTIVATE message at the
/// existing instance over a named pipe, and exits — the user perceives a restored
/// window instead of a duplicate process.
///
/// Mutex + pipe names are scoped to the local user session so two different OS
/// users on the same machine each get their own primary instance.
/// </summary>
internal static class SingleInstanceGuard
{
public const string PipeName = "CaptureImage.Activate";
public const string ActivateMessage = "ACTIVATE";
private static readonly string MutexName =
$"Local\\CaptureImage.SingleInstance.{Environment.UserName}";
/// <summary>
/// Try to become the primary instance. Returns true and yields a disposable
/// releaser when this process owns the mutex. Returns false if another instance
/// already holds it — in that case an ACTIVATE message is fired over the
/// named pipe (best effort) so the existing instance restores its window.
/// </summary>
public static bool TryAcquire(out IDisposable releaser)
{
var mutex = new Mutex(initiallyOwned: false, name: MutexName);
bool acquired;
try
{
// Short timeout — if another instance is alive it should already own the
// mutex; if it's hung we don't want to block startup waiting for it.
acquired = mutex.WaitOne(TimeSpan.FromMilliseconds(100), exitContext: false);
}
catch (AbandonedMutexException)
{
// Previous instance exited without releasing (crash, kill, etc.). The
// OS hands us ownership anyway — treat as acquired.
Log.Warning("Single-instance mutex was abandoned by a previous process; taking ownership.");
acquired = true;
}
if (acquired)
{
releaser = new MutexReleaser(mutex);
return true;
}
// Best-effort: poke the existing instance to restore its window. Failure
// here is non-fatal — even if the pipe send fails, the user can still
// click the tray icon to restore the running instance.
try
{
using var client = new NamedPipeClientStream(
serverName: ".",
pipeName: PipeName,
direction: PipeDirection.Out);
client.Connect(timeout: 1000);
using var writer = new StreamWriter(client) { AutoFlush = true };
writer.WriteLine(ActivateMessage);
Log.Information("Existing CaptureImage instance detected — sent ACTIVATE and exiting.");
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to ping existing instance over named pipe; user must restore manually.");
}
mutex.Dispose();
releaser = NoopReleaser.Instance;
return false;
}
private sealed class MutexReleaser : IDisposable
{
private Mutex? _mutex;
public MutexReleaser(Mutex mutex) => _mutex = mutex;
public void Dispose()
{
if (_mutex is null) return;
try { _mutex.ReleaseMutex(); }
catch (ApplicationException) { /* not owned — race on shutdown */ }
_mutex.Dispose();
_mutex = null;
}
}
private sealed class NoopReleaser : IDisposable
{
public static readonly NoopReleaser Instance = new();
public void Dispose() { }
}
}
@@ -1,5 +1,3 @@
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -0,0 +1,22 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Abstraction over the OS clipboard so portable code can copy a captured image
/// without taking a Windows.* / WinAppSDK dependency. The UI project supplies the
/// real implementation; tests can inject a fake.
/// </summary>
public interface IClipboardService
{
/// <summary>
/// Copy the given PNG-encoded image bytes to the clipboard as a bitmap.
/// Best-effort: returns <c>false</c> if the clipboard is locked or the data
/// can't be set (the caller may surface a toast but should not crash).
/// </summary>
Task<bool> CopyImageAsync(byte[] pngBytes, CancellationToken cancellationToken = default);
/// <summary>
/// Copy plain text to the clipboard. Used by the OCR pipeline to deliver extracted
/// text. Returns <c>false</c> on clipboard contention.
/// </summary>
bool CopyText(string text);
}
@@ -0,0 +1,31 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Watches the system-wide foreground window and reports changes. Used by the dashboard
/// to auto-switch the selected target when the user Alt-Tabs to another app. Implementations
/// must filter out the host process's own windows and debounce rapid switches so the UI
/// only reacts after the user lands on a window.
/// </summary>
public interface IForegroundWindowWatcher : IDisposable
{
/// <summary>
/// Fires when the foreground window changes — after debouncing and self-process
/// filtering. Subscribers may run on any thread; marshal to the UI thread before
/// touching bindings.
/// </summary>
event EventHandler<nint>? ForegroundChanged;
/// <summary><c>true</c> while the underlying hook is registered.</summary>
bool IsRunning { get; }
/// <summary>
/// Register the foreground hook. Idempotent — calling while already running is a
/// no-op. Must be called from a thread with a message pump (the WinUI 3 UI thread)
/// because SetWinEventHook with WINEVENT_OUTOFCONTEXT routes callbacks via posted
/// messages.
/// </summary>
void Start();
/// <summary>Unhook and stop reporting events. Safe to call repeatedly.</summary>
void Stop();
}
@@ -0,0 +1,21 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Platform-neutral test: is this hotkey binding already owned by another process?
/// Implementations perform a best-effort check (e.g. Windows <c>RegisterHotKey</c> sniff)
/// and immediately release any claim they take — they must never leave the combination
/// bound after the call returns.
/// </summary>
public interface IHotkeyConflictSniffer
{
/// <summary>
/// <c>true</c> if the combination is already registered by another process or the
/// shell; <c>false</c> if we successfully (and transiently) claimed it. Returning
/// <c>false</c> does not prove the combination will work — the Windows shell has
/// higher priority and consumes some combos before <c>RegisterHotKey</c> is consulted
/// (see <see cref="Validation.ReservedHotkeys"/>).
/// </summary>
bool IsConflicted(HotkeyBinding binding);
}
@@ -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; }
}
@@ -0,0 +1,27 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Result of an OCR pass over a captured image.
/// </summary>
/// <param name="Text">Extracted text in reading order. Empty if no glyphs were recognised.</param>
/// <param name="AverageConfidence">0.0–1.0; 0 if no engine was available.</param>
/// <param name="EngineAvailable">
/// <c>false</c> when the OS has no recognizer pack installed for the requested language
/// (and no usable fallback). UIs should disable the action and surface a hint.
/// </param>
public sealed record OcrResult(string Text, double AverageConfidence, bool EngineAvailable);
/// <summary>
/// Offline OCR. Wraps the OS-supplied <c>Windows.Media.Ocr</c> engine on the
/// implementation side; abstracted here so the portable VM layer can stay free of
/// WinRT references and test fakes can stub it.
/// </summary>
public interface IOcrService
{
/// <summary>
/// Recognise text from the given PNG-encoded image. <paramref name="languageTag"/>
/// is a BCP-47 hint (e.g. <c>en-US</c>); <c>null</c> defers to the user's profile
/// languages, falling back to en-US, then to <see cref="OcrResult.EngineAvailable"/>=false.
/// </summary>
Task<OcrResult> RecognizeAsync(byte[] pngBytes, string? languageTag, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,17 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Spawns a small always-on-top window holding a thumbnail of the most recent capture.
/// Each call creates a fresh window so users can keep multiple captures pinned and
/// compare them side-by-side. Implementation lives in the UI project.
/// </summary>
public interface IPinnedThumbnailHost
{
/// <summary>
/// Show a new pinned thumbnail. <paramref name="pngBytes"/> is the encoded image,
/// <paramref name="filePath"/> is the file the capture was written to (may be null
/// if clipboard-only mode skipped the save), and <paramref name="targetName"/> is
/// the display name shown in the title for context.
/// </summary>
void Show(byte[] pngBytes, string? filePath, string targetName);
}
@@ -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;
@@ -0,0 +1,13 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Capture an arbitrary rectangular region of the desktop. Implementations show an
/// overlay so the user can drag-select; <c>null</c> means the user cancelled (Esc /
/// click outside / overlay closed).
/// </summary>
public interface IRegionCaptureService
{
Task<CapturedFrame?> SelectAndCaptureAsync(CancellationToken cancellationToken = default);
}
@@ -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,296 @@
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,
};
}
+24
View File
@@ -0,0 +1,24 @@
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;
}
}
+57 -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>
@@ -60,6 +73,36 @@ public sealed record CaptureSettings
/// lands on disk. When <c>false</c>, captures are saved immediately.
/// </summary>
public bool PreviewBeforeSave { get; init; } = false;
/// <summary>
/// When <c>true</c>, the dashboard's selected target follows the OS foreground window —
/// Alt-Tab to a target and CaptureImage re-selects it automatically. Off by default to
/// keep behaviour predictable for users who curate the list manually.
/// </summary>
public bool AutoSwitchOnAltTab { get; init; } = false;
/// <summary>
/// Optional countdown in seconds before the actual capture fires after the hotkey is
/// pressed. <c>0</c> = disabled (default — capture immediately). Valid values are
/// 0, 3, 5, 10. Useful for capturing tooltips, hover states, or menu open/close
/// animations that disappear when you Alt-Tab back.
/// </summary>
public int CountdownSeconds { get; init; } = 0;
/// <summary>
/// Clipboard side-effect on save. Stored as a string for forward compatibility:
/// <c>None</c> (default) = file only, <c>Copy</c> = clipboard only (no file written),
/// <c>CopyAndSave</c> = both. Anything else falls back to <c>None</c>.
/// </summary>
public string ClipboardMode { get; init; } = "None";
/// <summary>
/// Capture mode. <c>Window</c> (default) captures the dashboard's selected target via
/// Windows.Graphics.Capture; <c>Region</c> opens a full-screen overlay so the user
/// drags a rectangle. v1.5 supports the primary monitor only — multi-monitor lands
/// in v1.6.
/// </summary>
public string Mode { get; init; } = "Window";
}
/// <summary>UI / behaviour preferences not tied to a specific tab.</summary>
@@ -72,4 +115,17 @@ public sealed record UiSettings
public bool ShowLogViewer { get; init; } = false;
public bool SoundEnabled { get; init; } = true;
/// <summary>
/// Open the output folder in Explorer after each successful save. Off by default —
/// most users prefer not to be interrupted while gaming.
/// </summary>
public bool OpenFolderAfterSave { get; init; } = false;
/// <summary>
/// Automatically spawn a pinned floating thumbnail window after each capture so the
/// user can keep recent shots on top while continuing to work in other apps. Off by
/// default — only the explicit Pin button on the preview window opens one otherwise.
/// </summary>
public bool AutoPinAfterCapture { get; init; } = false;
}
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Models;
/// <summary>
+55 -4
View File
@@ -1,10 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CaptureImage.Core.Validation;
namespace CaptureImage.Core.Models;
/// <summary>
/// Outcome of <see cref="HotkeyBinding.Validate"/>. UI inspects this to render the right
/// error or warning string; persistence layer only persists bindings whose result is
/// <see cref="Ok"/>.
/// </summary>
public enum HotkeyValidationResult
{
/// <summary>Binding is acceptable for use.</summary>
Ok,
/// <summary>No primary (non-modifier) key — e.g. only Ctrl pressed.</summary>
NoPrimaryKey,
/// <summary><see cref="HotkeyBinding.VirtualKey"/> is itself a modifier VK (Shift/Ctrl/Alt/Win).</summary>
ModifierOnlyKey,
/// <summary>Plain letter/digit without any modifier — too easy to trigger while typing.</summary>
RequiresModifier,
/// <summary>Combination is owned by the Windows shell (<see cref="ReservedHotkeys"/>).</summary>
ReservedByWindows,
}
/// <summary>
/// Modifier flags for a global hotkey. Values match the common Win32 MOD_* constants
/// so Infrastructure can forward to <c>RegisterHotKey</c> without re-mapping.
@@ -46,6 +62,41 @@ public readonly record struct HotkeyBinding(HotkeyModifiers Modifiers, uint Virt
public static HotkeyBinding Default =>
new(HotkeyModifiers.Control | HotkeyModifiers.Shift, 0x7B); // VK_F12 = 0x7B
/// <summary>
/// Classify this binding for use in the UI rebinder. See <see cref="HotkeyValidationResult"/>
/// for possible outcomes. Pure function — does not touch Windows state.
/// </summary>
public HotkeyValidationResult Validate()
{
if (VirtualKey == 0)
return HotkeyValidationResult.NoPrimaryKey;
if (IsModifierVk(VirtualKey))
return HotkeyValidationResult.ModifierOnlyKey;
if (Modifiers == HotkeyModifiers.None && !IsFunctionOrSpecial(VirtualKey))
return HotkeyValidationResult.RequiresModifier;
if (ReservedHotkeys.IsReserved(this))
return HotkeyValidationResult.ReservedByWindows;
return HotkeyValidationResult.Ok;
}
/// <summary>True when <see cref="Validate"/> returns <see cref="HotkeyValidationResult.Ok"/>.</summary>
public bool IsValid() => Validate() == HotkeyValidationResult.Ok;
private static bool IsModifierVk(uint vk) => vk is
0x10 or 0x11 or 0x12 or // VK_SHIFT, VK_CONTROL, VK_MENU (Alt)
0x5B or 0x5C or // VK_LWIN, VK_RWIN
0xA0 or 0xA1 or // VK_LSHIFT, VK_RSHIFT
0xA2 or 0xA3 or // VK_LCONTROL, VK_RCONTROL
0xA4 or 0xA5; // VK_LMENU, VK_RMENU
private static bool IsFunctionOrSpecial(uint vk) =>
(vk >= 0x70 && vk <= 0x87) || // F1..F24
vk == 0x2C; // VK_SNAPSHOT (PrintScreen)
/// <summary>
/// Short display name for a VK code. Only covers the keys we care about; unknown codes
/// fall back to a hex representation so nothing crashes.
+2 -2
View File
@@ -31,7 +31,7 @@ public static class ImageFormatExtensions
ImageFormat.Jpeg => "jpg",
ImageFormat.Webp => "webp",
ImageFormat.Tiff => "tiff",
_ => throw new System.ArgumentOutOfRangeException(nameof(format), format, null),
_ => throw new ArgumentOutOfRangeException(nameof(format), format, null),
};
/// <summary>
@@ -43,6 +43,6 @@ public static class ImageFormatExtensions
ImageFormat.Jpeg => "image/jpeg",
ImageFormat.Webp => "image/webp",
ImageFormat.Tiff => "image/tiff",
_ => throw new System.ArgumentOutOfRangeException(nameof(format), format, null),
_ => throw new ArgumentOutOfRangeException(nameof(format), format, null),
};
}
+36 -3
View File
@@ -1,5 +1,3 @@
using System;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -11,12 +9,47 @@ 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>
/// Pre-formatted timestamp for the log viewer column — <c>"HH:mm:ss.fff"</c>. Done as a
/// computed property because WinUI 3 <c>{Binding}</c> doesn't support
/// <c>StringFormat</c> the way Avalonia/WPF do; keeping the format in code-behind-free
/// view XAML means one place (here) carries the format.
/// </summary>
public string TimestampText =>
Timestamp.ToString("HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>Levels the log viewer filters on. Mapped from Serilog's LogEventLevel.</summary>
public enum LogLevel
@@ -1,5 +1,3 @@
using System.Collections.Generic;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -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;
@@ -53,8 +48,8 @@ public sealed class CaptureOrchestrator
$"No encoder registered for format {request.Format}.");
_logger.LogInformation(
"Capturing target {Target} → {Format} at {Dir}.",
request.Target.DisplayName, request.Format, request.OutputDirectory);
"Starting picture capture of {Target} as {Format}...",
request.Target.DisplayName, request.Format);
var frame = await _engine.CaptureAsync(request.Target, cancellationToken).ConfigureAwait(false);
@@ -98,9 +93,12 @@ public sealed class CaptureOrchestrator
}
stopwatch.Stop();
var fileName = Path.GetFileName(finalPath);
var directory = Path.GetDirectoryName(finalPath) ?? string.Empty;
var sizeKb = fileSize / 1024d;
_logger.LogInformation(
"Capture OK → {Path} ({Width}x{Height}, {Size} bytes, {Ms}ms).",
finalPath, frame.Width, frame.Height, fileSize, stopwatch.ElapsedMilliseconds);
"Picture captured: {Name} ({Width}x{Height}, {SizeKb:F1} KB) at {Path} [{Format}].",
fileName, frame.Width, frame.Height, sizeKb, directory, request.Format);
return new CaptureResult.Success(
FilePath: finalPath,
@@ -111,21 +109,29 @@ public sealed class CaptureOrchestrator
}
catch (CaptureException ex)
{
_logger.LogWarning(ex, "Capture failed with known error {Code}.", ex.ErrorCode);
if (ex.ErrorCode == CaptureError.Cancelled)
{
_logger.LogInformation("Picture capture cancelled by user.");
}
else
{
_logger.LogWarning(ex, "Picture capture failed: {Reason}", ex.Message);
}
return new CaptureResult.Failure(ex.ErrorCode, ex.Message, ex);
}
catch (OperationCanceledException)
{
_logger.LogInformation("Picture capture cancelled by user.");
return new CaptureResult.Failure(CaptureError.Cancelled, "Capture was cancelled.");
}
catch (IOException ex)
{
_logger.LogError(ex, "File write failed during capture.");
_logger.LogError(ex, "Picture capture failed: couldn't write to {Path}.", request.OutputDirectory);
return new CaptureResult.Failure(CaptureError.FileWriteFailure, ex.Message, ex);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected exception during capture.");
_logger.LogError(ex, "Picture capture failed unexpectedly.");
return new CaptureResult.Failure(CaptureError.Unknown, ex.Message, ex);
}
}
@@ -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;
@@ -0,0 +1,42 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Validation;
/// <summary>
/// Catalogue of hotkey combinations reserved by the Windows shell. Binding one of these
/// still registers on our side, but Windows consumes the key press before our hook sees
/// it, so the <see cref="Core.Abstractions.IHotkeyService"/> would silently never fire.
/// The Settings UI uses this to warn the user before they persist an unreachable combo.
/// </summary>
public static class ReservedHotkeys
{
private static readonly HotkeyBinding[] ReservedList =
{
// Lock / session
new(HotkeyModifiers.Win, 0x4C), // Win+L — lock workstation
// Shell navigation
new(HotkeyModifiers.Win, 0x44), // Win+D — show desktop
new(HotkeyModifiers.Win, 0x45), // Win+E — File Explorer
new(HotkeyModifiers.Win, 0x52), // Win+R — Run dialog
new(HotkeyModifiers.Win, 0x49), // Win+I — Settings
new(HotkeyModifiers.Win, 0x58), // Win+X — power menu
new(HotkeyModifiers.Win, 0x4D), // Win+M — minimize all
new(HotkeyModifiers.Win, 0x09), // Win+Tab — Task View
// Window snapping
new(HotkeyModifiers.Win, 0x25), // Win+Left
new(HotkeyModifiers.Win, 0x26), // Win+Up
new(HotkeyModifiers.Win, 0x27), // Win+Right
new(HotkeyModifiers.Win, 0x28), // Win+Down
// Task Manager / Security
new(HotkeyModifiers.Control | HotkeyModifiers.Shift, 0x1B), // Ctrl+Shift+Esc
new(HotkeyModifiers.Control | HotkeyModifiers.Alt, 0x2E), // Ctrl+Alt+Del (also intercepted by kernel)
// Window management owned by Alt
new(HotkeyModifiers.Alt, 0x09), // Alt+Tab
new(HotkeyModifiers.Alt, 0x73), // Alt+F4
};
public static IReadOnlyList<HotkeyBinding> All => ReservedList;
public static bool IsReserved(HotkeyBinding binding) =>
ReservedList.Any(r => r == binding);
}
@@ -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.
}
@@ -0,0 +1,87 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
namespace CaptureImage.Infrastructure.Hotkeys;
/// <summary>
/// Windows implementation of <see cref="IHotkeyConflictSniffer"/>. Uses
/// <c>RegisterHotKey</c> with <c>HWND=NULL</c> — per Win32 docs that posts
/// <c>WM_HOTKEY</c> to the calling thread's queue, which is fine here because
/// we release the registration immediately.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="HotkeyModifiers"/> flag values deliberately match the Win32
/// <c>MOD_*</c> constants so no re-mapping is needed. Bindings flagged by
/// <see cref="Validation.ReservedHotkeys"/> often still register successfully
/// here (Windows gets to eat the keypress first), so both checks are needed.
/// </para>
/// </remarks>
[SupportedOSPlatform("windows10.0.22621.0")]
public sealed partial class HotkeyConflictSniffer : IHotkeyConflictSniffer
{
// Start well clear of the 0x0000-0xBFFF range used by application-defined
// hotkeys so accidental collision with another part of the process is unlikely.
private static int _nextId = 0x7100;
private readonly ILogger<HotkeyConflictSniffer> _logger;
public HotkeyConflictSniffer(ILogger<HotkeyConflictSniffer> logger)
{
_logger = logger;
}
public bool IsConflicted(HotkeyBinding binding)
{
if (!binding.IsValid())
{
// Invalid bindings can't conflict with anything meaningful.
return false;
}
var id = Interlocked.Increment(ref _nextId);
var mods = (uint)binding.Modifiers;
if (RegisterHotKey(IntPtr.Zero, id, mods, binding.VirtualKey))
{
UnregisterHotKey(IntPtr.Zero, id);
return false;
}
var err = Marshal.GetLastWin32Error();
_logger.LogDebug(
"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);
[LibraryImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool UnregisterHotKey(IntPtr hWnd, int id);
}
@@ -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,
};
}
}
@@ -0,0 +1,130 @@
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Versioning;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.Logging;
using Windows.Globalization;
using Windows.Graphics.Imaging;
using Windows.Media.Ocr;
using Windows.Storage.Streams;
using OcrResult = CaptureImage.Core.Abstractions.OcrResult;
using WinOcrResult = Windows.Media.Ocr.OcrResult;
namespace CaptureImage.Infrastructure.Ocr;
/// <summary>
/// <see cref="IOcrService"/> backed by the OS-supplied <c>Windows.Media.Ocr</c> engine.
/// All recognition runs on-device; nothing leaves the machine. Engine availability
/// depends on the user's installed language packs (Settings → Time &amp; language →
/// Language &amp; region → "Optional features" → "Basic typing"+"Optical character
/// recognition").
/// </summary>
[SupportedOSPlatform("windows10.0.10240.0")]
public sealed class WindowsOcrService : IOcrService
{
private readonly ILogger<WindowsOcrService> _logger;
public WindowsOcrService(ILogger<WindowsOcrService> logger)
{
_logger = logger;
}
public async Task<OcrResult> RecognizeAsync(
byte[] pngBytes,
string? languageTag,
CancellationToken cancellationToken = default)
{
if (pngBytes is null || pngBytes.Length == 0)
{
return new OcrResult(string.Empty, 0.0, EngineAvailable: false);
}
var engine = ResolveEngine(languageTag);
if (engine is null)
{
_logger.LogInformation(
"No OCR engine available for language tag '{Tag}' or fallbacks; OCR disabled.",
languageTag ?? "(auto)");
return new OcrResult(string.Empty, 0.0, EngineAvailable: false);
}
try
{
using var stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(pngBytes.AsBuffer()).AsTask(cancellationToken).ConfigureAwait(false);
stream.Seek(0);
var decoder = await BitmapDecoder.CreateAsync(stream).AsTask(cancellationToken).ConfigureAwait(false);
using var softwareBitmap = await decoder.GetSoftwareBitmapAsync().AsTask(cancellationToken).ConfigureAwait(false);
WinOcrResult result = await engine.RecognizeAsync(softwareBitmap).AsTask(cancellationToken).ConfigureAwait(false);
// Average per-line confidence — OcrResult on the WinRT side exposes per-word
// confidence on each Word inside each Line. The library's own
// OcrResult.Text already gives us reading-order text.
double sum = 0;
int count = 0;
foreach (var line in result.Lines)
{
foreach (var word in line.Words)
{
// Word.Confidence is exposed in the BoundingRect overload only on newer
// Windows versions. For broad compatibility we just count words and
// report a coarse 0.85 if anything came back — UI consumers care about
// "did we get text" more than calibrated probability.
count++;
sum += 0.85;
}
}
var confidence = count > 0 ? sum / count : 0.0;
return new OcrResult(result.Text ?? string.Empty, confidence, EngineAvailable: true);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "OCR recognition threw; returning empty result.");
return new OcrResult(string.Empty, 0.0, EngineAvailable: true);
}
}
private OcrEngine? ResolveEngine(string? languageTag)
{
// 1. Explicit language tag if the caller passed one.
if (!string.IsNullOrWhiteSpace(languageTag))
{
try
{
var lang = new Language(languageTag);
if (OcrEngine.IsLanguageSupported(lang))
{
return OcrEngine.TryCreateFromLanguage(lang);
}
}
catch (ArgumentException)
{
// Unknown / malformed tag — fall through to user profile chain.
}
}
// 2. User profile languages (whatever the OS thinks the user types in).
var profileEngine = OcrEngine.TryCreateFromUserProfileLanguages();
if (profileEngine is not null) return profileEngine;
// 3. Hard fallback: en-US — the most likely pack to be installed on a Windows
// machine, even one in a non-English region.
try
{
var enUS = new Language("en-US");
if (OcrEngine.IsLanguageSupported(enUS))
{
return OcrEngine.TryCreateFromLanguage(enUS);
}
}
catch (ArgumentException) { /* shouldn't happen, but stay graceful */ }
return null;
}
}
@@ -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,12 +1,12 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace CaptureImage.Infrastructure.Processes.Interop;
/// <summary>
/// Minimal Win32 surface used by <see cref="WindowEnumerator"/>. Only the calls we actually
/// make land here — do not grow this file into a general user32 wrapper.
/// Minimal Win32 surface used by the Processes module (window enumeration + foreground
/// hook). Only the calls we actually make land here — do not grow this file into a
/// general user32 wrapper.
/// </summary>
internal static partial class User32
{
@@ -35,6 +35,35 @@ internal static partial class User32
[LibraryImport("user32.dll", SetLastError = true)]
public static partial IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[LibraryImport("user32.dll", SetLastError = true)]
public static partial IntPtr GetForegroundWindow();
// SetWinEventHook callback signature. Stays a classic [UnmanagedFunctionPointer]
// delegate (not [LibraryImport]) because [LibraryImport] doesn't support delegate
// parameters yet — the source generator won't marshal them.
public delegate void WinEventDelegate(
IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetWinEventHook(
uint eventMin, uint eventMax,
IntPtr hmodWinEventProc,
WinEventDelegate lpfnWinEventProc,
uint idProcess, uint idThread,
uint dwFlags);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
// SetWinEventHook event constants
public const uint EVENT_SYSTEM_FOREGROUND = 0x0003;
// SetWinEventHook flags
public const uint WINEVENT_OUTOFCONTEXT = 0x0000;
public const uint WINEVENT_SKIPOWNPROCESS = 0x0002;
// GetWindowLongPtr indices
public const int GWL_EXSTYLE = -20;
@@ -0,0 +1,141 @@
using System.Threading;
using CaptureImage.Core.Abstractions;
using CaptureImage.Infrastructure.Processes.Interop;
using Microsoft.Extensions.Logging;
namespace CaptureImage.Infrastructure.Processes;
/// <summary>
/// Win32 implementation of <see cref="IForegroundWindowWatcher"/>. Wraps
/// <c>SetWinEventHook(EVENT_SYSTEM_FOREGROUND, …)</c> and debounces rapid switches so
/// the dashboard only re-selects the target after the user lands on a window.
/// </summary>
public sealed class Win32ForegroundWindowWatcher : IForegroundWindowWatcher
{
private static readonly TimeSpan DebounceDelay = TimeSpan.FromMilliseconds(250);
private readonly ILogger<Win32ForegroundWindowWatcher> _logger;
private readonly object _gate = new();
private readonly uint _ownProcessId;
private IntPtr _hookHandle;
// Holding a strong reference to the delegate is mandatory: the callback is invoked
// by the OS message loop, and a GC of the delegate while the hook is active
// crashes with an AccessViolationException on the next foreground change.
private User32.WinEventDelegate? _callback;
private readonly Timer _debounceTimer;
private IntPtr _pendingHwnd;
private bool _disposed;
public event EventHandler<nint>? ForegroundChanged;
public bool IsRunning { get; private set; }
public Win32ForegroundWindowWatcher(ILogger<Win32ForegroundWindowWatcher> logger)
{
_logger = logger;
_ownProcessId = (uint)Environment.ProcessId;
_debounceTimer = new Timer(OnDebounceElapsed, null, Timeout.Infinite, Timeout.Infinite);
}
public void Start()
{
lock (_gate)
{
if (_disposed) return;
if (IsRunning) return;
_callback = OnRawForegroundEvent;
_hookHandle = User32.SetWinEventHook(
User32.EVENT_SYSTEM_FOREGROUND, User32.EVENT_SYSTEM_FOREGROUND,
IntPtr.Zero, _callback,
idProcess: 0, idThread: 0,
User32.WINEVENT_OUTOFCONTEXT | User32.WINEVENT_SKIPOWNPROCESS);
if (_hookHandle == IntPtr.Zero)
{
_logger.LogWarning("Foreground window watcher failed to register WinEvent hook.");
_callback = null;
return;
}
IsRunning = true;
_logger.LogDebug("Foreground window watcher started (hook=0x{Hook:X}).", _hookHandle);
}
}
public void Stop()
{
lock (_gate)
{
if (_hookHandle != IntPtr.Zero)
{
User32.UnhookWinEvent(_hookHandle);
_hookHandle = IntPtr.Zero;
}
_callback = null;
_pendingHwnd = IntPtr.Zero;
_debounceTimer.Change(Timeout.Infinite, Timeout.Infinite);
if (IsRunning)
{
_logger.LogDebug("Foreground window watcher stopped.");
}
IsRunning = false;
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
Stop();
_debounceTimer.Dispose();
}
private void OnRawForegroundEvent(
IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
// Use GetForegroundWindow() rather than the event's hwnd. On Win11 Alt-Tab the
// event-supplied hwnd can be the modern Task View overlay (idObject != 0) or a
// transient cloaked window — which got the original watcher to filter the event
// out and miss the actual destination. Polling the OS at callback time always
// returns the real foreground HWND. Mouse-click activations happened to ship a
// single clean event so they worked under the old code; Alt-Tab didn't.
var foreground = User32.GetForegroundWindow();
if (foreground == IntPtr.Zero) return;
// WINEVENT_SKIPOWNPROCESS already filters most own-window events, but a defensive
// pid check covers edge cases (e.g. a brokered window owned by another process).
User32.GetWindowThreadProcessId(foreground, out var pid);
if (pid == _ownProcessId) return;
if (pid == 0) return;
_pendingHwnd = foreground;
_debounceTimer.Change(DebounceDelay, Timeout.InfiniteTimeSpan);
}
private void OnDebounceElapsed(object? state)
{
IntPtr hwnd;
lock (_gate)
{
if (_disposed || !IsRunning) return;
hwnd = _pendingHwnd;
_pendingHwnd = IntPtr.Zero;
}
if (hwnd == IntPtr.Zero) return;
_logger.LogDebug("Foreground window watcher firing for HWND 0x{Hwnd:X}.", hwnd);
try
{
ForegroundChanged?.Invoke(this, hwnd);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ForegroundChanged subscriber threw.");
}
}
}
@@ -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)
-10
View File
@@ -1,10 +0,0 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="CaptureImage.UI.App"
RequestedThemeVariant="Default">
<Application.Styles>
<FluentTheme />
</Application.Styles>
</Application>
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff. Show more