19 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.7 4c1dba2dbd fix(release): v1.3.1 hotfix — copy .xbf + .pri to publish output
v1.3.0 shipped broken. The WinUI 3 publish pipeline silently omits two
file types from the self-contained publish output:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:17:11 +07:00
poli0981andClaude Opus 4.7 7bd2bf9df0 chore(release): bump to v1.2.0
Logging-overhaul release. Turns the v1.1 logging surface — working but
thin — into a diagnostic tool developers and end-users can rely on when
something misbehaves. No capture-engine changes, no breaking config
changes; Velopack publish on the existing `win` channel.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 08:54:03 +07:00
110 changed files with 4540 additions and 1900 deletions

No files matched your search

+14 -8
View File
@@ -1,9 +1,9 @@
name: Release
# Cut a new release when a tag of the form v1.2.3 is pushed. Packages the
# CaptureImage.App project as a single-file self-contained Win64 build,
# wraps it in a Velopack installer, and uploads the result to a GitHub
# Release matching the tag.
# Cut a new release when a tag of the form v1.2.3 is pushed. Publishes the
# CaptureImage.App project as a multi-file WinAppSDK self-contained Win64
# build (WinUI 3 can't bundle into a single .exe), wraps it in a Velopack
# installer, and uploads the result to a GitHub Release matching the tag.
#
# Code signing is NOT performed yet (SignPath application was declined).
# The installer will trigger Windows SmartScreen "Unknown publisher" until
@@ -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
@@ -143,6 +147,7 @@ jobs:
files: |
./releases/*.exe
./releases/*.nupkg
./releases/*.zip
./releases/RELEASES
./releases/releases.*.json
./releases/SHA256SUMS.txt
@@ -154,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.
+214
View File
@@ -7,6 +7,220 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.3.1] - 2026-04-26
**Critical hotfix.** v1.3.0 shipped broken — the WinUI 3 publish pipeline
omitted `.xbf` (compiled XAML binary) and `CaptureImage.App.pri` (resource
manifest) files from the self-contained publish output, so the installed
app silently failed at MainWindow.InitializeComponent on every launch
(the process stayed alive zombie-style; no window ever appeared). v1.2.x
auto-update users hit this on the first launch after Velopack restart.
### Fixed
- Add a `CopyWinUIArtifactsToPublishDirectory` MSBuild target to
`CaptureImage.App.csproj` that propagates every `.xbf` and the
`CaptureImage.App.pri` from `bin/.../win-x64/` into the publish
output, preserving the cross-assembly XAML resolution subfolders
(`CaptureImage.UI/Controls/`, `CaptureImage.UI/Views/`). `dotnet
publish` for unpackaged WinUI 3 self-contained apps doesn't include
these by default — known WinAppSDK gap.
### Recovery for v1.3.0 users
If you already updated to broken v1.3.0:
- The Update tab can't help (the app's window doesn't open).
- Download `CaptureImage-win-Setup.exe` from the v1.3.1 GitHub Release
and run it — the installer detects the existing install and replaces
it cleanly. Your `settings.json` and capture folder are untouched.
## [1.3.0] - 2026-04-26
UI framework migration from Avalonia 11 to **WinUI 3 (Windows App SDK 1.8.x)**
with Fluent 2 design — Mica backdrop, Segoe UI Variable, integrated title bar,
Composition-API animations. Logic layers (Core / Infrastructure / ViewModels)
were intentionally left untouched: the entire ~5,000-line domain + capture +
hotkey + settings + logging stack carries forward unchanged. Velopack ships
on the existing `win` channel so v1.2.x users auto-update; multi-file
WindowsAppSDK self-contained payload is ~80–120 MB (vs the v1.2 single-file
~30 MB) — accepted trade for stack-Microsoft-native parity on Windows-only.
### Added
- **Sound on capture success** (`UI.SoundEnabled` setting now has a consumer
for the first time since v1.0). Plays Windows `SystemAsterisk` via Win32
`PlaySound` P/Invoke, gated on the existing checkbox.
- **Browse button** on Settings → Output folder. Opens the modern
`IFileOpenDialog` (Vista+ folder picker) seeded at the current
OutputDirectory. Win32 COM-interop fallback because
`Windows.Storage.Pickers.FolderPicker` is unreliable in unpackaged
WinUI 3.
- **Mica backdrop** on the main window — translucent Win11 wallpaper tint.
- **Borderless title bar** integrated with the Fluent 2 chrome; caption
buttons sit in a 48 px reserved drag region.
- **Composition slide animation** on the log drawer — 220 ms slide + 180 ms
fade with CubicBezier(0.4, 0, 0.2, 1) decelerate. Mirrors the v1.2
Avalonia drawer at the visual layer; uses `UIElement.Translation` (additive
on layout) instead of `Visual.Offset` (overrides layout) so the drawer
stays anchored to its Grid column under all window sizes.
- **+164 tests, total 320** (up from 156). New coverage:
- 18 converter tests (FlowDirection / BoolToVisibility / InvertedBoolToVisibility / NotNullToVisibility).
- 5 LogEntry tests (TimestampText format, FileLineText edge cases).
- 141 Theory cases for localization completeness — 47 load-bearing keys
× 3 cultures (en-US / vi-VN / ar-SA) — every shipping label asserted
non-empty + non-bracketed.
### Changed
- **UI framework**: Avalonia 11.2.3 → WinUI 3 (Windows App SDK
1.8.260416003) self-contained x64. ViewModels project still
TFM-portable (`net9.0`); UI + UI.Tests TFM bumped to
`net9.0-windows10.0.22621.0` to link WinAppSDK assemblies.
- **Tray icon**: `H.NotifyIcon.WindowsAppSDK` → `H.NotifyIcon.WinUI` (the
actual nuget.org package id; the WindowsAppSDK suffix never existed on
nuget). Tray ships with OS default glyph for v1.3.0 — proper .ico
round-trip via `System.Drawing.Bitmap.GetHicon` + `Icon.Save` deferred
to v1.4.
- **Folder picker**: Win32 `IFileOpenDialog` COM interop replaces the
unreliable `Windows.Storage.Pickers.FolderPicker` in
`CaptureImage.UI.Services.Win32FolderPicker`.
- **Tray menu commands** wired through `MenuFlyoutItem.Command` (not
`Click` event) — the latter doesn't fire reliably from H.NotifyIcon's
out-of-tree popup.
- **Sound playback** uses Win32 `PlaySound` P/Invoke instead of
`System.Media.SystemSounds` (the latter ships in
`System.Windows.Extensions` which only targets Windows TFMs, too
restrictive for the portable ViewModels project).
- **Tray-restore from minimize** uses `AppWindow.Show` +
`User32.ShowWindow(SW_RESTORE)` + `Window.Activate` +
`User32.SetForegroundWindow` — `Show` alone leaves taskbar-minimized
windows minimized + behind whatever has foreground focus.
- **Auto-refresh suppression** while a preview modal is up — Dashboard's
WMI-driven Targets refresh used to clobber the in-flight
`SelectedTarget` and disrupt the preview decision; now skipped when
state is Previewing or Saving.
- **3rd-party list** in About: drop Avalonia + Inter typeface, add
Windows App SDK / WinUI 3 + H.NotifyIcon.WinUI.
### Removed
- `Avalonia.*` packages (Avalonia, Avalonia.Desktop, Avalonia.Themes.Fluent,
Avalonia.Fonts.Inter, Avalonia.Diagnostics) and 25 .axaml files / Avalonia
service implementations (`AvaloniaTrayIconHost`, `AvaloniaPreviewPresenter`,
`AvaloniaUIDispatcher`, `BytesToBitmapConverter` for Avalonia.Bitmap,
`ToastKindToBrushConverter` for Avalonia.IBrush). All replaced with WinUI 3
equivalents.
- Inter typeface — Fluent 2's Segoe UI Variable is the explicit body font now.
- `PublishSingleFile` from the release workflow — WinAppSDK can't be
bundled into a single .exe, ships as multi-file folder packaged by
Velopack.
### Fixed
- (in v1.3 from v1.2 carry-overs) Title-bar caption buttons no longer
overlap nav rail / Page content — 48 px drag region reserved at top
via `Window.SetTitleBar(AppTitleBar)`.
### Deferred to v1.4
- Real .ico tray icon via `System.Drawing.Bitmap.GetHicon` round-trip
(currently OS default glyph). H.NotifyIcon.WinUI's IconSource pipeline
ends in `System.Drawing.Icon` which only accepts .ico file streams.
- `release.yml` upload of `CaptureImage-win-Portable.zip` (carry-over
from v1.2 — added in v1.3 release cut).
- DPI-aware initial window sizing (`AppWindow.Resize` takes physical
pixels; v1.3 hardcodes 1200×720).
## [1.2.0] - 2026-04-21
Logging overhaul. Turns a working-but-thin diagnostic surface into one you
can actually rely on when things go wrong — developer and end-user alike.
No capture-engine changes; Velopack release on the existing `win` channel
so the delta chain from v1.1.2 stays intact.
### Added
- **Runtime log-level control.** New Settings → Logging group with a
minimum-level picker (Debug / Information / Warning / Error).
Persisted in `AppSettings.LogLevel` (new field, schema bump v1 → v2,
additive) and pushed into Serilog's `LoggingLevelSwitch` live — no
restart required.
- **Log viewer min-level filter.** Dropdown in the log drawer header
narrows what's shown without touching the sink buffer, so Export
still carries the full history regardless of the filter.
- **"Open folder" button in the log drawer.** Launches Explorer at
`%LocalAppData%\CaptureImage\logs` for support-session copy-paste.
Guarded with a Toast on failure.
- **Caller context on every log entry** — each line carries `File`,
`Line`, and `Member` structured properties, captured via new
`LogInformationAt` / `LogWarningAt` / `LogErrorAt` / `LogDebugAt`
extension methods on `ILogger`. Rolling-file template now prints
`(File.cs:42)`; log viewer shows a subdued `File:Line` column; Export
includes the same. Absolute build-machine paths are stripped via
`Path.GetFileName` so shipped logs stay clean.
- **Global exception handlers.** `AppDomain.UnhandledException`,
`TaskScheduler.UnobservedTaskException`, and
`Dispatcher.UIThread.UnhandledException` all now reach Serilog before
the process dies or the UI resumes. `SetObserved()` on unobserved
task exceptions keeps the default-crash policy from ending the app on
background-thread throws.
- **Startup + shutdown banner** — Program.Main logs
`Version` / `OS` / `Culture` / `Args` on start and a
`Reason=Normal|StartupCrash` line on exit, so support sessions can
tell which build produced the log at a glance.
- **Expanded coverage** — `Windows.Graphics.Capture` engine emits Info
on session start, Debug on first frame + session dispose, Warning on
frame timeout, Error with explicit `HRESULT=0x…` on `COMException`;
`HotkeyConflictSniffer` decodes Win32 error codes by name
(`ERROR_HOTKEY_ALREADY_REGISTERED` / `ERROR_INVALID_PARAMETER` / …);
`SharpHookHotkeyService` logs when `TaskPoolGlobalHook` boots;
`VelopackUpdateService` logs before + after
`ApplyUpdatesAndRestart`; `AvaloniaTrayIconHost` logs tray
init/dispose and guards the runtime SkiaSharp icon render so a
native-asset blow-up falls back to the platform default instead of
crashing startup; `ResxLocalizationService` warns once per
`(culture, key)` pair when a resource key is missing (dedup
prevents flooding on every refresh).
### Changed
- **Window widened to 1200×720** (was 960×600) and **log drawer
widened to 480 px** (was 400 px). The drawer now slides in with a
200 ms fade + 48 px translate-X easing (`CircularEaseOut`) instead
of snapping in and out. Content area visible while the drawer is
open is now ~500 px (was ~340 px).
- **Scroll bars hidden on About + Settings tabs.** Mouse-wheel
scrolling still works; the track is just no longer drawn, so the
view reads cleanly on the fixed-size window. Horizontal scrolling
on those tabs is disabled entirely. Diagnostic surfaces (Update
log, Log viewer drawer) keep their visible bars.
- **Default minimum log level is now `Information`** (was `Debug`).
v1 users are migrated in place: `settings.json` is stamped
Version=2 on first v1.2 launch and the LogLevel field defaults to
`Information`. Flip back to Debug via Settings → Logging if you
were relying on verbose output.
- Four previously-silent `catch { /* ignore */ }` blocks now log
their exceptions: `SharpHookHotkeyService.Stop/Dispose` (Warning),
`WmiProcessWatcher.DisposeWatchers_NoLock` (Debug),
`JsonSettingsStore.Deserialize` (Warning with JSON line / byte
position), `JsonSettingsStore.TryDelete` (Debug).
### Migration
- **`settings.json` schema v1 → v2.** Automatic on first v1.2 run —
the file is re-written in canonical v2 form with `LogLevel =
"Information"` and existing values preserved. Hand-edited files
with `logLevel` already present keep their value.
### Tests
- 33 new unit tests (total 156, up from 123). Covers the
`InMemorySink` ring buffer / pause / clear / snapshot-copy
semantics, `SerilogLogLevelSwitcher` string mapping + fallback,
`CallerAwareLoggerExtensions` scope + path-stripping behaviour,
`LogViewerViewModel` hydration / filter / live-tail paths, and the
v1 → v2 settings migration with write-back.
## [1.1.2] - 2026-04-20
Localization hotfix on top of v1.1.1 — closes 13 bugs and gaps found in
+9 -9
View File
@@ -5,12 +5,14 @@
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
<ItemGroup Label="Avalonia">
<PackageVersion Include="Avalonia" Version="11.2.3" />
<PackageVersion Include="Avalonia.Desktop" Version="11.2.3" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<PackageVersion Include="Avalonia.Diagnostics" Version="11.2.3" />
<ItemGroup Label="WinUI 3 / Windows App SDK">
<PackageVersion Include="Microsoft.WindowsAppSDK" Version="1.8.260416003" />
<PackageVersion Include="Microsoft.WindowsAppSDK.Base" Version="1.8.251216001" />
<PackageVersion Include="Microsoft.WindowsAppSDK.Foundation" Version="1.8.260415000" />
<PackageVersion Include="Microsoft.WindowsAppSDK.Runtime" Version="1.8.260416003" />
<PackageVersion Include="Microsoft.WindowsAppSDK.WinUI" Version="1.8.260415005" />
<PackageVersion Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.28000.1721" />
<PackageVersion Include="Microsoft.Web.WebView2" Version="1.0.3912.50" />
</ItemGroup>
<ItemGroup Label="MVVM">
@@ -28,7 +30,7 @@
</ItemGroup>
<ItemGroup Label="Tray">
<PackageVersion Include="H.NotifyIcon.WindowsAppSDK" Version="2.2.0" />
<PackageVersion Include="H.NotifyIcon.WinUI" Version="2.2.0" />
<PackageVersion Include="H.NotifyIcon" Version="2.2.0" />
</ItemGroup>
@@ -63,8 +65,6 @@
</ItemGroup>
<ItemGroup Label="Imaging">
<!-- Avalonia ships SkiaSharp transitively, but Infrastructure doesn't reference Avalonia
so we pin it explicitly here. Bumping deliberately to match Avalonia's choice. -->
<PackageVersion Include="SkiaSharp" Version="3.119.2" />
<PackageVersion Include="SkiaSharp.NativeAssets.Win32" Version="3.119.2" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" />
+4 -3
View File
@@ -139,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/
+24 -15
View File
@@ -20,10 +20,11 @@ Five projects, four rules:
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 Avalonia.
types exist so the UI logic is testable without WinUI 3.
**Depends on Core only.**
- **`CaptureImage.UI`** (net9.0) — Avalonia views, custom controls,
converters, resx localization. **Depends on Core + ViewModels.**
- **`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.**
@@ -31,7 +32,7 @@ Five projects, four rules:
```mermaid
graph LR
App[CaptureImage.App<br/>net9.0-windows]
UI[CaptureImage.UI<br/>net9.0 · Avalonia]
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]
@@ -50,8 +51,9 @@ graph LR
- `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 Avalonia's designer +
hot-reload tooling work without dragging in WinRT projections.
- `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.
@@ -223,13 +225,16 @@ at startup.
1. `VelopackApp.Build().Run()` — must be the first line of `Main` so
Velopack can handle `--squirrel-install`, `--squirrel-firstrun`, etc.
before Avalonia spins up.
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. Avalonia `BuildAvaloniaApp().StartWithClassicDesktopLifetime(args)`.
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
@@ -245,7 +250,7 @@ sequenceDiagram
participant Settings as SettingsViewModel
participant Loc as ResxLocalizationService
participant RM as ResourceManager
participant XAML as Avalonia bindings
participant XAML as WinUI 3 bindings
User->>Settings: Pick "العربية" in Language dropdown
Settings->>Loc: SetCulture(ar-SA)
@@ -261,11 +266,15 @@ sequenceDiagram
**Key properties:**
- `PropertyChanged("Item[]")` is the magic indexer-binding refresh
signal for Avalonia. Firing it once after a culture change refreshes
every `{Binding Localization[...]}` in the tree.
- `MainWindow.axaml` binds `FlowDirection` to
`Localization.CurrentFlowDirection`. Arabic, Hebrew, Farsi, Urdu —
any two-letter language code in the RTL set — mirrors the whole tree.
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.
@@ -294,7 +303,7 @@ sequenceDiagram
Main->>Velo: Build().Run(args)
Note over Velo: Handles --squirrel-install,<br/>--squirrel-firstrun etc.<br/>then returns to caller
Main->>Main: BuildAvaloniaApp()
Main->>Main: Application.Start(...)
User->>UI: Click "Check for updates"
UI->>VM: CheckCommand
+7 -2
View File
@@ -73,8 +73,13 @@ CaptureImage stands on the shoulders of several open-source projects.
See [`THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md) for the full
list with licenses. Special thanks to:
- The **Avalonia UI** team for a modern, cross-platform XAML framework
that also happens to run beautifully on Windows.
- The **Windows App SDK / WinUI 3** team at Microsoft for the modern
Win11-native XAML framework underneath the v1.3+ UI.
- The **Avalonia UI** team — v1.0 through v1.2 of CaptureImage shipped on
Avalonia, and the project owes a substantial debt to the cross-platform
XAML framework that got us off the ground.
- The **H.NotifyIcon** team for the WinUI 3 tray-icon library that fills
the gap WinAppSDK doesn't (yet) cover natively.
- The **OBS Studio** team for blazing the trail on Windows Graphics
Capture integration — their public source code was a useful reference
while wiring up `IGraphicsCaptureItemInterop`.
+3 -2
View File
@@ -110,8 +110,9 @@ invited to open a pull request — see [`CONTRIBUTORS.md`](../CONTRIBUTORS.md).
## 5. Trademarks
"Steam", "Dota", "Counter-Strike", "Windows", "DirectX",
"Microsoft .NET", "Avalonia", "Velopack", "SkiaSharp", "ImageSharp",
"Serilog", "SharpHook", and any other third-party names that appear in the
"Microsoft .NET", "WinUI", "Windows App SDK", "Velopack", "SkiaSharp",
"ImageSharp", "Serilog", "SharpHook", and any other third-party names that
appear in the
source, documentation, or UI strings are trademarks or registered
trademarks of their respective owners. Their use in this project is for
identification purposes only and does not imply any affiliation with, or
+3 -2
View File
@@ -58,8 +58,9 @@ freely, subject to the GPL's attribution requirements.
Third-party trademarks that appear in the source code, documentation,
user interface, or release notes (including but not limited to Microsoft,
Windows, DirectX, Steam, Valve, Avalonia, Velopack, SkiaSharp, ImageSharp,
Serilog, SharpHook, GitHub) are property of their respective owners. They
Windows, DirectX, WinUI, Windows App SDK, Steam, Valve, Velopack,
SkiaSharp, ImageSharp, Serilog, SharpHook, GitHub) are property of their
respective owners. They
are referenced for identification and interoperability only. No
endorsement is implied.
+5 -6
View File
@@ -16,14 +16,13 @@ CaptureImage binary is distributed under.
| Package | License | Upstream |
|---|---|---|
| Avalonia | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Desktop | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Themes.Fluent | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Fonts.Inter | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Avalonia.Diagnostics | MIT | <https://github.com/AvaloniaUI/Avalonia> |
| Inter typeface | SIL Open Font License 1.1 | <https://github.com/rsms/inter> |
| Microsoft.WindowsAppSDK (WinUI 3) | MIT | <https://github.com/microsoft/WindowsAppSDK> |
| Microsoft.WindowsAppSDK.WinUI | MIT | <https://github.com/microsoft/WindowsAppSDK> |
| Microsoft.Windows.SDK.BuildTools | MIT | <https://github.com/microsoft/Windows.SDK.BuildTools> |
| H.NotifyIcon.WinUI | MIT | <https://github.com/HavenDV/H.NotifyIcon> |
| SkiaSharp | MIT | <https://github.com/mono/SkiaSharp> |
| SkiaSharp.NativeAssets.Win32 | MIT | <https://github.com/mono/SkiaSharp> |
| System.Drawing.Common | MIT | <https://github.com/dotnet/runtime> |
### MVVM + DI + logging
+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Application
x:Class="CaptureImage.App.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="using:CaptureImage.UI.Converters">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
</ResourceDictionary.MergedDictionaries>
<!-- Globally-available converters. Declared at Application scope so any view's
{StaticResource X} lookup walks up the chain and finds them — local
Element.Resources scope hits a forward-reference issue when the host
element uses the converter on its own properties. See
feedback_winui3_resource_scope.md. -->
<conv:FlowDirectionConverter x:Key="FlowDirectionConverter" />
<conv:BytesToBitmapConverter x:Key="BytesToBitmapConverter" />
<conv:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<conv:InvertedBoolToVisibilityConverter x:Key="InvertedBoolToVisibilityConverter" />
<conv:NotNullToVisibilityConverter x:Key="NotNullToVisibilityConverter" />
<conv:ToastKindToBrushConverter x:Key="ToastKindToBrushConverter" />
<!-- Design tokens — port of the v1.2 Avalonia design-system comment block.
Keep the same scale (4/8/12/16/24 px spacing, 4/8 px corner radius) so the
view ports stay visually consistent with the v1.2 baseline.
FontFamily : Segoe UI Variable (Fluent 2 default — explicit for clarity).
Inter is dropped; Win11 native font carries the Fluent look.
FontSize : 11 (caption) / 12 (small) / 13 (body) / 14 (body-strong) /
16 (subtitle) / 22 (title).
CornerRadius: 8 px for cards/borders/containers, 4 px for inline pills.
Spacing : 4 / 8 / 12 / 16 / 24 px scale.
Contrast : secondary text uses TextFillColorSecondaryBrush, not
Opacity=0.6 — the theme brush keeps WCAG AA on light/dark.
-->
<FontFamily x:Key="BodyFontFamily">Segoe UI Variable Display</FontFamily>
<x:Double x:Key="FontSizeCaption">11</x:Double>
<x:Double x:Key="FontSizeSmall">12</x:Double>
<x:Double x:Key="FontSizeBody">13</x:Double>
<x:Double x:Key="FontSizeBodyStrong">14</x:Double>
<x:Double x:Key="FontSizeSubtitle">16</x:Double>
<x:Double x:Key="FontSizeTitle">22</x:Double>
<x:Double x:Key="SpacingXSmall">4</x:Double>
<x:Double x:Key="SpacingSmall">8</x:Double>
<x:Double x:Key="SpacingMedium">12</x:Double>
<x:Double x:Key="SpacingLarge">16</x:Double>
<x:Double x:Key="SpacingXLarge">24</x:Double>
<CornerRadius x:Key="PillCornerRadius">4</CornerRadius>
<CornerRadius x:Key="CardCornerRadius">8</CornerRadius>
</ResourceDictionary>
</Application.Resources>
</Application>
+64
View File
@@ -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;
}
}
+38 -9
View File
@@ -8,20 +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>
<!-- Release value for v1.1.2; release.yml still overrides via /p:Version=<git-tag>
for tag-driven builds. Bump to the next -dev suffix after the release lands. -->
<Version>1.1.2</Version>
<DefineConstants>$(DefineConstants);DISABLE_XAML_GENERATED_MAIN</DefineConstants>
<Version>1.3.1</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Diagnostics" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.WindowsAppSDK" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" />
<PackageReference Include="Serilog" />
<PackageReference Include="Serilog.Extensions.Hosting" />
<PackageReference Include="Serilog.Extensions.Logging" />
@@ -37,9 +41,34 @@
<ProjectReference Include="..\CaptureImage.UI\CaptureImage.UI.csproj" />
</ItemGroup>
<!-- Ship the legal and docs files next to the binary so the About tab can open them
with Process.Start. Links to the repo-root docs/ folder so there's a single source
of truth; content is copied into bin/.../docs/... at build time. -->
<!-- HOTFIX v1.3.1: WinUI 3 publish pipeline misses two file types when building
a self-contained unpackaged app via `dotnet publish`:
1. .xbf files — compiled XAML binary format produced by the WinUI 3 XAML
compiler. Without them, Application.LoadComponent fails on every
ms-appx:/// XAML reference at runtime with XamlParseException.
2. CaptureImage.App.pri — the app's compiled resource manifest. Without it,
Windows can't resolve ms-appx:/// URIs at all (incl. WinAppSDK theme
resources like ms-appx:///Microsoft.UI.Xaml/Themes/themeresources.xaml).
Both files are produced into bin/.../win-x64/ during build but `dotnet publish`
skips them in self-contained mode. v1.3.0 shipped without either and the
window never appeared (silent UI-thread crash; process stayed alive zombie).
This target adds every .xbf and .pri from $(OutDir) to the published file set,
preserving the CaptureImage.UI/Controls and CaptureImage.UI/Views subfolders
the XAML compiler creates for cross-assembly XAML resolution. -->
<Target Name="CopyWinUIArtifactsToPublishDirectory" AfterTargets="ComputeFilesToPublish">
<ItemGroup>
<_WinUIArtifactsToPublish Include="$(OutDir)**\*.xbf" />
<_WinUIArtifactsToPublish Include="$(OutDir)$(AssemblyName).pri" />
<ResolvedFileToPublish Include="@(_WinUIArtifactsToPublish)">
<RelativePath>%(RecursiveDir)%(Filename)%(Extension)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
<ItemGroup>
<Content Include="..\..\docs\legal\DISCLAIMER.md" Link="docs\legal\DISCLAIMER.md" CopyToOutputDirectory="PreserveNewest" />
<Content Include="..\..\docs\legal\PRIVACY.md" Link="docs\legal\PRIVACY.md" CopyToOutputDirectory="PreserveNewest" />
+16 -5
View File
@@ -21,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;
@@ -30,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();
@@ -39,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 ----------------------------------------------------------
@@ -84,8 +95,8 @@ internal static class CompositionRoot
// --- 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>();
+38 -12
View File
@@ -1,5 +1,7 @@
using CaptureImage.Core.Logging;
using CaptureImage.Infrastructure.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.App;
@@ -22,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(
@@ -51,9 +57,29 @@ internal static class LoggingSetup
fileSizeLimitBytes: 10L * 1024 * 1024,
rollOnFileSizeLimit: true,
shared: false,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"))
// {File}:{Line} shows caller context injected by CallerAwareLoggerExtensions.
// Missing on legacy call sites — Serilog prints a bare ":" then, so keep the
// template consistent and accept that one cosmetic artifact until those are
// migrated. {Properties:j} still JSON-dumps every non-templated property.
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] ({File}:{Line}) {Message:lj} {Properties:j}{NewLine}{Exception}"))
.CreateLogger();
return sink;
return (sink, levelSwitch);
}
/// <summary>
/// Map the persisted <c>LogLevel</c> string (one of <c>Debug</c> / <c>Information</c> /
/// <c>Warning</c> / <c>Error</c>) to a <see cref="LogEventLevel"/>. Unknown strings
/// fall back to <see cref="LogEventLevel.Information"/>.
/// </summary>
public static LogEventLevel ParseLevel(string? value) => value?.Trim().ToLowerInvariant() switch
{
"debug" => LogEventLevel.Debug,
"information" => LogEventLevel.Information,
"info" => LogEventLevel.Information,
"warning" => LogEventLevel.Warning,
"warn" => LogEventLevel.Warning,
"error" => LogEventLevel.Error,
_ => LogEventLevel.Information,
};
}
+121
View File
@@ -0,0 +1,121 @@
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="CaptureImage.App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:CaptureImage.UI.Views"
xmlns:controls="using:CaptureImage.UI.Controls"
mc:Ignorable="d">
<Grid x:Name="Root"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={StaticResource FlowDirectionConverter}}">
<Grid.RowDefinitions>
<!-- Title-bar drag region. Reserve 48 px so the OS-drawn caption buttons
(minimize / maximize / close) don't overlap the NavigationView pane
header, the LogViewer drawer, or any Page content. AppTitleBar is
marked as the window's title bar via Window.SetTitleBar in code-behind. -->
<RowDefinition Height="48" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Grid.Row="0" x:Name="AppTitleBar" Background="Transparent" />
<!-- Body grid: 2 columns so the LogViewer drawer can sit in a dedicated 480 px
column on the trailing edge instead of relying on HorizontalAlignment="Right",
which WinUI 3 doesn't honour reliably on first measure (the drawer would
render on the leading edge until a window resize forced a relayout). -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="480" />
</Grid.ColumnDefinitions>
<NavigationView
Grid.ColumnSpan="2"
x:Name="NavView"
IsBackButtonVisible="Collapsed"
IsSettingsVisible="False"
PaneDisplayMode="Left"
OpenPaneLength="220"
MenuItemsSource="{Binding NavItems}"
SelectedItem="{Binding SelectedNavItem, Mode=TwoWay}"
SelectionChanged="NavView_SelectionChanged">
<NavigationView.PaneHeader>
<StackPanel Margin="12,8,12,8">
<TextBlock
Text="{Binding AppTitle}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<TextBlock
Text="{Binding AppVersion}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Margin="0,4,0,0" />
</StackPanel>
</NavigationView.PaneHeader>
<NavigationView.MenuItemTemplate>
<DataTemplate>
<NavigationViewItem Content="{Binding Label}">
<NavigationViewItem.Icon>
<FontIcon
Glyph="{Binding IconGlyph}"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" />
</NavigationViewItem.Icon>
</NavigationViewItem>
</DataTemplate>
</NavigationView.MenuItemTemplate>
<NavigationView.PaneFooter>
<Button
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Margin="8,4,8,16"
Padding="12,8"
Background="Transparent"
BorderThickness="0"
Command="{Binding ToggleLogViewerCommand}"
ToolTipService.ToolTip="{Binding LogToggleTooltip}"
AutomationProperties.Name="{Binding LogToggleTooltip}">
<StackPanel Orientation="Horizontal" Spacing="12">
<FontIcon
Glyph="&#xE9F9;"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets"
FontSize="16" />
<TextBlock
Text="{Binding LogToggleLabel}"
FontFamily="{StaticResource BodyFontFamily}"
VerticalAlignment="Center" />
</StackPanel>
</Button>
</NavigationView.PaneFooter>
<Frame x:Name="ContentFrame" />
</NavigationView>
<!-- Log viewer drawer overlay — pinned to Column 1 (trailing edge under LTR,
leading under RTL — FlowDirection mirrors). Stays in the visual tree
always so the slide-in Composition animation has something to act on
every toggle. Initial collapsed state (Offset = ±48 px X, Opacity = 0,
IsHitTestVisible = false) is set in MainWindow.OnRootLoaded. -->
<views:LogViewerView
Grid.Column="1"
x:Name="LogDrawer"
DataContext="{Binding LogViewer}" />
<!-- Toast overlay — anchored bottom of the trailing edge column. Spans both
columns so MaxWidth + alignment can position it freely. -->
<controls:ToastHost
Grid.ColumnSpan="2"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Margin="0,0,20,20"
IsHitTestVisible="True" />
</Grid>
</Grid>
</Window>
+162
View File
@@ -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);
}
}
+58 -29
View File
@@ -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,36 +19,38 @@ 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. Only accept cultures the app
// actually ships translations for — a hand-edited settings.json with, say,
// Culture=fr-FR used to flip the app to fr and then fall through to neutral
// en strings with Settings showing "English" selected; refuse at startup
// instead so the default en-US stays coherent.
var 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))
@@ -81,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();
@@ -107,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();
};
}
}
@@ -0,0 +1,21 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Live control over the Serilog minimum-level floor. The Settings view mutates this
/// when the user picks a new log level, and the wrapper — implemented in
/// <c>CaptureImage.Infrastructure.Logging</c> — pushes the value through to Serilog's
/// <c>LoggingLevelSwitch</c> so new events are filtered immediately.
/// </summary>
/// <remarks>
/// Level strings accepted by <see cref="SetLevel"/>: <c>Debug</c>, <c>Information</c>,
/// <c>Warning</c>, <c>Error</c> (case-insensitive, aliases <c>info</c> / <c>warn</c>
/// accepted). Unknown strings fall back to <c>Information</c>.
/// </remarks>
public interface ILogLevelSwitcher
{
/// <summary>Set the minimum log level from a canonical string.</summary>
void SetLevel(string level);
/// <summary>Canonical name of the currently active minimum level.</summary>
string CurrentLevel { get; }
}
@@ -0,0 +1,296 @@
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
namespace CaptureImage.Core.Logging;
/// <summary>
/// Extension methods that inject <c>[CallerMemberName]</c>, <c>[CallerFilePath]</c>, and
/// <c>[CallerLineNumber]</c> as Serilog structured properties (<c>Member</c>, <c>File</c>,
/// <c>Line</c>) so every entry the log viewer shows — and every line the rolling file
/// receives — carries a cheap jump-to-source anchor.
/// </summary>
/// <remarks>
/// <para>
/// The properties are attached via <see cref="ILogger.BeginScope{TState}"/>. The
/// <c>Serilog.Extensions.Logging</c> provider forwards MEL scope state as
/// <see cref="Serilog.Events.LogEvent"/> properties, so the output template
/// <c>{File}:{Line}</c> and the <see cref="Models.LogEntry"/> mapper both see them.
/// </para>
/// <para>
/// <c>Path.GetFileName</c> strips the build-machine absolute path so we don't leak
/// <c>E:\capture\captureimg\…</c> into shipped binaries and user log exports.
/// </para>
/// <para>
/// Overloads are provided for 0–3 template arguments — that covers the vast majority of
/// call sites. For more arguments, fall back to <see cref="ILogger.BeginScope{TState}"/>
/// with a manual scope and regular <c>LogInformation</c>/<c>LogError</c>/etc.
/// </para>
/// </remarks>
public static class CallerAwareLoggerExtensions
{
// --- Information --------------------------------------------------------
public static void LogInformationAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(message);
}
}
public static void LogInformationAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0);
}
}
public static void LogInformationAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0, arg1);
}
}
public static void LogInformationAt<T0, T1, T2>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
T2 arg2,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0, arg1, arg2);
}
}
// --- Debug --------------------------------------------------------------
public static void LogDebugAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(message);
}
}
public static void LogDebugAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(messageTemplate, arg0);
}
}
public static void LogDebugAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(messageTemplate, arg0, arg1);
}
}
// --- Warning ------------------------------------------------------------
public static void LogWarningAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(message);
}
}
public static void LogWarningAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(messageTemplate, arg0);
}
}
public static void LogWarningAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(messageTemplate, arg0, arg1);
}
}
public static void LogWarningAt(
this ILogger logger,
Exception exception,
string messageTemplate,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate);
}
}
public static void LogWarningAt<T0>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate, arg0);
}
}
public static void LogWarningAt<T0, T1>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate, arg0, arg1);
}
}
// --- Error --------------------------------------------------------------
public static void LogErrorAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(message);
}
}
public static void LogErrorAt(
this ILogger logger,
Exception exception,
string messageTemplate,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate);
}
}
public static void LogErrorAt<T0>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate, arg0);
}
}
public static void LogErrorAt<T0, T1>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate, arg0, arg1);
}
}
// --- Shared scope builder -----------------------------------------------
private static Dictionary<string, object> CallerScope(string member, string filePath, int line)
=> new(3)
{
["Member"] = member ?? string.Empty,
// Path.GetFileName tolerates forward and back slashes, returns the input if the
// string doesn't look like a path — so empty / odd CallerFilePath values degrade
// gracefully.
["File"] = string.IsNullOrEmpty(filePath) ? string.Empty : Path.GetFileName(filePath),
["Line"] = line,
};
}
+24
View File
@@ -0,0 +1,24 @@
namespace CaptureImage.Core.Logging;
/// <summary>
/// Canonical on-disk locations for log files. Shared between <c>LoggingSetup</c> (which
/// configures Serilog's rolling-file sink) and <c>LogViewerViewModel</c> (which opens the
/// folder when the user clicks "Reveal logs folder") so both agree on the path.
/// </summary>
public static class LogPaths
{
/// <summary>
/// Returns <c>%LocalAppData%\CaptureImage\logs</c>, creating the directory tree if
/// missing. Uses <see cref="Environment.SpecialFolder.LocalApplicationData"/> so the
/// path is per-user and roams with the profile.
/// </summary>
public static string GetLogsDirectory()
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CaptureImage",
"logs");
Directory.CreateDirectory(dir);
return dir;
}
}
+14 -1
View File
@@ -19,7 +19,7 @@ namespace CaptureImage.Core.Models;
public sealed record AppSettings
{
/// <summary>Schema version. Bump when adding migration steps.</summary>
public int Version { get; init; } = 1;
public int Version { get; init; } = 2;
/// <summary>
/// IETF BCP-47 culture code for UI (e.g. <c>en-US</c>, <c>vi-VN</c>, <c>ar-SA</c>).
@@ -34,6 +34,19 @@ public sealed record AppSettings
public CaptureSettings Capture { get; init; } = new();
public UiSettings UI { get; init; } = new();
/// <summary>
/// Minimum log level retained in the rolling file and in-memory buffer.
/// One of <c>Debug</c>, <c>Information</c>, <c>Warning</c>, <c>Error</c> — case-insensitive
/// on parse. Unknown values fall back to <c>Information</c>.
/// </summary>
/// <remarks>
/// Stored as a string rather than an enum so hand-edited <c>settings.json</c> files stay
/// readable and so the persistence layer doesn't take a dependency on MEL's enum identity.
/// v1 files load with this defaulted to <c>Information</c>; legacy behaviour was
/// <c>Debug</c>, so users who relied on it get a note in CHANGELOG to flip it back.
/// </remarks>
public string LogLevel { get; init; } = "Information";
}
/// <summary>Capture-specific persisted options.</summary>
+2 -2
View File
@@ -31,7 +31,7 @@ public static class ImageFormatExtensions
ImageFormat.Jpeg => "jpg",
ImageFormat.Webp => "webp",
ImageFormat.Tiff => "tiff",
_ => throw new System.ArgumentOutOfRangeException(nameof(format), format, null),
_ => throw new ArgumentOutOfRangeException(nameof(format), format, null),
};
/// <summary>
@@ -43,6 +43,6 @@ public static class ImageFormatExtensions
ImageFormat.Jpeg => "image/jpeg",
ImageFormat.Webp => "image/webp",
ImageFormat.Tiff => "image/tiff",
_ => throw new System.ArgumentOutOfRangeException(nameof(format), format, null),
_ => throw new ArgumentOutOfRangeException(nameof(format), format, null),
};
}
+36 -1
View File
@@ -9,12 +9,47 @@ namespace CaptureImage.Core.Models;
/// <param name="SourceContext">Fully-qualified logger name if present, else empty.</param>
/// <param name="Message">Rendered message text (format tokens already applied).</param>
/// <param name="Exception">Exception stringification if any, else null.</param>
/// <remarks>
/// The <see cref="File"/>, <see cref="Line"/>, and <see cref="Member"/> init-only properties are
/// populated when the call site used the <c>LogXAt</c> helpers from
/// <c>CaptureImage.Core.Logging.CallerAwareLoggerExtensions</c>; they stay null for legacy
/// call sites that still log via <c>ILogger&lt;T&gt;.LogInformation</c> or the static
/// <c>Serilog.Log</c> API.
/// </remarks>
public sealed record LogEntry(
DateTimeOffset Timestamp,
LogLevel Level,
string SourceContext,
string Message,
string? Exception);
string? Exception)
{
/// <summary>Source file name (e.g. <c>WindowsGraphicsCaptureEngine.cs</c>) — no directory.</summary>
public string? File { get; init; }
/// <summary>Line number in <see cref="File"/> where the log was emitted.</summary>
public int? Line { get; init; }
/// <summary>Method or property name that emitted the log.</summary>
public string? Member { get; init; }
/// <summary>
/// Convenience string for the log viewer — <c>"File.cs:42"</c> when both are present,
/// else empty. Computed; never participates in record equality.
/// </summary>
public string FileLineText =>
!string.IsNullOrEmpty(File) && Line is > 0
? $"{File}:{Line}"
: string.Empty;
/// <summary>
/// Pre-formatted timestamp for the log viewer column — <c>"HH:mm:ss.fff"</c>. Done as a
/// computed property because WinUI 3 <c>{Binding}</c> doesn't support
/// <c>StringFormat</c> the way Avalonia/WPF do; keeping the format in code-behind-free
/// view XAML means one place (here) carries the format.
/// </summary>
public string TimestampText =>
Timestamp.ToString("HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>Levels the log viewer filters on. Mapped from Serilog's LogEventLevel.</summary>
public enum LogLevel
@@ -1,5 +1,3 @@
using System.Collections.Generic;
namespace CaptureImage.Core.Models;
/// <summary>
@@ -1,6 +1,8 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Errors;
using CaptureImage.Core.Logging;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
using Vortice.Direct3D11;
@@ -69,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.");
}
@@ -100,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);
@@ -129,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
{
@@ -157,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.
}
@@ -53,11 +53,30 @@ public sealed partial class HotkeyConflictSniffer : IHotkeyConflictSniffer
var err = Marshal.GetLastWin32Error();
_logger.LogDebug(
"RegisterHotKey sniff failed for {Binding} (win32 error {Err}); treating as conflicted.",
binding, err);
"RegisterHotKey sniff failed for {Binding}; treating as conflicted. ({ErrCode}: {ErrText})",
binding,
err,
DescribeWin32Error(err));
return true;
}
/// <summary>
/// Map the handful of Win32 errors <c>RegisterHotKey</c> can realistically produce back
/// to human-readable names. Unknown codes fall through to <c>"UNKNOWN"</c> — the
/// numeric value is always logged alongside so diagnosis isn't blocked on the map
/// having complete coverage.
/// </summary>
private static string DescribeWin32Error(int code) => code switch
{
0 => "ERROR_SUCCESS",
5 => "ERROR_ACCESS_DENIED",
87 => "ERROR_INVALID_PARAMETER",
1400 => "ERROR_INVALID_WINDOW_HANDLE",
1409 => "ERROR_HOTKEY_ALREADY_REGISTERED",
1419 => "ERROR_HOTKEY_NOT_REGISTERED",
_ => "UNKNOWN",
};
[LibraryImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
@@ -59,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.");
}
@@ -72,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;
}
}
@@ -84,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)
@@ -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));
}
}
}
@@ -93,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,
};
}
}
@@ -108,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;
@@ -18,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;
@@ -91,6 +91,35 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
}
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
@@ -103,7 +132,8 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
needsWriteBack = true;
}
_logger.LogInformation(
"Settings loaded from {Path} (version {Version}).", _filePath, loaded.Version);
"Settings loaded from {Path} (version {Version}, log level {LogLevel}).",
_filePath, loaded.Version, loaded.LogLevel);
}
}
}
@@ -269,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;
}
}
@@ -144,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)
-52
View File
@@ -1,52 +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 />
<!--
Visual system conventions (enforced through this file + view-level overrides):
FontFamily : Inter (shipped via Avalonia.Fonts.Inter) with Segoe UI fallback;
monospace (Consolas/Courier New) only for log entries + hotkey
display where fixed glyph width carries meaning.
FontSize : 11 (caption) / 12 (small) / 13 (body) / 14 (body-strong) /
16 (subtitle) / 22 (title).
CornerRadius: 8 px for cards, borders, containers. 4 px reserved for inline
badges/pills (e.g. Dashboard Steam badge).
Spacing : 4 / 8 / 12 / 16 / 24 px scale — every Margin, Padding, Spacing
value in a view should snap to one of these.
Contrast : secondary text uses SystemControlForegroundBaseMediumBrush,
not Opacity="0.6" — the theme brush keeps WCAG AA contrast on
both light and dark variants.
-->
<!-- Default UI text stack. View-level FontFamily overrides remain for monospace blocks. -->
<Style Selector="TextBlock">
<Setter Property="FontFamily" Value="Inter, Segoe UI, sans-serif" />
</Style>
<Style Selector="TextBox">
<Setter Property="FontFamily" Value="Inter, Segoe UI, sans-serif" />
</Style>
<Style Selector="Button">
<Setter Property="FontFamily" Value="Inter, Segoe UI, sans-serif" />
</Style>
<Style Selector="ComboBox">
<Setter Property="FontFamily" Value="Inter, Segoe UI, sans-serif" />
</Style>
<Style Selector="CheckBox">
<Setter Property="FontFamily" Value="Inter, Segoe UI, sans-serif" />
</Style>
<!-- Visible focus ring on list items. FluentTheme provides selection state styling
but no keyboard-focus outline; this ensures the :focus-visible pseudo-class
draws a border in the accent colour when a user tabs through the target list. -->
<Style Selector="ListBoxItem:focus-visible">
<Setter Property="BorderBrush" Value="{DynamicResource SystemControlHighlightAccentBrush}" />
<Setter Property="BorderThickness" Value="2" />
</Style>
</Application.Styles>
</Application>
-48
View File
@@ -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();
}
}
+8 -9
View File
@@ -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>
@@ -1,86 +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:vm="clr-namespace:CaptureImage.ViewModels.Settings;assembly=CaptureImage.ViewModels"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Controls.HotkeyRecorder"
x:DataType="vm:HotkeyBindingViewModel">
<UserControl.Styles>
<!-- Keyboard-focus ring on the BindingField. Fluent's default border is a neutral grey;
flip it to the accent brush when the control has focus so tab navigation is
visible and the recording-mode prompt is clearly "waiting on you". -->
<Style Selector="Border#BindingField:focus">
<Setter Property="BorderBrush" Value="{DynamicResource SystemControlHighlightAccentBrush}" />
<Setter Property="BorderThickness" Value="2" />
</Style>
</UserControl.Styles>
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,8,Auto,8,Auto">
<!-- The keyboard-focused surface. Receives KeyDown events while recording; shows the
current binding while idle. Focused programmatically from code-behind when
IsRecording flips to true. -->
<Border Grid.Column="0"
Name="BindingField"
Focusable="True"
MinHeight="34"
CornerRadius="8"
Padding="12,8"
BorderThickness="1"
BorderBrush="{DynamicResource SystemControlForegroundBaseMediumLowBrush}"
Background="{DynamicResource SystemControlBackgroundChromeMediumLowBrush}"
VerticalAlignment="Center"
AutomationProperties.Name="{Binding HotkeyFieldAutomationName}"
AutomationProperties.HelpText="{Binding RecorderPromptText}">
<Grid>
<TextBlock Text="{Binding DisplayText}"
FontFamily="Consolas, Courier New, monospace"
VerticalAlignment="Center"
IsVisible="{Binding !IsRecording}" />
<TextBlock Text="{Binding RecorderPromptText}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
FontStyle="Italic"
VerticalAlignment="Center"
IsVisible="{Binding IsRecording}" />
</Grid>
</Border>
<Button Grid.Column="2"
Content="{Binding RecordLabel}"
Command="{Binding StartRecordingCommand}"
IsVisible="{Binding !IsRecording}"
MinWidth="80" />
<Button Grid.Column="2"
Content="{Binding CancelLabel}"
Command="{Binding CancelRecordingCommand}"
IsVisible="{Binding IsRecording}"
MinWidth="80" />
<Button Grid.Column="4"
Content="{Binding ResetLabel}"
Command="{Binding ResetToDefaultCommand}"
IsVisible="{Binding !IsRecording}"
MinWidth="80" />
</Grid>
<!-- Validation error — visible only after a rejected commit. -->
<TextBlock Text="{Binding ErrorMessage}"
Foreground="#D13438"
FontSize="11"
TextWrapping="Wrap"
IsVisible="{Binding HasError}" />
<!-- Conflict warning — non-blocking, binding already persisted. -->
<TextBlock Text="{Binding ConflictWarningText}"
Foreground="#C19C00"
FontSize="11"
TextWrapping="Wrap"
IsVisible="{Binding ConflictDetected}" />
</StackPanel>
</UserControl>
@@ -1,146 +0,0 @@
using System.ComponentModel;
using Avalonia.Controls;
using Avalonia.Input;
using CaptureImage.Core.Models;
using CaptureImage.ViewModels.Settings;
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>
/// We map <see cref="Key"/> (Avalonia) to the Win32 virtual-key code because the backing
/// <c>HotkeyBinding</c> persists VKs. SharpHook would give us VK codes directly but it
/// lives in Infrastructure and the whole point of this control is to stay reusable from
/// the UI layer without a back-channel to the global hook.
/// </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. A truly bare
/// letter press would route through the IME — we require at least one modifier for all
/// non-function keys via <see cref="HotkeyBinding.Validate"/>, so this doesn't matter in
/// practice.
/// </para>
/// </remarks>
public partial class HotkeyRecorder : UserControl
{
private HotkeyBindingViewModel? _vm;
public HotkeyRecorder()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
KeyDown += OnKeyDown;
}
private void OnDataContextChanged(object? sender, EventArgs e)
{
if (_vm is not null)
_vm.PropertyChanged -= OnVmPropertyChanged;
_vm = DataContext 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 so the focus move happens after the current click has fully
// settled — calling Focus() inline sometimes races with Avalonia reassigning
// focus when the Record button collapses.
Avalonia.Threading.Dispatcher.UIThread.Post(() => BindingField.Focus());
}
}
private void OnKeyDown(object? sender, KeyEventArgs e)
{
if (_vm is null || !_vm.IsRecording) return;
// Esc alone cancels without committing.
if (e.Key == Key.Escape && e.KeyModifiers == KeyModifiers.None)
{
_vm.CancelRecordingCommand.Execute(null);
e.Handled = true;
return;
}
var vk = AvaloniaKeyToWin32Vk(e.Key);
if (vk is null)
{
// Pure modifier or an unmapped key — wait for a real combination.
e.Handled = true;
return;
}
var mods = HotkeyModifiers.None;
if ((e.KeyModifiers & KeyModifiers.Control) != 0) mods |= HotkeyModifiers.Control;
if ((e.KeyModifiers & KeyModifiers.Alt) != 0) mods |= HotkeyModifiers.Alt;
if ((e.KeyModifiers & KeyModifiers.Shift) != 0) mods |= HotkeyModifiers.Shift;
if ((e.KeyModifiers & KeyModifiers.Meta) != 0) mods |= HotkeyModifiers.Win;
_vm.TryCommitRecorded(new HotkeyBinding(mods, vk.Value));
e.Handled = true;
}
/// <summary>
/// Map Avalonia's platform-neutral <see cref="Key"/> enum to Win32 virtual-key codes
/// (<c>VK_*</c>). Returns <c>null</c> for pure modifier keys and anything we don't
/// bind for a capture hotkey — e.g. media keys, IME-specific modes.
/// </summary>
private static uint? AvaloniaKeyToWin32Vk(Key key)
{
// Letters A-Z → 0x41..0x5A. Avalonia keeps these contiguous.
if (key >= Key.A && key <= Key.Z)
return 0x41u + (uint)(key - Key.A);
// Top-row digits 0-9 → 0x30..0x39.
if (key >= Key.D0 && key <= Key.D9)
return 0x30u + (uint)(key - Key.D0);
// Function keys F1-F24 → 0x70..0x87.
if (key >= Key.F1 && key <= Key.F24)
return 0x70u + (uint)(key - Key.F1);
// Numpad 0-9 → 0x60..0x69.
if (key >= Key.NumPad0 && key <= Key.NumPad9)
return 0x60u + (uint)(key - Key.NumPad0);
return key switch
{
Key.Tab => 0x09u,
Key.Return => 0x0Du,
Key.Space => 0x20u,
Key.Back => 0x08u,
Key.Escape => 0x1Bu,
Key.Insert => 0x2Du,
Key.Delete => 0x2Eu,
Key.Home => 0x24u,
Key.End => 0x23u,
Key.PageUp => 0x21u,
Key.PageDown => 0x22u,
Key.Left => 0x25u,
Key.Up => 0x26u,
Key.Right => 0x27u,
Key.Down => 0x28u,
Key.PrintScreen => 0x2Cu,
Key.Pause => 0x13u,
Key.Multiply => 0x6Au,
Key.Add => 0x6Bu,
Key.Subtract => 0x6Du,
Key.Decimal => 0x6Eu,
Key.Divide => 0x6Fu,
// Anything else (modifiers, IME modes, media keys) → not bindable.
_ => null,
};
}
}
@@ -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="8"
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,20 +1,19 @@
using System.Globalization;
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)
{
@@ -23,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
{
@@ -32,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,23 +1,22 @@
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,23 +1,25 @@
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,
@@ -26,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,7 +1,9 @@
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;
@@ -22,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;
@@ -51,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);
@@ -88,6 +88,9 @@
<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>
@@ -131,6 +134,8 @@
<data name="Log_Clear" 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>
@@ -88,6 +88,9 @@
<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>
@@ -131,6 +134,8 @@
<data name="Log_Clear" xml:space="preserve"><value>Clear</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>
@@ -88,6 +88,9 @@
<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>
@@ -131,6 +134,8 @@
<data name="Log_Clear" xml:space="preserve"><value>Xoá</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>
@@ -1,229 +0,0 @@
using System.ComponentModel;
using System.Diagnostics;
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 += OnLocalizationChanged;
_logger.LogInformation("Tray icon initialized.");
}
private void OnLocalizationChanged(object? sender, PropertyChangedEventArgs e)
{
// `ResxLocalizationService.SetCulture` raises three events per switch
// (Item[], CurrentCulture, CurrentFlowDirection). Rebuild the menu once, not
// three times — Item[] is the canonical "all lookups may have changed" signal.
if (e.PropertyName == "Item[]")
{
RefreshMenuLabels();
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_localization.PropertyChanged -= OnLocalizationChanged;
if (_mainWindow is not null)
{
_mainWindow.Closing -= OnMainWindowClosing;
}
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()));
}
}
@@ -1,18 +0,0 @@
using Avalonia.Threading;
using CaptureImage.Core.Abstractions;
namespace CaptureImage.UI.Services;
/// <summary>
/// <see cref="IUIThreadDispatcher"/> implementation that marshals to
/// <see cref="Dispatcher.UIThread"/>. Kept in the UI project so the ViewModels project
/// never has to reference Avalonia.
/// </summary>
public sealed class AvaloniaUIDispatcher : IUIThreadDispatcher
{
public bool IsOnUIThread => Dispatcher.UIThread.CheckAccess();
public void Post(Action action) => Dispatcher.UIThread.Post(action);
public Task InvokeAsync(Action action) => Dispatcher.UIThread.InvokeAsync(action).GetTask();
}
@@ -1,5 +1,8 @@
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CaptureImage.UI.Views;
@@ -9,16 +12,17 @@ using SkiaSharp;
namespace CaptureImage.UI.Services;
/// <summary>
/// Avalonia-backed implementation of <see cref="IPreviewPresenter"/>. Encodes the captured
/// frame to PNG bytes (reusing SkiaSharp which we already ship), opens a modal
/// <see cref="PreviewWindow"/> as a child of the main window, and awaits the user decision.
/// WinUI 3-backed implementation of <see cref="IPreviewPresenter"/>. Encodes the captured
/// frame to PNG bytes (reusing SkiaSharp), opens a non-modal <see cref="PreviewWindow"/>,
/// and awaits the user decision via the window's <see cref="PreviewWindow.ResultAsync"/>
/// task. Replaces v1.2's <c>AvaloniaPreviewPresenter</c> with the same external contract.
/// </summary>
public sealed class AvaloniaPreviewPresenter : IPreviewPresenter
public sealed class PreviewPresenter : IPreviewPresenter
{
private readonly IUIThreadDispatcher _dispatcher;
private readonly ILocalizationService _localization;
public AvaloniaPreviewPresenter(IUIThreadDispatcher dispatcher, ILocalizationService localization)
public PreviewPresenter(IUIThreadDispatcher dispatcher, ILocalizationService localization)
{
_dispatcher = dispatcher;
_localization = localization;
@@ -29,40 +33,24 @@ public sealed class AvaloniaPreviewPresenter : IPreviewPresenter
GameTarget target,
CancellationToken cancellationToken = default)
{
// Encode once for the preview image. Only PNG — previews are display-only, the real
// Encode once for the preview image. PNG only — preview is display-only; the real
// save path goes through the orchestrator with the user-chosen format.
var pngBytes = EncodeAsPngBytes(frame);
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_dispatcher.Post(async () =>
_dispatcher.Post(() =>
{
try
{
// `using` so the VM's Localization.PropertyChanged subscription is detached
// after the modal closes — otherwise every preview leaks one handler into
// the singleton localization service.
using var vm = new PreviewViewModel(_localization);
var vm = new PreviewViewModel(_localization);
vm.SetFrame(frame, target, pngBytes);
var window = new PreviewWindow
{
DataContext = vm,
};
var window = new PreviewWindow();
window.SetViewModel(vm);
window.Activate();
var owner = GetMainWindow();
if (owner is not null)
{
// Fire-and-track: ShowDialog's own task completes when the window closes;
// we synchronize on the user's Save/Discard click via ResultAsync.
_ = window.ShowDialog(owner);
}
else
{
window.Show();
}
var result = await window.ResultAsync.ConfigureAwait(true);
tcs.TrySetResult(result);
_ = WaitForResultAsync(window, vm, tcs);
}
catch (Exception ex)
{
@@ -76,13 +64,26 @@ public sealed class AvaloniaPreviewPresenter : IPreviewPresenter
}
}
private static Window? GetMainWindow()
private static async Task WaitForResultAsync(
PreviewWindow window,
PreviewViewModel vm,
TaskCompletionSource<bool> tcs)
{
if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
try
{
return desktop.MainWindow;
var result = await window.ResultAsync.ConfigureAwait(true);
tcs.TrySetResult(result);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
finally
{
// Detach the VM's Localization.PropertyChanged subscription so each preview
// doesn't leak one handler into the singleton localization service.
vm.Dispose();
}
return null;
}
private static byte[] EncodeAsPngBytes(CapturedFrame frame)
@@ -96,7 +97,7 @@ public sealed class AvaloniaPreviewPresenter : IPreviewPresenter
colorType: SKColorType.Bgra8888,
alphaType: SKAlphaType.Premul);
var handle = System.Runtime.InteropServices.GCHandle.Alloc(pixels, System.Runtime.InteropServices.GCHandleType.Pinned);
var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try
{
using var bitmap = new SKBitmap();
+2 -3
View File
@@ -1,5 +1,4 @@
using System.Collections.ObjectModel;
using Avalonia.Threading;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
@@ -10,8 +9,8 @@ namespace CaptureImage.UI.Services;
/// dismisses each after its <see cref="ToastItem.EffectiveDuration"/> elapses.
/// </summary>
/// <remarks>
/// Lives in the UI project because it touches <see cref="Dispatcher.UIThread"/> directly,
/// which keeps the portable ViewModels assembly free of Avalonia.
/// Lives in the UI project because it marshals through <see cref="IUIThreadDispatcher"/>;
/// the portable ViewModels assembly stays free of any UI-framework reference.
/// </remarks>
public sealed class ToastService : IToastService
{
@@ -0,0 +1,323 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using CaptureImage.Core.Abstractions;
using H.NotifyIcon;
using Microsoft.Extensions.Logging;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using SkiaSharp;
using WinRT.Interop;
namespace CaptureImage.UI.Services;
/// <summary>
/// WinUI 3 tray-icon host backed by <c>H.NotifyIcon.WinUI</c>. Wires a localized context
/// menu, single-click-to-restore, and minimize-to-tray by intercepting the main window's
/// <see cref="AppWindow.Closing"/> event. Tray icon ships with the OS default glyph until
/// a real .ico round-trip lands (see feedback_h_notifyicon_winui_quirks.md).
/// </summary>
public sealed class TrayIconHost : ITrayIconHost
{
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;
private readonly ILocalizationService _localization;
private readonly ISettingsStore _settings;
private readonly ILogger<TrayIconHost> _logger;
private TaskbarIcon? _trayIcon;
private Window? _mainWindow;
private AppWindow? _appWindow;
private IntPtr _hwnd;
private bool _disposed;
// Set by QuitApp so OnAppWindowClosing knows to allow the close instead of swallowing
// it for minimize-to-tray. Without this, Application.Current.Exit() would hang
// because the closing handler keeps cancelling the shutdown.
private bool _quitting;
public TrayIconHost(
ILocalizationService localization,
ISettingsStore settings,
ILogger<TrayIconHost> 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 a WinUI 3 Window", nameof(mainWindow));
_hwnd = WindowNative.GetWindowHandle(_mainWindow);
var windowId = Win32Interop.GetWindowIdFromWindow(_hwnd);
_appWindow = AppWindow.GetFromWindowId(windowId);
_trayIcon = new TaskbarIcon
{
ToolTipText = "CaptureImage",
ContextFlyout = BuildMenu(),
// Single-click should fire immediately (no double-click wait). Default
// H.NotifyIcon behavior is to delay LeftClick by ~500 ms looking for a
// double-click, which made single-click-to-restore feel unresponsive.
NoLeftClickDelay = true,
};
// Render the icon at runtime via SkiaSharp PNG (kept alive for v1.4 .ico path).
TryCreateIconSource();
// Both single + double click restore the window — covers either user habit.
_trayIcon.LeftClickCommand = new SimpleCommand(_ =>
{
_logger.LogDebug("Tray left-click → restoring main window.");
ShowMainWindow();
});
_trayIcon.DoubleClickCommand = new SimpleCommand(_ =>
{
_logger.LogDebug("Tray double-click → restoring main window.");
ShowMainWindow();
});
_trayIcon.ForceCreate();
// close-to-tray: intercept AppWindow.Closing (Window.Closed has no cancel hook).
_appWindow.Closing += OnAppWindowClosing;
_localization.PropertyChanged += OnLocalizationChanged;
_logger.LogInformation("Tray icon initialized and visible.");
}
private void TryCreateIconSource()
{
// H.NotifyIcon.WinUI loads icons via a chain that ends in System.Drawing.Icon,
// which only accepts .ico file streams — a runtime-generated PNG fails with
// "Argument 'picture' must be a picture that can be used as an Icon". Generating
// a real .ico (System.Drawing.Icon.Save round-trip via HICON) needs P/Invoke
// cleanup that's deferred to v1.4. OS default glyph is functional in the meantime.
try
{
// Touch BuildRuntimeIconPng so the SkiaSharp drawing code stays alive +
// exercised under build; v1.4 swaps the consumer to write .ico instead.
_ = BuildRuntimeIconPng();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Runtime tray-icon SkiaSharp draw failed; tray will use default glyph anyway.");
}
}
private void OnLocalizationChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Item[]" && _trayIcon is not null)
{
_trayIcon.ContextFlyout = BuildMenu();
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_localization.PropertyChanged -= OnLocalizationChanged;
if (_appWindow is not null)
{
_appWindow.Closing -= OnAppWindowClosing;
}
if (_trayIcon is not null)
{
_trayIcon.Dispose();
_trayIcon = null;
}
_logger.LogInformation("Tray icon disposed.");
}
// -- menu ----------------------------------------------------------------
private MenuFlyout BuildMenu()
{
var menu = new MenuFlyout();
// MenuFlyoutItem.Click events don't fire reliably when the flyout is shown
// from a TaskbarIcon ContextFlyout — H.NotifyIcon hosts the popup outside the
// normal XAML routing chain so click routing drops on the floor. Command
// bindings on MenuFlyoutItem.Command DO route correctly (same path as the
// working LeftClickCommand / DoubleClickCommand on the TaskbarIcon itself).
// v1.3-M7a (1st pass) used Click; user-reported regression in 2nd pass.
var showItem = new MenuFlyoutItem
{
Text = _localization["Tray_ShowWindow"],
Command = new SimpleCommand(_ =>
{
_logger.LogInformation("Tray menu: Show invoked.");
ShowMainWindow();
}),
};
menu.Items.Add(showItem);
var openFolderItem = new MenuFlyoutItem
{
Text = _localization["Tray_OpenFolder"],
Command = new SimpleCommand(_ =>
{
_logger.LogInformation("Tray menu: Open Folder invoked.");
OpenCaptureFolder();
}),
};
menu.Items.Add(openFolderItem);
menu.Items.Add(new MenuFlyoutSeparator());
var exitItem = new MenuFlyoutItem
{
Text = _localization["Tray_Exit"],
Command = new SimpleCommand(_ =>
{
_logger.LogInformation("Tray menu: Exit invoked.");
QuitApp();
}),
};
menu.Items.Add(exitItem);
return menu;
}
// -- actions -------------------------------------------------------------
private void ShowMainWindow()
{
if (_mainWindow is null || _appWindow is null) return;
try
{
// AppWindow.Show brings the window back from Hide(). ShowWindow(SW_RESTORE)
// also handles the "minimized via taskbar" case (AppWindow.Show alone leaves
// a minimized window minimized). SetForegroundWindow forces Z-order to top
// even when another app has focus — without it the window comes back behind
// whatever the user was working in.
_appWindow.Show();
ShowWindow(_hwnd, SW_RESTORE);
_mainWindow.Activate();
SetForegroundWindow(_hwnd);
_logger.LogDebug("Main window restored from tray.");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to restore main window from tray.");
}
}
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()
{
// Bypass MinimizeToTray so OnAppWindowClosing lets the close through.
_quitting = true;
Application.Current.Exit();
}
private void OnAppWindowClosing(AppWindow sender, AppWindowClosingEventArgs args)
{
if (_disposed || _quitting) return;
if (!_settings.Current.UI.MinimizeToTray) return;
// Swallow the close, hide instead. User can quit via tray menu.
args.Cancel = true;
sender.Hide();
_logger.LogDebug("Main window hidden to tray (MinimizeToTray enabled).");
}
// -- icon generation -----------------------------------------------------
/// <summary>Port of v1.2's BuildRuntimeIcon — same shape, returns PNG bytes.</summary>
private static byte[] BuildRuntimeIconPng()
{
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,
})
{
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);
}
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 data.ToArray();
}
/// <summary>
/// Tiny ICommand for H.NotifyIcon's LeftClickCommand — avoids pulling in
/// CommunityToolkit's RelayCommand for a single click handler.
/// </summary>
private sealed class SimpleCommand : System.Windows.Input.ICommand
{
private readonly Action<object?> _execute;
public SimpleCommand(Action<object?> execute) => _execute = execute;
public bool CanExecute(object? parameter) => true;
public void Execute(object? parameter) => _execute(parameter);
public event EventHandler? CanExecuteChanged { add { } remove { } }
}
}
@@ -0,0 +1,140 @@
using System.Runtime.InteropServices;
namespace CaptureImage.UI.Services;
/// <summary>
/// Folder picker via the Win32 <c>IFileOpenDialog</c> COM interface (the modern Vista+
/// dialog set to <c>FOS_PICKFOLDERS</c> mode). Replaces
/// <see cref="Windows.Storage.Pickers.FolderPicker"/> for unpackaged WinUI 3 apps where
/// the WinRT picker throws <c>COMException 0x80004005</c> on
/// <c>PickSingleFolderAsync</c> regardless of <c>InitializeWithWindow</c> being called.
/// IFileOpenDialog is rock-solid across all Windows versions and doesn't need
/// package identity.
/// </summary>
public static class Win32FolderPicker
{
/// <summary>
/// Show a folder browser dialog parented to <paramref name="ownerHwnd"/> and return
/// the chosen folder's full path, or <c>null</c> if the user cancelled.
/// </summary>
public static string? PickSingleFolder(IntPtr ownerHwnd, string? initialDirectory = null)
{
var dialog = (IFileOpenDialog)new FileOpenDialog();
try
{
// FOS_PICKFOLDERS = 0x20: dialog returns folders instead of files.
// FOS_FORCEFILESYSTEM = 0x40: only file-system items (no virtual locations
// like Recycle Bin), so GetDisplayName(FILESYSPATH) always returns a real path.
// FOS_NOCHANGEDIR = 0x08: don't change the process working directory.
const uint FOS_PICKFOLDERS = 0x20;
const uint FOS_FORCEFILESYSTEM = 0x40;
const uint FOS_NOCHANGEDIR = 0x08;
dialog.GetOptions(out var options);
dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR);
if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory))
{
if (SHCreateItemFromParsingName(initialDirectory, IntPtr.Zero,
typeof(IShellItem).GUID, out var folder) == 0 && folder is not null)
{
try
{
dialog.SetFolder(folder);
}
finally
{
Marshal.ReleaseComObject(folder);
}
}
}
// Show returns 0 (S_OK) on accept, 0x800704C7 (E_CANCELLED) on cancel,
// other HRESULTs on error. We treat any non-zero as "no result".
var hr = dialog.Show(ownerHwnd);
if (hr != 0) return null;
dialog.GetResult(out var result);
if (result is null) return null;
try
{
// SIGDN_FILESYSPATH = 0x80058000: full filesystem path.
result.GetDisplayName(unchecked((uint)0x80058000), out var path);
return path;
}
finally
{
Marshal.ReleaseComObject(result);
}
}
finally
{
Marshal.ReleaseComObject(dialog);
}
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)]
private static extern int SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string pszPath,
IntPtr pbc,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid,
out IShellItem ppv);
[ComImport]
[Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
private class FileOpenDialog
{
}
[ComImport]
[Guid("d57c7288-d4ad-4768-be02-9d969532d960")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog
{
// IModalWindow
[PreserveSig]
int Show(IntPtr parent);
// IFileDialog
void SetFileTypes(uint cFileTypes, IntPtr rgFilterSpec);
void SetFileTypeIndex(uint iFileType);
void GetFileTypeIndex(out uint piFileType);
void Advise(IntPtr pfde, out uint pdwCookie);
void Unadvise(uint dwCookie);
void SetOptions(uint fos);
void GetOptions(out uint pfos);
void SetDefaultFolder(IShellItem psi);
void SetFolder(IShellItem psi);
void GetFolder(out IShellItem ppsi);
void GetCurrentSelection(out IShellItem ppsi);
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
void GetResult(out IShellItem ppsi);
void AddPlace(IShellItem psi, int alignment);
void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
void Close(int hr);
void SetClientGuid(ref Guid guid);
void ClearClientData();
void SetFilter(IntPtr pFilter);
// IFileOpenDialog
void GetResults(out IntPtr ppenum);
void GetSelectedItems(out IntPtr ppsai);
}
[ComImport]
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
void BindToHandler(IntPtr pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid bhid,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IntPtr ppv);
void GetParent(out IShellItem ppsi);
void GetDisplayName(uint sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
void Compare(IShellItem psi, uint hint, out int piOrder);
}
}
@@ -0,0 +1,78 @@
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Dispatching;
namespace CaptureImage.UI.Services;
/// <summary>
/// <see cref="IUIThreadDispatcher"/> implementation that marshals to the WinUI 3
/// <see cref="DispatcherQueue"/>. The queue must be captured on the UI thread, so callers
/// resolve this concretely from DI in <c>App.OnLaunched</c> and invoke <see cref="Bind"/>
/// before any background code starts posting work. Calls before binding fall back to
/// running inline with a warning so first-frame startup doesn't silently drop work.
/// </summary>
public sealed class WinUIThreadDispatcher : IUIThreadDispatcher
{
private readonly ILogger<WinUIThreadDispatcher> _logger;
private DispatcherQueue? _queue;
public WinUIThreadDispatcher(ILogger<WinUIThreadDispatcher> logger)
{
_logger = logger;
}
public void Bind(DispatcherQueue queue)
{
_queue = queue;
}
public bool IsOnUIThread => _queue is not null && _queue.HasThreadAccess;
public void Post(Action action)
{
ArgumentNullException.ThrowIfNull(action);
var queue = _queue;
if (queue is null)
{
_logger.LogWarning("Post called before WinUIThreadDispatcher was bound; running inline.");
action();
return;
}
queue.TryEnqueue(() => action());
}
public Task InvokeAsync(Action action)
{
ArgumentNullException.ThrowIfNull(action);
var queue = _queue;
if (queue is null)
{
_logger.LogWarning("InvokeAsync called before WinUIThreadDispatcher was bound; running inline.");
action();
return Task.CompletedTask;
}
if (queue.HasThreadAccess)
{
action();
return Task.CompletedTask;
}
var tcs = new TaskCompletionSource();
var enqueued = queue.TryEnqueue(() =>
{
try
{
action();
tcs.SetResult();
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
if (!enqueued)
{
tcs.SetException(new InvalidOperationException("DispatcherQueue.TryEnqueue refused the work item."));
}
return tcs.Task;
}
}
+165
View File
@@ -0,0 +1,165 @@
<?xml version="1.0" encoding="utf-8"?>
<Page
x:Class="CaptureImage.UI.Views.AboutPage"
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">
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16,24,24" Spacing="18" MaxWidth="640" HorizontalAlignment="Left">
<!-- Header -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[About_Title]}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<TextBlock Text="{Binding Localization[About_Tagline]}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeSmall}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
<!-- App metadata -->
<Border Padding="16"
CornerRadius="{StaticResource CardCornerRadius}"
BorderThickness="1"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
Background="{ThemeResource CardBackgroundFillColorDefaultBrush}">
<Grid ColumnSpacing="16" RowSpacing="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Localization[About_AppLabel]}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding AppName}" FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Localization[About_VersionLabel]}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding AppVersion}" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="{Binding Localization[About_LicenseLabel]}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding License}" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="{Binding Localization[About_DeveloperLabel]}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding Developer}" />
<TextBlock Grid.Row="4" Grid.Column="0" Text="{Binding Localization[About_RepositoryLabel]}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
<HyperlinkButton Grid.Row="4" Grid.Column="1"
Content="{Binding RepositoryUrl}"
Command="{Binding OpenRepositoryCommand}"
Padding="0"
HorizontalAlignment="Left" />
</Grid>
</Border>
<!-- AI assistance disclosure -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[About_AiSection]}" FontWeight="SemiBold" />
<TextBlock Text="{Binding AiAssistanceNotice}"
TextWrapping="Wrap"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
</StackPanel>
<!-- Disclaimers -->
<StackPanel Spacing="10">
<TextBlock Text="{Binding Localization[About_DisclaimersSection]}" FontWeight="SemiBold" />
<StackPanel Spacing="3">
<TextBlock Text="{Binding Localization[About_TranslationDisclaimer]}"
FontWeight="SemiBold"
FontSize="{StaticResource FontSizeSmall}" />
<TextBlock Text="{Binding TranslationDisclaimer}"
TextWrapping="Wrap"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
</StackPanel>
<StackPanel Spacing="3">
<TextBlock Text="{Binding Localization[About_CaptureDisclaimer]}"
FontWeight="SemiBold"
FontSize="{StaticResource FontSizeSmall}" />
<TextBlock Text="{Binding CaptureLimitationDisclaimer}"
TextWrapping="Wrap"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
</StackPanel>
<StackPanel Spacing="3">
<TextBlock Text="{Binding Localization[About_LiabilityDisclaimer]}"
FontWeight="SemiBold"
FontSize="{StaticResource FontSizeSmall}" />
<TextBlock Text="{Binding LiabilityDisclaimer}"
TextWrapping="Wrap"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
</StackPanel>
</StackPanel>
<!-- Legal document links — StackPanel horizontal because WinUI 3 has no built-in
WrapPanel; the 6 buttons fit in one row at 1200 px width. M7 polish can
introduce a real wrap layout if smaller window sizes ever ship. -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding Localization[About_LegalSection]}" FontWeight="SemiBold" />
<StackPanel Orientation="Horizontal" Spacing="6">
<Button Content="{Binding Localization[About_OpenDisclaimer]}" Command="{Binding OpenDisclaimerCommand}" />
<Button Content="{Binding Localization[About_OpenPrivacy]}" Command="{Binding OpenPrivacyCommand}" />
<Button Content="{Binding Localization[About_OpenTerms]}" Command="{Binding OpenTermsCommand}" />
<Button Content="{Binding Localization[About_OpenLicense]}" Command="{Binding OpenLicenseCommand}" />
<Button Content="{Binding Localization[About_OpenThirdParty]}" Command="{Binding OpenThirdPartyCommand}" />
<Button Content="{Binding Localization[About_OpenContributors]}" Command="{Binding OpenContributorsCommand}" />
</StackPanel>
</StackPanel>
<!-- Third-party list -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding Localization[About_ThirdPartySection]}" FontWeight="SemiBold" />
<Border BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="{StaticResource CardCornerRadius}"
Padding="8">
<ItemsControl ItemsSource="{Binding ThirdPartyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding Name}"
FontSize="{StaticResource FontSizeSmall}"
TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="1"
Text="{Binding License}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Margin="8,0,0,0" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<TextBlock Text="{Binding Localization[About_ThirdPartyHint]}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Page>
@@ -0,0 +1,23 @@
using CaptureImage.ViewModels.About;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Navigation;
namespace CaptureImage.UI.Views;
public sealed partial class AboutPage : Page
{
public AboutPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is IServiceProvider services)
{
DataContext = services.GetRequiredService<AboutViewModel>();
}
}
}
-137
View File
@@ -1,137 +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:vm="clr-namespace:CaptureImage.ViewModels.About;assembly=CaptureImage.ViewModels"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.AboutView"
x:DataType="vm:AboutViewModel">
<ScrollViewer>
<StackPanel Margin="24,16,24,24" Spacing="18" MaxWidth="640">
<!-- Header -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[About_Title]}" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{Binding Localization[About_Tagline]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
</StackPanel>
<!-- App metadata -->
<Border Padding="16"
CornerRadius="8"
BorderThickness="1"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}">
<Grid ColumnDefinitions="140,*" RowDefinitions="Auto,Auto,Auto,Auto,Auto">
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Localization[About_AppLabel]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" Margin="0,0,0,6" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding AppName}" FontWeight="SemiBold" Margin="0,0,0,6" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Localization[About_VersionLabel]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" Margin="0,0,0,6" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding AppVersion}" Margin="0,0,0,6" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="{Binding Localization[About_LicenseLabel]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" Margin="0,0,0,6" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding License}" Margin="0,0,0,6" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="{Binding Localization[About_DeveloperLabel]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" Margin="0,0,0,6" />
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding Developer}" Margin="0,0,0,6" />
<TextBlock Grid.Row="4" Grid.Column="0" Text="{Binding Localization[About_RepositoryLabel]}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
<Button Grid.Row="4" Grid.Column="1"
Content="{Binding RepositoryUrl}"
Command="{Binding OpenRepositoryCommand}"
Padding="0"
Background="Transparent"
BorderThickness="0"
HorizontalAlignment="Left"
Foreground="#4F46E5" />
</Grid>
</Border>
<!-- AI assistance disclosure -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding Localization[About_AiSection]}" FontWeight="SemiBold" />
<TextBlock Text="{Binding AiAssistanceNotice}"
TextWrapping="Wrap"
Opacity="0.8"
FontSize="12" />
</StackPanel>
<!-- Disclaimers -->
<StackPanel Spacing="10">
<TextBlock Text="{Binding Localization[About_DisclaimersSection]}" FontWeight="SemiBold" />
<StackPanel Spacing="3">
<TextBlock Text="{Binding Localization[About_TranslationDisclaimer]}"
FontWeight="SemiBold"
FontSize="12" />
<TextBlock Text="{Binding TranslationDisclaimer}"
TextWrapping="Wrap"
Opacity="0.75"
FontSize="12" />
</StackPanel>
<StackPanel Spacing="3">
<TextBlock Text="{Binding Localization[About_CaptureDisclaimer]}"
FontWeight="SemiBold"
FontSize="12" />
<TextBlock Text="{Binding CaptureLimitationDisclaimer}"
TextWrapping="Wrap"
Opacity="0.75"
FontSize="12" />
</StackPanel>
<StackPanel Spacing="3">
<TextBlock Text="{Binding Localization[About_LiabilityDisclaimer]}"
FontWeight="SemiBold"
FontSize="12" />
<TextBlock Text="{Binding LiabilityDisclaimer}"
TextWrapping="Wrap"
Opacity="0.75"
FontSize="12" />
</StackPanel>
</StackPanel>
<!-- Legal document links -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding Localization[About_LegalSection]}" FontWeight="SemiBold" />
<WrapPanel>
<Button Content="{Binding Localization[About_OpenDisclaimer]}" Command="{Binding OpenDisclaimerCommand}" Margin="0,0,6,6" />
<Button Content="{Binding Localization[About_OpenPrivacy]}" Command="{Binding OpenPrivacyCommand}" Margin="0,0,6,6" />
<Button Content="{Binding Localization[About_OpenTerms]}" Command="{Binding OpenTermsCommand}" Margin="0,0,6,6" />
<Button Content="{Binding Localization[About_OpenLicense]}" Command="{Binding OpenLicenseCommand}" Margin="0,0,6,6" />
<Button Content="{Binding Localization[About_OpenThirdParty]}" Command="{Binding OpenThirdPartyCommand}" Margin="0,0,6,6" />
<Button Content="{Binding Localization[About_OpenContributors]}" Command="{Binding OpenContributorsCommand}" Margin="0,0,6,6" />
</WrapPanel>
</StackPanel>
<!-- Third-party list -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding Localization[About_ThirdPartySection]}" FontWeight="SemiBold" />
<Border BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
BorderThickness="1" CornerRadius="8" Padding="8">
<ItemsControl ItemsSource="{Binding ThirdPartyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="vm:ThirdPartyItem">
<Grid ColumnDefinitions="*,Auto" Margin="0,2">
<TextBlock Grid.Column="0"
Text="{Binding Name}"
FontSize="12"
TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="1"
Text="{Binding License}"
FontSize="11"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
Margin="8,0,0,0" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<TextBlock Text="{Binding Localization[About_ThirdPartyHint]}"
FontSize="11"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</UserControl>
@@ -1,11 +0,0 @@
using Avalonia.Controls;
namespace CaptureImage.UI.Views;
public partial class AboutView : UserControl
{
public AboutView()
{
InitializeComponent();
}
}
@@ -0,0 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<Page
x:Class="CaptureImage.UI.Views.DashboardPage"
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">
<Grid Margin="24,16,24,16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Header -->
<Grid Grid.Row="0" Margin="0,0,0,12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<TextBlock Text="{Binding Localization[Dashboard_Title]}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<TextBlock Text="{Binding Localization[Dashboard_Subtitle]}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeSmall}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Margin="0,4,0,0" />
</StackPanel>
<Button Grid.Column="1"
Content="{Binding Localization[Dashboard_Refresh]}"
Command="{Binding RefreshCommand}"
IsEnabled="{Binding IsLoading, Converter={StaticResource InvertedBoolToVisibilityConverter}}"
VerticalAlignment="Center"
Margin="0,0,8,0" />
<Button Grid.Column="2"
Content="{Binding Localization[Dashboard_Arm]}"
Command="{Binding ArmCommand}"
Visibility="{Binding IsArmed, Converter={StaticResource InvertedBoolToVisibilityConverter}}"
VerticalAlignment="Center"
Style="{StaticResource AccentButtonStyle}"
Margin="0,0,8,0" />
<Button Grid.Column="3"
Content="{Binding Localization[Dashboard_Disarm]}"
Command="{Binding DisarmCommand}"
Visibility="{Binding IsArmed, Converter={StaticResource BoolToVisibilityConverter}}"
VerticalAlignment="Center" />
</Grid>
<!-- Target list -->
<Border Grid.Row="1"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="{StaticResource CardCornerRadius}">
<Grid>
<ListView ItemsSource="{Binding Targets}"
SelectedItem="{Binding SelectedTarget, Mode=TwoWay}"
Background="Transparent"
BorderThickness="0"
Padding="4"
Visibility="{Binding HasNoTargets, Converter={StaticResource InvertedBoolToVisibilityConverter}}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="40" Margin="4,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="32" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0"
Source="{Binding IconBytes, Converter={StaticResource BytesToBitmapConverter}}"
Width="24" Height="24"
VerticalAlignment="Center" />
<StackPanel Grid.Column="1" VerticalAlignment="Center" Margin="8,0,0,0">
<TextBlock Text="{Binding DisplayName}"
FontWeight="SemiBold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding ProcessName}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
TextTrimming="CharacterEllipsis" />
</StackPanel>
<Border Grid.Column="2"
Visibility="{Binding IsSteamGame, Converter={StaticResource BoolToVisibilityConverter}}"
Background="#FF6B35"
CornerRadius="{StaticResource PillCornerRadius}"
Padding="8,2"
VerticalAlignment="Center"
ToolTipService.ToolTip="{Binding SteamBadgeTooltip}">
<TextBlock Text="STEAM"
FontSize="{StaticResource FontSizeCaption}"
FontWeight="Bold"
Foreground="White" />
</Border>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<!-- Empty state: no top-level windows detected. -->
<TextBlock Text="{Binding EmptyStateText}"
Visibility="{Binding HasNoTargets, Converter={StaticResource BoolToVisibilityConverter}}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
Margin="24" />
</Grid>
</Border>
<!-- Armed / capture state -->
<Border Grid.Row="2"
Margin="0,12,0,0"
Padding="12,8"
CornerRadius="{StaticResource CardCornerRadius}"
BorderThickness="1"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
AutomationProperties.Name="{Binding StatusMessage}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Width="10" Height="10" VerticalAlignment="Center" Margin="0,0,12,0">
<Border CornerRadius="5" Background="Gray"
Visibility="{Binding IsArmed, Converter={StaticResource InvertedBoolToVisibilityConverter}}" />
<Border CornerRadius="5" Background="#3CB371"
Visibility="{Binding IsArmed, Converter={StaticResource BoolToVisibilityConverter}}" />
<Border CornerRadius="5" Background="#FFA500"
Visibility="{Binding IsCapturing, Converter={StaticResource BoolToVisibilityConverter}}" />
</Grid>
<TextBlock Grid.Column="1"
Text="{Binding StatusMessage}"
VerticalAlignment="Center"
TextTrimming="CharacterEllipsis" />
</Grid>
</Border>
<!-- Status bar -->
<Grid Grid.Row="3" Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding TargetsCountText}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
VerticalAlignment="Center" />
<TextBlock Grid.Column="1"
Text="{Binding LoadingText}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Visibility="{Binding IsLoading, Converter={StaticResource BoolToVisibilityConverter}}"
VerticalAlignment="Center" />
</Grid>
</Grid>
</Page>
@@ -0,0 +1,23 @@
using CaptureImage.ViewModels.Dashboard;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Navigation;
namespace CaptureImage.UI.Views;
public sealed partial class DashboardPage : Page
{
public DashboardPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is IServiceProvider services)
{
DataContext = services.GetRequiredService<DashboardViewModel>();
}
}
}
@@ -1,150 +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:vm="clr-namespace:CaptureImage.ViewModels.Dashboard;assembly=CaptureImage.ViewModels"
xmlns:conv="clr-namespace:CaptureImage.UI.Converters"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.DashboardView"
x:DataType="vm:DashboardViewModel">
<UserControl.Resources>
<conv:BytesToBitmapConverter x:Key="BytesToBitmap" />
</UserControl.Resources>
<Grid RowDefinitions="Auto,*,Auto,Auto" Margin="24,16,24,16">
<!-- Header -->
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto,Auto" Margin="0,0,0,12">
<StackPanel Grid.Column="0" Orientation="Vertical">
<TextBlock Text="{Binding Localization[Dashboard_Title]}" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{Binding Localization[Dashboard_Subtitle]}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
FontSize="12" Margin="0,4,0,0" />
</StackPanel>
<Button Grid.Column="1"
Content="{Binding Localization[Dashboard_Refresh]}"
Command="{Binding RefreshCommand}"
IsEnabled="{Binding !IsLoading}"
VerticalAlignment="Center"
Margin="0,0,8,0" />
<Button Grid.Column="2"
Content="{Binding Localization[Dashboard_Arm]}"
Command="{Binding ArmCommand}"
IsVisible="{Binding !IsArmed}"
VerticalAlignment="Center"
Classes="accent"
Margin="0,0,8,0" />
<Button Grid.Column="3"
Content="{Binding Localization[Dashboard_Disarm]}"
Command="{Binding DisarmCommand}"
IsVisible="{Binding IsArmed}"
VerticalAlignment="Center" />
</Grid>
<!-- Target list -->
<Border Grid.Row="1"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
BorderThickness="1"
CornerRadius="8">
<Grid>
<ListBox ItemsSource="{Binding Targets}"
SelectedItem="{Binding SelectedTarget, Mode=TwoWay}"
Background="Transparent"
BorderThickness="0"
Padding="4"
IsVisible="{Binding !HasNoTargets}">
<ListBox.ItemTemplate>
<DataTemplate DataType="vm:GameTargetViewModel">
<Grid ColumnDefinitions="32,*,Auto" Height="40" Margin="4,2">
<Image Grid.Column="0"
Source="{Binding IconBytes, Converter={StaticResource BytesToBitmap}}"
Width="24" Height="24"
VerticalAlignment="Center" />
<StackPanel Grid.Column="1" VerticalAlignment="Center" Margin="8,0,0,0">
<TextBlock Text="{Binding DisplayName}"
FontWeight="SemiBold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding ProcessName}"
FontSize="11"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
TextTrimming="CharacterEllipsis" />
</StackPanel>
<Border Grid.Column="2"
IsVisible="{Binding IsSteamGame}"
Background="#FF6B35"
CornerRadius="4"
Padding="8,2"
VerticalAlignment="Center"
ToolTip.Tip="{Binding SteamBadgeTooltip}">
<TextBlock Text="STEAM"
FontSize="11"
FontWeight="Bold"
Foreground="White" />
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- Empty state: no top-level windows detected. -->
<TextBlock Text="{Binding EmptyStateText}"
IsVisible="{Binding HasNoTargets}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
Margin="24" />
</Grid>
</Border>
<!-- Armed / capture state -->
<Border Grid.Row="2"
Margin="0,12,0,0"
Padding="12,8"
CornerRadius="8"
BorderThickness="1"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
AutomationProperties.Name="{Binding StatusMessage}">
<Grid ColumnDefinitions="Auto,*">
<Grid Grid.Column="0" Width="10" Height="10" VerticalAlignment="Center" Margin="0,0,12,0"
AutomationProperties.Name="{Binding StatusMessage}">
<!-- Idle dot (gray) -->
<Border CornerRadius="5" Background="Gray"
IsVisible="{Binding !IsArmed}" />
<!-- Armed dot (green) — hidden while capturing -->
<Border CornerRadius="5" Background="#3CB371"
IsVisible="{Binding IsArmed}" />
<!-- Capturing dot (orange) overlays when capture in progress -->
<Border CornerRadius="5" Background="#FFA500"
IsVisible="{Binding IsCapturing}" />
</Grid>
<TextBlock Grid.Column="1"
Text="{Binding StatusMessage}"
VerticalAlignment="Center"
TextTrimming="CharacterEllipsis" />
</Grid>
</Border>
<!-- Status bar -->
<Grid Grid.Row="3" ColumnDefinitions="*,Auto" Margin="0,8,0,0">
<TextBlock Grid.Column="0"
Text="{Binding TargetsCountText}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
VerticalAlignment="Center" />
<TextBlock Grid.Column="1"
Text="{Binding LoadingText}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
IsVisible="{Binding IsLoading}"
VerticalAlignment="Center" />
</Grid>
</Grid>
</UserControl>
@@ -1,11 +0,0 @@
using Avalonia.Controls;
namespace CaptureImage.UI.Views;
public partial class DashboardView : UserControl
{
public DashboardView()
{
InitializeComponent();
}
}
@@ -1,86 +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:vm="clr-namespace:CaptureImage.ViewModels.Logs;assembly=CaptureImage.ViewModels"
xmlns:models="clr-namespace:CaptureImage.Core.Models;assembly=CaptureImage.Core"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.LogViewerView"
x:DataType="vm:LogViewerViewModel">
<Border Background="{DynamicResource SystemControlBackgroundChromeMediumBrush}"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
BorderThickness="1,1,0,0"
CornerRadius="8,0,0,0"
Padding="12">
<Grid RowDefinitions="Auto,*">
<!-- Header + controls -->
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto,Auto" Margin="0,0,0,8">
<TextBlock Grid.Column="0"
Text="{Binding Localization[Log_Title]}"
FontSize="14"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<Button Grid.Column="1"
Command="{Binding TogglePauseCommand}"
Content="{Binding TogglePauseLabel}"
Margin="0,0,8,0" />
<Button Grid.Column="2"
Command="{Binding ClearCommand}"
Content="{Binding Localization[Log_Clear]}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="3"
Text="{Binding EventsCountText}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
VerticalAlignment="Center" />
</Grid>
<!-- Entries list -->
<Grid Grid.Row="1">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
IsVisible="{Binding !HasNoEntries}">
<ItemsControl ItemsSource="{Binding Entries}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="models:LogEntry">
<Grid ColumnDefinitions="Auto,Auto,*" Margin="0,1">
<TextBlock Grid.Column="0"
Text="{Binding Timestamp, StringFormat='HH:mm:ss.fff'}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="1"
Text="{Binding Level}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
Width="45"
Margin="0,0,8,0" />
<TextBlock Grid.Column="2"
Text="{Binding Message}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
TextWrapping="NoWrap"
TextTrimming="CharacterEllipsis" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- Empty state: no log events yet. -->
<TextBlock Text="{Binding EmptyStateText}"
IsVisible="{Binding HasNoEntries}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
Margin="24" />
</Grid>
</Grid>
</Border>
</UserControl>
@@ -1,11 +0,0 @@
using Avalonia.Controls;
namespace CaptureImage.UI.Views;
public partial class LogViewerView : UserControl
{
public LogViewerView()
{
InitializeComponent();
}
}
@@ -0,0 +1,132 @@
<?xml version="1.0" encoding="utf-8"?>
<UserControl
x:Class="CaptureImage.UI.Views.LogViewerView"
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">
<Border Background="{ThemeResource LayerFillColorAltBrush}"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
BorderThickness="1,1,0,0"
CornerRadius="8,0,0,0"
Padding="12">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header + controls -->
<Grid Grid.Row="0" Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding Localization[Log_Title]}"
FontSize="{StaticResource FontSizeBodyStrong}"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<TextBlock Grid.Column="1"
Text="{Binding FilterLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
VerticalAlignment="Center"
Margin="0,0,6,0" />
<ComboBox Grid.Column="2"
ItemsSource="{Binding FilterLevels}"
SelectedItem="{Binding SelectedFilterLevel, Mode=TwoWay}"
MinWidth="110"
Margin="0,0,8,0" />
<Button Grid.Column="3"
Command="{Binding TogglePauseCommand}"
Content="{Binding TogglePauseLabel}"
Margin="0,0,8,0" />
<Button Grid.Column="4"
Command="{Binding ClearCommand}"
Content="{Binding Localization[Log_Clear]}"
Margin="0,0,8,0" />
<Button Grid.Column="5"
Command="{Binding RevealLogsFolderCommand}"
Content="{Binding RevealFolderLabel}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="6"
Text="{Binding EventsCountText}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeCaption}"
VerticalAlignment="Center" />
</Grid>
<!-- Entries list -->
<Grid Grid.Row="1">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
Visibility="{Binding HasNoEntries, Converter={StaticResource InvertedBoolToVisibilityConverter}}">
<ItemsControl ItemsSource="{Binding Entries}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding TimestampText}"
FontFamily="Consolas, Courier New"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="1"
Text="{Binding Level}"
FontFamily="Consolas, Courier New"
FontSize="{StaticResource FontSizeCaption}"
Width="45"
Margin="0,0,8,0" />
<TextBlock Grid.Column="2"
Text="{Binding FileLineText}"
FontFamily="Consolas, Courier New"
FontSize="{StaticResource FontSizeCaption}"
Width="170"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
TextTrimming="CharacterEllipsis"
Margin="0,0,8,0" />
<TextBlock Grid.Column="3"
Text="{Binding Message}"
FontFamily="Consolas, Courier New"
FontSize="{StaticResource FontSizeCaption}"
TextWrapping="NoWrap"
TextTrimming="CharacterEllipsis" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- Empty state: no log events yet. -->
<TextBlock Text="{Binding EmptyStateText}"
Visibility="{Binding HasNoEntries, Converter={StaticResource BoolToVisibilityConverter}}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
Margin="24" />
</Grid>
</Grid>
</Border>
</UserControl>
@@ -0,0 +1,17 @@
using Microsoft.UI.Xaml.Controls;
namespace CaptureImage.UI.Views;
/// <summary>
/// Slide-in log drawer. The animated show/hide is driven by <c>MainWindow</c> code-behind
/// against the host's <c>IsLogViewerVisible</c> property — keeping this UserControl
/// presentation-only means it stays composable in tests + the future toast/preview
/// surfaces can reuse the same Composition pattern.
/// </summary>
public sealed partial class LogViewerView : UserControl
{
public LogViewerView()
{
InitializeComponent();
}
}
-128
View File
@@ -1,128 +0,0 @@
<Window 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:vm="clr-namespace:CaptureImage.ViewModels;assembly=CaptureImage.ViewModels"
xmlns:nav="clr-namespace:CaptureImage.ViewModels.Navigation;assembly=CaptureImage.ViewModels"
xmlns:dashboard="clr-namespace:CaptureImage.ViewModels.Dashboard;assembly=CaptureImage.ViewModels"
xmlns:update="clr-namespace:CaptureImage.ViewModels.Update;assembly=CaptureImage.ViewModels"
xmlns:settings="clr-namespace:CaptureImage.ViewModels.Settings;assembly=CaptureImage.ViewModels"
xmlns:about="clr-namespace:CaptureImage.ViewModels.About;assembly=CaptureImage.ViewModels"
xmlns:views="clr-namespace:CaptureImage.UI.Views"
xmlns:controls="clr-namespace:CaptureImage.UI.Controls"
xmlns:conv="clr-namespace:CaptureImage.UI.Converters"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.MainWindow"
x:DataType="vm:MainWindowViewModel"
Title="CaptureImage"
Width="960" Height="600"
MinWidth="960" MinHeight="600"
MaxWidth="960" MaxHeight="600"
CanResize="False"
WindowStartupLocation="CenterScreen"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={x:Static conv:FlowDirectionConverter.Instance}}">
<Window.DataTemplates>
<DataTemplate DataType="dashboard:DashboardViewModel">
<views:DashboardView />
</DataTemplate>
<DataTemplate DataType="update:UpdateViewModel">
<views:UpdateView />
</DataTemplate>
<DataTemplate DataType="settings:SettingsViewModel">
<views:SettingsView />
</DataTemplate>
<DataTemplate DataType="about:AboutViewModel">
<views:AboutView />
</DataTemplate>
</Window.DataTemplates>
<Panel>
<Grid ColumnDefinitions="220,*">
<!-- Nav rail -->
<Border Grid.Column="0"
Background="{DynamicResource SystemControlBackgroundChromeMediumLowBrush}"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
BorderThickness="0,0,1,0">
<DockPanel LastChildFill="True">
<StackPanel DockPanel.Dock="Top" Margin="16,24,16,16">
<TextBlock Text="{Binding AppTitle}"
FontSize="22"
FontWeight="SemiBold"
Foreground="{DynamicResource SystemControlForegroundBaseHighBrush}" />
<TextBlock Text="{Binding AppVersion}"
FontSize="11"
Margin="0,4,0,0"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
</StackPanel>
<!-- Log viewer toggle at the bottom of the nav rail -->
<Button DockPanel.Dock="Bottom"
Command="{Binding ToggleLogViewerCommand}"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Margin="8,4,8,16"
Padding="12,8"
AutomationProperties.Name="{Binding LogToggleTooltip}"
ToolTip.Tip="{Binding LogToggleTooltip}">
<StackPanel Orientation="Horizontal" Spacing="12">
<TextBlock Text="&#xE9F9;"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets"
FontSize="16"
VerticalAlignment="Center" />
<TextBlock Text="{Binding LogToggleLabel}"
VerticalAlignment="Center" />
</StackPanel>
</Button>
<ListBox ItemsSource="{Binding NavItems}"
SelectedItem="{Binding SelectedNavItem, Mode=TwoWay}"
Background="Transparent"
BorderThickness="0"
Margin="8,8,8,8">
<ListBox.ItemTemplate>
<DataTemplate DataType="nav:NavItemViewModel">
<Grid ColumnDefinitions="32,*" Height="40">
<TextBlock Grid.Column="0"
Text="{Binding IconGlyph}"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets"
FontSize="16"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
<TextBlock Grid.Column="1"
Text="{Binding Label}"
VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Border>
<!-- Content host -->
<ContentControl Grid.Column="1"
Content="{Binding CurrentViewModel}"
Margin="0" />
</Grid>
<!-- Log viewer drawer — overlays the right 400px when toggled. -->
<views:LogViewerView Width="400"
HorizontalAlignment="Right"
DataContext="{Binding LogViewer}"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}" />
<!-- Toast overlay — anchored bottom-right, floats over the content grid.
Under RTL FlowDirection Avalonia automatically mirrors Right/Left edges,
so this ends up bottom-left for ar-SA etc. -->
<controls:ToastHost ItemsSource="{Binding Toasts}"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Margin="0,0,20,20"
IsHitTestVisible="True" />
</Panel>
</Window>
@@ -1,11 +0,0 @@
using Avalonia.Controls;
namespace CaptureImage.UI.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
@@ -1,61 +0,0 @@
<Window 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:vm="clr-namespace:CaptureImage.ViewModels.Preview;assembly=CaptureImage.ViewModels"
xmlns:conv="clr-namespace:CaptureImage.UI.Converters"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.PreviewWindow"
x:DataType="vm:PreviewViewModel"
Title="{Binding Localization[Preview_Title]}"
Width="720" Height="560"
WindowStartupLocation="CenterOwner"
CanResize="False"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={x:Static conv:FlowDirectionConverter.Instance}}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16">
<!-- Header -->
<StackPanel Grid.Row="0" Margin="0,0,0,12">
<TextBlock Text="{Binding Localization[Preview_Title]}" FontSize="22" FontWeight="SemiBold" />
<TextBlock Margin="0,4,0,0" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}">
<Run Text="{Binding TargetName}" />
<Run Text="— " />
<Run Text="{Binding Width}" />
<Run Text="×" />
<Run Text="{Binding Height}" />
</TextBlock>
</StackPanel>
<!-- Image preview -->
<Border Grid.Row="1"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
BorderThickness="1"
CornerRadius="8"
Background="#111">
<Image Source="{Binding PngBytes, Converter={x:Static conv:BytesToBitmapConverter.Instance}}"
Stretch="Uniform"
Margin="8" />
</Border>
<!-- Accept / discard -->
<StackPanel Grid.Row="2"
Orientation="Horizontal"
HorizontalAlignment="Right"
Spacing="8"
Margin="0,12,0,0">
<TextBlock Text="{Binding Localization[Preview_Prompt]}"
VerticalAlignment="Center"
Margin="0,0,12,0" />
<Button Name="DiscardButton"
Content="{Binding Localization[Preview_Discard]}"
MinWidth="100" />
<Button Name="SaveButton"
Content="{Binding Localization[Preview_Save]}"
Classes="accent"
MinWidth="100" />
</StackPanel>
</Grid>
</Window>
@@ -1,48 +0,0 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace CaptureImage.UI.Views;
public partial class PreviewWindow : Window
{
private readonly TaskCompletionSource<bool> _result = new();
public PreviewWindow()
{
InitializeComponent();
var saveButton = this.FindControl<Button>("SaveButton");
var discardButton = this.FindControl<Button>("DiscardButton");
if (saveButton is not null)
{
saveButton.Click += OnSaveClick;
}
if (discardButton is not null)
{
discardButton.Click += OnDiscardClick;
}
Closed += OnClosed;
}
/// <summary>Task that completes when the user accepts (true) or discards (false).</summary>
public Task<bool> ResultAsync => _result.Task;
private void OnSaveClick(object? sender, RoutedEventArgs e)
{
_result.TrySetResult(true);
Close();
}
private void OnDiscardClick(object? sender, RoutedEventArgs e)
{
_result.TrySetResult(false);
Close();
}
private void OnClosed(object? sender, EventArgs e)
{
// Closing via the X button counts as discard.
_result.TrySetResult(false);
}
}
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="CaptureImage.UI.Views.PreviewWindow"
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">
<Grid x:Name="Root"
Margin="16"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={StaticResource FlowDirectionConverter}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Header -->
<StackPanel Grid.Row="0" Margin="0,0,0,12">
<TextBlock Text="{Binding Localization[Preview_Title]}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<TextBlock Margin="0,4,0,0"
Foreground="{ThemeResource TextFillColorSecondaryBrush}">
<Run Text="{Binding TargetName}" />
<Run Text=" — " />
<Run Text="{Binding Width}" />
<Run Text="×" />
<Run Text="{Binding Height}" />
</TextBlock>
</StackPanel>
<!-- Image preview -->
<Border Grid.Row="1"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="{StaticResource CardCornerRadius}"
Background="#111111">
<Image Source="{Binding PngBytes, Converter={StaticResource BytesToBitmapConverter}}"
Stretch="Uniform"
Margin="8" />
</Border>
<!-- Accept / discard -->
<StackPanel Grid.Row="2"
Orientation="Horizontal"
HorizontalAlignment="Right"
Spacing="8"
Margin="0,12,0,0">
<TextBlock Text="{Binding Localization[Preview_Prompt]}"
VerticalAlignment="Center"
Margin="0,0,12,0" />
<Button x:Name="DiscardButton"
Content="{Binding Localization[Preview_Discard]}"
Click="OnDiscardClick"
MinWidth="100" />
<Button x:Name="SaveButton"
Content="{Binding Localization[Preview_Save]}"
Style="{StaticResource AccentButtonStyle}"
Click="OnSaveClick"
MinWidth="100" />
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,65 @@
using CaptureImage.ViewModels.Preview;
using Microsoft.UI;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media;
using Windows.Graphics;
using WinRT.Interop;
namespace CaptureImage.UI.Views;
/// <summary>
/// WinUI 3 preview window for a captured frame. Closed by the Save / Discard buttons or
/// the title-bar X — <see cref="ResultAsync"/> resolves true only when the user clicks Save.
/// </summary>
public sealed partial class PreviewWindow : Window
{
private const int InitialWidth = 720;
private const int InitialHeight = 560;
private readonly TaskCompletionSource<bool> _result =
new(TaskCreationOptions.RunContinuationsAsynchronously);
public PreviewWindow()
{
InitializeComponent();
Title = "CaptureImage — Preview";
SystemBackdrop = new MicaBackdrop { Kind = MicaKind.Base };
ExtendsContentIntoTitleBar = true;
var hwnd = WindowNative.GetWindowHandle(this);
var windowId = Win32Interop.GetWindowIdFromWindow(hwnd);
var appWindow = AppWindow.GetFromWindowId(windowId);
appWindow.Resize(new SizeInt32(InitialWidth, InitialHeight));
Closed += OnClosed;
}
/// <summary>Task that completes when the user accepts (true) or discards (false).</summary>
public Task<bool> ResultAsync => _result.Task;
public void SetViewModel(PreviewViewModel vm)
{
Root.DataContext = vm;
}
private void OnSaveClick(object sender, RoutedEventArgs e)
{
_result.TrySetResult(true);
Close();
}
private void OnDiscardClick(object sender, RoutedEventArgs e)
{
_result.TrySetResult(false);
Close();
}
private void OnClosed(object sender, WindowEventArgs args)
{
// Closing via the X button counts as discard.
_result.TrySetResult(false);
}
}
+163
View File
@@ -0,0 +1,163 @@
<?xml version="1.0" encoding="utf-8"?>
<Page
x:Class="CaptureImage.UI.Views.SettingsPage"
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:controls="using:CaptureImage.UI.Controls"
mc:Ignorable="d">
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16" Spacing="18" MaxWidth="620" HorizontalAlignment="Left">
<TextBlock Text="{Binding TitleLabel}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<!-- Language -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding LanguageLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<ComboBox ItemsSource="{Binding SupportedCultures}"
SelectedItem="{Binding SelectedCulture, Mode=TwoWay}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DisplayName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<!-- Hotkey: HotkeyRecorder custom control owns the key-capture flow. Bound
to the SettingsViewModel.Hotkey child VM (HotkeyBindingViewModel). -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding HotkeyLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<controls:HotkeyRecorder DataContext="{Binding Hotkey}" />
<TextBlock Text="{Binding HotkeyHint}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
<!-- Default format -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding FormatLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<ComboBox ItemsSource="{Binding SupportedFormats}"
SelectedItem="{Binding DefaultFormat, Mode=TwoWay}"
HorizontalAlignment="Stretch" />
</StackPanel>
<!-- Quality sliders side-by-side -->
<Grid ColumnSpacing="16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Spacing="4">
<TextBlock Text="{Binding JpegQualityLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<Slider Minimum="1" Maximum="100"
Value="{Binding JpegQuality, Mode=TwoWay}"
TickFrequency="10" />
<TextBlock Text="{Binding JpegQuality}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
HorizontalAlignment="Right" />
</StackPanel>
<StackPanel Grid.Column="1" Spacing="4">
<TextBlock Text="{Binding WebpQualityLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<Slider Minimum="1" Maximum="100"
Value="{Binding WebpQuality, Mode=TwoWay}"
TickFrequency="10" />
<TextBlock Text="{Binding WebpQuality}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
HorizontalAlignment="Right" />
</StackPanel>
</Grid>
<!-- Output folder -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding OutputFolderLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<Grid ColumnSpacing="8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0"
Text="{Binding OutputDirectory, Mode=TwoWay}"
PlaceholderText="{Binding OutputFolderWatermark}" />
<Button Grid.Column="1"
x:Name="BrowseOutputButton"
Content="{Binding BrowseLabel}"
ToolTipService.ToolTip="{Binding BrowseTooltip}"
MinWidth="100" />
</Grid>
</StackPanel>
<!-- File name template -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding FileNameTemplateLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<TextBox Text="{Binding FileNameTemplate, Mode=TwoWay}"
FontFamily="Consolas, Courier New" />
</StackPanel>
<!-- Toggles -->
<StackPanel Spacing="6">
<CheckBox Content="{Binding PreviewBeforeSaveLabel}"
IsChecked="{Binding PreviewBeforeSave, Mode=TwoWay}" />
<CheckBox Content="{Binding MinimizeToTrayLabel}"
IsChecked="{Binding MinimizeToTray, Mode=TwoWay}" />
<CheckBox Content="{Binding SoundEnabledLabel}"
IsChecked="{Binding SoundEnabled, Mode=TwoWay}" />
</StackPanel>
<!-- Logging -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding LoggingLabel}"
FontSize="{StaticResource FontSizeBody}"
FontWeight="SemiBold" />
<StackPanel Spacing="4">
<TextBlock Text="{Binding LogLevelLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<ComboBox ItemsSource="{Binding SupportedLogLevels}"
SelectedItem="{Binding SelectedLogLevel, Mode=TwoWay}"
HorizontalAlignment="Stretch" />
<TextBlock Text="{Binding LogLevelHint}"
FontSize="{StaticResource FontSizeCaption}"
TextWrapping="Wrap"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
</StackPanel>
<!-- Import / export / open settings file -->
<StackPanel Orientation="Horizontal" Spacing="8">
<Button x:Name="ImportButton" Content="{Binding ImportLabel}" />
<Button x:Name="ExportButton" Content="{Binding ExportLabel}" />
<Button Content="{Binding OpenFileLabel}"
Command="{Binding OpenSettingsFileCommand}" />
</StackPanel>
<TextBlock Text="{Binding SettingsFilePath}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeCaption}"
TextWrapping="Wrap" />
</StackPanel>
</ScrollViewer>
</Page>
@@ -0,0 +1,59 @@
using CaptureImage.UI.Services;
using CaptureImage.ViewModels.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Navigation;
using WinRT.Interop;
namespace CaptureImage.UI.Views;
public sealed partial class SettingsPage : Page
{
public SettingsPage()
{
InitializeComponent();
BrowseOutputButton.Click += OnBrowseOutputClicked;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is IServiceProvider services)
{
DataContext = services.GetRequiredService<SettingsViewModel>();
}
}
private void OnBrowseOutputClicked(object sender, RoutedEventArgs e)
{
var window = WindowHostHelper.MainWindow;
if (window is null) return;
var hwnd = WindowNative.GetWindowHandle(window);
if (hwnd == IntPtr.Zero) return;
// Use the Win32 IFileOpenDialog COM interface instead of
// Windows.Storage.Pickers.FolderPicker — the WinRT picker throws
// COMException 0x80004005 on PickSingleFolderAsync in unpackaged WinUI 3 apps
// even with InitializeWithWindow set up correctly. IFileOpenDialog works
// on all Windows versions without packaging requirements.
var initial = (DataContext as SettingsViewModel)?.OutputDirectory;
var folder = Win32FolderPicker.PickSingleFolder(hwnd, initial);
if (folder is null) return;
if (DataContext is SettingsViewModel vm)
{
vm.OutputDirectory = folder;
}
}
}
/// <summary>
/// Tiny static bridge that lets CaptureImage.UI Pages reach the host Window without
/// taking a project reference back to CaptureImage.App. Set by App.OnLaunched once the
/// main window exists.
/// </summary>
public static class WindowHostHelper
{
public static Window? MainWindow { get; set; }
}
@@ -1,105 +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:vm="clr-namespace:CaptureImage.ViewModels.Settings;assembly=CaptureImage.ViewModels"
xmlns:ctrl="clr-namespace:CaptureImage.UI.Controls"
xmlns:sys="clr-namespace:System.Globalization;assembly=System.Runtime"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.SettingsView"
x:DataType="vm:SettingsViewModel">
<ScrollViewer>
<StackPanel Margin="24,16" Spacing="18" MaxWidth="620">
<TextBlock Text="{Binding TitleLabel}" FontSize="22" FontWeight="SemiBold" />
<!-- Language -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding LanguageLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<ComboBox ItemsSource="{Binding SupportedCultures}"
SelectedItem="{Binding SelectedCulture, Mode=TwoWay}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate DataType="sys:CultureInfo">
<TextBlock Text="{Binding DisplayName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<!-- Hotkey -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding HotkeyLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<ctrl:HotkeyRecorder DataContext="{Binding Hotkey}" />
<TextBlock Text="{Binding HotkeyHint}" FontSize="11" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
</StackPanel>
<!-- Default format -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding FormatLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<ComboBox ItemsSource="{Binding SupportedFormats}"
SelectedItem="{Binding DefaultFormat, Mode=TwoWay}"
HorizontalAlignment="Stretch" />
</StackPanel>
<!-- Quality sliders -->
<Grid ColumnDefinitions="*,16,*">
<StackPanel Grid.Column="0" Spacing="4">
<TextBlock Text="{Binding JpegQualityLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<Slider Minimum="1" Maximum="100" Value="{Binding JpegQuality, Mode=TwoWay}" TickFrequency="10" />
<TextBlock Text="{Binding JpegQuality}" FontSize="11" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" HorizontalAlignment="Right" />
</StackPanel>
<StackPanel Grid.Column="2" Spacing="4">
<TextBlock Text="{Binding WebpQualityLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<Slider Minimum="1" Maximum="100" Value="{Binding WebpQuality, Mode=TwoWay}" TickFrequency="10" />
<TextBlock Text="{Binding WebpQuality}" FontSize="11" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" HorizontalAlignment="Right" />
</StackPanel>
</Grid>
<!-- Output folder -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding OutputFolderLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<Grid ColumnDefinitions="*,8,Auto">
<TextBox Grid.Column="0"
Text="{Binding OutputDirectory, Mode=TwoWay}"
Watermark="{Binding OutputFolderWatermark}" />
<Button Grid.Column="2"
Name="BrowseOutputButton"
Content="{Binding BrowseLabel}"
ToolTip.Tip="{Binding BrowseTooltip}"
MinWidth="100" />
</Grid>
</StackPanel>
<!-- File name template -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding FileNameTemplateLabel}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12" />
<TextBox Text="{Binding FileNameTemplate, Mode=TwoWay}"
FontFamily="Consolas, Courier New, monospace" />
</StackPanel>
<!-- Toggles -->
<StackPanel Spacing="6">
<CheckBox Content="{Binding PreviewBeforeSaveLabel}"
IsChecked="{Binding PreviewBeforeSave, Mode=TwoWay}" />
<CheckBox Content="{Binding MinimizeToTrayLabel}"
IsChecked="{Binding MinimizeToTray, Mode=TwoWay}" />
<CheckBox Content="{Binding SoundEnabledLabel}"
IsChecked="{Binding SoundEnabled, Mode=TwoWay}" />
</StackPanel>
<!-- Import / export / open -->
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Name="ImportButton" Content="{Binding ImportLabel}" />
<Button Name="ExportButton" Content="{Binding ExportLabel}" />
<Button Content="{Binding OpenFileLabel}"
Command="{Binding OpenSettingsFileCommand}" />
</StackPanel>
<TextBlock Text="{Binding SettingsFilePath}" Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="11" TextWrapping="Wrap" />
</StackPanel>
</ScrollViewer>
</UserControl>
@@ -1,125 +0,0 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using CaptureImage.ViewModels.Settings;
namespace CaptureImage.UI.Views;
public partial class SettingsView : UserControl
{
public SettingsView()
{
InitializeComponent();
var importButton = this.FindControl<Button>("ImportButton");
var exportButton = this.FindControl<Button>("ExportButton");
var browseOutputButton = this.FindControl<Button>("BrowseOutputButton");
if (importButton is not null)
{
importButton.Click += OnImportClick;
}
if (exportButton is not null)
{
exportButton.Click += OnExportClick;
}
if (browseOutputButton is not null)
{
browseOutputButton.Click += OnBrowseOutputClick;
}
}
private async void OnBrowseOutputClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not SettingsViewModel vm) return;
var top = TopLevel.GetTopLevel(this);
if (top is null) return;
// Seed the picker at whatever the user has configured (or the system default if
// the field is empty). Failing to resolve the suggested start is non-fatal — the
// picker falls back to its own default.
IStorageFolder? suggestedStart = null;
if (!string.IsNullOrWhiteSpace(vm.OutputDirectory))
{
try
{
suggestedStart = await top.StorageProvider.TryGetFolderFromPathAsync(vm.OutputDirectory);
}
catch
{
// Ignore — start elsewhere.
}
}
var folders = await top.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
{
Title = vm.Localization["Settings_BrowseTitle"],
AllowMultiple = false,
SuggestedStartLocation = suggestedStart,
});
if (folders.Count == 0) return;
var path = folders[0].TryGetLocalPath();
if (!string.IsNullOrEmpty(path))
{
// Two-way binding pushes back into AppSettings through the
// OnOutputDirectoryChanged partial handler in the VM.
vm.OutputDirectory = path;
}
}
private async void OnImportClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not SettingsViewModel vm) return;
var top = TopLevel.GetTopLevel(this);
if (top is null) return;
var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = vm.Localization["Settings_ImportTitle"],
AllowMultiple = false,
FileTypeFilter = new[]
{
new FilePickerFileType("JSON") { Patterns = new[] { "*.json" } },
},
});
if (files.Count == 0) return;
var path = files[0].TryGetLocalPath();
if (!string.IsNullOrEmpty(path))
{
await vm.ImportCommand.ExecuteAsync(path);
}
}
private async void OnExportClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not SettingsViewModel vm) return;
var top = TopLevel.GetTopLevel(this);
if (top is null) return;
var file = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = vm.Localization["Settings_ExportTitle"],
DefaultExtension = "json",
SuggestedFileName = "captureimage-settings.json",
FileTypeChoices = new[]
{
new FilePickerFileType("JSON") { Patterns = new[] { "*.json" } },
},
});
if (file is null) return;
var path = file.TryGetLocalPath();
if (!string.IsNullOrEmpty(path))
{
await vm.ExportCommand.ExecuteAsync(path);
}
}
}
+113
View File
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="utf-8"?>
<Page
x:Class="CaptureImage.UI.Views.UpdatePage"
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">
<Grid Margin="24,16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header -->
<StackPanel Grid.Row="0" Spacing="4" Margin="0,0,0,16">
<TextBlock Text="{Binding Localization[Update_Title]}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<TextBlock Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontFamily="{StaticResource BodyFontFamily}">
<Run Text="{Binding Localization[About_VersionLabel]}" />
<Run Text=": " />
<Run Text="{Binding CurrentVersion}" />
</TextBlock>
</StackPanel>
<!-- Available version + release notes -->
<Border Grid.Row="1"
Visibility="{Binding AvailableVersion, Converter={StaticResource NotNullToVisibilityConverter}}"
Padding="12"
CornerRadius="{StaticResource CardCornerRadius}"
BorderThickness="1"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
Margin="0,0,0,12">
<StackPanel Spacing="6">
<TextBlock FontWeight="SemiBold">
<Run Text="{Binding Localization[Update_NewVersion]}" />
<Run Text=" " />
<Run Text="{Binding AvailableVersion}" />
</TextBlock>
<TextBlock Text="{Binding ReleaseNotes}"
Visibility="{Binding ReleaseNotes, Converter={StaticResource NotNullToVisibilityConverter}}"
TextWrapping="Wrap"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
</StackPanel>
</Border>
<!-- Action buttons -->
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="8" Margin="0,0,0,12">
<Button Content="{Binding Localization[Update_Check]}"
Command="{Binding CheckCommand}" />
<Button Content="{Binding Localization[Update_Download]}"
Command="{Binding DownloadCommand}"
Style="{StaticResource AccentButtonStyle}" />
<Button Content="{Binding Localization[Update_Install]}"
Command="{Binding InstallCommand}"
Style="{StaticResource AccentButtonStyle}" />
</StackPanel>
<!-- Progress + status -->
<StackPanel Grid.Row="3" Spacing="6" Margin="0,0,0,12">
<ProgressBar Value="{Binding DownloadProgress}"
Minimum="0" Maximum="100"
Visibility="{Binding IsBusy, Converter={StaticResource BoolToVisibilityConverter}}" />
<TextBlock Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}">
<Run Text="{Binding Localization[Update_Status]}" />
<Run Text=": " />
<Run Text="{Binding Status}" />
</TextBlock>
</StackPanel>
<!-- Log section -->
<Border Grid.Row="4"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="{StaticResource CardCornerRadius}"
Padding="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Text="{Binding Localization[Update_Log]}"
FontWeight="SemiBold"
FontSize="{StaticResource FontSizeSmall}"
Margin="0,0,0,8" />
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding LogLines}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"
FontFamily="Consolas, Courier New"
FontSize="{StaticResource FontSizeCaption}"
TextWrapping="NoWrap" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Border>
</Grid>
</Page>
@@ -0,0 +1,23 @@
using CaptureImage.ViewModels.Update;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Navigation;
namespace CaptureImage.UI.Views;
public sealed partial class UpdatePage : Page
{
public UpdatePage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is IServiceProvider services)
{
DataContext = services.GetRequiredService<UpdateViewModel>();
}
}
}
-103
View File
@@ -1,103 +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:vm="clr-namespace:CaptureImage.ViewModels.Update;assembly=CaptureImage.ViewModels"
mc:Ignorable="d"
x:Class="CaptureImage.UI.Views.UpdateView"
x:DataType="vm:UpdateViewModel">
<Grid RowDefinitions="Auto,Auto,Auto,Auto,*" Margin="24,16">
<!-- Header -->
<StackPanel Grid.Row="0" Spacing="4" Margin="0,0,0,16">
<TextBlock Text="{Binding Localization[Update_Title]}" FontSize="22" FontWeight="SemiBold" />
<TextBlock Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}">
<Run Text="{Binding Localization[About_VersionLabel]}" />
<Run Text=": " />
<Run Text="{Binding CurrentVersion}" />
</TextBlock>
</StackPanel>
<!-- Available version + release notes -->
<Border Grid.Row="1"
IsVisible="{Binding AvailableVersion, Converter={x:Static ObjectConverters.IsNotNull}}"
Padding="12"
CornerRadius="8"
BorderThickness="1"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
Background="{DynamicResource SystemControlBackgroundChromeMediumLowBrush}"
Margin="0,0,0,12">
<StackPanel Spacing="6">
<TextBlock FontWeight="SemiBold">
<Run Text="{Binding Localization[Update_NewVersion]}" />
<Run Text=" " />
<Run Text="{Binding AvailableVersion}" />
</TextBlock>
<TextBlock Text="{Binding ReleaseNotes}"
IsVisible="{Binding ReleaseNotes, Converter={x:Static ObjectConverters.IsNotNull}}"
TextWrapping="Wrap"
Opacity="0.85"
FontSize="12" />
</StackPanel>
</Border>
<!-- Action buttons + progress -->
<Grid Grid.Row="2" ColumnDefinitions="Auto,Auto,Auto,*" Margin="0,0,0,12">
<Button Grid.Column="0"
Content="{Binding Localization[Update_Check]}"
Command="{Binding CheckCommand}"
Margin="0,0,8,0" />
<Button Grid.Column="1"
Content="{Binding Localization[Update_Download]}"
Command="{Binding DownloadCommand}"
Classes="accent"
Margin="0,0,8,0" />
<Button Grid.Column="2"
Content="{Binding Localization[Update_Install]}"
Command="{Binding InstallCommand}"
Classes="accent" />
</Grid>
<!-- Progress + status -->
<StackPanel Grid.Row="3" Spacing="6" Margin="0,0,0,12">
<ProgressBar Value="{Binding DownloadProgress}"
Minimum="0" Maximum="100"
IsVisible="{Binding IsBusy}" />
<TextBlock Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" FontSize="12">
<Run Text="{Binding Localization[Update_Status]}" />
<Run Text=": " />
<Run Text="{Binding Status}" />
</TextBlock>
</StackPanel>
<!-- Log section -->
<Border Grid.Row="4"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
BorderThickness="1"
CornerRadius="8"
Padding="10">
<Grid RowDefinitions="Auto,*">
<TextBlock Grid.Row="0"
Text="{Binding Localization[Update_Log]}"
FontWeight="SemiBold"
FontSize="12"
Margin="0,0,0,8" />
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding LogLines}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="x:String">
<TextBlock Text="{Binding}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
TextWrapping="NoWrap" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Border>
</Grid>
</UserControl>
@@ -1,11 +0,0 @@
using Avalonia.Controls;
namespace CaptureImage.UI.Views;
public partial class UpdateView : UserControl
{
public UpdateView()
{
InitializeComponent();
}
}
@@ -1,7 +1,5 @@
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using CaptureImage.Core.Abstractions;
using CommunityToolkit.Mvvm.Input;
@@ -47,7 +45,8 @@ public sealed partial class AboutViewModel : ViewModelBase
ThirdPartyItems = new ObservableCollection<ThirdPartyItem>
{
new("Avalonia", "MIT", "https://github.com/AvaloniaUI/Avalonia"),
new("Windows App SDK / WinUI 3", "MIT", "https://github.com/microsoft/WindowsAppSDK"),
new("H.NotifyIcon.WinUI", "MIT", "https://github.com/HavenDV/H.NotifyIcon"),
new("SkiaSharp", "MIT", "https://github.com/mono/SkiaSharp"),
new("CommunityToolkit.Mvvm", "MIT", "https://github.com/CommunityToolkit/dotnet"),
new("Microsoft.Extensions.*", "MIT", "https://github.com/dotnet/runtime"),
@@ -58,7 +57,6 @@ public sealed partial class AboutViewModel : ViewModelBase
new("libuiohook", "GPL-3.0", "https://github.com/kwhat/libuiohook"),
new("Stateless", "Apache-2.0", "https://github.com/dotnet-state-machine/stateless"),
new("Velopack", "MIT", "https://github.com/velopack/velopack"),
new("Inter typeface", "OFL-1.1", "https://github.com/rsms/inter"),
};
}
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CaptureImage.Core.Pipeline;
@@ -377,6 +372,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
_toasts.ShowSuccess(
Localization["Toast_CaptureSaved"],
Path.GetFileName(ok.FilePath));
PlayCaptureSoundIfEnabled();
break;
case CaptureResult.Failure fail:
_stateMachine.Fire(CaptureTrigger.ErrorOccurred);
@@ -485,6 +481,20 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
{
await Task.Delay(RefreshDebounce, token).ConfigureAwait(true);
if (token.IsCancellationRequested) return;
// Suppress refresh while a preview modal is up — rebuilding Targets
// would replace the GameTargetViewModel instances and the user-visible
// SelectedTarget would shuffle out from under the preview decision.
// The next process event after the preview closes triggers a fresh
// debounce, so nothing's lost.
if (_stateMachine.CurrentState is CaptureState.Previewing or CaptureState.Saving)
{
_logger.LogDebug(
"Suppressed dashboard refresh while in {State} state.",
_stateMachine.CurrentState);
return;
}
await RefreshAsync().ConfigureAwait(true);
}
catch (TaskCanceledException)
@@ -502,6 +512,35 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
}
}
/// <summary>
/// Play the standard Windows "SystemAsterisk" notification sound on a successful
/// capture when <c>UI.SoundEnabled</c> is on. The setting has lived in
/// <c>AppSettings</c> since v1.0 but had no consumer until v1.3-M7a — this hooks it
/// up. Uses Win32 PlaySound directly (via P/Invoke) instead of
/// <c>System.Media.SystemSounds</c> because the latter lives in
/// <c>System.Windows.Extensions</c> which only ships for Windows TFMs, and the
/// ViewModels project is intentionally TFM-portable. Failures are non-fatal: the
/// capture has already succeeded; missing audio devices just get logged.
/// </summary>
[System.Runtime.InteropServices.DllImport("winmm.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern bool PlaySound(string? pszSound, IntPtr hmod, uint fdwSound);
private const uint SND_ASYNC = 0x0001;
private const uint SND_ALIAS = 0x00010000;
private void PlayCaptureSoundIfEnabled()
{
if (!_settings.Current.UI.SoundEnabled) return;
try
{
PlaySound("SystemAsterisk", IntPtr.Zero, SND_ASYNC | SND_ALIAS);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Failed to play capture sound.");
}
}
public void Dispose()
{
if (_disposed) return;
@@ -1,4 +1,3 @@
using System;
using System.ComponentModel;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
@@ -1,19 +1,23 @@
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Logging;
using CaptureImage.Core.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
// Disambiguate — `LogLevel` here means the one in LogEntry (Serilog-derived severity),
// not MEL's `Microsoft.Extensions.Logging.LogLevel` used by the `_logger` field.
using LogLevel = CaptureImage.Core.Models.LogLevel;
namespace CaptureImage.ViewModels.Logs;
/// <summary>
/// Live log viewer for the drawer pane. Hydrates from the ring buffer on first show,
/// appends new entries as they fire, and supports pause/resume/clear/export.
/// appends new entries as they fire, and supports pause/resume/clear/export plus a
/// view-side level filter and a button to open the rolling-file folder in Explorer.
/// </summary>
public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
{
@@ -23,6 +27,8 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
private readonly ILogBufferSource _source;
private readonly IUIThreadDispatcher _dispatcher;
private readonly ILogger<LogViewerViewModel> _logger;
private readonly IToastService _toasts;
private bool _hydrated;
private bool _disposed;
@@ -30,20 +36,42 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
public ObservableCollection<LogEntry> Entries { get; } = new();
/// <summary>Options shown in the level-filter dropdown. Order matters: lowest to highest.</summary>
public IReadOnlyList<LogLevel> FilterLevels { get; } = new[]
{
LogLevel.Verbose,
LogLevel.Debug,
LogLevel.Information,
LogLevel.Warning,
LogLevel.Error,
};
[ObservableProperty]
private bool _isPaused;
[ObservableProperty]
private bool _isVisible;
/// <summary>
/// Minimum level the viewer displays. Entries below this get hidden from
/// <see cref="Entries"/> but still live in the sink buffer, so Export always carries
/// the full history regardless of this filter.
/// </summary>
[ObservableProperty]
private LogLevel _selectedFilterLevel = LogLevel.Verbose;
public LogViewerViewModel(
ILogBufferSource source,
IUIThreadDispatcher dispatcher,
ILocalizationService localization)
ILocalizationService localization,
ILogger<LogViewerViewModel> logger,
IToastService toasts)
{
_source = source;
_dispatcher = dispatcher;
Localization = localization;
_logger = logger;
_toasts = toasts;
_source.Emitted += OnEmitted;
Localization.PropertyChanged += OnLocalizationChanged;
@@ -63,6 +91,8 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
OnPropertyChanged(nameof(TogglePauseLabel));
OnPropertyChanged(nameof(EventsCountText));
OnPropertyChanged(nameof(EmptyStateText));
OnPropertyChanged(nameof(FilterLabel));
OnPropertyChanged(nameof(RevealFolderLabel));
// Refresh the `{Binding Localization[Log_Title]}` / `[Log_Clear]` direct
// indexer bindings in the header. v1.1.1 hotfix — the service's own
// Item[] notification alone doesn't reliably re-resolve the path.
@@ -92,6 +122,12 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
/// <summary>Localized hint shown inside the drawer when no log events have fired yet.</summary>
public string EmptyStateText => Localization["Log_EmptyState"];
/// <summary>Localized label for the minimum-level filter dropdown.</summary>
public string FilterLabel => Localization["Log_Filter"];
/// <summary>Localized button label that opens the rolling-file folder in Explorer.</summary>
public string RevealFolderLabel => Localization["Log_RevealFolder"];
public bool HasNoEntries => Entries.Count == 0;
partial void OnIsPausedChanged(bool value)
@@ -100,6 +136,24 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
OnPropertyChanged(nameof(TogglePauseLabel));
}
partial void OnSelectedFilterLevelChanged(LogLevel value)
{
// Rebuild the visible list from the sink snapshot whenever the filter moves.
// O(2000) — trivial and only runs on user input.
Entries.Clear();
var snapshot = _source.Snapshot();
var start = Math.Max(0, snapshot.Count - MaxVisibleEntries);
for (var i = start; i < snapshot.Count; i++)
{
if (PassesFilter(snapshot[i]))
{
Entries.Add(snapshot[i]);
}
}
}
private bool PassesFilter(LogEntry entry) => entry.Level >= SelectedFilterLevel;
/// <summary>
/// Called the first time the drawer is shown. Fills the ObservableCollection from the
/// sink's snapshot so the user sees historical log events too.
@@ -112,7 +166,10 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
var start = Math.Max(0, snapshot.Count - MaxVisibleEntries);
for (var i = start; i < snapshot.Count; i++)
{
Entries.Add(snapshot[i]);
if (PassesFilter(snapshot[i]))
{
Entries.Add(snapshot[i]);
}
}
}
@@ -126,6 +183,21 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
[RelayCommand]
private void TogglePause() => IsPaused = !IsPaused;
[RelayCommand]
private void RevealLogsFolder()
{
var folder = LogPaths.GetLogsDirectory();
try
{
Process.Start(new ProcessStartInfo(folder) { UseShellExecute = true });
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to open logs folder {Path}.", folder);
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
[RelayCommand]
private async Task ExportAsync(string filePath)
{
@@ -137,6 +209,11 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
{
sb.Append('[').Append(entry.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sb.Append(' ').Append(entry.Level.ToString().ToUpperInvariant().Substring(0, 3)).Append("] ");
var fileLine = entry.FileLineText;
if (!string.IsNullOrEmpty(fileLine))
{
sb.Append('(').Append(fileLine).Append(") ");
}
if (!string.IsNullOrEmpty(entry.SourceContext))
{
sb.Append(entry.SourceContext).Append(": ");
@@ -155,6 +232,7 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
// Marshal to UI thread before mutating the ObservableCollection.
_dispatcher.Post(() =>
{
if (!PassesFilter(entry)) return;
Entries.Add(entry);
while (Entries.Count > MaxVisibleEntries)
{
@@ -1,4 +1,3 @@
using System;
using System.ComponentModel;
using CaptureImage.Core.Abstractions;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -1,4 +1,3 @@
using System;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -21,6 +21,7 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
private readonly ISettingsStore _settings;
private readonly IToastService _toasts;
private readonly ILogger<SettingsViewModel> _logger;
private readonly ILogLevelSwitcher _logLevelSwitcher;
private bool _suppressPush;
private bool _disposed;
@@ -34,6 +35,14 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
public ObservableCollection<ImageFormat> SupportedFormats { get; } =
new(new[] { ImageFormat.Png, ImageFormat.Jpeg, ImageFormat.Webp, ImageFormat.Tiff });
/// <summary>
/// Log-level options shown in the Settings Logging picker. Order matches user
/// expectation (most-verbose first) and the strings match <see cref="AppSettings.LogLevel"/>
/// so the picker can bind directly to <see cref="SelectedLogLevel"/>.
/// </summary>
public ObservableCollection<string> SupportedLogLevels { get; } =
new(new[] { "Debug", "Information", "Warning", "Error" });
[ObservableProperty]
private CultureInfo _selectedCulture;
@@ -61,6 +70,9 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
[ObservableProperty]
private bool _soundEnabled;
[ObservableProperty]
private string _selectedLogLevel = "Information";
public string SettingsFilePath => _settings.SettingsFilePath;
// -- localized labels ---------------------------------------------------
@@ -91,17 +103,22 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
public string ImportLabel => Localization["Settings_Import"];
public string ExportLabel => Localization["Settings_Export"];
public string OpenFileLabel => Localization["Settings_OpenFile"];
public string LoggingLabel => Localization["Settings_Logging"];
public string LogLevelLabel => Localization["Settings_LogLevel"];
public string LogLevelHint => Localization["Settings_LogLevelHint"];
public SettingsViewModel(
ISettingsStore settings,
ILocalizationService localization,
IToastService toasts,
HotkeyBindingViewModel hotkey,
ILogger<SettingsViewModel> logger)
ILogger<SettingsViewModel> logger,
ILogLevelSwitcher logLevelSwitcher)
{
_settings = settings;
_toasts = toasts;
_logger = logger;
_logLevelSwitcher = logLevelSwitcher;
Localization = localization;
Hotkey = hotkey;
@@ -152,6 +169,9 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
OnPropertyChanged(nameof(ImportLabel));
OnPropertyChanged(nameof(ExportLabel));
OnPropertyChanged(nameof(OpenFileLabel));
OnPropertyChanged(nameof(LoggingLabel));
OnPropertyChanged(nameof(LogLevelLabel));
OnPropertyChanged(nameof(LogLevelHint));
}
}
@@ -190,6 +210,11 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
PreviewBeforeSave = current.Capture.PreviewBeforeSave;
MinimizeToTray = current.UI.MinimizeToTray;
SoundEnabled = current.UI.SoundEnabled;
// Fall back to the first supported value if the persisted string doesn't match —
// that can happen after a hand-edit or a downgrade from a future schema.
SelectedLogLevel = SupportedLogLevels.Contains(current.LogLevel)
? current.LogLevel
: SupportedLogLevels[1]; // Information
}
finally
{
@@ -252,6 +277,16 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
_settings.Update(s => s with { UI = s.UI with { SoundEnabled = value } });
}
partial void OnSelectedLogLevelChanged(string value)
{
if (_suppressPush || string.IsNullOrWhiteSpace(value)) return;
_settings.Update(s => s with { LogLevel = value });
// Flip the live Serilog minimum level immediately — no restart needed. The
// persisted value syncs via the debounced settings writer.
_logLevelSwitcher.SetLevel(value);
_logger.LogInformation("Log level changed to {Level}.", value);
}
private static int Clamp(int v) => v < 1 ? 1 : v > 100 ? 100 : v;
[RelayCommand]
@@ -1,6 +1,4 @@
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -0,0 +1,127 @@
using CaptureImage.Core.Logging;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Xunit;
namespace CaptureImage.Core.Tests.Logging;
/// <summary>
/// Validates that <c>LogXAt</c> extensions attach <c>File</c> / <c>Line</c> / <c>Member</c>
/// as MEL scope state — which Serilog's MEL bridge then surfaces as structured
/// <see cref="Serilog.Events.LogEvent"/> properties at runtime.
/// </summary>
/// <remarks>
/// Rather than stand up the real Serilog pipeline, we use a tiny spy <see cref="ILogger"/>
/// that captures whatever scope state arrives. That's enough to assert the extensions
/// pass the caller context through correctly; the end-to-end "scope reaches the rolling
/// file" behaviour is covered by manual verification.
/// </remarks>
public class CallerAwareLoggerExtensionsTests
{
[Fact]
public void LogInformationAt_InjectsCallerContextIntoScope()
{
var spy = new ScopeCapturingLogger();
spy.LogInformationAt("hello");
var captured = spy.Scopes.Should().ContainSingle().Subject;
captured.Should().ContainKey("Member");
captured.Should().ContainKey("File");
captured.Should().ContainKey("Line");
captured["Member"].Should().Be(nameof(LogInformationAt_InjectsCallerContextIntoScope));
captured["File"].Should().Be("CallerAwareLoggerExtensionsTests.cs");
((int)captured["Line"]!).Should().BeGreaterThan(0);
}
[Fact]
public void LogWarningAt_WithException_ForwardsExceptionAndCaller()
{
var spy = new ScopeCapturingLogger();
var ex = new InvalidOperationException("boom");
spy.LogWarningAt(ex, "with exception");
spy.Entries.Should().ContainSingle()
.Which.Exception.Should().Be(ex);
spy.Scopes.Should().ContainSingle()
.Which.Should().ContainKey("File").WhoseValue
.Should().Be("CallerAwareLoggerExtensionsTests.cs");
}
[Fact]
public void LogErrorAt_WithTwoArgs_PassesArgsThroughToLogger()
{
var spy = new ScopeCapturingLogger();
var ex = new IOException("disk full");
spy.LogErrorAt(ex, "failed to save {Path} size={Size}", "/tmp/x", 1024);
spy.Entries.Should().ContainSingle()
.Which.State!.ToString().Should().Contain("/tmp/x").And.Contain("1024");
}
[Fact]
public void CallerScope_StripsBuildMachineAbsolutePath()
{
// Simulate [CallerFilePath] having produced an absolute path — the helper must
// strip the directory portion so we don't leak E:\build-agent\... into the log.
var spy = new ScopeCapturingLogger();
spy.LogInformationAt(
"probe",
member: "test",
filePath: @"C:\build\machine\deep\path\Module.cs",
line: 7);
var scope = spy.Scopes.Should().ContainSingle().Subject;
scope["File"].Should().Be("Module.cs");
}
// -- helpers --------------------------------------------------------------
/// <summary>Minimal spy capturing every Log call + its surrounding scope state.</summary>
private sealed class ScopeCapturingLogger : ILogger
{
public List<Dictionary<string, object?>> Scopes { get; } = new();
public List<(LogLevel Level, Exception? Exception, object? State)> Entries { get; } = new();
private readonly Stack<Dictionary<string, object?>> _currentScopes = new();
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
var dict = new Dictionary<string, object?>();
if (state is IEnumerable<KeyValuePair<string, object>> pairs)
{
foreach (var kvp in pairs)
{
dict[kvp.Key] = kvp.Value;
}
}
Scopes.Add(dict);
_currentScopes.Push(dict);
return new ScopeToken(this);
}
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
Entries.Add((logLevel, exception, state));
}
private sealed class ScopeToken : IDisposable
{
private readonly ScopeCapturingLogger _owner;
public ScopeToken(ScopeCapturingLogger owner) => _owner = owner;
public void Dispose()
{
if (_owner._currentScopes.Count > 0) _owner._currentScopes.Pop();
}
}
}
}
@@ -0,0 +1,54 @@
using CaptureImage.Core.Models;
using FluentAssertions;
using Xunit;
namespace CaptureImage.Core.Tests.Models;
public class LogEntryTests
{
private static LogEntry MakeEntry(string? file = null, int? line = null) =>
new(
Timestamp: new DateTimeOffset(2026, 4, 26, 14, 30, 5, 123, TimeSpan.Zero),
Level: LogLevel.Information,
SourceContext: "Test",
Message: "hello",
Exception: null)
{
File = file,
Line = line,
};
[Fact]
public void TimestampText_FormatsAsHHmmssfff()
{
// Added in v1.3-M5 because WinUI 3 {Binding} doesn't support StringFormat.
// The format must be culture-invariant so vi-VN / ar-SA users get the same
// timestamps as en-US (the log viewer is technical content, not localized).
MakeEntry().TimestampText.Should().Be("14:30:05.123");
}
[Fact]
public void FileLineText_BothPresent_RendersFileColonLine()
{
MakeEntry(file: "Foo.cs", line: 42).FileLineText.Should().Be("Foo.cs:42");
}
[Fact]
public void FileLineText_FileMissing_RendersEmpty()
{
MakeEntry(file: null, line: 42).FileLineText.Should().BeEmpty();
}
[Fact]
public void FileLineText_LineMissing_RendersEmpty()
{
MakeEntry(file: "Foo.cs", line: null).FileLineText.Should().BeEmpty();
}
[Fact]
public void FileLineText_LineZero_RendersEmpty()
{
// Line is uint? — 0 is a sentinel for "unknown" since real source lines are 1+.
MakeEntry(file: "Foo.cs", line: 0).FileLineText.Should().BeEmpty();
}
}
@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using CaptureImage.Core.Models;
using CaptureImage.Infrastructure.Logging;
using FluentAssertions;
using Serilog.Events;
using Serilog.Parsing;
using Xunit;
namespace CaptureImage.Infrastructure.Tests.Logging;
/// <summary>
/// Covers the ring-buffer semantics, pause/resume behaviour, and <c>Snapshot()</c> copy
/// guarantees of <see cref="InMemorySink"/> — the real-time log viewer's event source.
/// </summary>
public class InMemorySinkTests
{
[Fact]
public void Emit_AppendsToBuffer_AndRaisesEmitted_WhenNotPaused()
{
var sink = new InMemorySink();
var raised = new List<LogEntry>();
sink.Emitted += (_, entry) => raised.Add(entry);
sink.Emit(Event("hello", LogEventLevel.Information));
sink.Snapshot().Should().HaveCount(1);
sink.Snapshot()[0].Message.Should().Be("hello");
raised.Should().HaveCount(1);
raised[0].Level.Should().Be(LogLevel.Information);
}
[Fact]
public void Emit_WhilePaused_StillBuffersButDoesNotRaiseEmitted()
{
var sink = new InMemorySink { Paused = true };
var raised = new List<LogEntry>();
sink.Emitted += (_, entry) => raised.Add(entry);
sink.Emit(Event("hidden", LogEventLevel.Warning));
sink.Snapshot().Should().HaveCount(1);
raised.Should().BeEmpty();
}
[Fact]
public void Emit_OverflowingCapacity_EvictsOldestFirst()
{
var sink = new InMemorySink();
// Fire one beyond capacity so the first event has to be dropped.
for (var i = 0; i < InMemorySink.MaxCapacity + 1; i++)
{
sink.Emit(Event($"msg-{i}", LogEventLevel.Information));
}
var snapshot = sink.Snapshot();
snapshot.Should().HaveCount(InMemorySink.MaxCapacity);
snapshot[0].Message.Should().Be("msg-1"); // index 0 evicted
snapshot[^1].Message.Should().Be($"msg-{InMemorySink.MaxCapacity}");
}
[Fact]
public void Snapshot_ReturnsCopy_MutationsDontAffectBuffer()
{
var sink = new InMemorySink();
sink.Emit(Event("a", LogEventLevel.Information));
var firstSnapshot = sink.Snapshot();
sink.Emit(Event("b", LogEventLevel.Information));
// The earlier snapshot is frozen at the moment it was taken.
firstSnapshot.Should().HaveCount(1);
firstSnapshot[0].Message.Should().Be("a");
// But the sink itself has moved on.
sink.Snapshot().Should().HaveCount(2);
}
[Fact]
public void Clear_EmptiesBuffer()
{
var sink = new InMemorySink();
sink.Emit(Event("x", LogEventLevel.Information));
sink.Emit(Event("y", LogEventLevel.Information));
sink.Clear();
sink.Snapshot().Should().BeEmpty();
}
[Fact]
public void Emit_CapturesCallerProperties_WhenPresentOnEvent()
{
var sink = new InMemorySink();
var ev = EventWithCaller("with caller", "Engine.cs", 42, "Start");
sink.Emit(ev);
var entry = sink.Snapshot()[0];
entry.File.Should().Be("Engine.cs");
entry.Line.Should().Be(42);
entry.Member.Should().Be("Start");
entry.FileLineText.Should().Be("Engine.cs:42");
}
[Fact]
public void Emit_LeavesCallerPropertiesNull_WhenAbsent()
{
var sink = new InMemorySink();
sink.Emit(Event("plain", LogEventLevel.Information));
var entry = sink.Snapshot()[0];
entry.File.Should().BeNull();
entry.Line.Should().BeNull();
entry.Member.Should().BeNull();
entry.FileLineText.Should().BeEmpty();
}
// -- helpers --------------------------------------------------------------
private static LogEvent Event(string message, LogEventLevel level)
{
var template = new MessageTemplateParser().Parse(message);
return new LogEvent(
DateTimeOffset.UtcNow,
level,
exception: null,
template,
properties: Array.Empty<LogEventProperty>());
}
private static LogEvent EventWithCaller(string message, string file, int line, string member)
{
var template = new MessageTemplateParser().Parse(message);
return new LogEvent(
DateTimeOffset.UtcNow,
LogEventLevel.Information,
exception: null,
template,
properties: new[]
{
new LogEventProperty("File", new ScalarValue(file)),
new LogEventProperty("Line", new ScalarValue(line)),
new LogEventProperty("Member", new ScalarValue(member)),
});
}
}
@@ -0,0 +1,61 @@
using CaptureImage.Infrastructure.Logging;
using FluentAssertions;
using Serilog.Core;
using Serilog.Events;
using Xunit;
namespace CaptureImage.Infrastructure.Tests.Logging;
/// <summary>
/// Verifies the canonical mapping between <see cref="AppSettings.LogLevel"/> strings and
/// Serilog's <see cref="LogEventLevel"/>. Covers the alias forms (info/warn) and the
/// unknown-value fallback.
/// </summary>
public class SerilogLogLevelSwitcherTests
{
[Theory]
[InlineData("Debug", LogEventLevel.Debug)]
[InlineData("debug", LogEventLevel.Debug)]
[InlineData("Information", LogEventLevel.Information)]
[InlineData("info", LogEventLevel.Information)]
[InlineData("Warning", LogEventLevel.Warning)]
[InlineData("warn", LogEventLevel.Warning)]
[InlineData("Error", LogEventLevel.Error)]
[InlineData("ERROR", LogEventLevel.Error)]
public void SetLevel_CanonicalAndAliasNames_MapToSerilogLevel(string input, LogEventLevel expected)
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel(input);
levelSwitch.MinimumLevel.Should().Be(expected);
}
[Theory]
[InlineData("")]
[InlineData("TRACE")]
[InlineData("Verbose")]
[InlineData(null)]
[InlineData("nonsense")]
public void SetLevel_UnknownOrNull_FallsBackToInformation(string? input)
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel(input!);
levelSwitch.MinimumLevel.Should().Be(LogEventLevel.Information);
}
[Fact]
public void CurrentLevel_ReportsCanonicalNameAfterSetLevel()
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel("debug");
switcher.CurrentLevel.Should().Be("Debug");
}
}
@@ -36,10 +36,11 @@ public class JsonSettingsStoreTests
await store.LoadAsync();
store.Current.Version.Should().Be(1);
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("en-US");
store.Current.CaptureHotkey.Should().Be(HotkeyBinding.Default);
store.Current.Capture.DefaultFormat.Should().Be(ImageFormat.Png);
store.Current.LogLevel.Should().Be("Information");
}
[Fact]
@@ -136,7 +137,7 @@ public class JsonSettingsStoreTests
await store.LoadAsync();
store.Current.Version.Should().Be(1);
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("en-US");
}
@@ -154,6 +155,46 @@ public class JsonSettingsStoreTests
store.Current.Culture.Should().Be("en-US");
}
[Fact]
public async Task LoadAsync_V1File_MigratesToV2AndWritesBack()
{
var (store, fs) = Build();
var appDataRoot = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var dir = Path.Combine(appDataRoot, "CaptureImage");
fs.Directory.CreateDirectory(dir);
// Hand-crafted v1 document — no logLevel field present. System.Text.Json fills
// it with the init default (Information), and the migration path stamps Version=2
// + triggers a write-back so the on-disk file ends up canonical.
fs.File.WriteAllText(ExpectedPath,
"{\"version\": 1, \"culture\": \"vi-VN\", \"theme\": \"System\"}");
await store.LoadAsync();
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("vi-VN");
store.Current.LogLevel.Should().Be("Information");
// Write-back normalised the file — next parse sees v2 directly.
var written = fs.File.ReadAllText(ExpectedPath);
written.Should().Contain("\"version\": 2");
written.Should().Contain("\"logLevel\": \"Information\"");
}
[Fact]
public async Task LoadAsync_V2File_PreservesLogLevelField()
{
var (store, fs) = Build();
var appDataRoot = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var dir = Path.Combine(appDataRoot, "CaptureImage");
fs.Directory.CreateDirectory(dir);
fs.File.WriteAllText(ExpectedPath,
"{\"version\": 2, \"culture\": \"en-US\", \"logLevel\": \"Debug\"}");
await store.LoadAsync();
store.Current.Version.Should().Be(2);
store.Current.LogLevel.Should().Be("Debug");
}
[Fact]
public async Task ExportAsync_WritesCurrentSettings()
{
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more