Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0967de6ceb | ||
|
|
0cb119be6e | ||
|
|
319a3756ba | ||
|
|
8d460a5afa | ||
|
|
6656e6380c | ||
|
|
c7e9db3673 | ||
|
|
d0ebf6548d | ||
|
|
c477dfe144 | ||
|
|
a85dfa8ec0 | ||
|
|
241bad20be | ||
|
|
310708483e | ||
|
|
7bd2bf9df0 | ||
|
|
7cd59eac36 | ||
|
|
f82b300d25 | ||
|
|
e6ba7b4dfa | ||
|
|
3ae8fdddfe | ||
|
|
2367082aab | ||
|
|
b72d9d9e22 | ||
|
|
3224ad65c2 | ||
|
|
eaf34e5543 | ||
|
|
4d358028d0 | ||
|
|
5ac99712b0 | ||
|
|
5b6c2ddf01 | ||
|
|
d3e9b7df5c | ||
|
|
3da2fcc65d | ||
|
|
395728142b | ||
|
|
35d5fd47bd | ||
|
|
0f7985a644 | ||
|
|
5f19835ce6 | ||
|
|
16dcfb71dc | ||
|
|
5f5e878e0b | ||
|
|
a44b65d86c | ||
|
|
8e374a024e | ||
|
|
cb3ec44693 | ||
|
|
d5706f2dee | ||
|
|
64164b4690 | ||
|
|
0482f718cb |
No files matched your search
@@ -24,12 +24,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 +48,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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
+475
@@ -7,6 +7,481 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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;
|
||||
|
||||
@@ -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
@@ -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>
|
||||
@@ -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 |
|
||||
|:-:|:-:|:-:|
|
||||
|  |  |  |
|
||||
|
||||
| Update | Log viewer | RTL (Arabic) |
|
||||
|:-:|:-:|:-:|
|
||||
|  |  |  |
|
||||
|
||||
## 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
|
||||
|
||||
@@ -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.
|
||||
@@ -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`.
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
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 |
@@ -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>
|
||||
@@ -0,0 +1,64 @@
|
||||
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;
|
||||
|
||||
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;
|
||||
_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);
|
||||
}
|
||||
|
||||
private static void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
|
||||
{
|
||||
Log.Error(e.Exception, "Unhandled exception on UI dispatcher.");
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
@@ -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.3.0</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,6 @@
|
||||
<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. -->
|
||||
<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" />
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using System.IO.Abstractions;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using CaptureImage.Core.Pipeline;
|
||||
@@ -22,6 +21,7 @@ using CaptureImage.ViewModels.Update;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Core;
|
||||
using Serilog.Extensions.Logging;
|
||||
|
||||
namespace CaptureImage.App;
|
||||
@@ -31,7 +31,7 @@ namespace CaptureImage.App;
|
||||
/// </summary>
|
||||
internal static class CompositionRoot
|
||||
{
|
||||
public static IServiceProvider BuildServices(InMemorySink inMemorySink)
|
||||
public static IServiceProvider BuildServices(InMemorySink inMemorySink, LoggingLevelSwitch loggingLevelSwitch)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
|
||||
@@ -40,17 +40,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 ----------------------------------------------------------
|
||||
@@ -73,19 +83,20 @@ 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>();
|
||||
|
||||
// --- Navigation --------------------------------------------------------
|
||||
services.AddSingleton<INavigationService, NavigationService>();
|
||||
@@ -94,6 +105,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>();
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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=""
|
||||
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>
|
||||
@@ -0,0 +1,162 @@
|
||||
using System.ComponentModel;
|
||||
using System.Numerics;
|
||||
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));
|
||||
|
||||
Root.Loaded += OnRootLoaded;
|
||||
}
|
||||
|
||||
public MainWindowViewModel? ViewModel { get; private set; }
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Serilog;
|
||||
using Velopack;
|
||||
|
||||
@@ -17,39 +19,65 @@ 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();
|
||||
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 +85,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 +122,30 @@ internal static class Program
|
||||
{
|
||||
Log.Warning(ex, "Failed to flush settings 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();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
namespace CaptureImage.Core.Abstractions;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
|
||||
namespace CaptureImage.Core.Errors;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ namespace CaptureImage.Core.Models;
|
||||
public sealed record AppSettings
|
||||
{
|
||||
/// <summary>Schema version. Bump when adding migration steps.</summary>
|
||||
public int Version { get; init; } = 1;
|
||||
public int Version { get; init; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// IETF BCP-47 culture code for UI (e.g. <c>en-US</c>, <c>vi-VN</c>, <c>ar-SA</c>).
|
||||
@@ -34,6 +34,19 @@ public sealed record AppSettings
|
||||
public CaptureSettings Capture { get; init; } = new();
|
||||
|
||||
public UiSettings UI { get; init; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Minimum log level retained in the rolling file and in-memory buffer.
|
||||
/// One of <c>Debug</c>, <c>Information</c>, <c>Warning</c>, <c>Error</c> — case-insensitive
|
||||
/// on parse. Unknown values fall back to <c>Information</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Stored as a string rather than an enum so hand-edited <c>settings.json</c> files stay
|
||||
/// readable and so the persistence layer doesn't take a dependency on MEL's enum identity.
|
||||
/// v1 files load with this defaulted to <c>Information</c>; legacy behaviour was
|
||||
/// <c>Debug</c>, so users who relied on it get a note in CHANGELOG to flip it back.
|
||||
/// </remarks>
|
||||
public string LogLevel { get; init; } = "Information";
|
||||
}
|
||||
|
||||
/// <summary>Capture-specific persisted options.</summary>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
|
||||
namespace CaptureImage.Core.Models;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
|
||||
namespace CaptureImage.Core.Models;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,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.
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -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<T>.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;
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using CaptureImage.Core.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Runtime.Versioning;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CaptureImage.Infrastructure.Processes.Interop;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using CaptureImage.Infrastructure.Processes.Interop;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using System.Management;
|
||||
using System.Runtime.Versioning;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
@@ -109,8 +108,10 @@ public sealed class WmiProcessWatcher : IProcessWatcher
|
||||
|
||||
private void DisposeWatchers_NoLock()
|
||||
{
|
||||
try { _startWatcher?.Stop(); } catch { /* ignore */ }
|
||||
try { _stopWatcher?.Stop(); } catch { /* ignore */ }
|
||||
try { _startWatcher?.Stop(); }
|
||||
catch (Exception ex) { _logger.LogDebug(ex, "Failed to stop WMI creation watcher during teardown."); }
|
||||
try { _stopWatcher?.Stop(); }
|
||||
catch (Exception ex) { _logger.LogDebug(ex, "Failed to stop WMI deletion watcher during teardown."); }
|
||||
_startWatcher?.Dispose();
|
||||
_stopWatcher?.Dispose();
|
||||
_startWatcher = null;
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Abstractions;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using CaptureImage.Core.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -22,7 +18,7 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
|
||||
private static readonly TimeSpan WriteDebounce = TimeSpan.FromMilliseconds(300);
|
||||
|
||||
/// <summary>Highest schema version this binary understands.</summary>
|
||||
private const int SupportedVersion = 1;
|
||||
private const int SupportedVersion = 2;
|
||||
|
||||
private readonly IFileSystem _fs;
|
||||
private readonly ILogger<JsonSettingsStore> _logger;
|
||||
@@ -56,35 +52,114 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
|
||||
public async Task LoadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
AppSettings loaded;
|
||||
// Ensure settings.json exists on disk after a successful load. Four paths trigger
|
||||
// a write-back:
|
||||
// (1) file missing — first run, we want the user to see defaults they can edit;
|
||||
// (2) parse failure — bad/corrupt JSON, replace with defaults so next run is clean;
|
||||
// (3) version newer than we support — fall back to defaults;
|
||||
// (4) partial/missing/extra fields — `System.Text.Json` fills init defaults for
|
||||
// absent properties on deserialize, but on-disk file stays skewed; normalize
|
||||
// by comparing re-serialized form with the raw JSON.
|
||||
var needsWriteBack = false;
|
||||
try
|
||||
{
|
||||
if (!_fs.File.Exists(_filePath))
|
||||
{
|
||||
_logger.LogInformation("Settings file not found; using defaults at {Path}.", _filePath);
|
||||
_logger.LogInformation(
|
||||
"Settings file not found at {Path}; initialising with defaults.", _filePath);
|
||||
loaded = new AppSettings();
|
||||
needsWriteBack = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
var json = await _fs.File.ReadAllTextAsync(_filePath, cancellationToken).ConfigureAwait(false);
|
||||
loaded = Deserialize(json) ?? new AppSettings();
|
||||
if (loaded.Version > SupportedVersion)
|
||||
var parsed = Deserialize(json);
|
||||
if (parsed is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Settings file {Path} could not be parsed; replacing with defaults.", _filePath);
|
||||
loaded = new AppSettings();
|
||||
needsWriteBack = true;
|
||||
}
|
||||
else if (parsed.Version > SupportedVersion)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Settings file version {Found} is newer than supported {Supported}; using defaults.",
|
||||
loaded.Version, SupportedVersion);
|
||||
parsed.Version, SupportedVersion);
|
||||
loaded = new AppSettings();
|
||||
needsWriteBack = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// v1 → v2 migration: earlier builds only tracked fields up to UI.
|
||||
// System.Text.Json's source-gen deserializer leaves absent init-only
|
||||
// strings at null instead of the record's init default, so explicitly
|
||||
// set LogLevel here; then stamp Version=2 and trigger a write-back
|
||||
// so the canonical on-disk form matches the current schema.
|
||||
if (parsed.Version < SupportedVersion)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Migrating settings file {Path} from version {From} to {To}.",
|
||||
_filePath, parsed.Version, SupportedVersion);
|
||||
parsed = parsed with
|
||||
{
|
||||
Version = SupportedVersion,
|
||||
LogLevel = string.IsNullOrWhiteSpace(parsed.LogLevel)
|
||||
? "Information"
|
||||
: parsed.LogLevel,
|
||||
};
|
||||
needsWriteBack = true;
|
||||
}
|
||||
|
||||
// Defensive: even a v2-stamped file can arrive with LogLevel=null if it
|
||||
// was hand-edited or produced by an older preview binary. Fill in the
|
||||
// default so downstream code never sees null.
|
||||
if (string.IsNullOrWhiteSpace(parsed.LogLevel))
|
||||
{
|
||||
parsed = parsed with { LogLevel = "Information" };
|
||||
needsWriteBack = true;
|
||||
}
|
||||
|
||||
loaded = parsed;
|
||||
// Partial/missing/extra fields — re-serializing fills init defaults, so
|
||||
// if the canonical form differs from the raw JSON, write back to
|
||||
// normalize the on-disk file.
|
||||
var canonical = Serialize(loaded);
|
||||
if (!string.Equals(json.Trim(), canonical.Trim(), StringComparison.Ordinal))
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Settings file {Path} differs from canonical form; normalizing.", _filePath);
|
||||
needsWriteBack = true;
|
||||
}
|
||||
_logger.LogInformation(
|
||||
"Settings loaded from {Path} (version {Version}, log level {LogLevel}).",
|
||||
_filePath, loaded.Version, loaded.LogLevel);
|
||||
}
|
||||
_logger.LogInformation("Settings loaded from {Path} (version {Version}).",
|
||||
_filePath, loaded.Version);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to load settings from {Path}; reverting to defaults.", _filePath);
|
||||
loaded = new AppSettings();
|
||||
needsWriteBack = true;
|
||||
}
|
||||
|
||||
SetCurrent(loaded, persistImmediately: false);
|
||||
|
||||
if (needsWriteBack)
|
||||
{
|
||||
try
|
||||
{
|
||||
await WriteAsync(loaded, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Best-effort: Load must succeed even if the disk is read-only. A subsequent
|
||||
// Update() will retry via the debounced write path.
|
||||
_logger.LogWarning(
|
||||
ex, "Could not write initial/normalized settings file to {Path}.", _filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Update(Func<AppSettings, AppSettings> mutator)
|
||||
@@ -224,21 +299,37 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
|
||||
|
||||
private void TryDelete(string path)
|
||||
{
|
||||
try { if (_fs.File.Exists(path)) _fs.File.Delete(path); }
|
||||
catch { /* best-effort */ }
|
||||
try
|
||||
{
|
||||
if (_fs.File.Exists(path)) _fs.File.Delete(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Best-effort cleanup — if the temp file can't be removed, a subsequent write
|
||||
// will overwrite it via the rename-into-place path. Log at Debug so we can still
|
||||
// correlate if it compounds into a real failure later.
|
||||
_logger.LogDebug(ex, "Failed to delete {Path}.", path);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Serialize(AppSettings settings) =>
|
||||
JsonSerializer.Serialize(settings, SettingsJsonContext.Default.AppSettings);
|
||||
|
||||
private static AppSettings? Deserialize(string json)
|
||||
private AppSettings? Deserialize(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(json, SettingsJsonContext.Default.AppSettings);
|
||||
}
|
||||
catch (JsonException)
|
||||
catch (JsonException ex)
|
||||
{
|
||||
// The caller turns a null return into "replace with defaults". Surface the root
|
||||
// cause here so the log explains why, not just that parsing failed.
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Malformed settings JSON ({LineNumber}:{BytePositionInLine}); reverting to defaults.",
|
||||
ex.LineNumber,
|
||||
ex.BytePositionInLine);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using System.IO.Abstractions;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Abstractions;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using CaptureImage.Core.Models;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace CaptureImage.Infrastructure.Steam;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace CaptureImage.Infrastructure.Steam;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using CaptureImage.Core.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -147,12 +144,28 @@ public sealed class VelopackUpdateService : IUpdateService
|
||||
{
|
||||
if (_manager is null || _pendingUpdate is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"ApplyAndRestart invoked with no pending update (manager={HasManager}, pending={HasPending}).",
|
||||
_manager is not null,
|
||||
_pendingUpdate is not null);
|
||||
throw new InvalidOperationException(
|
||||
"No pending update to install. Call CheckAsync + DownloadAsync first.");
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"Applying update {Version} and restarting.",
|
||||
_pendingUpdate.TargetFullRelease.Version);
|
||||
EmitLog("Applying update and restarting…");
|
||||
_manager.ApplyUpdatesAndRestart(_pendingUpdate.TargetFullRelease);
|
||||
try
|
||||
{
|
||||
_manager.ApplyUpdatesAndRestart(_pendingUpdate.TargetFullRelease);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "ApplyUpdatesAndRestart failed.");
|
||||
EmitLog($"Apply failed: {ex.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void EmitLog(string line)
|
||||
|
||||
@@ -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>
|
||||
@@ -1,48 +0,0 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using CaptureImage.UI.Views;
|
||||
using CaptureImage.ViewModels;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace CaptureImage.UI;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
/// <summary>
|
||||
/// Service provider is assigned by the host (CaptureImage.App) before
|
||||
/// <see cref="OnFrameworkInitializationCompleted"/> runs, so view-models can be resolved from DI.
|
||||
/// </summary>
|
||||
public static IServiceProvider? Services { get; set; }
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
var services = Services
|
||||
?? throw new InvalidOperationException(
|
||||
"App.Services must be assigned before the Avalonia lifetime starts.");
|
||||
|
||||
var mainVm = services.GetRequiredService<MainWindowViewModel>();
|
||||
var mainWindow = new MainWindow
|
||||
{
|
||||
DataContext = mainVm,
|
||||
};
|
||||
desktop.MainWindow = mainWindow;
|
||||
|
||||
// Attach the tray icon now that the main window is constructed — the host needs
|
||||
// a live Window reference for Show / Hide / Close-to-tray wiring.
|
||||
var trayHost = services.GetRequiredService<ITrayIconHost>();
|
||||
trayHost.Initialize(mainWindow);
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net9.0-windows10.0.22621.0</TargetFramework>
|
||||
<SupportedOSPlatformVersion>10.0.22621.0</SupportedOSPlatformVersion>
|
||||
<RootNamespace>CaptureImage.UI</RootNamespace>
|
||||
<AssemblyName>CaptureImage.UI</AssemblyName>
|
||||
<EnableAvaloniaXamlCompilation>true</EnableAvaloniaXamlCompilation>
|
||||
<UseWinUI>true</UseWinUI>
|
||||
<EnableMsixTooling>false</EnableMsixTooling>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" />
|
||||
<PackageReference Include="Microsoft.WindowsAppSDK" />
|
||||
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" />
|
||||
<PackageReference Include="SkiaSharp" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||
<PackageReference Include="H.NotifyIcon.WinUI" />
|
||||
<PackageReference Include="System.Drawing.Common" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
@@ -22,8 +25,4 @@
|
||||
<ProjectReference Include="..\CaptureImage.ViewModels\CaptureImage.ViewModels.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,86 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<UserControl
|
||||
x:Class="CaptureImage.UI.Controls.HotkeyRecorder"
|
||||
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"
|
||||
mc:Ignorable="d">
|
||||
|
||||
<StackPanel Spacing="8">
|
||||
<Grid ColumnSpacing="8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Focusable surface that captures key events while recording. ContentControl
|
||||
is the simplest WinUI 3 element that supports IsTabStop + KeyDown without
|
||||
a custom Control template. Border itself is not focusable. -->
|
||||
<ContentControl
|
||||
x:Name="BindingField"
|
||||
Grid.Column="0"
|
||||
IsTabStop="True"
|
||||
MinHeight="34"
|
||||
CornerRadius="{StaticResource CardCornerRadius}"
|
||||
Padding="12,8"
|
||||
BorderThickness="1"
|
||||
BorderBrush="{ThemeResource ControlElevationBorderBrush}"
|
||||
Background="{ThemeResource ControlFillColorDefaultBrush}"
|
||||
HorizontalContentAlignment="Stretch"
|
||||
VerticalContentAlignment="Center"
|
||||
AutomationProperties.Name="{Binding HotkeyFieldAutomationName}"
|
||||
AutomationProperties.HelpText="{Binding RecorderPromptText}"
|
||||
KeyDown="OnFieldKeyDown">
|
||||
<Grid>
|
||||
<TextBlock
|
||||
Text="{Binding DisplayText}"
|
||||
FontFamily="Consolas, Courier New"
|
||||
VerticalAlignment="Center"
|
||||
Visibility="{Binding IsRecording, Converter={StaticResource InvertedBoolToVisibilityConverter}}" />
|
||||
<TextBlock
|
||||
Text="{Binding RecorderPromptText}"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
FontStyle="Italic"
|
||||
VerticalAlignment="Center"
|
||||
Visibility="{Binding IsRecording, Converter={StaticResource BoolToVisibilityConverter}}" />
|
||||
</Grid>
|
||||
</ContentControl>
|
||||
|
||||
<Button
|
||||
Grid.Column="1"
|
||||
Content="{Binding RecordLabel}"
|
||||
Command="{Binding StartRecordingCommand}"
|
||||
Visibility="{Binding IsRecording, Converter={StaticResource InvertedBoolToVisibilityConverter}}"
|
||||
MinWidth="80" />
|
||||
<Button
|
||||
Grid.Column="1"
|
||||
Content="{Binding CancelLabel}"
|
||||
Command="{Binding CancelRecordingCommand}"
|
||||
Visibility="{Binding IsRecording, Converter={StaticResource BoolToVisibilityConverter}}"
|
||||
MinWidth="80" />
|
||||
|
||||
<Button
|
||||
Grid.Column="2"
|
||||
Content="{Binding ResetLabel}"
|
||||
Command="{Binding ResetToDefaultCommand}"
|
||||
Visibility="{Binding IsRecording, Converter={StaticResource InvertedBoolToVisibilityConverter}}"
|
||||
MinWidth="80" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock
|
||||
Text="{Binding ErrorMessage}"
|
||||
Foreground="#D13438"
|
||||
FontSize="{StaticResource FontSizeCaption}"
|
||||
TextWrapping="Wrap"
|
||||
Visibility="{Binding HasError, Converter={StaticResource BoolToVisibilityConverter}}" />
|
||||
|
||||
<TextBlock
|
||||
Text="{Binding ConflictWarningText}"
|
||||
Foreground="#C19C00"
|
||||
FontSize="{StaticResource FontSizeCaption}"
|
||||
TextWrapping="Wrap"
|
||||
Visibility="{Binding ConflictDetected, Converter={StaticResource BoolToVisibilityConverter}}" />
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.ComponentModel;
|
||||
using CaptureImage.Core.Models;
|
||||
using CaptureImage.ViewModels.Settings;
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Input;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Input;
|
||||
using Windows.System;
|
||||
using Windows.UI.Core;
|
||||
|
||||
namespace CaptureImage.UI.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// Keyboard-driven rebinder for <see cref="HotkeyBinding"/>. Owns no state itself —
|
||||
/// it forwards completed combinations to the attached <see cref="HotkeyBindingViewModel"/>
|
||||
/// and reads validation / conflict flags back to drive its own visibility.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// WinUI 3's <see cref="VirtualKey"/> values match the Win32 VK codes 1:1, so persistence
|
||||
/// can carry the integer through unchanged. Modifier state is queried via
|
||||
/// <see cref="InputKeyboardSource.GetKeyStateForCurrentThread"/> rather than e.KeyModifiers
|
||||
/// because WinUI 3's <c>KeyRoutedEventArgs</c> doesn't expose a Modifiers field directly.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>IME caveat:</b> Ctrl/Alt/Win-qualified combos bypass most IMEs (including VN telex
|
||||
/// and Arabic input), so the recorder should be stable on those layouts. We require at
|
||||
/// least one modifier for all non-function keys via <see cref="HotkeyBinding.Validate"/>,
|
||||
/// so the bare-letter IME path doesn't matter in practice.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed partial class HotkeyRecorder : UserControl
|
||||
{
|
||||
private HotkeyBindingViewModel? _vm;
|
||||
|
||||
public HotkeyRecorder()
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
}
|
||||
|
||||
private void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
|
||||
{
|
||||
if (_vm is not null)
|
||||
{
|
||||
_vm.PropertyChanged -= OnVmPropertyChanged;
|
||||
}
|
||||
|
||||
_vm = args.NewValue as HotkeyBindingViewModel;
|
||||
|
||||
if (_vm is not null)
|
||||
{
|
||||
_vm.PropertyChanged += OnVmPropertyChanged;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnVmPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(HotkeyBindingViewModel.IsRecording)
|
||||
&& _vm?.IsRecording == true)
|
||||
{
|
||||
// Grab keyboard focus so the next key press lands on our handler. Posted via
|
||||
// the dispatcher queue so the focus move happens after the current click has
|
||||
// fully settled — calling Focus() inline can race with WinUI reassigning focus
|
||||
// when the Record button collapses.
|
||||
DispatcherQueue.TryEnqueue(() => BindingField.Focus(FocusState.Programmatic));
|
||||
}
|
||||
}
|
||||
|
||||
private void OnFieldKeyDown(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
if (_vm is null || !_vm.IsRecording) return;
|
||||
|
||||
var modifiers = GetCurrentModifiers();
|
||||
|
||||
// Esc alone cancels without committing.
|
||||
if (e.Key == VirtualKey.Escape && modifiers == HotkeyModifiers.None)
|
||||
{
|
||||
_vm.CancelRecordingCommand.Execute(null);
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsModifier(e.Key))
|
||||
{
|
||||
// Pure modifier keypress — wait for a real combination.
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// VirtualKey enum values are exactly the Win32 VK codes; cast to uint round-trips
|
||||
// cleanly through HotkeyBinding.VirtualKey (which is itself a uint VK).
|
||||
var vk = (uint)e.Key;
|
||||
_vm.TryCommitRecorded(new HotkeyBinding(modifiers, vk));
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private static HotkeyModifiers GetCurrentModifiers()
|
||||
{
|
||||
var mods = HotkeyModifiers.None;
|
||||
if (IsKeyDown(VirtualKey.Control)) mods |= HotkeyModifiers.Control;
|
||||
if (IsKeyDown(VirtualKey.Shift)) mods |= HotkeyModifiers.Shift;
|
||||
if (IsKeyDown(VirtualKey.Menu)) mods |= HotkeyModifiers.Alt;
|
||||
if (IsKeyDown(VirtualKey.LeftWindows) || IsKeyDown(VirtualKey.RightWindows)) mods |= HotkeyModifiers.Win;
|
||||
return mods;
|
||||
}
|
||||
|
||||
private static bool IsKeyDown(VirtualKey key) =>
|
||||
(InputKeyboardSource.GetKeyStateForCurrentThread(key) & CoreVirtualKeyStates.Down) != 0;
|
||||
|
||||
private static bool IsModifier(VirtualKey key) => key
|
||||
is VirtualKey.Control or VirtualKey.LeftControl or VirtualKey.RightControl
|
||||
or VirtualKey.Shift or VirtualKey.LeftShift or VirtualKey.RightShift
|
||||
or VirtualKey.Menu or VirtualKey.LeftMenu or VirtualKey.RightMenu
|
||||
or VirtualKey.LeftWindows or VirtualKey.RightWindows;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
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:models="clr-namespace:CaptureImage.Core.Models;assembly=CaptureImage.Core"
|
||||
xmlns:conv="clr-namespace:CaptureImage.UI.Converters"
|
||||
mc:Ignorable="d"
|
||||
x:Class="CaptureImage.UI.Controls.ToastHost"
|
||||
IsHitTestVisible="True">
|
||||
|
||||
<ItemsControl Name="ToastList">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Vertical" Spacing="8" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="models:ToastItem">
|
||||
<Border CornerRadius="6"
|
||||
Background="{DynamicResource SystemControlBackgroundChromeMediumBrush}"
|
||||
BorderBrush="{Binding Kind, Converter={x:Static conv:ToastKindToBrushConverter.Instance}}"
|
||||
BorderThickness="0,0,0,3"
|
||||
Padding="14,10"
|
||||
MinWidth="260"
|
||||
MaxWidth="340">
|
||||
<StackPanel Orientation="Vertical" Spacing="2">
|
||||
<TextBlock Text="{Binding Title}"
|
||||
FontWeight="SemiBold"
|
||||
FontSize="13"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding Message}"
|
||||
FontSize="12"
|
||||
Opacity="0.8"
|
||||
TextWrapping="Wrap"
|
||||
MaxHeight="80" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
|
||||
</UserControl>
|
||||
@@ -1,35 +0,0 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using System.Collections;
|
||||
|
||||
namespace CaptureImage.UI.Controls;
|
||||
|
||||
public partial class ToastHost : UserControl
|
||||
{
|
||||
/// <summary>
|
||||
/// Source collection for the toast stack. The MainWindow sets this to
|
||||
/// <c>IToastService.Visible</c>.
|
||||
/// </summary>
|
||||
public static readonly StyledProperty<IEnumerable?> ItemsSourceProperty =
|
||||
AvaloniaProperty.Register<ToastHost, IEnumerable?>(nameof(ItemsSource));
|
||||
|
||||
public IEnumerable? ItemsSource
|
||||
{
|
||||
get => GetValue(ItemsSourceProperty);
|
||||
set => SetValue(ItemsSourceProperty, value);
|
||||
}
|
||||
|
||||
public ToastHost()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
|
||||
{
|
||||
base.OnPropertyChanged(change);
|
||||
if (change.Property == ItemsSourceProperty)
|
||||
{
|
||||
ToastList.ItemsSource = change.NewValue as IEnumerable;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<UserControl
|
||||
x:Class="CaptureImage.UI.Controls.ToastHost"
|
||||
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"
|
||||
mc:Ignorable="d"
|
||||
IsHitTestVisible="True">
|
||||
|
||||
<ItemsControl x:Name="ToastList" ItemsSource="{Binding Toasts}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Vertical" Spacing="8" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border CornerRadius="{StaticResource CardCornerRadius}"
|
||||
Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
|
||||
BorderBrush="{Binding Kind, Converter={StaticResource ToastKindToBrushConverter}}"
|
||||
BorderThickness="0,0,0,3"
|
||||
Padding="14,10"
|
||||
MinWidth="260"
|
||||
MaxWidth="340">
|
||||
<StackPanel Orientation="Vertical" Spacing="2">
|
||||
<TextBlock Text="{Binding Title}"
|
||||
FontWeight="SemiBold"
|
||||
FontSize="{StaticResource FontSizeBody}"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding Message}"
|
||||
FontSize="{StaticResource FontSizeSmall}"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
TextWrapping="Wrap"
|
||||
MaxHeight="80" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,17 @@
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace CaptureImage.UI.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// Toast overlay. Inherits its <c>DataContext</c> from the host (MainWindow's root Grid =
|
||||
/// MainWindowViewModel) and binds the inner ItemsControl to <c>{Binding Toasts}</c>. The
|
||||
/// v1.2 custom ItemsSourceProperty is dropped — direct binding is cleaner and sufficient
|
||||
/// for v1.3 (only one host).
|
||||
/// </summary>
|
||||
public sealed partial class ToastHost : UserControl
|
||||
{
|
||||
public ToastHost()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Data;
|
||||
|
||||
namespace CaptureImage.UI.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Maps <see cref="bool"/> -> <see cref="Visibility"/>. <c>true</c> = Visible.
|
||||
/// </summary>
|
||||
public sealed class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, string language) =>
|
||||
value is true ? Visibility.Visible : Visibility.Collapsed;
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, string language) =>
|
||||
value is Visibility v && v == Visibility.Visible;
|
||||
}
|
||||
@@ -1,22 +1,19 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Avalonia.Data.Converters;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Microsoft.UI.Xaml.Data;
|
||||
using Microsoft.UI.Xaml.Media.Imaging;
|
||||
|
||||
namespace CaptureImage.UI.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Converts raw PNG <c>byte[]</c> to an Avalonia <see cref="Bitmap"/>. Used by the
|
||||
/// Dashboard list so icon data can travel through ViewModels without a direct
|
||||
/// Avalonia dependency. Returns <c>null</c> on any failure so XAML falls back to
|
||||
/// the default image placeholder.
|
||||
/// Converts a raw PNG <c>byte[]</c> to a <see cref="BitmapImage"/>. Used by the Dashboard
|
||||
/// list so icon data flows through the portable VMs without taking a UI-framework
|
||||
/// dependency. Returns <c>null</c> on any failure so XAML falls back to its default
|
||||
/// placeholder.
|
||||
/// </summary>
|
||||
public sealed class BytesToBitmapConverter : IValueConverter
|
||||
{
|
||||
public static readonly BytesToBitmapConverter Instance = new();
|
||||
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
public object? Convert(object? value, Type targetType, object? parameter, string language)
|
||||
{
|
||||
if (value is not byte[] { Length: > 0 } bytes)
|
||||
{
|
||||
@@ -25,8 +22,13 @@ public sealed class BytesToBitmapConverter : IValueConverter
|
||||
|
||||
try
|
||||
{
|
||||
using var stream = new MemoryStream(bytes);
|
||||
return new Bitmap(stream);
|
||||
// BitmapImage.SetSource is sync in WinUI 3 — it just hands the stream off to the
|
||||
// decoder, which loads asynchronously on a background thread. The Image control
|
||||
// shows nothing until decode completes, then refreshes in place.
|
||||
using var ms = new MemoryStream(bytes);
|
||||
var bitmap = new BitmapImage();
|
||||
bitmap.SetSource(ms.AsRandomAccessStream());
|
||||
return bitmap;
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -34,6 +36,6 @@ public sealed class BytesToBitmapConverter : IValueConverter
|
||||
}
|
||||
}
|
||||
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, string language)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
@@ -1,24 +1,22 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia.Data.Converters;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Data;
|
||||
|
||||
namespace CaptureImage.UI.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Maps the portable <see cref="TextFlowDirection"/> enum (defined in Core so view models can
|
||||
/// talk about direction without referencing Avalonia) to Avalonia's
|
||||
/// <see cref="Avalonia.Media.FlowDirection"/>.
|
||||
/// talk about direction without referencing WinUI 3) to <see cref="FlowDirection"/>.
|
||||
/// </summary>
|
||||
public sealed class FlowDirectionConverter : IValueConverter
|
||||
{
|
||||
public static readonly FlowDirectionConverter Instance = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
public object Convert(object value, Type targetType, object parameter, string language) =>
|
||||
value is TextFlowDirection.RightToLeft
|
||||
? Avalonia.Media.FlowDirection.RightToLeft
|
||||
: Avalonia.Media.FlowDirection.LeftToRight;
|
||||
? FlowDirection.RightToLeft
|
||||
: FlowDirection.LeftToRight;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
public object ConvertBack(object value, Type targetType, object parameter, string language)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Data;
|
||||
|
||||
namespace CaptureImage.UI.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Maps <see cref="bool"/> -> <see cref="Visibility"/> with inversion. <c>true</c> = Collapsed.
|
||||
/// Replaces Avalonia's <c>IsVisible="{Binding !X}"</c> negation pattern.
|
||||
/// </summary>
|
||||
public sealed class InvertedBoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly InvertedBoolToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, string language) =>
|
||||
value is true ? Visibility.Collapsed : Visibility.Visible;
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, string language) =>
|
||||
value is Visibility v && v == Visibility.Collapsed;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Data;
|
||||
|
||||
namespace CaptureImage.UI.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Maps an object reference -> <see cref="Visibility"/>. Non-null = Visible.
|
||||
/// Replaces Avalonia's <c>IsVisible="{Binding X, Converter={x:Static ObjectConverters.IsNotNull}}"</c>.
|
||||
/// </summary>
|
||||
public sealed class NotNullToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly NotNullToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object parameter, string language) =>
|
||||
value is null ? Visibility.Collapsed : Visibility.Visible;
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, string language) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
@@ -1,24 +1,25 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia.Data.Converters;
|
||||
using Avalonia.Media;
|
||||
using CaptureImage.Core.Models;
|
||||
using Microsoft.UI.Xaml.Data;
|
||||
using Microsoft.UI.Xaml.Media;
|
||||
using Windows.UI;
|
||||
|
||||
namespace CaptureImage.UI.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Maps a <see cref="ToastKind"/> to the accent color the toast card should use.
|
||||
/// Maps a <see cref="ToastKind"/> to the accent <see cref="SolidColorBrush"/> the toast
|
||||
/// card should use for its bottom-edge stripe. Same colors as the v1.2 Avalonia version
|
||||
/// (Tailwind sky-500 / green-500 / amber-500 / red-500).
|
||||
/// </summary>
|
||||
public sealed class ToastKindToBrushConverter : IValueConverter
|
||||
{
|
||||
public static readonly ToastKindToBrushConverter Instance = new();
|
||||
|
||||
private static readonly IBrush InfoBrush = new SolidColorBrush(Color.Parse("#3B82F6"));
|
||||
private static readonly IBrush SuccessBrush = new SolidColorBrush(Color.Parse("#22C55E"));
|
||||
private static readonly IBrush WarningBrush = new SolidColorBrush(Color.Parse("#F59E0B"));
|
||||
private static readonly IBrush ErrorBrush = new SolidColorBrush(Color.Parse("#EF4444"));
|
||||
private static readonly SolidColorBrush InfoBrush = new(ColorHelper.FromArgb(0xFF, 0x3B, 0x82, 0xF6));
|
||||
private static readonly SolidColorBrush SuccessBrush = new(ColorHelper.FromArgb(0xFF, 0x22, 0xC5, 0x5E));
|
||||
private static readonly SolidColorBrush WarningBrush = new(ColorHelper.FromArgb(0xFF, 0xF5, 0x9E, 0x0B));
|
||||
private static readonly SolidColorBrush ErrorBrush = new(ColorHelper.FromArgb(0xFF, 0xEF, 0x44, 0x44));
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
public object Convert(object value, Type targetType, object parameter, string language) =>
|
||||
value switch
|
||||
{
|
||||
ToastKind.Success => SuccessBrush,
|
||||
@@ -27,6 +28,11 @@ public sealed class ToastKindToBrushConverter : IValueConverter
|
||||
_ => InfoBrush,
|
||||
};
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
public object ConvertBack(object value, Type targetType, object parameter, string language)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
|
||||
internal static class ColorHelper
|
||||
{
|
||||
public static Color FromArgb(byte a, byte r, byte g, byte b) => Color.FromArgb(a, r, g, b);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.Resources;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CaptureImage.UI.Localization;
|
||||
|
||||
@@ -24,12 +24,22 @@ public sealed class ResxLocalizationService : ILocalizationService
|
||||
};
|
||||
|
||||
private readonly ResourceManager _resourceManager;
|
||||
private readonly ILogger<ResxLocalizationService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks <c>(culture, key)</c> pairs we've already logged a "missing string" warning for.
|
||||
/// Missing keys are usually the same handful repeated on every refresh; logging once per
|
||||
/// pair per process keeps the signal without flooding the rolling file.
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<string, byte> _loggedMissingKeys = new();
|
||||
|
||||
private CultureInfo _currentCulture;
|
||||
|
||||
public ResxLocalizationService()
|
||||
public ResxLocalizationService(ILogger<ResxLocalizationService> logger)
|
||||
{
|
||||
_resourceManager = new ResourceManager(ResourceBaseName, typeof(ResxLocalizationService).Assembly);
|
||||
_currentCulture = CultureInfo.GetCultureInfo("en-US");
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
@@ -53,15 +63,42 @@ public sealed class ResxLocalizationService : ILocalizationService
|
||||
if (string.IsNullOrEmpty(key)) return string.Empty;
|
||||
try
|
||||
{
|
||||
return _resourceManager.GetString(key, _currentCulture) ?? $"[{key}]";
|
||||
var value = _resourceManager.GetString(key, _currentCulture);
|
||||
if (value is null)
|
||||
{
|
||||
LogMissingKeyOnce(key);
|
||||
return $"[{key}]";
|
||||
}
|
||||
return value;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogMissingKeyOnce(key, ex);
|
||||
return $"[{key}]";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void LogMissingKeyOnce(string key, Exception? exception = null)
|
||||
{
|
||||
var dedupKey = $"{_currentCulture.Name}|{key}";
|
||||
if (!_loggedMissingKeys.TryAdd(dedupKey, 0)) return;
|
||||
|
||||
if (exception is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Localization key '{Key}' missing for culture {Culture}; falling back to bracketed key.",
|
||||
key, _currentCulture.Name);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning(
|
||||
exception,
|
||||
"Localization lookup threw for key '{Key}' culture {Culture}; falling back to bracketed key.",
|
||||
key, _currentCulture.Name);
|
||||
}
|
||||
}
|
||||
|
||||
public void SetCulture(CultureInfo culture)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(culture);
|
||||
@@ -71,7 +108,18 @@ public sealed class ResxLocalizationService : ILocalizationService
|
||||
}
|
||||
|
||||
_currentCulture = culture;
|
||||
|
||||
// The indexer passes _currentCulture explicitly to ResourceManager so resx lookup
|
||||
// is correct regardless of thread culture — but date/number/currency formatting
|
||||
// elsewhere in the app uses the ambient CurrentCulture. Align both so a vi-VN
|
||||
// user sees Vietnamese dates and an ar-SA user sees Arabic-Indic digits wherever
|
||||
// implicit .ToString() lands. DefaultThread* sets the baseline for threads that
|
||||
// haven't overridden their own culture (e.g. background threads the user hasn't
|
||||
// touched yet); the UI thread gets both explicit assignments.
|
||||
CultureInfo.CurrentUICulture = culture;
|
||||
CultureInfo.CurrentCulture = culture;
|
||||
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
||||
CultureInfo.DefaultThreadCurrentCulture = culture;
|
||||
|
||||
// "Item[]" is the magic property name that tells Avalonia to refresh every indexer binding.
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
|
||||
|
||||
@@ -52,27 +52,45 @@
|
||||
<data name="Dashboard_StatusFailed" xml:space="preserve"><value>فشل الالتقاط ({0}): {1}</value></data>
|
||||
<data name="Dashboard_TargetsCount" xml:space="preserve"><value>{0} هدف/أهداف متاح</value></data>
|
||||
<data name="Dashboard_Loading" xml:space="preserve"><value>جاري التحميل…</value></data>
|
||||
<data name="Dashboard_EmptyState" xml:space="preserve"><value>لا توجد نوافذ مرئية للالتقاط — شغّل لعبتك أو تطبيقك، ثم انقر على تحديث.</value></data>
|
||||
<data name="Dashboard_LogToggle" xml:space="preserve"><value>تبديل درج السجل في الوقت الفعلي</value></data>
|
||||
<data name="Dashboard_SteamBadge" xml:space="preserve"><value>STEAM</value></data>
|
||||
<data name="Dashboard_SteamBadgeTooltip" xml:space="preserve"><value>لعبة Steam: {0} (AppId {1}). F12 متاح عبر Steam Overlay. بعض الألعاب المحمية بـ anti-cheat قد تمنع الالتقاط الخارجي.</value></data>
|
||||
|
||||
<!-- Settings -->
|
||||
<data name="Settings_Title" xml:space="preserve"><value>الإعدادات</value></data>
|
||||
<data name="Settings_Language" xml:space="preserve"><value>اللغة</value></data>
|
||||
<data name="Settings_Theme" xml:space="preserve"><value>المظهر</value></data>
|
||||
<data name="Settings_Hotkey" xml:space="preserve"><value>مفتاح اختصار الالتقاط</value></data>
|
||||
<data name="Settings_HotkeyHint" xml:space="preserve"><value>افتراضي: Ctrl+Shift+F12. تحرير مفتاح الاختصار في المراحل القادمة.</value></data>
|
||||
<data name="Settings_HotkeyHint" xml:space="preserve"><value>انقر تسجيل ثم اضغط على مجموعة مفاتيح. Esc للإلغاء. إعادة التعيين تستعيد Ctrl+Shift+F12.</value></data>
|
||||
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>تسجيل…</value></data>
|
||||
<data name="Settings_HotkeyCancel" xml:space="preserve"><value>إلغاء</value></data>
|
||||
<data name="Settings_HotkeyReset" xml:space="preserve"><value>إعادة تعيين</value></data>
|
||||
<data name="Settings_HotkeyRecorderPrompt" xml:space="preserve"><value>اضغط على مجموعة مفاتيح (Esc للإلغاء)…</value></data>
|
||||
<data name="Settings_HotkeyErrorNoPrimary" xml:space="preserve"><value>حدد مفتاحًا رئيسيًا (مثل حرف أو مفتاح F).</value></data>
|
||||
<data name="Settings_HotkeyErrorModifierOnly" xml:space="preserve"><value>مفتاح التعديل وحده غير كافٍ — أضف حرفًا أو مفتاح F.</value></data>
|
||||
<data name="Settings_HotkeyErrorNeedsModifier" xml:space="preserve"><value>الحروف والأرقام العادية تحتاج إلى مفتاح تعديل واحد على الأقل (Ctrl/Alt/Shift/Win).</value></data>
|
||||
<data name="Settings_HotkeyErrorReserved" xml:space="preserve"><value>هذه المجموعة محجوزة من قبل Windows ولا يمكن التقاطها.</value></data>
|
||||
<data name="Settings_HotkeyConflictWarning" xml:space="preserve"><value>قد يستخدم تطبيق آخر هذه المجموعة بالفعل — قد لا تعمل أثناء تشغيل ذلك التطبيق.</value></data>
|
||||
<data name="Settings_Format" xml:space="preserve"><value>التنسيق الافتراضي</value></data>
|
||||
<data name="Settings_JpegQuality" xml:space="preserve"><value>جودة JPEG</value></data>
|
||||
<data name="Settings_WebpQuality" xml:space="preserve"><value>جودة WebP</value></data>
|
||||
<data name="Settings_OutputFolder" xml:space="preserve"><value>مجلد الإخراج</value></data>
|
||||
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(افتراضي: Pictures\CaptureImage)</value></data>
|
||||
<data name="Settings_Browse" xml:space="preserve"><value>استعراض…</value></data>
|
||||
<data name="Settings_BrowseTitle" xml:space="preserve"><value>اختر مجلد الإخراج</value></data>
|
||||
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>اختر مجلدًا بدلاً من كتابة المسار.</value></data>
|
||||
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>قالب اسم الملف</value></data>
|
||||
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>معاينة كل التقاط قبل الحفظ</value></data>
|
||||
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>زر الإغلاق يصغر إلى علبة النظام</value></data>
|
||||
<data name="Settings_SoundEnabled" xml:space="preserve"><value>تشغيل صوت الالتقاط</value></data>
|
||||
<data name="Settings_Import" xml:space="preserve"><value>استيراد…</value></data>
|
||||
<data name="Settings_Export" xml:space="preserve"><value>تصدير…</value></data>
|
||||
<data name="Settings_ImportTitle" xml:space="preserve"><value>استيراد الإعدادات</value></data>
|
||||
<data name="Settings_ExportTitle" xml:space="preserve"><value>تصدير الإعدادات</value></data>
|
||||
<data name="Settings_OpenFile" xml:space="preserve"><value>فتح ملف الإعدادات</value></data>
|
||||
<data name="Settings_Logging" xml:space="preserve"><value>السجلات</value></data>
|
||||
<data name="Settings_LogLevel" xml:space="preserve"><value>الحد الأدنى لمستوى السجل</value></data>
|
||||
<data name="Settings_LogLevelHint" xml:space="preserve"><value>يُصفّي ملف السجل المتدوّر وعارض السجل. اختر Debug للتشخيص، Information للاستخدام اليومي، Warning أو Error لتقليل الضوضاء.</value></data>
|
||||
|
||||
<!-- Update -->
|
||||
<data name="Update_Title" xml:space="preserve"><value>تحديث</value></data>
|
||||
@@ -94,8 +112,11 @@
|
||||
<data name="About_AiSection" xml:space="preserve"><value>التطوير بمساعدة الذكاء الاصطناعي</value></data>
|
||||
<data name="About_DisclaimersSection" xml:space="preserve"><value>إخلاءات المسؤولية</value></data>
|
||||
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>الترجمات</value></data>
|
||||
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>حزم اللغة العربية والفيتنامية مترجمة بمساعدة الآلة. قد لا تتطابق المصطلحات مع العرف المحلي، وبعض الكلمات التقنية (hotkey، toast، frame، إلخ) تُركت بالإنجليزية عمداً. نرحب بمتحدثي اللغة الأم الراغبين في المراجعة لإرسال طلبات سحب على ملفات .resx في src/CaptureImage.UI/Resources/Strings/.</value></data>
|
||||
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>دعم الالتقاط</value></data>
|
||||
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>يمكن لـ CaptureImage التقاط معظم الألعاب النافذية وعديمة الحدود عبر Windows.Graphics.Capture، لكن ليست كل لعبة تعمل. الأسطح المحمية بـ DRM، وألعاب Direct3D 9 بالشاشة الكاملة الحصرية، والألعاب ذات خطافات anti-cheat قد تعيد إطارات سوداء أو ترفض الالتقاط. تُجرَّب آلية احتياطية GDI PrintWindow للتطبيقات القديمة. راجع docs/legal/DISCLAIMER.md §2 للقائمة الكاملة.</value></data>
|
||||
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>بدون ضمان</value></data>
|
||||
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>يُوزَّع CaptureImage بموجب GPL-3.0-or-later كما هو، دون أي ضمان من أي نوع. المؤلفون غير مسؤولين عن لقطات الشاشة المفقودة أو تعطل الألعاب أو عقوبات anti-cheat أو فقد البيانات. الاستخدام على مسؤوليتك الخاصة. راجع docs/legal/DISCLAIMER.md للنص الكامل.</value></data>
|
||||
<data name="About_LegalSection" xml:space="preserve"><value>المستندات القانونية</value></data>
|
||||
<data name="About_ThirdPartySection" xml:space="preserve"><value>مكونات الطرف الثالث</value></data>
|
||||
<data name="About_ThirdPartyHint" xml:space="preserve"><value>انقر على "Third-party notices" أعلاه للحصول على القائمة الكاملة مع عناوين URL.</value></data>
|
||||
@@ -111,7 +132,10 @@
|
||||
<data name="Log_Pause" xml:space="preserve"><value>إيقاف مؤقت</value></data>
|
||||
<data name="Log_Resume" xml:space="preserve"><value>استئناف</value></data>
|
||||
<data name="Log_Clear" xml:space="preserve"><value>مسح</value></data>
|
||||
<data name="Log_Export" xml:space="preserve"><value>تصدير…</value></data>
|
||||
<data name="Log_EventsCount" xml:space="preserve"><value>{0} حدث</value></data>
|
||||
<data name="Log_EmptyState" xml:space="preserve"><value>لا توجد أحداث سجل بعد. ستظهر الأحداث المباشرة من محرك الالتقاط هنا.</value></data>
|
||||
<data name="Log_Filter" xml:space="preserve"><value>الحد الأدنى:</value></data>
|
||||
<data name="Log_RevealFolder" xml:space="preserve"><value>فتح المجلد</value></data>
|
||||
|
||||
<!-- Preview -->
|
||||
<data name="Preview_Title" xml:space="preserve"><value>معاينة</value></data>
|
||||
@@ -124,11 +148,10 @@
|
||||
<data name="Toast_CaptureFailed" xml:space="preserve"><value>فشل الالتقاط</value></data>
|
||||
<data name="Toast_SettingsImported" xml:space="preserve"><value>تم استيراد الإعدادات</value></data>
|
||||
<data name="Toast_SettingsExported" xml:space="preserve"><value>تم تصدير الإعدادات</value></data>
|
||||
<data name="Toast_Error" xml:space="preserve"><value>خطأ</value></data>
|
||||
|
||||
<!-- Tray menu -->
|
||||
<data name="Tray_ShowWindow" xml:space="preserve"><value>عرض CaptureImage</value></data>
|
||||
<data name="Tray_Arm" xml:space="preserve"><value>تفعيل الالتقاط</value></data>
|
||||
<data name="Tray_Disarm" xml:space="preserve"><value>إلغاء تفعيل الالتقاط</value></data>
|
||||
<data name="Tray_OpenFolder" xml:space="preserve"><value>فتح مجلد اللقطات</value></data>
|
||||
<data name="Tray_Exit" xml:space="preserve"><value>خروج</value></data>
|
||||
|
||||
|
||||
@@ -52,27 +52,45 @@
|
||||
<data name="Dashboard_StatusFailed" xml:space="preserve"><value>Capture failed ({0}): {1}</value></data>
|
||||
<data name="Dashboard_TargetsCount" xml:space="preserve"><value>{0} target(s) visible</value></data>
|
||||
<data name="Dashboard_Loading" xml:space="preserve"><value>Loading…</value></data>
|
||||
<data name="Dashboard_EmptyState" xml:space="preserve"><value>No visible windows to capture — launch your game or app, then click Refresh.</value></data>
|
||||
<data name="Dashboard_LogToggle" xml:space="preserve"><value>Toggle real-time log drawer</value></data>
|
||||
<data name="Dashboard_SteamBadge" xml:space="preserve"><value>STEAM</value></data>
|
||||
<data name="Dashboard_SteamBadgeTooltip" xml:space="preserve"><value>Steam game: {0} (AppId {1}). F12 screenshot is available via Steam Overlay. Some anti-cheat protected games may block external capture.</value></data>
|
||||
|
||||
<!-- Settings -->
|
||||
<data name="Settings_Title" xml:space="preserve"><value>Settings</value></data>
|
||||
<data name="Settings_Language" xml:space="preserve"><value>Language</value></data>
|
||||
<data name="Settings_Theme" xml:space="preserve"><value>Theme</value></data>
|
||||
<data name="Settings_Hotkey" xml:space="preserve"><value>Capture hotkey</value></data>
|
||||
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Default: Ctrl+Shift+F12. Hotkey editing lands in a future milestone.</value></data>
|
||||
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Click Record and press a combination. Esc cancels. Reset restores Ctrl+Shift+F12.</value></data>
|
||||
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>Record…</value></data>
|
||||
<data name="Settings_HotkeyCancel" xml:space="preserve"><value>Cancel</value></data>
|
||||
<data name="Settings_HotkeyReset" xml:space="preserve"><value>Reset</value></data>
|
||||
<data name="Settings_HotkeyRecorderPrompt" xml:space="preserve"><value>Press a key combination (Esc to cancel)…</value></data>
|
||||
<data name="Settings_HotkeyErrorNoPrimary" xml:space="preserve"><value>Select a primary key (e.g. a letter or an F-key).</value></data>
|
||||
<data name="Settings_HotkeyErrorModifierOnly" xml:space="preserve"><value>A modifier key alone isn't enough — add a letter or an F-key.</value></data>
|
||||
<data name="Settings_HotkeyErrorNeedsModifier" xml:space="preserve"><value>Plain letters and digits need at least one modifier (Ctrl/Alt/Shift/Win).</value></data>
|
||||
<data name="Settings_HotkeyErrorReserved" xml:space="preserve"><value>This combination is reserved by Windows and cannot be captured.</value></data>
|
||||
<data name="Settings_HotkeyConflictWarning" xml:space="preserve"><value>Another application may already own this combination — it might not fire while that app is running.</value></data>
|
||||
<data name="Settings_Format" xml:space="preserve"><value>Default format</value></data>
|
||||
<data name="Settings_JpegQuality" xml:space="preserve"><value>JPEG quality</value></data>
|
||||
<data name="Settings_WebpQuality" xml:space="preserve"><value>WebP quality</value></data>
|
||||
<data name="Settings_OutputFolder" xml:space="preserve"><value>Output folder</value></data>
|
||||
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(default: Pictures\CaptureImage)</value></data>
|
||||
<data name="Settings_Browse" xml:space="preserve"><value>Browse…</value></data>
|
||||
<data name="Settings_BrowseTitle" xml:space="preserve"><value>Choose output folder</value></data>
|
||||
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>Pick a folder instead of typing the path.</value></data>
|
||||
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>File name template</value></data>
|
||||
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>Preview each capture before saving</value></data>
|
||||
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>Close button minimizes to tray</value></data>
|
||||
<data name="Settings_SoundEnabled" xml:space="preserve"><value>Play capture sound</value></data>
|
||||
<data name="Settings_Import" xml:space="preserve"><value>Import…</value></data>
|
||||
<data name="Settings_Export" xml:space="preserve"><value>Export…</value></data>
|
||||
<data name="Settings_ImportTitle" xml:space="preserve"><value>Import settings</value></data>
|
||||
<data name="Settings_ExportTitle" xml:space="preserve"><value>Export settings</value></data>
|
||||
<data name="Settings_OpenFile" xml:space="preserve"><value>Open settings file</value></data>
|
||||
<data name="Settings_Logging" xml:space="preserve"><value>Logging</value></data>
|
||||
<data name="Settings_LogLevel" xml:space="preserve"><value>Minimum log level</value></data>
|
||||
<data name="Settings_LogLevelHint" xml:space="preserve"><value>Filters the rolling log file and viewer. Pick Debug for support diagnostics, Information for day-to-day, Warning or Error to keep logs quiet.</value></data>
|
||||
|
||||
<!-- Update -->
|
||||
<data name="Update_Title" xml:space="preserve"><value>Update</value></data>
|
||||
@@ -94,8 +112,11 @@
|
||||
<data name="About_AiSection" xml:space="preserve"><value>AI-assisted development</value></data>
|
||||
<data name="About_DisclaimersSection" xml:space="preserve"><value>Disclaimers</value></data>
|
||||
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>Translations</value></data>
|
||||
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Vietnamese and Arabic language packs are machine-assisted. Terminology may not match native conventions, and some technical words (hotkey, toast, frame, etc.) are kept in English on purpose. Native speakers willing to proofread are warmly invited to submit pull requests against the .resx files in src/CaptureImage.UI/Resources/Strings/.</value></data>
|
||||
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>Capture support</value></data>
|
||||
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage can capture most windowed and borderless games via Windows.Graphics.Capture, but not every title works. DRM-protected surfaces, exclusive-fullscreen Direct3D 9 games, and titles with anti-cheat hooks may return black frames or refuse capture. A GDI PrintWindow fallback is attempted for legacy apps. See docs/legal/DISCLAIMER.md §2 for the full list.</value></data>
|
||||
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>No warranty</value></data>
|
||||
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage is distributed under GPL-3.0-or-later AS IS, without warranty of any kind. The authors are not liable for lost screenshots, game crashes, anti-cheat sanctions, or data loss. Use at your own risk. See docs/legal/DISCLAIMER.md for the full text.</value></data>
|
||||
<data name="About_LegalSection" xml:space="preserve"><value>Legal documents</value></data>
|
||||
<data name="About_ThirdPartySection" xml:space="preserve"><value>Third-party components</value></data>
|
||||
<data name="About_ThirdPartyHint" xml:space="preserve"><value>Click "Third-party notices" above for the full list with upstream URLs.</value></data>
|
||||
@@ -111,7 +132,10 @@
|
||||
<data name="Log_Pause" xml:space="preserve"><value>Pause</value></data>
|
||||
<data name="Log_Resume" xml:space="preserve"><value>Resume</value></data>
|
||||
<data name="Log_Clear" xml:space="preserve"><value>Clear</value></data>
|
||||
<data name="Log_Export" xml:space="preserve"><value>Export…</value></data>
|
||||
<data name="Log_EventsCount" xml:space="preserve"><value>{0} events</value></data>
|
||||
<data name="Log_EmptyState" xml:space="preserve"><value>No log events yet. Live events from the capture engine will appear here.</value></data>
|
||||
<data name="Log_Filter" xml:space="preserve"><value>Min level:</value></data>
|
||||
<data name="Log_RevealFolder" xml:space="preserve"><value>Open folder</value></data>
|
||||
|
||||
<!-- Preview -->
|
||||
<data name="Preview_Title" xml:space="preserve"><value>Preview</value></data>
|
||||
@@ -124,11 +148,10 @@
|
||||
<data name="Toast_CaptureFailed" xml:space="preserve"><value>Capture failed</value></data>
|
||||
<data name="Toast_SettingsImported" xml:space="preserve"><value>Settings imported</value></data>
|
||||
<data name="Toast_SettingsExported" xml:space="preserve"><value>Settings exported</value></data>
|
||||
<data name="Toast_Error" xml:space="preserve"><value>Error</value></data>
|
||||
|
||||
<!-- Tray menu -->
|
||||
<data name="Tray_ShowWindow" xml:space="preserve"><value>Show CaptureImage</value></data>
|
||||
<data name="Tray_Arm" xml:space="preserve"><value>Arm capture</value></data>
|
||||
<data name="Tray_Disarm" xml:space="preserve"><value>Disarm capture</value></data>
|
||||
<data name="Tray_OpenFolder" xml:space="preserve"><value>Open captures folder</value></data>
|
||||
<data name="Tray_Exit" xml:space="preserve"><value>Exit</value></data>
|
||||
|
||||
|
||||
@@ -52,27 +52,45 @@
|
||||
<data name="Dashboard_StatusFailed" xml:space="preserve"><value>Chụp lỗi ({0}): {1}</value></data>
|
||||
<data name="Dashboard_TargetsCount" xml:space="preserve"><value>{0} đối tượng khả dụng</value></data>
|
||||
<data name="Dashboard_Loading" xml:space="preserve"><value>Đang tải…</value></data>
|
||||
<data name="Dashboard_EmptyState" xml:space="preserve"><value>Không có cửa sổ nào để chụp — khởi chạy game hoặc ứng dụng của bạn, rồi bấm Làm mới.</value></data>
|
||||
<data name="Dashboard_LogToggle" xml:space="preserve"><value>Bật/tắt khay nhật ký thời gian thực</value></data>
|
||||
<data name="Dashboard_SteamBadge" xml:space="preserve"><value>STEAM</value></data>
|
||||
<data name="Dashboard_SteamBadgeTooltip" xml:space="preserve"><value>Game Steam: {0} (AppId {1}). Phím F12 có sẵn qua Steam Overlay. Một số game có anti-cheat có thể chặn capture từ bên ngoài.</value></data>
|
||||
|
||||
<!-- Settings -->
|
||||
<data name="Settings_Title" xml:space="preserve"><value>Cài đặt</value></data>
|
||||
<data name="Settings_Language" xml:space="preserve"><value>Ngôn ngữ</value></data>
|
||||
<data name="Settings_Theme" xml:space="preserve"><value>Giao diện</value></data>
|
||||
<data name="Settings_Hotkey" xml:space="preserve"><value>Hotkey chụp</value></data>
|
||||
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Mặc định: Ctrl+Shift+F12. Chỉnh sửa hotkey sẽ có trong milestone sau.</value></data>
|
||||
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Nhấn Ghi rồi nhấn tổ hợp phím. Esc để huỷ. Đặt lại sẽ khôi phục Ctrl+Shift+F12.</value></data>
|
||||
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>Ghi…</value></data>
|
||||
<data name="Settings_HotkeyCancel" xml:space="preserve"><value>Huỷ</value></data>
|
||||
<data name="Settings_HotkeyReset" xml:space="preserve"><value>Đặt lại</value></data>
|
||||
<data name="Settings_HotkeyRecorderPrompt" xml:space="preserve"><value>Nhấn tổ hợp phím (Esc để huỷ)…</value></data>
|
||||
<data name="Settings_HotkeyErrorNoPrimary" xml:space="preserve"><value>Chọn một phím chính (ví dụ chữ cái hoặc phím F).</value></data>
|
||||
<data name="Settings_HotkeyErrorModifierOnly" xml:space="preserve"><value>Chỉ phím bổ trợ là chưa đủ — hãy thêm chữ cái hoặc phím F.</value></data>
|
||||
<data name="Settings_HotkeyErrorNeedsModifier" xml:space="preserve"><value>Chữ cái hoặc chữ số cần kèm ít nhất một phím bổ trợ (Ctrl/Alt/Shift/Win).</value></data>
|
||||
<data name="Settings_HotkeyErrorReserved" xml:space="preserve"><value>Tổ hợp này bị Windows giữ và không thể chụp được.</value></data>
|
||||
<data name="Settings_HotkeyConflictWarning" xml:space="preserve"><value>Ứng dụng khác có thể đã đăng ký tổ hợp này — nó có thể không kích hoạt khi ứng dụng đó đang chạy.</value></data>
|
||||
<data name="Settings_Format" xml:space="preserve"><value>Định dạng mặc định</value></data>
|
||||
<data name="Settings_JpegQuality" xml:space="preserve"><value>Chất lượng JPEG</value></data>
|
||||
<data name="Settings_WebpQuality" xml:space="preserve"><value>Chất lượng WebP</value></data>
|
||||
<data name="Settings_OutputFolder" xml:space="preserve"><value>Thư mục lưu</value></data>
|
||||
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(mặc định: Pictures\CaptureImage)</value></data>
|
||||
<data name="Settings_Browse" xml:space="preserve"><value>Duyệt…</value></data>
|
||||
<data name="Settings_BrowseTitle" xml:space="preserve"><value>Chọn thư mục lưu</value></data>
|
||||
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>Chọn thư mục thay vì phải gõ đường dẫn.</value></data>
|
||||
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>Mẫu tên tệp</value></data>
|
||||
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>Xem trước từng ảnh chụp trước khi lưu</value></data>
|
||||
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>Nút đóng sẽ thu nhỏ xuống tray</value></data>
|
||||
<data name="Settings_SoundEnabled" xml:space="preserve"><value>Phát âm thanh khi chụp</value></data>
|
||||
<data name="Settings_Import" xml:space="preserve"><value>Nhập…</value></data>
|
||||
<data name="Settings_Export" xml:space="preserve"><value>Xuất…</value></data>
|
||||
<data name="Settings_ImportTitle" xml:space="preserve"><value>Nhập cài đặt</value></data>
|
||||
<data name="Settings_ExportTitle" xml:space="preserve"><value>Xuất cài đặt</value></data>
|
||||
<data name="Settings_OpenFile" xml:space="preserve"><value>Mở tệp cài đặt</value></data>
|
||||
<data name="Settings_Logging" xml:space="preserve"><value>Ghi log</value></data>
|
||||
<data name="Settings_LogLevel" xml:space="preserve"><value>Mức log tối thiểu</value></data>
|
||||
<data name="Settings_LogLevelHint" xml:space="preserve"><value>Lọc cả file log xoay vòng và cửa sổ Log. Chọn Debug khi gỡ lỗi, Information cho vận hành hằng ngày, Warning hoặc Error để giữ log gọn.</value></data>
|
||||
|
||||
<!-- Update -->
|
||||
<data name="Update_Title" xml:space="preserve"><value>Cập nhật</value></data>
|
||||
@@ -94,8 +112,11 @@
|
||||
<data name="About_AiSection" xml:space="preserve"><value>Phát triển có hỗ trợ AI</value></data>
|
||||
<data name="About_DisclaimersSection" xml:space="preserve"><value>Tuyên bố miễn trừ</value></data>
|
||||
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>Bản dịch</value></data>
|
||||
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Gói ngôn ngữ tiếng Việt và tiếng Ả Rập đang dùng bản dịch máy. Thuật ngữ có thể không khớp với quy ước bản ngữ, và một số từ kỹ thuật (hotkey, toast, frame, v.v.) được giữ tiếng Anh có chủ đích. Người bản ngữ sẵn lòng hiệu đính xin gửi pull request vào các tệp .resx trong src/CaptureImage.UI/Resources/Strings/.</value></data>
|
||||
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>Khả năng chụp</value></data>
|
||||
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage có thể chụp hầu hết game cửa sổ và borderless qua Windows.Graphics.Capture, nhưng không phải game nào cũng hoạt động. Bề mặt có DRM, game Direct3D 9 exclusive-fullscreen, và game có hook anti-cheat có thể trả khung đen hoặc từ chối chụp. Cơ chế dự phòng GDI PrintWindow được thử cho ứng dụng cũ. Xem docs/legal/DISCLAIMER.md §2 để biết danh sách đầy đủ.</value></data>
|
||||
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>Không bảo hành</value></data>
|
||||
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage được phân phối theo GPL-3.0-or-later NGUYÊN TRẠNG, không kèm bảo đảm dưới bất kỳ hình thức nào. Các tác giả không chịu trách nhiệm về ảnh chụp bị mất, game crash, chế tài từ anti-cheat, hay mất dữ liệu. Dùng với rủi ro của chính bạn. Xem docs/legal/DISCLAIMER.md để biết toàn văn.</value></data>
|
||||
<data name="About_LegalSection" xml:space="preserve"><value>Tài liệu pháp lý</value></data>
|
||||
<data name="About_ThirdPartySection" xml:space="preserve"><value>Thành phần third-party</value></data>
|
||||
<data name="About_ThirdPartyHint" xml:space="preserve"><value>Bấm "Third-party notices" phía trên để xem danh sách đầy đủ kèm URL upstream.</value></data>
|
||||
@@ -111,7 +132,10 @@
|
||||
<data name="Log_Pause" xml:space="preserve"><value>Tạm dừng</value></data>
|
||||
<data name="Log_Resume" xml:space="preserve"><value>Tiếp tục</value></data>
|
||||
<data name="Log_Clear" xml:space="preserve"><value>Xoá</value></data>
|
||||
<data name="Log_Export" xml:space="preserve"><value>Xuất…</value></data>
|
||||
<data name="Log_EventsCount" xml:space="preserve"><value>{0} sự kiện</value></data>
|
||||
<data name="Log_EmptyState" xml:space="preserve"><value>Chưa có sự kiện nhật ký nào. Sự kiện thời gian thực từ capture engine sẽ xuất hiện ở đây.</value></data>
|
||||
<data name="Log_Filter" xml:space="preserve"><value>Mức tối thiểu:</value></data>
|
||||
<data name="Log_RevealFolder" xml:space="preserve"><value>Mở thư mục</value></data>
|
||||
|
||||
<!-- Preview -->
|
||||
<data name="Preview_Title" xml:space="preserve"><value>Xem trước</value></data>
|
||||
@@ -124,11 +148,10 @@
|
||||
<data name="Toast_CaptureFailed" xml:space="preserve"><value>Chụp thất bại</value></data>
|
||||
<data name="Toast_SettingsImported" xml:space="preserve"><value>Đã nhập cài đặt</value></data>
|
||||
<data name="Toast_SettingsExported" xml:space="preserve"><value>Đã xuất cài đặt</value></data>
|
||||
<data name="Toast_Error" xml:space="preserve"><value>Lỗi</value></data>
|
||||
|
||||
<!-- Tray menu -->
|
||||
<data name="Tray_ShowWindow" xml:space="preserve"><value>Hiện CaptureImage</value></data>
|
||||
<data name="Tray_Arm" xml:space="preserve"><value>Sẵn sàng chụp</value></data>
|
||||
<data name="Tray_Disarm" xml:space="preserve"><value>Ngừng chụp</value></data>
|
||||
<data name="Tray_OpenFolder" xml:space="preserve"><value>Mở thư mục ảnh</value></data>
|
||||
<data name="Tray_Exit" xml:space="preserve"><value>Thoát</value></data>
|
||||
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using CaptureImage.Core.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SkiaSharp;
|
||||
|
||||
namespace CaptureImage.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Avalonia-backed tray icon host. Draws its own icon at runtime via SkiaSharp so we don't
|
||||
/// need to ship an <c>.ico</c> asset yet, wires a localized context menu, and implements
|
||||
/// minimize-to-tray behaviour by intercepting the main window's <c>Closing</c> event.
|
||||
/// </summary>
|
||||
public sealed class AvaloniaTrayIconHost : ITrayIconHost
|
||||
{
|
||||
private readonly ILocalizationService _localization;
|
||||
private readonly ISettingsStore _settings;
|
||||
private readonly ILogger<AvaloniaTrayIconHost> _logger;
|
||||
|
||||
private TrayIcon? _trayIcon;
|
||||
private Window? _mainWindow;
|
||||
private bool _disposed;
|
||||
|
||||
public AvaloniaTrayIconHost(
|
||||
ILocalizationService localization,
|
||||
ISettingsStore settings,
|
||||
ILogger<AvaloniaTrayIconHost> logger)
|
||||
{
|
||||
_localization = localization;
|
||||
_settings = settings;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public void Initialize(object mainWindow)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_mainWindow = mainWindow as Window
|
||||
?? throw new ArgumentException("mainWindow must be an Avalonia Window", nameof(mainWindow));
|
||||
|
||||
_trayIcon = new TrayIcon
|
||||
{
|
||||
Icon = BuildRuntimeIcon(),
|
||||
ToolTipText = "CaptureImage",
|
||||
IsVisible = true,
|
||||
Menu = BuildMenu(),
|
||||
};
|
||||
|
||||
_trayIcon.Clicked += (_, _) => ShowMainWindow();
|
||||
|
||||
var icons = new TrayIcons { _trayIcon };
|
||||
TrayIcon.SetIcons(Application.Current!, icons);
|
||||
|
||||
_mainWindow.Closing += OnMainWindowClosing;
|
||||
_localization.PropertyChanged += (_, _) => RefreshMenuLabels();
|
||||
|
||||
_logger.LogInformation("Tray icon initialized.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
if (_mainWindow is not null)
|
||||
{
|
||||
_mainWindow.Closing -= OnMainWindowClosing;
|
||||
}
|
||||
if (_trayIcon is not null)
|
||||
{
|
||||
_trayIcon.IsVisible = false;
|
||||
_trayIcon.Dispose();
|
||||
_trayIcon = null;
|
||||
}
|
||||
}
|
||||
|
||||
// -- menu ----------------------------------------------------------------
|
||||
|
||||
private NativeMenu BuildMenu()
|
||||
{
|
||||
var menu = new NativeMenu();
|
||||
|
||||
var showItem = new NativeMenuItem(_localization["Tray_ShowWindow"]);
|
||||
showItem.Click += (_, _) => ShowMainWindow();
|
||||
menu.Add(showItem);
|
||||
|
||||
var openFolderItem = new NativeMenuItem(_localization["Tray_OpenFolder"]);
|
||||
openFolderItem.Click += (_, _) => OpenCaptureFolder();
|
||||
menu.Add(openFolderItem);
|
||||
|
||||
menu.Add(new NativeMenuItemSeparator());
|
||||
|
||||
var exitItem = new NativeMenuItem(_localization["Tray_Exit"]);
|
||||
exitItem.Click += (_, _) => QuitApp();
|
||||
menu.Add(exitItem);
|
||||
|
||||
return menu;
|
||||
}
|
||||
|
||||
private void RefreshMenuLabels()
|
||||
{
|
||||
if (_trayIcon?.Menu is null) return;
|
||||
// Rebuild the menu from scratch — simplest approach, and the menu is tiny.
|
||||
var newMenu = BuildMenu();
|
||||
_trayIcon.Menu = newMenu;
|
||||
}
|
||||
|
||||
// -- actions -------------------------------------------------------------
|
||||
|
||||
private void ShowMainWindow()
|
||||
{
|
||||
if (_mainWindow is null) return;
|
||||
_mainWindow.Show();
|
||||
_mainWindow.WindowState = WindowState.Normal;
|
||||
_mainWindow.Activate();
|
||||
}
|
||||
|
||||
private void OpenCaptureFolder()
|
||||
{
|
||||
var outputDir = !string.IsNullOrWhiteSpace(_settings.Current.Capture.OutputDirectory)
|
||||
? _settings.Current.Capture.OutputDirectory
|
||||
: Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
|
||||
"CaptureImage");
|
||||
Directory.CreateDirectory(outputDir);
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(outputDir) { UseShellExecute = true });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to open capture folder {Path}", outputDir);
|
||||
}
|
||||
}
|
||||
|
||||
private void QuitApp()
|
||||
{
|
||||
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
desktop.Shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnMainWindowClosing(object? sender, WindowClosingEventArgs e)
|
||||
{
|
||||
if (_disposed) return;
|
||||
if (!_settings.Current.UI.MinimizeToTray) return;
|
||||
|
||||
// Swallow the close, hide instead. User can quit via tray menu.
|
||||
e.Cancel = true;
|
||||
_mainWindow?.Hide();
|
||||
_logger.LogDebug("Main window hidden to tray (MinimizeToTray enabled).");
|
||||
}
|
||||
|
||||
// -- icon generation -----------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Draw a 32×32 PNG icon at runtime and wrap it in a <see cref="WindowIcon"/>. Keeps
|
||||
/// the repo free of binary assets until we have real branding.
|
||||
/// </summary>
|
||||
private static WindowIcon BuildRuntimeIcon()
|
||||
{
|
||||
const int size = 32;
|
||||
var info = new SKImageInfo(size, size);
|
||||
using var surface = SKSurface.Create(info);
|
||||
var canvas = surface.Canvas;
|
||||
canvas.Clear(SKColors.Transparent);
|
||||
|
||||
using (var body = new SKPaint
|
||||
{
|
||||
Color = SKColor.Parse("#FF6B35"),
|
||||
Style = SKPaintStyle.Fill,
|
||||
IsAntialias = true,
|
||||
})
|
||||
{
|
||||
// Rounded rectangle body.
|
||||
var rect = new SKRect(3, 8, size - 3, size - 4);
|
||||
canvas.DrawRoundRect(rect, 4, 4, body);
|
||||
}
|
||||
|
||||
using (var lens = new SKPaint
|
||||
{
|
||||
Color = SKColor.Parse("#1F2937"),
|
||||
Style = SKPaintStyle.Fill,
|
||||
IsAntialias = true,
|
||||
})
|
||||
{
|
||||
canvas.DrawCircle(size / 2f, size / 2f + 2, 6, lens);
|
||||
}
|
||||
|
||||
using (var lensInner = new SKPaint
|
||||
{
|
||||
Color = SKColors.White,
|
||||
Style = SKPaintStyle.Fill,
|
||||
IsAntialias = true,
|
||||
})
|
||||
{
|
||||
canvas.DrawCircle(size / 2f, size / 2f + 2, 3, lensInner);
|
||||
}
|
||||
|
||||
// Shutter tab on top.
|
||||
using (var tab = new SKPaint
|
||||
{
|
||||
Color = SKColor.Parse("#FF6B35"),
|
||||
Style = SKPaintStyle.Fill,
|
||||
IsAntialias = true,
|
||||
})
|
||||
{
|
||||
canvas.DrawRoundRect(new SKRect(12, 4, 20, 8), 2, 2, tab);
|
||||
}
|
||||
|
||||
using var image = surface.Snapshot();
|
||||
using var data = image.Encode(SKEncodedImageFormat.Png, 100);
|
||||
return new WindowIcon(new MemoryStream(data.ToArray()));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user