11 Commits
Author SHA1 Message Date
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
89 changed files with 2868 additions and 1899 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.
+97
View File
@@ -7,6 +7,103 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.3.0] - 2026-04-26
UI framework migration from Avalonia 11 to **WinUI 3 (Windows App SDK 1.8.x)**
with Fluent 2 design — Mica backdrop, Segoe UI Variable, integrated title bar,
Composition-API animations. Logic layers (Core / Infrastructure / ViewModels)
were intentionally left untouched: the entire ~5,000-line domain + capture +
hotkey + settings + logging stack carries forward unchanged. Velopack ships
on the existing `win` channel so v1.2.x users auto-update; multi-file
WindowsAppSDK self-contained payload is ~80–120 MB (vs the v1.2 single-file
~30 MB) — accepted trade for stack-Microsoft-native parity on Windows-only.
### Added
- **Sound on capture success** (`UI.SoundEnabled` setting now has a consumer
for the first time since v1.0). Plays Windows `SystemAsterisk` via Win32
`PlaySound` P/Invoke, gated on the existing checkbox.
- **Browse button** on Settings → Output folder. Opens the modern
`IFileOpenDialog` (Vista+ folder picker) seeded at the current
OutputDirectory. Win32 COM-interop fallback because
`Windows.Storage.Pickers.FolderPicker` is unreliable in unpackaged
WinUI 3.
- **Mica backdrop** on the main window — translucent Win11 wallpaper tint.
- **Borderless title bar** integrated with the Fluent 2 chrome; caption
buttons sit in a 48 px reserved drag region.
- **Composition slide animation** on the log drawer — 220 ms slide + 180 ms
fade with CubicBezier(0.4, 0, 0.2, 1) decelerate. Mirrors the v1.2
Avalonia drawer at the visual layer; uses `UIElement.Translation` (additive
on layout) instead of `Visual.Offset` (overrides layout) so the drawer
stays anchored to its Grid column under all window sizes.
- **+164 tests, total 320** (up from 156). New coverage:
- 18 converter tests (FlowDirection / BoolToVisibility / InvertedBoolToVisibility / NotNullToVisibility).
- 5 LogEntry tests (TimestampText format, FileLineText edge cases).
- 141 Theory cases for localization completeness — 47 load-bearing keys
× 3 cultures (en-US / vi-VN / ar-SA) — every shipping label asserted
non-empty + non-bracketed.
### Changed
- **UI framework**: Avalonia 11.2.3 → WinUI 3 (Windows App SDK
1.8.260416003) self-contained x64. ViewModels project still
TFM-portable (`net9.0`); UI + UI.Tests TFM bumped to
`net9.0-windows10.0.22621.0` to link WinAppSDK assemblies.
- **Tray icon**: `H.NotifyIcon.WindowsAppSDK` → `H.NotifyIcon.WinUI` (the
actual nuget.org package id; the WindowsAppSDK suffix never existed on
nuget). Tray ships with OS default glyph for v1.3.0 — proper .ico
round-trip via `System.Drawing.Bitmap.GetHicon` + `Icon.Save` deferred
to v1.4.
- **Folder picker**: Win32 `IFileOpenDialog` COM interop replaces the
unreliable `Windows.Storage.Pickers.FolderPicker` in
`CaptureImage.UI.Services.Win32FolderPicker`.
- **Tray menu commands** wired through `MenuFlyoutItem.Command` (not
`Click` event) — the latter doesn't fire reliably from H.NotifyIcon's
out-of-tree popup.
- **Sound playback** uses Win32 `PlaySound` P/Invoke instead of
`System.Media.SystemSounds` (the latter ships in
`System.Windows.Extensions` which only targets Windows TFMs, too
restrictive for the portable ViewModels project).
- **Tray-restore from minimize** uses `AppWindow.Show` +
`User32.ShowWindow(SW_RESTORE)` + `Window.Activate` +
`User32.SetForegroundWindow` — `Show` alone leaves taskbar-minimized
windows minimized + behind whatever has foreground focus.
- **Auto-refresh suppression** while a preview modal is up — Dashboard's
WMI-driven Targets refresh used to clobber the in-flight
`SelectedTarget` and disrupt the preview decision; now skipped when
state is Previewing or Saving.
- **3rd-party list** in About: drop Avalonia + Inter typeface, add
Windows App SDK / WinUI 3 + H.NotifyIcon.WinUI.
### Removed
- `Avalonia.*` packages (Avalonia, Avalonia.Desktop, Avalonia.Themes.Fluent,
Avalonia.Fonts.Inter, Avalonia.Diagnostics) and 25 .axaml files / Avalonia
service implementations (`AvaloniaTrayIconHost`, `AvaloniaPreviewPresenter`,
`AvaloniaUIDispatcher`, `BytesToBitmapConverter` for Avalonia.Bitmap,
`ToastKindToBrushConverter` for Avalonia.IBrush). All replaced with WinUI 3
equivalents.
- Inter typeface — Fluent 2's Segoe UI Variable is the explicit body font now.
- `PublishSingleFile` from the release workflow — WinAppSDK can't be
bundled into a single .exe, ships as multi-file folder packaged by
Velopack.
### Fixed
- (in v1.3 from v1.2 carry-overs) Title-bar caption buttons no longer
overlap nav rail / Page content — 48 px drag region reserved at top
via `Window.SetTitleBar(AppTitleBar)`.
### Deferred to v1.4
- Real .ico tray icon via `System.Drawing.Bitmap.GetHicon` round-trip
(currently OS default glyph). H.NotifyIcon.WinUI's IconSource pipeline
ends in `System.Drawing.Icon` which only accepts .ico file streams.
- `release.yml` upload of `CaptureImage-win-Portable.zip` (carry-over
from v1.2 — added in v1.3 release cut).
- DPI-aware initial window sizing (`AppWindow.Resize` takes physical
pixels; v1.3 hardcodes 1200×720).
## [1.2.0] - 2026-04-21
Logging overhaul. Turns a working-but-thin diagnostic surface into one you
+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;
}
}
+10 -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.2.0; release.yml still overrides via /p:Version=<git-tag>
for tag-driven builds. Bump to the next -dev suffix after the release lands. -->
<Version>1.2.0</Version>
<DefineConstants>$(DefineConstants);DISABLE_XAML_GENERATED_MAIN</DefineConstants>
<Version>1.3.0</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Diagnostics" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.WindowsAppSDK" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" />
<PackageReference Include="Serilog" />
<PackageReference Include="Serilog.Extensions.Hosting" />
<PackageReference Include="Serilog.Extensions.Logging" />
@@ -37,9 +41,6 @@
<ProjectReference Include="..\CaptureImage.UI\CaptureImage.UI.csproj" />
</ItemGroup>
<!-- Ship the legal and docs files next to the binary so the About tab can open them
with Process.Start. Links to the repo-root docs/ folder so there's a single source
of truth; content is copied into bin/.../docs/... at build time. -->
<ItemGroup>
<Content Include="..\..\docs\legal\DISCLAIMER.md" Link="docs\legal\DISCLAIMER.md" CopyToOutputDirectory="PreserveNewest" />
<Content Include="..\..\docs\legal\PRIVACY.md" Link="docs\legal\PRIVACY.md" CopyToOutputDirectory="PreserveNewest" />
+7 -3
View File
@@ -56,7 +56,11 @@ internal static class CompositionRoot
// --- 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 ----------------------------------------------------------
@@ -91,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>();
+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);
}
}
+20 -51
View File
@@ -1,9 +1,10 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Threading;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Serilog;
using Velopack;
@@ -18,21 +19,16 @@ 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 (keep the in-memory sink + runtime level switch for DI).
var (inMemorySink, loggingLevelSwitch) = LoggingSetup.Initialize();
// Catch anything that escapes try/catch on any thread. Register before we stand up DI
// or UI so background-thread crashes during startup still reach the rolling file.
RegisterGlobalExceptionHandlers();
var shutdownReason = "Normal";
@@ -46,26 +42,15 @@ internal static class Program
args);
var services = CompositionRoot.BuildServices(inMemorySink, loggingLevelSwitch);
UI.App.Services = services;
App.Services = services;
// Load persisted settings before the UI binds to them.
var settingsStore = services.GetRequiredService<ISettingsStore>();
settingsStore.LoadAsync().GetAwaiter().GetResult();
// Narrow Serilog's minimum level from the boot default (Debug) down to whatever
// the user chose via Settings last run. This happens after LoadAsync so that
// early-startup lines — "CaptureImage starting", "Settings loaded …" — always
// land in the file regardless of the configured floor.
var configuredLevel = LoggingSetup.ParseLevel(settingsStore.Current.LogLevel);
loggingLevelSwitch.MinimumLevel = configuredLevel;
Log.Information("Log level set to {Level} from settings.", configuredLevel);
// Apply persisted culture before the first window is constructed so nav labels etc.
// render in the right language from frame zero. Only accept cultures the app
// actually ships translations for — a hand-edited settings.json with, say,
// Culture=fr-FR used to flip the app to fr and then fall through to neutral
// en strings with Settings showing "English" selected; refuse at startup
// instead so the default en-US stays coherent.
var localization = services.GetRequiredService<ILocalizationService>();
var cultureName = settingsStore.Current.Culture;
if (!string.IsNullOrWhiteSpace(cultureName))
@@ -100,8 +85,19 @@ 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)
{
@@ -111,12 +107,11 @@ internal static class Program
}
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();
@@ -132,21 +127,6 @@ internal static class Program
}
}
/// <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()
.AfterSetup(_ =>
{
// Hook the Avalonia UI-thread dispatcher so exceptions raised by command
// handlers, bindings, and tick callbacks don't silently kill the UI.
Dispatcher.UIThread.UnhandledException += OnDispatcherUnhandledException;
});
private static void RegisterGlobalExceptionHandlers()
{
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
@@ -158,7 +138,6 @@ internal static class Program
e.IsTerminating);
if (e.IsTerminating)
{
// Last-ditch flush — CLR is about to pull the rug.
Log.CloseAndFlush();
}
};
@@ -166,17 +145,7 @@ internal static class Program
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error(e.Exception, "Unobserved task exception.");
// Claim the exception so the default .NET policy doesn't terminate the process
// on the next GC — structured log is enough signal for us to investigate.
e.SetObserved();
};
}
private static void OnDispatcherUnhandledException(object? sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "Unhandled exception on UI dispatcher.");
// Don't let a single bad command tear down the window — swallow after logging so the
// user can keep using the app (and notice the Toast / LogViewer will surface it).
e.Handled = true;
}
}
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
@@ -1,6 +1,3 @@
using System;
using System.IO;
namespace CaptureImage.Core.Logging;
/// <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),
};
}
+9
View File
@@ -40,6 +40,15 @@ public sealed record LogEntry(
!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>
@@ -1,5 +1,3 @@
using System.Collections.Generic;
namespace CaptureImage.Core.Models;
/// <summary>
-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,246 +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 = BuildRuntimeIconSafely(),
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 and visible.");
}
private WindowIcon? BuildRuntimeIconSafely()
{
try
{
return BuildRuntimeIcon();
}
catch (Exception ex)
{
// A SkiaSharp / native-asset failure here used to take the whole startup down.
// Fall back to a null icon (Avalonia renders a default glyph) and log — the
// user still gets a tray entry, just one without our branding.
_logger.LogWarning(ex, "Failed to render runtime tray icon via SkiaSharp; falling back to default.");
return null;
}
}
private void OnLocalizationChanged(object? sender, PropertyChangedEventArgs e)
{
// `ResxLocalizationService.SetCulture` raises three events per switch
// (Item[], CurrentCulture, CurrentFlowDirection). Rebuild the menu once, not
// three times — Item[] is the canonical "all lookups may have changed" signal.
if (e.PropertyName == "Item[]")
{
RefreshMenuLabels();
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_localization.PropertyChanged -= OnLocalizationChanged;
if (_mainWindow is not null)
{
_mainWindow.Closing -= OnMainWindowClosing;
}
if (_trayIcon is not null)
{
_trayIcon.IsVisible = false;
_trayIcon.Dispose();
_trayIcon = null;
}
_logger.LogInformation("Tray icon disposed.");
}
// -- 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>();
}
}
}
-141
View File
@@ -1,141 +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">
<!-- HorizontalScrollBarVisibility=Disabled prevents the horizontal bar from ever
appearing; Vertical=Hidden lets mouse-wheel scrolling keep working but hides
the track so the view reads cleanly on a fixed window. -->
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16,24,24" Spacing="18" MaxWidth="640">
<!-- Header -->
<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,11 +0,0 @@
using Avalonia.Controls;
namespace CaptureImage.UI.Views;
public partial class LogViewerView : UserControl
{
public LogViewerView()
{
InitializeComponent();
}
}
@@ -1,54 +1,72 @@
<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">
<?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="{DynamicResource SystemControlBackgroundChromeMediumBrush}"
BorderBrush="{DynamicResource SystemControlForegroundBaseLowBrush}"
<Border Background="{ThemeResource LayerFillColorAltBrush}"
BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
BorderThickness="1,1,0,0"
CornerRadius="8,0,0,0"
Padding="12">
<Grid RowDefinitions="Auto,*">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header + controls -->
<Grid Grid.Row="0"
ColumnDefinitions="*,Auto,Auto,Auto,Auto,Auto,Auto"
Margin="0,0,0,8">
<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="14"
FontSize="{StaticResource FontSizeBodyStrong}"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<TextBlock Grid.Column="1"
Text="{Binding FilterLabel}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
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="{DynamicResource SystemControlForegroundBaseMediumBrush}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeCaption}"
VerticalAlignment="Center" />
</Grid>
@@ -56,35 +74,41 @@
<Grid Grid.Row="1">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
IsVisible="{Binding !HasNoEntries}">
Visibility="{Binding HasNoEntries, Converter={StaticResource InvertedBoolToVisibilityConverter}}">
<ItemsControl ItemsSource="{Binding Entries}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="models:LogEntry">
<Grid ColumnDefinitions="Auto,Auto,Auto,*" Margin="0,1">
<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 Timestamp, StringFormat='HH:mm:ss.fff'}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
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, monospace"
FontSize="11"
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, monospace"
FontSize="11"
FontFamily="Consolas, Courier New"
FontSize="{StaticResource FontSizeCaption}"
Width="170"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
TextTrimming="CharacterEllipsis"
Margin="0,0,8,0" />
<TextBlock Grid.Column="3"
Text="{Binding Message}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
FontFamily="Consolas, Courier New"
FontSize="{StaticResource FontSizeCaption}"
TextWrapping="NoWrap"
TextTrimming="CharacterEllipsis" />
</Grid>
@@ -95,16 +119,14 @@
<!-- Empty state: no log events yet. -->
<TextBlock Text="{Binding EmptyStateText}"
IsVisible="{Binding HasNoEntries}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
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();
}
}
-150
View File
@@ -1,150 +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="1200" Height="720"
MinWidth="1200" MinHeight="720"
MaxWidth="1200" MaxHeight="720"
CanResize="False"
WindowStartupLocation="CenterScreen"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={x:Static conv:FlowDirectionConverter.Instance}}">
<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 480px of the content grid with a
200ms slide-in + fade. Always kept in the visual tree so the transitions
fire on every toggle; IsHitTestVisible + Classes.visible let us collapse
interaction + drive the animation state from IsLogViewerVisible. -->
<views:LogViewerView x:Name="LogDrawer"
Width="480"
HorizontalAlignment="Right"
DataContext="{Binding LogViewer}"
Classes.visible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}"
IsHitTestVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}">
<views:LogViewerView.Styles>
<Style Selector="views|LogViewerView">
<Setter Property="Opacity" Value="0" />
<Setter Property="RenderTransform" Value="translateX(48px)" />
<Setter Property="Transitions">
<Transitions>
<DoubleTransition Property="Opacity" Duration="0:0:0.18" Easing="CircularEaseOut" />
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.22" Easing="CircularEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="views|LogViewerView.visible">
<Setter Property="Opacity" Value="1" />
<Setter Property="RenderTransform" Value="translateX(0)" />
</Style>
</views:LogViewerView.Styles>
</views:LogViewerView>
<!-- Toast overlay — anchored bottom-right, floats over the content grid.
Under RTL FlowDirection Avalonia automatically mirrors Right/Left edges,
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,128 +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">
<!-- HorizontalScrollBarVisibility=Disabled prevents the horizontal bar from ever
appearing; Vertical=Hidden lets mouse-wheel scrolling keep working but hides
the track so the view reads cleanly on a fixed window. -->
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16" Spacing="18" MaxWidth="620">
<TextBlock Text="{Binding 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>
<!-- Logging -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding LoggingLabel}"
FontSize="13"
FontWeight="SemiBold" />
<StackPanel Spacing="4">
<TextBlock Text="{Binding LogLevelLabel}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
FontSize="12" />
<ComboBox ItemsSource="{Binding SupportedLogLevels}"
SelectedItem="{Binding SelectedLogLevel, Mode=TwoWay}"
HorizontalAlignment="Stretch" />
<TextBlock Text="{Binding LogLevelHint}"
FontSize="11"
TextWrapping="Wrap"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
</StackPanel>
</StackPanel>
<!-- Import / export / open -->
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Name="ImportButton" Content="{Binding 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,11 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Logging;
using CaptureImage.Core.Models;
@@ -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;
@@ -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;
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.IO;
using CaptureImage.Core.Logging;
using FluentAssertions;
using Microsoft.Extensions.Logging;
@@ -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();
}
}
@@ -1,7 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net9.0-windows10.0.22621.0</TargetFramework>
<SupportedOSPlatformVersion>10.0.22621.0</SupportedOSPlatformVersion>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
@@ -0,0 +1,36 @@
using CaptureImage.UI.Converters;
using FluentAssertions;
using Microsoft.UI.Xaml;
using Xunit;
namespace CaptureImage.UI.Tests.Converters;
public class BoolToVisibilityConverterTests
{
private static readonly BoolToVisibilityConverter Converter = BoolToVisibilityConverter.Instance;
[Fact]
public void Convert_True_ReturnsVisible()
{
Converter.Convert(true, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Visible);
}
[Fact]
public void Convert_False_ReturnsCollapsed()
{
Converter.Convert(false, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Collapsed);
}
[Fact]
public void Convert_Null_ReturnsCollapsed()
{
Converter.Convert(null!, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Collapsed);
}
[Fact]
public void ConvertBack_VisibleRoundtrip()
{
Converter.ConvertBack(Visibility.Visible, typeof(bool), null!, "en-US").Should().Be(true);
Converter.ConvertBack(Visibility.Collapsed, typeof(bool), null!, "en-US").Should().Be(false);
}
}
@@ -0,0 +1,48 @@
using CaptureImage.Core.Abstractions;
using CaptureImage.UI.Converters;
using FluentAssertions;
using Microsoft.UI.Xaml;
using Xunit;
namespace CaptureImage.UI.Tests.Converters;
public class FlowDirectionConverterTests
{
private static readonly FlowDirectionConverter Converter = FlowDirectionConverter.Instance;
[Fact]
public void Convert_LeftToRight_ReturnsLeftToRight()
{
var result = Converter.Convert(TextFlowDirection.LeftToRight, typeof(FlowDirection), null!, "en-US");
result.Should().Be(FlowDirection.LeftToRight);
}
[Fact]
public void Convert_RightToLeft_ReturnsRightToLeft()
{
var result = Converter.Convert(TextFlowDirection.RightToLeft, typeof(FlowDirection), null!, "ar-SA");
result.Should().Be(FlowDirection.RightToLeft);
}
[Fact]
public void Convert_Null_DefaultsToLeftToRight()
{
// Defensive default — bindings can momentarily be null during construction.
var result = Converter.Convert(null!, typeof(FlowDirection), null!, "en-US");
result.Should().Be(FlowDirection.LeftToRight);
}
[Fact]
public void Convert_UnexpectedType_DefaultsToLeftToRight()
{
var result = Converter.Convert("not an enum", typeof(FlowDirection), null!, "en-US");
result.Should().Be(FlowDirection.LeftToRight);
}
[Fact]
public void ConvertBack_Throws()
{
var act = () => Converter.ConvertBack(FlowDirection.RightToLeft, typeof(TextFlowDirection), null!, "en-US");
act.Should().Throw<NotSupportedException>();
}
}
@@ -0,0 +1,37 @@
using CaptureImage.UI.Converters;
using FluentAssertions;
using Microsoft.UI.Xaml;
using Xunit;
namespace CaptureImage.UI.Tests.Converters;
public class InvertedBoolToVisibilityConverterTests
{
private static readonly InvertedBoolToVisibilityConverter Converter = InvertedBoolToVisibilityConverter.Instance;
[Fact]
public void Convert_True_ReturnsCollapsed()
{
Converter.Convert(true, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Collapsed);
}
[Fact]
public void Convert_False_ReturnsVisible()
{
Converter.Convert(false, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Visible);
}
[Fact]
public void Convert_Null_ReturnsVisible()
{
// Inverted: null is "not true" so it maps to Visible (the default-show case).
Converter.Convert(null!, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Visible);
}
[Fact]
public void ConvertBack_CollapsedRoundtripToTrue()
{
Converter.ConvertBack(Visibility.Collapsed, typeof(bool), null!, "en-US").Should().Be(true);
Converter.ConvertBack(Visibility.Visible, typeof(bool), null!, "en-US").Should().Be(false);
}
}
@@ -0,0 +1,44 @@
using CaptureImage.UI.Converters;
using FluentAssertions;
using Microsoft.UI.Xaml;
using Xunit;
namespace CaptureImage.UI.Tests.Converters;
public class NotNullToVisibilityConverterTests
{
private static readonly NotNullToVisibilityConverter Converter = NotNullToVisibilityConverter.Instance;
[Fact]
public void Convert_Null_ReturnsCollapsed()
{
Converter.Convert(null, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Collapsed);
}
[Fact]
public void Convert_String_ReturnsVisible()
{
Converter.Convert("hello", typeof(Visibility), null!, "en-US").Should().Be(Visibility.Visible);
}
[Fact]
public void Convert_EmptyString_ReturnsVisible()
{
// Empty-but-non-null is still "not null" semantically — the converter only
// distinguishes against the null reference, not against truthy/falsey values.
Converter.Convert(string.Empty, typeof(Visibility), null!, "en-US").Should().Be(Visibility.Visible);
}
[Fact]
public void Convert_Object_ReturnsVisible()
{
Converter.Convert(new object(), typeof(Visibility), null!, "en-US").Should().Be(Visibility.Visible);
}
[Fact]
public void ConvertBack_Throws()
{
var act = () => Converter.ConvertBack(Visibility.Visible, typeof(object), null!, "en-US");
act.Should().Throw<NotSupportedException>();
}
}
@@ -0,0 +1,92 @@
using System.Globalization;
using CaptureImage.UI.Localization;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace CaptureImage.UI.Tests.Localization;
/// <summary>
/// Asserts that every load-bearing UI string is translated in all 3 shipped cultures
/// (en-US / vi-VN / ar-SA). The bracketed fallback (e.g. <c>"[Nav_Dashboard]"</c>) means
/// a key is missing from the resx — these tests catch that before it reaches the user.
/// </summary>
public class LocalizationCompletenessTests : IDisposable
{
private readonly CultureInfo _savedUICulture;
private readonly CultureInfo _savedCulture;
private readonly CultureInfo? _savedDefaultUICulture;
private readonly CultureInfo? _savedDefaultCulture;
public LocalizationCompletenessTests()
{
_savedUICulture = CultureInfo.CurrentUICulture;
_savedCulture = CultureInfo.CurrentCulture;
_savedDefaultUICulture = CultureInfo.DefaultThreadCurrentUICulture;
_savedDefaultCulture = CultureInfo.DefaultThreadCurrentCulture;
}
public void Dispose()
{
CultureInfo.CurrentUICulture = _savedUICulture;
CultureInfo.CurrentCulture = _savedCulture;
CultureInfo.DefaultThreadCurrentUICulture = _savedDefaultUICulture;
CultureInfo.DefaultThreadCurrentCulture = _savedDefaultCulture;
}
/// <summary>
/// Curated list of keys that drive the v1.3 nav rail, page headers, and dialog
/// buttons. Adding a new visible label? Append the key here so the matrix catches
/// it if a translator misses one of the cultures.
/// </summary>
public static readonly string[] LoadBearingKeys =
{
// Nav rail
"Nav_Dashboard", "Nav_Update", "Nav_Settings", "Nav_About", "Nav_LogViewer",
// Page titles
"Dashboard_Title", "Dashboard_Subtitle", "Dashboard_Refresh",
"Dashboard_Arm", "Dashboard_Disarm", "Dashboard_StatusIdle",
"Settings_Title", "Settings_Language", "Settings_Hotkey",
"Settings_Format", "Settings_OutputFolder", "Settings_Browse",
"Settings_PreviewBeforeSave", "Settings_MinimizeToTray", "Settings_SoundEnabled",
"Settings_Logging", "Settings_LogLevel",
"About_Title", "About_Tagline", "About_VersionLabel", "About_LicenseLabel",
"Update_Title", "Update_Check", "Update_Download", "Update_Install",
// LogViewer drawer
"Log_Title", "Log_Filter", "Log_Pause", "Log_Resume", "Log_Clear",
"Log_RevealFolder", "Log_EmptyState",
// Tray menu
"Tray_ShowWindow", "Tray_OpenFolder", "Tray_Exit",
// Toast headlines
"Toast_CaptureSaved", "Toast_CaptureFailed", "Toast_Error",
// Preview dialog
"Preview_Title", "Preview_Prompt", "Preview_Save", "Preview_Discard",
};
public static IEnumerable<object[]> CultureMatrix()
{
foreach (var culture in new[] { "en-US", "vi-VN", "ar-SA" })
{
foreach (var key in LoadBearingKeys)
{
yield return new object[] { culture, key };
}
}
}
[Theory]
[MemberData(nameof(CultureMatrix))]
public void Key_HasNonBracketedTranslation(string cultureName, string key)
{
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc.SetCulture(CultureInfo.GetCultureInfo(cultureName));
var value = svc[key];
// Bracketed = missing key fallback. Empty = also a problem (nothing to render).
value.Should().NotBe($"[{key}]",
$"key '{key}' is missing from {cultureName} resx");
value.Should().NotBeNullOrEmpty(
$"key '{key}' renders empty in {cultureName} resx");
}
}
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using CaptureImage.Core.Abstractions;
using CaptureImage.UI.Localization;
using FluentAssertions;
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CaptureImage.ViewModels.Logs;
@@ -1,5 +1,3 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using CaptureImage.Core.Abstractions;
@@ -1,8 +1,5 @@
using System;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CaptureImage.ViewModels.Settings;