21 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.7 81563c65f0 fix(v1.4-M3): use GetForegroundWindow inside the WinEvent callback
The original M3 implementation trusted the hwnd parameter the OS
passes to the WinEvent callback. On Win11 that's reliable for
mouse-click activations (single clean event with idObject=OBJID_WINDOW)
but breaks Alt-Tab: the modern Task View overlay fires events whose
hwnd points at a DWM-cloaked window, and the secondary event for the
real destination sometimes carries idObject != 0 (which the previous
'if (idObject != 0) return' filter dropped on the floor).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:17:11 +07:00
105 changed files with 4119 additions and 1926 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.
+165
View File
@@ -7,6 +7,171 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.4.0] - 2026-04-27
UX polish + accessibility cycle. No breaking changes; settings.json
schema unchanged.
### Added
- **Light / Dark / System theme** picker on the Settings tab. The
preference was already reserved in `AppSettings.Theme` since v1.3
but had no consumer; v1.4 wires it through to
`FrameworkElement.RequestedTheme` and re-applies on every
`ISettingsStore.Changed`. Mica retints automatically with the
resolved theme.
- **Auto-switch on Alt-Tab** (opt-in, default off). When enabled,
the dashboard's selected target follows the OS foreground window
via a `SetWinEventHook(EVENT_SYSTEM_FOREGROUND)` watcher with a
250 ms debounce. Apps not in the target list keep your current
selection. Toggle lives next to the existing capture toggles.
- **Four new language packs**: Japanese (ja-JP), Simplified Chinese
(zh-Hans), Korean (ko-KR), Spanish (es-ES). All machine-assisted —
the About → Translations disclaimer lists every machine-assisted
pack and invites native-speaker proofreading PRs.
- **Friendlier log lines** for end-user lifecycle events: `Picture
captured: {Name} ({W}×{H}, {KB} KB) at {Path} [{Format}]`,
`Picture capture cancelled by user.`, `Language switched to
{Code} ({Name}).`, `Theme switched to {Theme}.`, `Capture sound
{State}.`, `Auto-switch on Alt-Tab {State}.` Logs remain
English-only by design (file shareability + parser stability
across cultures).
### Changed
- **Window is now fixed-size** at 1200×720. Both maximize and
resize are disabled via `OverlappedPresenter.IsMaximizable` /
`IsResizable`; minimize remains enabled for the tray flow.
- **Tone shift on existing log call sites**: "Failed to X" →
"Couldn't X" across `DashboardViewModel`, `SettingsViewModel`,
`UpdateViewModel`, `AboutViewModel`, `LogViewerViewModel`.
Structured properties are unchanged so log queries and external
diagnostics still work.
## [1.3.1] - 2026-04-26
**Critical hotfix.** v1.3.0 shipped broken — the WinUI 3 publish pipeline
omitted `.xbf` (compiled XAML binary) and `CaptureImage.App.pri` (resource
manifest) files from the self-contained publish output, so the installed
app silently failed at MainWindow.InitializeComponent on every launch
(the process stayed alive zombie-style; no window ever appeared). v1.2.x
auto-update users hit this on the first launch after Velopack restart.
### Fixed
- Add a `CopyWinUIArtifactsToPublishDirectory` MSBuild target to
`CaptureImage.App.csproj` that propagates every `.xbf` and the
`CaptureImage.App.pri` from `bin/.../win-x64/` into the publish
output, preserving the cross-assembly XAML resolution subfolders
(`CaptureImage.UI/Controls/`, `CaptureImage.UI/Views/`). `dotnet
publish` for unpackaged WinUI 3 self-contained apps doesn't include
these by default — known WinAppSDK gap.
### Recovery for v1.3.0 users
If you already updated to broken v1.3.0:
- The Update tab can't help (the app's window doesn't open).
- Download `CaptureImage-win-Setup.exe` from the v1.3.1 GitHub Release
and run it — the installer detects the existing install and replaces
it cleanly. Your `settings.json` and capture folder are untouched.
## [1.3.0] - 2026-04-26
UI framework migration from Avalonia 11 to **WinUI 3 (Windows App SDK 1.8.x)**
with Fluent 2 design — Mica backdrop, Segoe UI Variable, integrated title bar,
Composition-API animations. Logic layers (Core / Infrastructure / ViewModels)
were intentionally left untouched: the entire ~5,000-line domain + capture +
hotkey + settings + logging stack carries forward unchanged. Velopack ships
on the existing `win` channel so v1.2.x users auto-update; multi-file
WindowsAppSDK self-contained payload is ~80–120 MB (vs the v1.2 single-file
~30 MB) — accepted trade for stack-Microsoft-native parity on Windows-only.
### Added
- **Sound on capture success** (`UI.SoundEnabled` setting now has a consumer
for the first time since v1.0). Plays Windows `SystemAsterisk` via Win32
`PlaySound` P/Invoke, gated on the existing checkbox.
- **Browse button** on Settings → Output folder. Opens the modern
`IFileOpenDialog` (Vista+ folder picker) seeded at the current
OutputDirectory. Win32 COM-interop fallback because
`Windows.Storage.Pickers.FolderPicker` is unreliable in unpackaged
WinUI 3.
- **Mica backdrop** on the main window — translucent Win11 wallpaper tint.
- **Borderless title bar** integrated with the Fluent 2 chrome; caption
buttons sit in a 48 px reserved drag region.
- **Composition slide animation** on the log drawer — 220 ms slide + 180 ms
fade with CubicBezier(0.4, 0, 0.2, 1) decelerate. Mirrors the v1.2
Avalonia drawer at the visual layer; uses `UIElement.Translation` (additive
on layout) instead of `Visual.Offset` (overrides layout) so the drawer
stays anchored to its Grid column under all window sizes.
- **+164 tests, total 320** (up from 156). New coverage:
- 18 converter tests (FlowDirection / BoolToVisibility / InvertedBoolToVisibility / NotNullToVisibility).
- 5 LogEntry tests (TimestampText format, FileLineText edge cases).
- 141 Theory cases for localization completeness — 47 load-bearing keys
× 3 cultures (en-US / vi-VN / ar-SA) — every shipping label asserted
non-empty + non-bracketed.
### Changed
- **UI framework**: Avalonia 11.2.3 → WinUI 3 (Windows App SDK
1.8.260416003) self-contained x64. ViewModels project still
TFM-portable (`net9.0`); UI + UI.Tests TFM bumped to
`net9.0-windows10.0.22621.0` to link WinAppSDK assemblies.
- **Tray icon**: `H.NotifyIcon.WindowsAppSDK` → `H.NotifyIcon.WinUI` (the
actual nuget.org package id; the WindowsAppSDK suffix never existed on
nuget). Tray ships with OS default glyph for v1.3.0 — proper .ico
round-trip via `System.Drawing.Bitmap.GetHicon` + `Icon.Save` deferred
to v1.4.
- **Folder picker**: Win32 `IFileOpenDialog` COM interop replaces the
unreliable `Windows.Storage.Pickers.FolderPicker` in
`CaptureImage.UI.Services.Win32FolderPicker`.
- **Tray menu commands** wired through `MenuFlyoutItem.Command` (not
`Click` event) — the latter doesn't fire reliably from H.NotifyIcon's
out-of-tree popup.
- **Sound playback** uses Win32 `PlaySound` P/Invoke instead of
`System.Media.SystemSounds` (the latter ships in
`System.Windows.Extensions` which only targets Windows TFMs, too
restrictive for the portable ViewModels project).
- **Tray-restore from minimize** uses `AppWindow.Show` +
`User32.ShowWindow(SW_RESTORE)` + `Window.Activate` +
`User32.SetForegroundWindow` — `Show` alone leaves taskbar-minimized
windows minimized + behind whatever has foreground focus.
- **Auto-refresh suppression** while a preview modal is up — Dashboard's
WMI-driven Targets refresh used to clobber the in-flight
`SelectedTarget` and disrupt the preview decision; now skipped when
state is Previewing or Saving.
- **3rd-party list** in About: drop Avalonia + Inter typeface, add
Windows App SDK / WinUI 3 + H.NotifyIcon.WinUI.
### Removed
- `Avalonia.*` packages (Avalonia, Avalonia.Desktop, Avalonia.Themes.Fluent,
Avalonia.Fonts.Inter, Avalonia.Diagnostics) and 25 .axaml files / Avalonia
service implementations (`AvaloniaTrayIconHost`, `AvaloniaPreviewPresenter`,
`AvaloniaUIDispatcher`, `BytesToBitmapConverter` for Avalonia.Bitmap,
`ToastKindToBrushConverter` for Avalonia.IBrush). All replaced with WinUI 3
equivalents.
- Inter typeface — Fluent 2's Segoe UI Variable is the explicit body font now.
- `PublishSingleFile` from the release workflow — WinAppSDK can't be
bundled into a single .exe, ships as multi-file folder packaged by
Velopack.
### Fixed
- (in v1.3 from v1.2 carry-overs) Title-bar caption buttons no longer
overlap nav rail / Page content — 48 px drag region reserved at top
via `Window.SetTitleBar(AppTitleBar)`.
### Deferred to v1.4
- Real .ico tray icon via `System.Drawing.Bitmap.GetHicon` round-trip
(currently OS default glyph). H.NotifyIcon.WinUI's IconSource pipeline
ends in `System.Drawing.Icon` which only accepts .ico file streams.
- `release.yml` upload of `CaptureImage-win-Portable.zip` (carry-over
from v1.2 — added in v1.3 release cut).
- DPI-aware initial window sizing (`AppWindow.Resize` takes physical
pixels; v1.3 hardcodes 1200×720).
## [1.2.0] - 2026-04-21
Logging overhaul. Turns a working-but-thin diagnostic surface into one you
+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>
+70
View File
@@ -0,0 +1,70 @@
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;
// Apply persisted theme before first paint, then keep it in sync with settings.
var settings = services.GetRequiredService<ISettingsStore>();
mainWindow.ApplyTheme(settings.Current.Theme);
settings.Changed += (_, _) => mainWindow.ApplyTheme(settings.Current.Theme);
_window.Activate();
// Tray host attaches to the live Window. M1 ships a no-op stub; M6 wires the real
// H.NotifyIcon.WindowsAppSDK implementation.
var tray = services.GetRequiredService<ITrayIconHost>();
tray.Initialize(_window);
}
private static void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "Unhandled exception on UI dispatcher.");
e.Handled = true;
}
}
+38 -9
View File
@@ -8,20 +8,24 @@
<AssemblyName>CaptureImage.App</AssemblyName>
<UseWindowsForms>false</UseWindowsForms>
<UseWpf>false</UseWpf>
<!-- App icon + manifest are added in M4 -->
<UseWinUI>true</UseWinUI>
<EnableMsixTooling>false</EnableMsixTooling>
<WindowsPackageType>None</WindowsPackageType>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
<Platforms>x64</Platforms>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<!-- Release value for v1.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.4.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,34 @@
<ProjectReference Include="..\CaptureImage.UI\CaptureImage.UI.csproj" />
</ItemGroup>
<!-- Ship the legal and docs files next to the binary so the About tab can open them
with Process.Start. Links to the repo-root docs/ folder so there's a single source
of truth; content is copied into bin/.../docs/... at build time. -->
<!-- HOTFIX v1.3.1: WinUI 3 publish pipeline misses two file types when building
a self-contained unpackaged app via `dotnet publish`:
1. .xbf files — compiled XAML binary format produced by the WinUI 3 XAML
compiler. Without them, Application.LoadComponent fails on every
ms-appx:/// XAML reference at runtime with XamlParseException.
2. CaptureImage.App.pri — the app's compiled resource manifest. Without it,
Windows can't resolve ms-appx:/// URIs at all (incl. WinAppSDK theme
resources like ms-appx:///Microsoft.UI.Xaml/Themes/themeresources.xaml).
Both files are produced into bin/.../win-x64/ during build but `dotnet publish`
skips them in self-contained mode. v1.3.0 shipped without either and the
window never appeared (silent UI-thread crash; process stayed alive zombie).
This target adds every .xbf and .pri from $(OutDir) to the published file set,
preserving the CaptureImage.UI/Controls and CaptureImage.UI/Views subfolders
the XAML compiler creates for cross-assembly XAML resolution. -->
<Target Name="CopyWinUIArtifactsToPublishDirectory" AfterTargets="ComputeFilesToPublish">
<ItemGroup>
<_WinUIArtifactsToPublish Include="$(OutDir)**\*.xbf" />
<_WinUIArtifactsToPublish Include="$(OutDir)$(AssemblyName).pri" />
<ResolvedFileToPublish Include="@(_WinUIArtifactsToPublish)">
<RelativePath>%(RecursiveDir)%(Filename)%(Extension)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
<ItemGroup>
<Content Include="..\..\docs\legal\DISCLAIMER.md" Link="docs\legal\DISCLAIMER.md" CopyToOutputDirectory="PreserveNewest" />
<Content Include="..\..\docs\legal\PRIVACY.md" Link="docs\legal\PRIVACY.md" CopyToOutputDirectory="PreserveNewest" />
+8 -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 ----------------------------------------------------------
@@ -71,6 +75,7 @@ internal static class CompositionRoot
services.AddSingleton<IconExtractor>();
services.AddSingleton<IProcessDetector, GameDetector>();
services.AddSingleton<IProcessWatcher, WmiProcessWatcher>();
services.AddSingleton<IForegroundWindowWatcher, Win32ForegroundWindowWatcher>();
// --- Capture engine + encoders -----------------------------------------
services.AddSingleton<D3D11DeviceManager>();
@@ -91,8 +96,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>
+190
View File
@@ -0,0 +1,190 @@
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));
if (appWindow.Presenter is OverlappedPresenter presenter)
{
presenter.IsMaximizable = false;
presenter.IsResizable = false;
}
Root.Loaded += OnRootLoaded;
}
public MainWindowViewModel? ViewModel { get; private set; }
/// <summary>
/// Apply the persisted theme preference to the window root. <c>System</c> falls back
/// to <see cref="ElementTheme.Default"/> which lets the OS theme drive everything,
/// including Mica. Called at startup and whenever <c>ISettingsStore.Changed</c> fires.
/// Safe to call from any thread — internally hops to the dispatcher.
/// </summary>
public void ApplyTheme(string theme)
{
DispatcherQueue.TryEnqueue(() =>
{
if (Content is FrameworkElement root)
{
root.RequestedTheme = theme switch
{
"Light" => ElementTheme.Light,
"Dark" => ElementTheme.Dark,
_ => ElementTheme.Default,
};
}
});
}
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);
}
}
+19 -53
View File
@@ -1,9 +1,7 @@
using System;
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 +16,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 +39,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 +82,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 +104,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 +124,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 +135,6 @@ internal static class Program
e.IsTerminating);
if (e.IsTerminating)
{
// Last-ditch flush — CLR is about to pull the rug.
Log.CloseAndFlush();
}
};
@@ -166,17 +142,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;
}
}
@@ -0,0 +1,31 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Watches the system-wide foreground window and reports changes. Used by the dashboard
/// to auto-switch the selected target when the user Alt-Tabs to another app. Implementations
/// must filter out the host process's own windows and debounce rapid switches so the UI
/// only reacts after the user lands on a window.
/// </summary>
public interface IForegroundWindowWatcher : IDisposable
{
/// <summary>
/// Fires when the foreground window changes — after debouncing and self-process
/// filtering. Subscribers may run on any thread; marshal to the UI thread before
/// touching bindings.
/// </summary>
event EventHandler<nint>? ForegroundChanged;
/// <summary><c>true</c> while the underlying hook is registered.</summary>
bool IsRunning { get; }
/// <summary>
/// Register the foreground hook. Idempotent — calling while already running is a
/// no-op. Must be called from a thread with a message pump (the WinUI 3 UI thread)
/// because SetWinEventHook with WINEVENT_OUTOFCONTEXT routes callbacks via posted
/// messages.
/// </summary>
void Start();
/// <summary>Unhook and stop reporting events. Safe to call repeatedly.</summary>
void Stop();
}
@@ -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>
@@ -73,6 +73,13 @@ public sealed record CaptureSettings
/// lands on disk. When <c>false</c>, captures are saved immediately.
/// </summary>
public bool PreviewBeforeSave { get; init; } = false;
/// <summary>
/// When <c>true</c>, the dashboard's selected target follows the OS foreground window —
/// Alt-Tab to a target and CaptureImage re-selects it automatically. Off by default to
/// keep behaviour predictable for users who curate the list manually.
/// </summary>
public bool AutoSwitchOnAltTab { get; init; } = false;
}
/// <summary>UI / behaviour preferences not tied to a specific tab.</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>
@@ -48,8 +48,8 @@ public sealed class CaptureOrchestrator
$"No encoder registered for format {request.Format}.");
_logger.LogInformation(
"Capturing target {Target} → {Format} at {Dir}.",
request.Target.DisplayName, request.Format, request.OutputDirectory);
"Starting picture capture of {Target} as {Format}...",
request.Target.DisplayName, request.Format);
var frame = await _engine.CaptureAsync(request.Target, cancellationToken).ConfigureAwait(false);
@@ -93,9 +93,12 @@ public sealed class CaptureOrchestrator
}
stopwatch.Stop();
var fileName = Path.GetFileName(finalPath);
var directory = Path.GetDirectoryName(finalPath) ?? string.Empty;
var sizeKb = fileSize / 1024d;
_logger.LogInformation(
"Capture OK → {Path} ({Width}x{Height}, {Size} bytes, {Ms}ms).",
finalPath, frame.Width, frame.Height, fileSize, stopwatch.ElapsedMilliseconds);
"Picture captured: {Name} ({Width}x{Height}, {SizeKb:F1} KB) at {Path} [{Format}].",
fileName, frame.Width, frame.Height, sizeKb, directory, request.Format);
return new CaptureResult.Success(
FilePath: finalPath,
@@ -106,21 +109,29 @@ public sealed class CaptureOrchestrator
}
catch (CaptureException ex)
{
_logger.LogWarning(ex, "Capture failed with known error {Code}.", ex.ErrorCode);
if (ex.ErrorCode == CaptureError.Cancelled)
{
_logger.LogInformation("Picture capture cancelled by user.");
}
else
{
_logger.LogWarning(ex, "Picture capture failed: {Reason}", ex.Message);
}
return new CaptureResult.Failure(ex.ErrorCode, ex.Message, ex);
}
catch (OperationCanceledException)
{
_logger.LogInformation("Picture capture cancelled by user.");
return new CaptureResult.Failure(CaptureError.Cancelled, "Capture was cancelled.");
}
catch (IOException ex)
{
_logger.LogError(ex, "File write failed during capture.");
_logger.LogError(ex, "Picture capture failed: couldn't write to {Path}.", request.OutputDirectory);
return new CaptureResult.Failure(CaptureError.FileWriteFailure, ex.Message, ex);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected exception during capture.");
_logger.LogError(ex, "Picture capture failed unexpectedly.");
return new CaptureResult.Failure(CaptureError.Unknown, ex.Message, ex);
}
}
@@ -4,8 +4,9 @@ using System.Text;
namespace CaptureImage.Infrastructure.Processes.Interop;
/// <summary>
/// Minimal Win32 surface used by <see cref="WindowEnumerator"/>. Only the calls we actually
/// make land here — do not grow this file into a general user32 wrapper.
/// Minimal Win32 surface used by the Processes module (window enumeration + foreground
/// hook). Only the calls we actually make land here — do not grow this file into a
/// general user32 wrapper.
/// </summary>
internal static partial class User32
{
@@ -34,6 +35,35 @@ internal static partial class User32
[LibraryImport("user32.dll", SetLastError = true)]
public static partial IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[LibraryImport("user32.dll", SetLastError = true)]
public static partial IntPtr GetForegroundWindow();
// SetWinEventHook callback signature. Stays a classic [UnmanagedFunctionPointer]
// delegate (not [LibraryImport]) because [LibraryImport] doesn't support delegate
// parameters yet — the source generator won't marshal them.
public delegate void WinEventDelegate(
IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetWinEventHook(
uint eventMin, uint eventMax,
IntPtr hmodWinEventProc,
WinEventDelegate lpfnWinEventProc,
uint idProcess, uint idThread,
uint dwFlags);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
// SetWinEventHook event constants
public const uint EVENT_SYSTEM_FOREGROUND = 0x0003;
// SetWinEventHook flags
public const uint WINEVENT_OUTOFCONTEXT = 0x0000;
public const uint WINEVENT_SKIPOWNPROCESS = 0x0002;
// GetWindowLongPtr indices
public const int GWL_EXSTYLE = -20;
@@ -0,0 +1,141 @@
using System.Threading;
using CaptureImage.Core.Abstractions;
using CaptureImage.Infrastructure.Processes.Interop;
using Microsoft.Extensions.Logging;
namespace CaptureImage.Infrastructure.Processes;
/// <summary>
/// Win32 implementation of <see cref="IForegroundWindowWatcher"/>. Wraps
/// <c>SetWinEventHook(EVENT_SYSTEM_FOREGROUND, …)</c> and debounces rapid switches so
/// the dashboard only re-selects the target after the user lands on a window.
/// </summary>
public sealed class Win32ForegroundWindowWatcher : IForegroundWindowWatcher
{
private static readonly TimeSpan DebounceDelay = TimeSpan.FromMilliseconds(250);
private readonly ILogger<Win32ForegroundWindowWatcher> _logger;
private readonly object _gate = new();
private readonly uint _ownProcessId;
private IntPtr _hookHandle;
// Holding a strong reference to the delegate is mandatory: the callback is invoked
// by the OS message loop, and a GC of the delegate while the hook is active
// crashes with an AccessViolationException on the next foreground change.
private User32.WinEventDelegate? _callback;
private readonly Timer _debounceTimer;
private IntPtr _pendingHwnd;
private bool _disposed;
public event EventHandler<nint>? ForegroundChanged;
public bool IsRunning { get; private set; }
public Win32ForegroundWindowWatcher(ILogger<Win32ForegroundWindowWatcher> logger)
{
_logger = logger;
_ownProcessId = (uint)Environment.ProcessId;
_debounceTimer = new Timer(OnDebounceElapsed, null, Timeout.Infinite, Timeout.Infinite);
}
public void Start()
{
lock (_gate)
{
if (_disposed) return;
if (IsRunning) return;
_callback = OnRawForegroundEvent;
_hookHandle = User32.SetWinEventHook(
User32.EVENT_SYSTEM_FOREGROUND, User32.EVENT_SYSTEM_FOREGROUND,
IntPtr.Zero, _callback,
idProcess: 0, idThread: 0,
User32.WINEVENT_OUTOFCONTEXT | User32.WINEVENT_SKIPOWNPROCESS);
if (_hookHandle == IntPtr.Zero)
{
_logger.LogWarning("Foreground window watcher failed to register WinEvent hook.");
_callback = null;
return;
}
IsRunning = true;
_logger.LogDebug("Foreground window watcher started (hook=0x{Hook:X}).", _hookHandle);
}
}
public void Stop()
{
lock (_gate)
{
if (_hookHandle != IntPtr.Zero)
{
User32.UnhookWinEvent(_hookHandle);
_hookHandle = IntPtr.Zero;
}
_callback = null;
_pendingHwnd = IntPtr.Zero;
_debounceTimer.Change(Timeout.Infinite, Timeout.Infinite);
if (IsRunning)
{
_logger.LogDebug("Foreground window watcher stopped.");
}
IsRunning = false;
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
Stop();
_debounceTimer.Dispose();
}
private void OnRawForegroundEvent(
IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
// Use GetForegroundWindow() rather than the event's hwnd. On Win11 Alt-Tab the
// event-supplied hwnd can be the modern Task View overlay (idObject != 0) or a
// transient cloaked window — which got the original watcher to filter the event
// out and miss the actual destination. Polling the OS at callback time always
// returns the real foreground HWND. Mouse-click activations happened to ship a
// single clean event so they worked under the old code; Alt-Tab didn't.
var foreground = User32.GetForegroundWindow();
if (foreground == IntPtr.Zero) return;
// WINEVENT_SKIPOWNPROCESS already filters most own-window events, but a defensive
// pid check covers edge cases (e.g. a brokered window owned by another process).
User32.GetWindowThreadProcessId(foreground, out var pid);
if (pid == _ownProcessId) return;
if (pid == 0) return;
_pendingHwnd = foreground;
_debounceTimer.Change(DebounceDelay, Timeout.InfiniteTimeSpan);
}
private void OnDebounceElapsed(object? state)
{
IntPtr hwnd;
lock (_gate)
{
if (_disposed || !IsRunning) return;
hwnd = _pendingHwnd;
_pendingHwnd = IntPtr.Zero;
}
if (hwnd == IntPtr.Zero) return;
_logger.LogDebug("Foreground window watcher firing for HWND 0x{Hwnd:X}.", hwnd);
try
{
ForegroundChanged?.Invoke(this, hwnd);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ForegroundChanged subscriber threw.");
}
}
}
-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);
}
@@ -21,6 +21,10 @@ public sealed class ResxLocalizationService : ILocalizationService
new("en-US"),
new("vi-VN"),
new("ar-SA"),
new("ja-JP"),
new("zh-Hans"),
new("ko-KR"),
new("es-ES"),
};
private readonly ResourceManager _resourceManager;
@@ -60,6 +60,10 @@
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>الإعدادات</value></data>
<data name="Settings_Language" xml:space="preserve"><value>اللغة</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>السمة</value></data>
<data name="Settings_Theme_System" xml:space="preserve"><value>حسب النظام</value></data>
<data name="Settings_Theme_Light" xml:space="preserve"><value>فاتح</value></data>
<data name="Settings_Theme_Dark" xml:space="preserve"><value>داكن</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>مفتاح اختصار الالتقاط</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>انقر تسجيل ثم اضغط على مجموعة مفاتيح. Esc للإلغاء. إعادة التعيين تستعيد Ctrl+Shift+F12.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>تسجيل…</value></data>
@@ -81,6 +85,8 @@
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>اختر مجلدًا بدلاً من كتابة المسار.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>قالب اسم الملف</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>معاينة كل التقاط قبل الحفظ</value></data>
<data name="Settings_AutoSwitchOnAltTab" xml:space="preserve"><value>التبديل التلقائي للهدف عند Alt-Tab</value></data>
<data name="Settings_AutoSwitchOnAltTabHint" xml:space="preserve"><value>يتبع الهدف المحدد النافذة في المقدمة. التطبيقات غير المدرجة تترك تحديدك الحالي كما هو.</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>زر الإغلاق يصغر إلى علبة النظام</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>تشغيل صوت الالتقاط</value></data>
<data name="Settings_Import" xml:space="preserve"><value>استيراد…</value></data>
@@ -112,7 +118,7 @@
<data name="About_AiSection" xml:space="preserve"><value>التطوير بمساعدة الذكاء الاصطناعي</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>إخلاءات المسؤولية</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>الترجمات</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>حزم اللغة العربية والفيتنامية مترجمة بمساعدة الآلة. قد لا تتطابق المصطلحات مع العرف المحلي، وبعض الكلمات التقنية (hotkey، toast، frame، إلخ) تُركت بالإنجليزية عمداً. نرحب بمتحدثي اللغة الأم الراغبين في المراجعة لإرسال طلبات سحب على ملفات .resx في src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>حزم لغة الفيتنامية والعربية واليابانية والصينية المبسطة والكورية والإسبانية مترجمة بمساعدة الآلة. قد لا تتطابق المصطلحات مع العرف المحلي، وبعض الكلمات التقنية (hotkey، toast، frame، إلخ) تُركت بالإنجليزية عمداً. نرحب بمتحدثي اللغة الأم الراغبين في المراجعة لإرسال طلبات سحب على ملفات .resx في src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>دعم الالتقاط</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>يمكن لـ CaptureImage التقاط معظم الألعاب النافذية وعديمة الحدود عبر Windows.Graphics.Capture، لكن ليست كل لعبة تعمل. الأسطح المحمية بـ DRM، وألعاب Direct3D 9 بالشاشة الكاملة الحصرية، والألعاب ذات خطافات anti-cheat قد تعيد إطارات سوداء أو ترفض الالتقاط. تُجرَّب آلية احتياطية GDI PrintWindow للتطبيقات القديمة. راجع docs/legal/DISCLAIMER.md §2 للقائمة الكاملة.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>بدون ضمان</value></data>
@@ -0,0 +1,164 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="xml:space" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype"><value>text/microsoft-resx</value></resheader>
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<!-- Navigation -->
<data name="Nav_Dashboard" xml:space="preserve"><value>Panel</value></data>
<data name="Nav_Update" xml:space="preserve"><value>Actualización</value></data>
<data name="Nav_Settings" xml:space="preserve"><value>Configuración</value></data>
<data name="Nav_About" xml:space="preserve"><value>Acerca de</value></data>
<data name="Nav_LogViewer" xml:space="preserve"><value>Registro</value></data>
<!-- Dashboard -->
<data name="Dashboard_Title" xml:space="preserve"><value>Panel</value></data>
<data name="Dashboard_Subtitle" xml:space="preserve"><value>Selecciona un objetivo y actívalo — pulsa la tecla rápida para capturar.</value></data>
<data name="Dashboard_Refresh" xml:space="preserve"><value>Actualizar</value></data>
<data name="Dashboard_Arm" xml:space="preserve"><value>Activar</value></data>
<data name="Dashboard_Disarm" xml:space="preserve"><value>Desactivar</value></data>
<data name="Dashboard_StatusIdle" xml:space="preserve"><value>Inactivo — selecciona un objetivo y actívalo para empezar.</value></data>
<data name="Dashboard_StatusArmed" xml:space="preserve"><value>Activado: pulsa {0} para capturar {1}.</value></data>
<data name="Dashboard_StatusCapturing" xml:space="preserve"><value>Capturando {0}…</value></data>
<data name="Dashboard_StatusDisarmed" xml:space="preserve"><value>Desactivado.</value></data>
<data name="Dashboard_StatusSaved" xml:space="preserve"><value>Guardado: {0} ({1}x{2}, {3} ms)</value></data>
<data name="Dashboard_StatusFailed" xml:space="preserve"><value>Captura fallida ({0}): {1}</value></data>
<data name="Dashboard_TargetsCount" xml:space="preserve"><value>{0} objetivo(s) visible(s)</value></data>
<data name="Dashboard_Loading" xml:space="preserve"><value>Cargando…</value></data>
<data name="Dashboard_EmptyState" xml:space="preserve"><value>No hay ventanas visibles para capturar — abre tu juego o aplicación y pulsa Actualizar.</value></data>
<data name="Dashboard_LogToggle" xml:space="preserve"><value>Mostrar/ocultar el panel de registro en tiempo real</value></data>
<data name="Dashboard_SteamBadge" xml:space="preserve"><value>STEAM</value></data>
<data name="Dashboard_SteamBadgeTooltip" xml:space="preserve"><value>Juego de Steam: {0} (AppId {1}). La captura con F12 está disponible mediante la superposición de Steam. Algunos juegos protegidos por anticheat pueden bloquear la captura externa.</value></data>
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>Configuración</value></data>
<data name="Settings_Language" xml:space="preserve"><value>Idioma</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>Tema</value></data>
<data name="Settings_Theme_System" xml:space="preserve"><value>Sistema</value></data>
<data name="Settings_Theme_Light" xml:space="preserve"><value>Claro</value></data>
<data name="Settings_Theme_Dark" xml:space="preserve"><value>Oscuro</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>Tecla rápida de captura</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Pulsa Grabar y luego una combinación de teclas. Esc cancela. Restablecer recupera Ctrl+Shift+F12.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>Grabar…</value></data>
<data name="Settings_HotkeyCancel" xml:space="preserve"><value>Cancelar</value></data>
<data name="Settings_HotkeyReset" xml:space="preserve"><value>Restablecer</value></data>
<data name="Settings_HotkeyRecorderPrompt" xml:space="preserve"><value>Pulsa una combinación de teclas (Esc para cancelar)…</value></data>
<data name="Settings_HotkeyErrorNoPrimary" xml:space="preserve"><value>Selecciona una tecla principal (por ejemplo, una letra o una tecla F).</value></data>
<data name="Settings_HotkeyErrorModifierOnly" xml:space="preserve"><value>Una tecla modificadora sola no basta — añade una letra o una tecla F.</value></data>
<data name="Settings_HotkeyErrorNeedsModifier" xml:space="preserve"><value>Las letras y dígitos sueltos requieren al menos un modificador (Ctrl/Alt/Shift/Win).</value></data>
<data name="Settings_HotkeyErrorReserved" xml:space="preserve"><value>Esta combinación está reservada por Windows y no puede usarse.</value></data>
<data name="Settings_HotkeyConflictWarning" xml:space="preserve"><value>Otra aplicación puede estar usando esta combinación — quizá no funcione mientras esa app esté abierta.</value></data>
<data name="Settings_Format" xml:space="preserve"><value>Formato predeterminado</value></data>
<data name="Settings_JpegQuality" xml:space="preserve"><value>Calidad JPEG</value></data>
<data name="Settings_WebpQuality" xml:space="preserve"><value>Calidad WebP</value></data>
<data name="Settings_OutputFolder" xml:space="preserve"><value>Carpeta de salida</value></data>
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(predeterminado: Pictures\CaptureImage)</value></data>
<data name="Settings_Browse" xml:space="preserve"><value>Examinar…</value></data>
<data name="Settings_BrowseTitle" xml:space="preserve"><value>Elegir carpeta de salida</value></data>
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>Elige una carpeta en lugar de escribir la ruta.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>Plantilla del nombre de archivo</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>Previsualizar cada captura antes de guardar</value></data>
<data name="Settings_AutoSwitchOnAltTab" xml:space="preserve"><value>Cambiar automáticamente de objetivo al usar Alt-Tab</value></data>
<data name="Settings_AutoSwitchOnAltTabHint" xml:space="preserve"><value>El objetivo seleccionado sigue a la ventana en primer plano. Las apps que no estén en la lista mantienen tu selección actual.</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>El botón Cerrar minimiza a la bandeja</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>Reproducir sonido al capturar</value></data>
<data name="Settings_Import" xml:space="preserve"><value>Importar…</value></data>
<data name="Settings_Export" xml:space="preserve"><value>Exportar…</value></data>
<data name="Settings_ImportTitle" xml:space="preserve"><value>Importar configuración</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>Exportar configuración</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>Abrir archivo de configuración</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>Registro</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>Nivel mínimo del registro</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>Filtra el archivo de registro rotativo y el visor. Elige Debug para diagnóstico, Information para uso diario, o Warning/Error para reducir el volumen.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>Actualización</value></data>
<data name="Update_Check" xml:space="preserve"><value>Buscar actualizaciones</value></data>
<data name="Update_Download" xml:space="preserve"><value>Descargar</value></data>
<data name="Update_Install" xml:space="preserve"><value>Instalar y reiniciar</value></data>
<data name="Update_Status" xml:space="preserve"><value>Estado</value></data>
<data name="Update_Log" xml:space="preserve"><value>Registro</value></data>
<data name="Update_NewVersion" xml:space="preserve"><value>Nueva versión:</value></data>
<!-- About -->
<data name="About_Title" xml:space="preserve"><value>Acerca de CaptureImage</value></data>
<data name="About_Tagline" xml:space="preserve"><value>Captura de pantalla ligera para Windows pensada para juegos sin tecla de captura propia.</value></data>
<data name="About_AppLabel" xml:space="preserve"><value>Aplicación</value></data>
<data name="About_VersionLabel" xml:space="preserve"><value>Versión</value></data>
<data name="About_LicenseLabel" xml:space="preserve"><value>Licencia</value></data>
<data name="About_DeveloperLabel" xml:space="preserve"><value>Desarrollador</value></data>
<data name="About_RepositoryLabel" xml:space="preserve"><value>Repositorio</value></data>
<data name="About_AiSection" xml:space="preserve"><value>Desarrollo asistido por IA</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>Avisos legales</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>Traducciones</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Los paquetes de idioma japonés, chino simplificado, coreano y español están traducidos con asistencia automática. Es posible que la terminología no coincida con las convenciones nativas, y algunos términos técnicos (hotkey, toast, frame, etc.) se mantienen en inglés a propósito. Los hablantes nativos dispuestos a revisarlos pueden enviar pull requests sobre los archivos .resx en src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>Compatibilidad de captura</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage puede capturar la mayoría de los juegos en ventana o sin bordes mediante Windows.Graphics.Capture, pero no todos los títulos funcionan. Las superficies protegidas por DRM, los juegos en pantalla completa exclusiva con Direct3D 9 y los títulos con ganchos anticheat pueden devolver fotogramas en negro o rechazar la captura. Para apps antiguas se intenta un fallback con GDI PrintWindow. Consulta la lista completa en docs/legal/DISCLAIMER.md §2.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>Sin garantía</value></data>
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage se distribuye bajo GPL-3.0-or-later TAL CUAL, sin garantía de ningún tipo. Los autores no son responsables de capturas perdidas, fallos del juego, sanciones de anticheat ni pérdida de datos. Úsalo bajo tu propia responsabilidad. Consulta el texto completo en docs/legal/DISCLAIMER.md.</value></data>
<data name="About_LegalSection" xml:space="preserve"><value>Documentos legales</value></data>
<data name="About_ThirdPartySection" xml:space="preserve"><value>Componentes de terceros</value></data>
<data name="About_ThirdPartyHint" xml:space="preserve"><value>Pulsa "Avisos de terceros" arriba para ver la lista completa con las URLs originales.</value></data>
<data name="About_OpenDisclaimer" xml:space="preserve"><value>Aviso legal</value></data>
<data name="About_OpenPrivacy" xml:space="preserve"><value>Privacidad</value></data>
<data name="About_OpenTerms" xml:space="preserve"><value>Términos</value></data>
<data name="About_OpenLicense" xml:space="preserve"><value>Licencia (GPL-3.0)</value></data>
<data name="About_OpenThirdParty" xml:space="preserve"><value>Avisos de terceros</value></data>
<data name="About_OpenContributors" xml:space="preserve"><value>Colaboradores</value></data>
<!-- Log viewer -->
<data name="Log_Title" xml:space="preserve"><value>Registro en tiempo real</value></data>
<data name="Log_Pause" xml:space="preserve"><value>Pausar</value></data>
<data name="Log_Resume" xml:space="preserve"><value>Reanudar</value></data>
<data name="Log_Clear" xml:space="preserve"><value>Limpiar</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} eventos</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>Aún no hay eventos. Los eventos en tiempo real del motor de captura aparecerán aquí.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>Nivel mínimo:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>Abrir carpeta</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>Vista previa</value></data>
<data name="Preview_Prompt" xml:space="preserve"><value>¿Guardar esta captura?</value></data>
<data name="Preview_Save" xml:space="preserve"><value>Guardar</value></data>
<data name="Preview_Discard" xml:space="preserve"><value>Descartar</value></data>
<!-- Toasts -->
<data name="Toast_CaptureSaved" xml:space="preserve"><value>Captura guardada</value></data>
<data name="Toast_CaptureFailed" xml:space="preserve"><value>Captura fallida</value></data>
<data name="Toast_SettingsImported" xml:space="preserve"><value>Configuración importada</value></data>
<data name="Toast_SettingsExported" xml:space="preserve"><value>Configuración exportada</value></data>
<data name="Toast_Error" xml:space="preserve"><value>Error</value></data>
<!-- Tray menu -->
<data name="Tray_ShowWindow" xml:space="preserve"><value>Mostrar CaptureImage</value></data>
<data name="Tray_OpenFolder" xml:space="preserve"><value>Abrir carpeta de capturas</value></data>
<data name="Tray_Exit" xml:space="preserve"><value>Salir</value></data>
</root>
@@ -0,0 +1,164 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="xml:space" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype"><value>text/microsoft-resx</value></resheader>
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<!-- Navigation -->
<data name="Nav_Dashboard" xml:space="preserve"><value>ダッシュボード</value></data>
<data name="Nav_Update" xml:space="preserve"><value>アップデート</value></data>
<data name="Nav_Settings" xml:space="preserve"><value>設定</value></data>
<data name="Nav_About" xml:space="preserve"><value>情報</value></data>
<data name="Nav_LogViewer" xml:space="preserve"><value>ログ</value></data>
<!-- Dashboard -->
<data name="Dashboard_Title" xml:space="preserve"><value>ダッシュボード</value></data>
<data name="Dashboard_Subtitle" xml:space="preserve"><value>対象を選択して起動 — ホットキーでキャプチャします。</value></data>
<data name="Dashboard_Refresh" xml:space="preserve"><value>更新</value></data>
<data name="Dashboard_Arm" xml:space="preserve"><value>起動</value></data>
<data name="Dashboard_Disarm" xml:space="preserve"><value>停止</value></data>
<data name="Dashboard_StatusIdle" xml:space="preserve"><value>待機中 — 対象を選択して起動してください。</value></data>
<data name="Dashboard_StatusArmed" xml:space="preserve"><value>起動中: {0} を押すと {1} をキャプチャします。</value></data>
<data name="Dashboard_StatusCapturing" xml:space="preserve"><value>{0} をキャプチャ中…</value></data>
<data name="Dashboard_StatusDisarmed" xml:space="preserve"><value>停止しました。</value></data>
<data name="Dashboard_StatusSaved" xml:space="preserve"><value>保存: {0} ({1}x{2}, {3} ms)</value></data>
<data name="Dashboard_StatusFailed" xml:space="preserve"><value>キャプチャ失敗 ({0}): {1}</value></data>
<data name="Dashboard_TargetsCount" xml:space="preserve"><value>{0} 件の対象が表示されています</value></data>
<data name="Dashboard_Loading" xml:space="preserve"><value>読み込み中…</value></data>
<data name="Dashboard_EmptyState" xml:space="preserve"><value>キャプチャ可能なウィンドウがありません — ゲームやアプリを起動してから「更新」をクリックしてください。</value></data>
<data name="Dashboard_LogToggle" xml:space="preserve"><value>リアルタイムログを開閉</value></data>
<data name="Dashboard_SteamBadge" xml:space="preserve"><value>STEAM</value></data>
<data name="Dashboard_SteamBadgeTooltip" xml:space="preserve"><value>Steam ゲーム: {0} (AppId {1})。F12 のスクリーンショットは Steam オーバーレイで利用できます。アンチチート保護されたゲームでは外部キャプチャがブロックされる場合があります。</value></data>
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>設定</value></data>
<data name="Settings_Language" xml:space="preserve"><value>言語</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>テーマ</value></data>
<data name="Settings_Theme_System" xml:space="preserve"><value>システム</value></data>
<data name="Settings_Theme_Light" xml:space="preserve"><value>ライト</value></data>
<data name="Settings_Theme_Dark" xml:space="preserve"><value>ダーク</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>キャプチャ用ホットキー</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>「録音」をクリックしてキーの組み合わせを押します。Esc でキャンセル。「リセット」で Ctrl+Shift+F12 に戻します。</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>録音…</value></data>
<data name="Settings_HotkeyCancel" xml:space="preserve"><value>キャンセル</value></data>
<data name="Settings_HotkeyReset" xml:space="preserve"><value>リセット</value></data>
<data name="Settings_HotkeyRecorderPrompt" xml:space="preserve"><value>キーの組み合わせを押してください (Esc でキャンセル)…</value></data>
<data name="Settings_HotkeyErrorNoPrimary" xml:space="preserve"><value>主キーを選択してください (例: 文字キーまたは F キー)。</value></data>
<data name="Settings_HotkeyErrorModifierOnly" xml:space="preserve"><value>修飾キーだけでは登録できません — 文字キーまたは F キーを追加してください。</value></data>
<data name="Settings_HotkeyErrorNeedsModifier" xml:space="preserve"><value>文字や数字には少なくとも 1 つの修飾キー (Ctrl/Alt/Shift/Win) が必要です。</value></data>
<data name="Settings_HotkeyErrorReserved" xml:space="preserve"><value>この組み合わせは Windows により予約されており、使用できません。</value></data>
<data name="Settings_HotkeyConflictWarning" xml:space="preserve"><value>他のアプリがこの組み合わせを使用中の可能性があります — そのアプリの実行中は反応しないことがあります。</value></data>
<data name="Settings_Format" xml:space="preserve"><value>既定のフォーマット</value></data>
<data name="Settings_JpegQuality" xml:space="preserve"><value>JPEG 品質</value></data>
<data name="Settings_WebpQuality" xml:space="preserve"><value>WebP 品質</value></data>
<data name="Settings_OutputFolder" xml:space="preserve"><value>出力フォルダー</value></data>
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(既定: Pictures\CaptureImage)</value></data>
<data name="Settings_Browse" xml:space="preserve"><value>参照…</value></data>
<data name="Settings_BrowseTitle" xml:space="preserve"><value>出力フォルダーを選択</value></data>
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>パスを入力する代わりにフォルダーを選択します。</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>ファイル名テンプレート</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>保存前に各キャプチャをプレビュー</value></data>
<data name="Settings_AutoSwitchOnAltTab" xml:space="preserve"><value>Alt-Tab で対象を自動切り替え</value></data>
<data name="Settings_AutoSwitchOnAltTabHint" xml:space="preserve"><value>選択中の対象がフォアグラウンドウィンドウに追従します。対象一覧にないアプリでは現在の選択を維持します。</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>閉じるボタンでトレイに最小化</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>キャプチャ音を再生</value></data>
<data name="Settings_Import" xml:space="preserve"><value>インポート…</value></data>
<data name="Settings_Export" xml:space="preserve"><value>エクスポート…</value></data>
<data name="Settings_ImportTitle" xml:space="preserve"><value>設定をインポート</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>設定をエクスポート</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>設定ファイルを開く</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>ログ</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>最小ログレベル</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>ローリングログファイルとビューアをフィルタします。サポート診断には Debug、日常使用には Information、Warning または Error を選ぶと出力を抑えられます。</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>アップデート</value></data>
<data name="Update_Check" xml:space="preserve"><value>更新を確認</value></data>
<data name="Update_Download" xml:space="preserve"><value>ダウンロード</value></data>
<data name="Update_Install" xml:space="preserve"><value>インストールして再起動</value></data>
<data name="Update_Status" xml:space="preserve"><value>状態</value></data>
<data name="Update_Log" xml:space="preserve"><value>ログ</value></data>
<data name="Update_NewVersion" xml:space="preserve"><value>新しいバージョン:</value></data>
<!-- About -->
<data name="About_Title" xml:space="preserve"><value>CaptureImage について</value></data>
<data name="About_Tagline" xml:space="preserve"><value>スクリーンショット機能のないゲーム向けの軽量 Windows 画面キャプチャツール。</value></data>
<data name="About_AppLabel" xml:space="preserve"><value>アプリ</value></data>
<data name="About_VersionLabel" xml:space="preserve"><value>バージョン</value></data>
<data name="About_LicenseLabel" xml:space="preserve"><value>ライセンス</value></data>
<data name="About_DeveloperLabel" xml:space="preserve"><value>開発者</value></data>
<data name="About_RepositoryLabel" xml:space="preserve"><value>リポジトリ</value></data>
<data name="About_AiSection" xml:space="preserve"><value>AI 支援開発</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>免責事項</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>翻訳について</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>日本語、中国語(簡体)、韓国語、スペイン語の言語パックは機械支援で翻訳されています。用語が母語の慣習と一致しない場合があり、一部の技術用語(hotkey、toast、frame など)はあえて英語のままにしています。校正に協力してくださるネイティブスピーカーの方は、src/CaptureImage.UI/Resources/Strings/ の .resx ファイルへの Pull Request を歓迎します。</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>キャプチャ対応</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage は Windows.Graphics.Capture により多くのウィンドウ・ボーダーレスゲームをキャプチャできますが、すべてのタイトルで動作するわけではありません。DRM 保護されたサーフェス、排他的フルスクリーンの Direct3D 9 ゲーム、アンチチートフックを持つタイトルは、黒フレームを返したりキャプチャを拒否することがあります。レガシーアプリには GDI PrintWindow フォールバックを試みます。完全な一覧は docs/legal/DISCLAIMER.md §2 を参照してください。</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>無保証</value></data>
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage は GPL-3.0-or-later の下で「現状のまま」配布され、いかなる種類の保証もありません。作者はスクリーンショットの紛失、ゲームクラッシュ、アンチチート制裁、データ損失について責任を負いません。自己責任でご使用ください。完全な文章は docs/legal/DISCLAIMER.md を参照してください。</value></data>
<data name="About_LegalSection" xml:space="preserve"><value>法的文書</value></data>
<data name="About_ThirdPartySection" xml:space="preserve"><value>サードパーティコンポーネント</value></data>
<data name="About_ThirdPartyHint" xml:space="preserve"><value>上記の「サードパーティ通知」をクリックすると、上流 URL を含む完全な一覧が表示されます。</value></data>
<data name="About_OpenDisclaimer" xml:space="preserve"><value>免責事項</value></data>
<data name="About_OpenPrivacy" xml:space="preserve"><value>プライバシー</value></data>
<data name="About_OpenTerms" xml:space="preserve"><value>利用規約</value></data>
<data name="About_OpenLicense" xml:space="preserve"><value>ライセンス (GPL-3.0)</value></data>
<data name="About_OpenThirdParty" xml:space="preserve"><value>サードパーティ通知</value></data>
<data name="About_OpenContributors" xml:space="preserve"><value>貢献者</value></data>
<!-- Log viewer -->
<data name="Log_Title" xml:space="preserve"><value>リアルタイムログ</value></data>
<data name="Log_Pause" xml:space="preserve"><value>一時停止</value></data>
<data name="Log_Resume" xml:space="preserve"><value>再開</value></data>
<data name="Log_Clear" xml:space="preserve"><value>クリア</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} 件のイベント</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>まだログイベントがありません。キャプチャエンジンからのリアルタイムイベントがここに表示されます。</value></data>
<data name="Log_Filter" xml:space="preserve"><value>最小レベル:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>フォルダーを開く</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>プレビュー</value></data>
<data name="Preview_Prompt" xml:space="preserve"><value>このキャプチャを保存しますか?</value></data>
<data name="Preview_Save" xml:space="preserve"><value>保存</value></data>
<data name="Preview_Discard" xml:space="preserve"><value>破棄</value></data>
<!-- Toasts -->
<data name="Toast_CaptureSaved" xml:space="preserve"><value>キャプチャを保存しました</value></data>
<data name="Toast_CaptureFailed" xml:space="preserve"><value>キャプチャ失敗</value></data>
<data name="Toast_SettingsImported" xml:space="preserve"><value>設定をインポートしました</value></data>
<data name="Toast_SettingsExported" xml:space="preserve"><value>設定をエクスポートしました</value></data>
<data name="Toast_Error" xml:space="preserve"><value>エラー</value></data>
<!-- Tray menu -->
<data name="Tray_ShowWindow" xml:space="preserve"><value>CaptureImage を表示</value></data>
<data name="Tray_OpenFolder" xml:space="preserve"><value>キャプチャフォルダーを開く</value></data>
<data name="Tray_Exit" xml:space="preserve"><value>終了</value></data>
</root>
@@ -0,0 +1,164 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="xml:space" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype"><value>text/microsoft-resx</value></resheader>
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<!-- Navigation -->
<data name="Nav_Dashboard" xml:space="preserve"><value>대시보드</value></data>
<data name="Nav_Update" xml:space="preserve"><value>업데이트</value></data>
<data name="Nav_Settings" xml:space="preserve"><value>설정</value></data>
<data name="Nav_About" xml:space="preserve"><value>정보</value></data>
<data name="Nav_LogViewer" xml:space="preserve"><value>로그</value></data>
<!-- Dashboard -->
<data name="Dashboard_Title" xml:space="preserve"><value>대시보드</value></data>
<data name="Dashboard_Subtitle" xml:space="preserve"><value>대상을 선택하고 활성화한 다음 단축키를 눌러 캡처하세요.</value></data>
<data name="Dashboard_Refresh" xml:space="preserve"><value>새로 고침</value></data>
<data name="Dashboard_Arm" xml:space="preserve"><value>활성화</value></data>
<data name="Dashboard_Disarm" xml:space="preserve"><value>비활성화</value></data>
<data name="Dashboard_StatusIdle" xml:space="preserve"><value>대기 중 — 대상을 선택하고 활성화하세요.</value></data>
<data name="Dashboard_StatusArmed" xml:space="preserve"><value>활성화됨: {0} 키를 눌러 {1}을(를) 캡처합니다.</value></data>
<data name="Dashboard_StatusCapturing" xml:space="preserve"><value>{0} 캡처 중…</value></data>
<data name="Dashboard_StatusDisarmed" xml:space="preserve"><value>비활성화되었습니다.</value></data>
<data name="Dashboard_StatusSaved" xml:space="preserve"><value>저장됨: {0} ({1}x{2}, {3} ms)</value></data>
<data name="Dashboard_StatusFailed" xml:space="preserve"><value>캡처 실패 ({0}): {1}</value></data>
<data name="Dashboard_TargetsCount" xml:space="preserve"><value>{0}개의 대상이 표시됨</value></data>
<data name="Dashboard_Loading" xml:space="preserve"><value>불러오는 중…</value></data>
<data name="Dashboard_EmptyState" xml:space="preserve"><value>캡처할 수 있는 창이 없습니다 — 게임이나 앱을 실행한 다음 새로 고침을 클릭하세요.</value></data>
<data name="Dashboard_LogToggle" xml:space="preserve"><value>실시간 로그 패널 열기/닫기</value></data>
<data name="Dashboard_SteamBadge" xml:space="preserve"><value>STEAM</value></data>
<data name="Dashboard_SteamBadgeTooltip" xml:space="preserve"><value>Steam 게임: {0} (AppId {1}). F12 스크린샷은 Steam 오버레이를 통해 사용할 수 있습니다. 안티치트가 적용된 일부 게임은 외부 캡처를 차단할 수 있습니다.</value></data>
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>설정</value></data>
<data name="Settings_Language" xml:space="preserve"><value>언어</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>테마</value></data>
<data name="Settings_Theme_System" xml:space="preserve"><value>시스템</value></data>
<data name="Settings_Theme_Light" xml:space="preserve"><value>라이트</value></data>
<data name="Settings_Theme_Dark" xml:space="preserve"><value>다크</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>캡처 단축키</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>녹화를 클릭한 다음 키 조합을 누르세요. Esc로 취소합니다. 재설정은 Ctrl+Shift+F12로 되돌립니다.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>녹화…</value></data>
<data name="Settings_HotkeyCancel" xml:space="preserve"><value>취소</value></data>
<data name="Settings_HotkeyReset" xml:space="preserve"><value>재설정</value></data>
<data name="Settings_HotkeyRecorderPrompt" xml:space="preserve"><value>키 조합을 누르세요 (Esc로 취소)…</value></data>
<data name="Settings_HotkeyErrorNoPrimary" xml:space="preserve"><value>기본 키를 선택하세요 (예: 문자 또는 F 키).</value></data>
<data name="Settings_HotkeyErrorModifierOnly" xml:space="preserve"><value>수정자 키만으로는 충분하지 않습니다 — 문자나 F 키를 추가하세요.</value></data>
<data name="Settings_HotkeyErrorNeedsModifier" xml:space="preserve"><value>일반 문자와 숫자에는 최소 하나의 수정자 키(Ctrl/Alt/Shift/Win)가 필요합니다.</value></data>
<data name="Settings_HotkeyErrorReserved" xml:space="preserve"><value>이 조합은 Windows에서 예약되어 있어 사용할 수 없습니다.</value></data>
<data name="Settings_HotkeyConflictWarning" xml:space="preserve"><value>다른 응용 프로그램이 이 조합을 사용 중일 수 있습니다 — 해당 앱이 실행 중일 때는 작동하지 않을 수 있습니다.</value></data>
<data name="Settings_Format" xml:space="preserve"><value>기본 형식</value></data>
<data name="Settings_JpegQuality" xml:space="preserve"><value>JPEG 품질</value></data>
<data name="Settings_WebpQuality" xml:space="preserve"><value>WebP 품질</value></data>
<data name="Settings_OutputFolder" xml:space="preserve"><value>출력 폴더</value></data>
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(기본값: Pictures\CaptureImage)</value></data>
<data name="Settings_Browse" xml:space="preserve"><value>찾아보기…</value></data>
<data name="Settings_BrowseTitle" xml:space="preserve"><value>출력 폴더 선택</value></data>
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>경로를 입력하는 대신 폴더를 선택합니다.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>파일 이름 템플릿</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>저장 전에 각 캡처 미리보기</value></data>
<data name="Settings_AutoSwitchOnAltTab" xml:space="preserve"><value>Alt-Tab 시 대상 자동 전환</value></data>
<data name="Settings_AutoSwitchOnAltTabHint" xml:space="preserve"><value>선택된 대상이 포그라운드 창을 따라갑니다. 대상 목록에 없는 앱은 현재 선택을 유지합니다.</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>닫기 버튼으로 트레이로 최소화</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>캡처 사운드 재생</value></data>
<data name="Settings_Import" xml:space="preserve"><value>가져오기…</value></data>
<data name="Settings_Export" xml:space="preserve"><value>내보내기…</value></data>
<data name="Settings_ImportTitle" xml:space="preserve"><value>설정 가져오기</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>설정 내보내기</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>설정 파일 열기</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>로그</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>최소 로그 수준</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>롤링 로그 파일과 뷰어를 필터링합니다. 지원 진단에는 Debug, 일상 사용에는 Information, 출력을 줄이려면 Warning이나 Error를 선택하세요.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>업데이트</value></data>
<data name="Update_Check" xml:space="preserve"><value>업데이트 확인</value></data>
<data name="Update_Download" xml:space="preserve"><value>다운로드</value></data>
<data name="Update_Install" xml:space="preserve"><value>설치 후 다시 시작</value></data>
<data name="Update_Status" xml:space="preserve"><value>상태</value></data>
<data name="Update_Log" xml:space="preserve"><value>로그</value></data>
<data name="Update_NewVersion" xml:space="preserve"><value>새 버전:</value></data>
<!-- About -->
<data name="About_Title" xml:space="preserve"><value>CaptureImage 정보</value></data>
<data name="About_Tagline" xml:space="preserve"><value>스크린샷 키가 없는 게임을 위한 가벼운 Windows 화면 캡처 도구.</value></data>
<data name="About_AppLabel" xml:space="preserve"><value>앱</value></data>
<data name="About_VersionLabel" xml:space="preserve"><value>버전</value></data>
<data name="About_LicenseLabel" xml:space="preserve"><value>라이선스</value></data>
<data name="About_DeveloperLabel" xml:space="preserve"><value>개발자</value></data>
<data name="About_RepositoryLabel" xml:space="preserve"><value>저장소</value></data>
<data name="About_AiSection" xml:space="preserve"><value>AI 보조 개발</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>면책 조항</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>번역</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>일본어, 중국어(간체), 한국어, 스페인어 언어 팩은 기계 보조로 번역되었습니다. 용어가 모국어 관습과 일치하지 않을 수 있으며, 일부 기술 용어(hotkey, toast, frame 등)는 의도적으로 영어로 유지되었습니다. 교정에 도움을 주실 원어민 분들의 src/CaptureImage.UI/Resources/Strings/ .resx 파일에 대한 풀 리퀘스트를 환영합니다.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>캡처 지원</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage는 Windows.Graphics.Capture를 통해 대부분의 창 모드 및 테두리 없는 게임을 캡처할 수 있지만, 모든 타이틀에서 작동하지는 않습니다. DRM 보호된 표면, 독점 전체 화면 Direct3D 9 게임, 안티치트 후크가 있는 타이틀은 검은 프레임을 반환하거나 캡처를 거부할 수 있습니다. 레거시 앱에는 GDI PrintWindow 폴백이 시도됩니다. 전체 목록은 docs/legal/DISCLAIMER.md §2를 참조하세요.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>무보증</value></data>
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage는 GPL-3.0-or-later에 따라 어떠한 종류의 보증도 없이 "있는 그대로" 배포됩니다. 작성자는 손실된 스크린샷, 게임 충돌, 안티치트 제재 또는 데이터 손실에 대해 책임을 지지 않습니다. 본인 책임 하에 사용하세요. 전체 내용은 docs/legal/DISCLAIMER.md를 참조하세요.</value></data>
<data name="About_LegalSection" xml:space="preserve"><value>법적 문서</value></data>
<data name="About_ThirdPartySection" xml:space="preserve"><value>타사 구성 요소</value></data>
<data name="About_ThirdPartyHint" xml:space="preserve"><value>위의 "타사 고지"를 클릭하면 업스트림 URL이 포함된 전체 목록이 표시됩니다.</value></data>
<data name="About_OpenDisclaimer" xml:space="preserve"><value>면책 조항</value></data>
<data name="About_OpenPrivacy" xml:space="preserve"><value>개인정보</value></data>
<data name="About_OpenTerms" xml:space="preserve"><value>약관</value></data>
<data name="About_OpenLicense" xml:space="preserve"><value>라이선스 (GPL-3.0)</value></data>
<data name="About_OpenThirdParty" xml:space="preserve"><value>타사 고지</value></data>
<data name="About_OpenContributors" xml:space="preserve"><value>기여자</value></data>
<!-- Log viewer -->
<data name="Log_Title" xml:space="preserve"><value>실시간 로그</value></data>
<data name="Log_Pause" xml:space="preserve"><value>일시 중지</value></data>
<data name="Log_Resume" xml:space="preserve"><value>재개</value></data>
<data name="Log_Clear" xml:space="preserve"><value>지우기</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0}개의 이벤트</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>아직 로그 이벤트가 없습니다. 캡처 엔진의 실시간 이벤트가 여기에 표시됩니다.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>최소 수준:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>폴더 열기</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>미리보기</value></data>
<data name="Preview_Prompt" xml:space="preserve"><value>이 캡처를 저장하시겠습니까?</value></data>
<data name="Preview_Save" xml:space="preserve"><value>저장</value></data>
<data name="Preview_Discard" xml:space="preserve"><value>버리기</value></data>
<!-- Toasts -->
<data name="Toast_CaptureSaved" xml:space="preserve"><value>캡처 저장됨</value></data>
<data name="Toast_CaptureFailed" xml:space="preserve"><value>캡처 실패</value></data>
<data name="Toast_SettingsImported" xml:space="preserve"><value>설정 가져옴</value></data>
<data name="Toast_SettingsExported" xml:space="preserve"><value>설정 내보냄</value></data>
<data name="Toast_Error" xml:space="preserve"><value>오류</value></data>
<!-- Tray menu -->
<data name="Tray_ShowWindow" xml:space="preserve"><value>CaptureImage 표시</value></data>
<data name="Tray_OpenFolder" xml:space="preserve"><value>캡처 폴더 열기</value></data>
<data name="Tray_Exit" xml:space="preserve"><value>종료</value></data>
</root>
@@ -60,6 +60,10 @@
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>Settings</value></data>
<data name="Settings_Language" xml:space="preserve"><value>Language</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>Theme</value></data>
<data name="Settings_Theme_System" xml:space="preserve"><value>System</value></data>
<data name="Settings_Theme_Light" xml:space="preserve"><value>Light</value></data>
<data name="Settings_Theme_Dark" xml:space="preserve"><value>Dark</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>Capture hotkey</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Click Record and press a combination. Esc cancels. Reset restores Ctrl+Shift+F12.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>Record…</value></data>
@@ -81,6 +85,8 @@
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>Pick a folder instead of typing the path.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>File name template</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>Preview each capture before saving</value></data>
<data name="Settings_AutoSwitchOnAltTab" xml:space="preserve"><value>Auto-switch target when I Alt-Tab</value></data>
<data name="Settings_AutoSwitchOnAltTabHint" xml:space="preserve"><value>The selected target follows the foreground window. Apps not in the target list keep your current selection.</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>Close button minimizes to tray</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>Play capture sound</value></data>
<data name="Settings_Import" xml:space="preserve"><value>Import…</value></data>
@@ -112,7 +118,7 @@
<data name="About_AiSection" xml:space="preserve"><value>AI-assisted development</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>Disclaimers</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>Translations</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Vietnamese and Arabic language packs are machine-assisted. Terminology may not match native conventions, and some technical words (hotkey, toast, frame, etc.) are kept in English on purpose. Native speakers willing to proofread are warmly invited to submit pull requests against the .resx files in src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>The Vietnamese, Arabic, Japanese, Simplified Chinese, Korean, and Spanish language packs are machine-assisted. Terminology may not match native conventions, and some technical words (hotkey, toast, frame, etc.) are kept in English on purpose. Native speakers willing to proofread are warmly invited to submit pull requests against the .resx files in src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>Capture support</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage can capture most windowed and borderless games via Windows.Graphics.Capture, but not every title works. DRM-protected surfaces, exclusive-fullscreen Direct3D 9 games, and titles with anti-cheat hooks may return black frames or refuse capture. A GDI PrintWindow fallback is attempted for legacy apps. See docs/legal/DISCLAIMER.md §2 for the full list.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>No warranty</value></data>
@@ -60,6 +60,10 @@
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>Cài đặt</value></data>
<data name="Settings_Language" xml:space="preserve"><value>Ngôn ngữ</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>Giao diện</value></data>
<data name="Settings_Theme_System" xml:space="preserve"><value>Theo hệ thống</value></data>
<data name="Settings_Theme_Light" xml:space="preserve"><value>Sáng</value></data>
<data name="Settings_Theme_Dark" xml:space="preserve"><value>Tối</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>Hotkey chụp</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>Nhấn Ghi rồi nhấn tổ hợp phím. Esc để huỷ. Đặt lại sẽ khôi phục Ctrl+Shift+F12.</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>Ghi…</value></data>
@@ -81,6 +85,8 @@
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>Chọn thư mục thay vì phải gõ đường dẫn.</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>Mẫu tên tệp</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>Xem trước từng ảnh chụp trước khi lưu</value></data>
<data name="Settings_AutoSwitchOnAltTab" xml:space="preserve"><value>Tự động chuyển mục tiêu khi Alt-Tab</value></data>
<data name="Settings_AutoSwitchOnAltTabHint" xml:space="preserve"><value>Mục tiêu được chọn sẽ theo cửa sổ đang foreground. Các ứng dụng không có trong danh sách sẽ giữ nguyên lựa chọn hiện tại.</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>Nút đóng sẽ thu nhỏ xuống tray</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>Phát âm thanh khi chụp</value></data>
<data name="Settings_Import" xml:space="preserve"><value>Nhập…</value></data>
@@ -112,7 +118,7 @@
<data name="About_AiSection" xml:space="preserve"><value>Phát triển có hỗ trợ AI</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>Tuyên bố miễn trừ</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>Bản dịch</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Gói ngôn ngữ tiếng Việt và tiếng Ả Rập đang dùng bản dịch máy. Thuật ngữ có thể không khớp với quy ước bản ngữ, và một số từ kỹ thuật (hotkey, toast, frame, v.v.) được giữ tiếng Anh có chủ đích. Người bản ngữ sẵn lòng hiệu đính xin gửi pull request vào các tệp .resx trong src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>Các gói ngôn ngữ tiếng Việt, tiếng Ả Rập, tiếng Nhật, tiếng Trung giản thể, tiếng Hàn và tiếng Tây Ban Nha đang dùng bản dịch máy. Thuật ngữ có thể không khớp với quy ước bản ngữ, và một số từ kỹ thuật (hotkey, toast, frame, v.v.) được giữ tiếng Anh có chủ đích. Người bản ngữ sẵn lòng hiệu đính xin gửi pull request vào các tệp .resx trong src/CaptureImage.UI/Resources/Strings/.</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>Khả năng chụp</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage có thể chụp hầu hết game cửa sổ và borderless qua Windows.Graphics.Capture, nhưng không phải game nào cũng hoạt động. Bề mặt có DRM, game Direct3D 9 exclusive-fullscreen, và game có hook anti-cheat có thể trả khung đen hoặc từ chối chụp. Cơ chế dự phòng GDI PrintWindow được thử cho ứng dụng cũ. Xem docs/legal/DISCLAIMER.md §2 để biết danh sách đầy đủ.</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>Không bảo hành</value></data>
@@ -0,0 +1,164 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="xml:space" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype"><value>text/microsoft-resx</value></resheader>
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<!-- Navigation -->
<data name="Nav_Dashboard" xml:space="preserve"><value>仪表板</value></data>
<data name="Nav_Update" xml:space="preserve"><value>更新</value></data>
<data name="Nav_Settings" xml:space="preserve"><value>设置</value></data>
<data name="Nav_About" xml:space="preserve"><value>关于</value></data>
<data name="Nav_LogViewer" xml:space="preserve"><value>日志</value></data>
<!-- Dashboard -->
<data name="Dashboard_Title" xml:space="preserve"><value>仪表板</value></data>
<data name="Dashboard_Subtitle" xml:space="preserve"><value>选择目标并启动 — 按热键即可截图。</value></data>
<data name="Dashboard_Refresh" xml:space="preserve"><value>刷新</value></data>
<data name="Dashboard_Arm" xml:space="preserve"><value>启动</value></data>
<data name="Dashboard_Disarm" xml:space="preserve"><value>停止</value></data>
<data name="Dashboard_StatusIdle" xml:space="preserve"><value>空闲 — 选择目标并启动后开始。</value></data>
<data name="Dashboard_StatusArmed" xml:space="preserve"><value>已启动:按 {0} 截取 {1}。</value></data>
<data name="Dashboard_StatusCapturing" xml:space="preserve"><value>正在截取 {0}…</value></data>
<data name="Dashboard_StatusDisarmed" xml:space="preserve"><value>已停止。</value></data>
<data name="Dashboard_StatusSaved" xml:space="preserve"><value>已保存:{0} ({1}x{2}, {3} ms)</value></data>
<data name="Dashboard_StatusFailed" xml:space="preserve"><value>截图失败 ({0}):{1}</value></data>
<data name="Dashboard_TargetsCount" xml:space="preserve"><value>显示 {0} 个目标</value></data>
<data name="Dashboard_Loading" xml:space="preserve"><value>正在加载…</value></data>
<data name="Dashboard_EmptyState" xml:space="preserve"><value>没有可截取的可见窗口 — 启动游戏或应用后单击"刷新"。</value></data>
<data name="Dashboard_LogToggle" xml:space="preserve"><value>切换实时日志面板</value></data>
<data name="Dashboard_SteamBadge" xml:space="preserve"><value>STEAM</value></data>
<data name="Dashboard_SteamBadgeTooltip" xml:space="preserve"><value>Steam 游戏:{0} (AppId {1})。可通过 Steam 叠加层使用 F12 截图。部分受反作弊保护的游戏可能会阻止外部截图。</value></data>
<!-- Settings -->
<data name="Settings_Title" xml:space="preserve"><value>设置</value></data>
<data name="Settings_Language" xml:space="preserve"><value>语言</value></data>
<data name="Settings_Theme" xml:space="preserve"><value>主题</value></data>
<data name="Settings_Theme_System" xml:space="preserve"><value>系统</value></data>
<data name="Settings_Theme_Light" xml:space="preserve"><value>浅色</value></data>
<data name="Settings_Theme_Dark" xml:space="preserve"><value>深色</value></data>
<data name="Settings_Hotkey" xml:space="preserve"><value>截图热键</value></data>
<data name="Settings_HotkeyHint" xml:space="preserve"><value>单击"录制"并按下组合键。Esc 取消。"重置"将恢复 Ctrl+Shift+F12。</value></data>
<data name="Settings_HotkeyRecord" xml:space="preserve"><value>录制…</value></data>
<data name="Settings_HotkeyCancel" xml:space="preserve"><value>取消</value></data>
<data name="Settings_HotkeyReset" xml:space="preserve"><value>重置</value></data>
<data name="Settings_HotkeyRecorderPrompt" xml:space="preserve"><value>请按下组合键(按 Esc 取消)…</value></data>
<data name="Settings_HotkeyErrorNoPrimary" xml:space="preserve"><value>请选择主键(例如字母键或 F 键)。</value></data>
<data name="Settings_HotkeyErrorModifierOnly" xml:space="preserve"><value>仅修饰键不够 — 请添加字母或 F 键。</value></data>
<data name="Settings_HotkeyErrorNeedsModifier" xml:space="preserve"><value>普通字母和数字至少需要一个修饰键(Ctrl/Alt/Shift/Win)。</value></data>
<data name="Settings_HotkeyErrorReserved" xml:space="preserve"><value>该组合键已被 Windows 保留,无法使用。</value></data>
<data name="Settings_HotkeyConflictWarning" xml:space="preserve"><value>另一个应用程序可能已经占用了该组合键 — 当该应用运行时可能不会触发。</value></data>
<data name="Settings_Format" xml:space="preserve"><value>默认格式</value></data>
<data name="Settings_JpegQuality" xml:space="preserve"><value>JPEG 质量</value></data>
<data name="Settings_WebpQuality" xml:space="preserve"><value>WebP 质量</value></data>
<data name="Settings_OutputFolder" xml:space="preserve"><value>输出文件夹</value></data>
<data name="Settings_OutputFolderDefault" xml:space="preserve"><value>(默认:Pictures\CaptureImage)</value></data>
<data name="Settings_Browse" xml:space="preserve"><value>浏览…</value></data>
<data name="Settings_BrowseTitle" xml:space="preserve"><value>选择输出文件夹</value></data>
<data name="Settings_BrowseTooltip" xml:space="preserve"><value>选择文件夹而不是手动输入路径。</value></data>
<data name="Settings_FileNameTemplate" xml:space="preserve"><value>文件名模板</value></data>
<data name="Settings_PreviewBeforeSave" xml:space="preserve"><value>保存前预览每张截图</value></data>
<data name="Settings_AutoSwitchOnAltTab" xml:space="preserve"><value>Alt-Tab 时自动切换目标</value></data>
<data name="Settings_AutoSwitchOnAltTabHint" xml:space="preserve"><value>所选目标将跟随前台窗口。不在目标列表中的应用将保留当前选择。</value></data>
<data name="Settings_MinimizeToTray" xml:space="preserve"><value>关闭按钮最小化到系统托盘</value></data>
<data name="Settings_SoundEnabled" xml:space="preserve"><value>播放截图音效</value></data>
<data name="Settings_Import" xml:space="preserve"><value>导入…</value></data>
<data name="Settings_Export" xml:space="preserve"><value>导出…</value></data>
<data name="Settings_ImportTitle" xml:space="preserve"><value>导入设置</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>导出设置</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>打开设置文件</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>日志</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>最低日志级别</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>过滤滚动日志文件和查看器。支持诊断时选 Debug,日常使用选 Information,如需安静可选 Warning 或 Error。</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>更新</value></data>
<data name="Update_Check" xml:space="preserve"><value>检查更新</value></data>
<data name="Update_Download" xml:space="preserve"><value>下载</value></data>
<data name="Update_Install" xml:space="preserve"><value>安装并重启</value></data>
<data name="Update_Status" xml:space="preserve"><value>状态</value></data>
<data name="Update_Log" xml:space="preserve"><value>日志</value></data>
<data name="Update_NewVersion" xml:space="preserve"><value>新版本:</value></data>
<!-- About -->
<data name="About_Title" xml:space="preserve"><value>关于 CaptureImage</value></data>
<data name="About_Tagline" xml:space="preserve"><value>面向无内置截图键游戏的轻量级 Windows 屏幕截图工具。</value></data>
<data name="About_AppLabel" xml:space="preserve"><value>应用</value></data>
<data name="About_VersionLabel" xml:space="preserve"><value>版本</value></data>
<data name="About_LicenseLabel" xml:space="preserve"><value>许可证</value></data>
<data name="About_DeveloperLabel" xml:space="preserve"><value>开发者</value></data>
<data name="About_RepositoryLabel" xml:space="preserve"><value>仓库</value></data>
<data name="About_AiSection" xml:space="preserve"><value>AI 辅助开发</value></data>
<data name="About_DisclaimersSection" xml:space="preserve"><value>免责声明</value></data>
<data name="About_TranslationDisclaimer" xml:space="preserve"><value>翻译</value></data>
<data name="About_TranslationDisclaimerBody" xml:space="preserve"><value>日语、简体中文、韩语和西班牙语语言包采用机器辅助翻译。术语可能与母语习惯不一致,部分技术术语(hotkey、toast、frame 等)有意保留为英文。欢迎母语为相关语言的志愿者校对,可通过对 src/CaptureImage.UI/Resources/Strings/ 下的 .resx 文件提交 Pull Request。</value></data>
<data name="About_CaptureDisclaimer" xml:space="preserve"><value>截图支持</value></data>
<data name="About_CaptureLimitationDisclaimerBody" xml:space="preserve"><value>CaptureImage 通过 Windows.Graphics.Capture 可截取大多数窗口化和无边框游戏,但并非所有游戏都受支持。受 DRM 保护的画面、独占全屏 Direct3D 9 游戏以及带反作弊钩子的游戏可能会返回黑屏或拒绝截图。对于旧应用会尝试 GDI PrintWindow 回退。完整列表请参阅 docs/legal/DISCLAIMER.md §2。</value></data>
<data name="About_LiabilityDisclaimer" xml:space="preserve"><value>无担保</value></data>
<data name="About_LiabilityDisclaimerBody" xml:space="preserve"><value>CaptureImage 按 GPL-3.0-or-later 协议"按原样"分发,不提供任何形式的担保。作者对截图丢失、游戏崩溃、反作弊处罚或数据丢失不承担责任。使用风险自负。完整文本请参阅 docs/legal/DISCLAIMER.md。</value></data>
<data name="About_LegalSection" xml:space="preserve"><value>法律文件</value></data>
<data name="About_ThirdPartySection" xml:space="preserve"><value>第三方组件</value></data>
<data name="About_ThirdPartyHint" xml:space="preserve"><value>单击上方"第三方声明"查看包含上游 URL 的完整列表。</value></data>
<data name="About_OpenDisclaimer" xml:space="preserve"><value>免责声明</value></data>
<data name="About_OpenPrivacy" xml:space="preserve"><value>隐私</value></data>
<data name="About_OpenTerms" xml:space="preserve"><value>条款</value></data>
<data name="About_OpenLicense" xml:space="preserve"><value>许可证 (GPL-3.0)</value></data>
<data name="About_OpenThirdParty" xml:space="preserve"><value>第三方声明</value></data>
<data name="About_OpenContributors" xml:space="preserve"><value>贡献者</value></data>
<!-- Log viewer -->
<data name="Log_Title" xml:space="preserve"><value>实时日志</value></data>
<data name="Log_Pause" xml:space="preserve"><value>暂停</value></data>
<data name="Log_Resume" xml:space="preserve"><value>继续</value></data>
<data name="Log_Clear" xml:space="preserve"><value>清除</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} 条事件</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>尚无日志事件。截图引擎的实时事件将显示在此处。</value></data>
<data name="Log_Filter" xml:space="preserve"><value>最低级别:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>打开文件夹</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>预览</value></data>
<data name="Preview_Prompt" xml:space="preserve"><value>是否保存此截图?</value></data>
<data name="Preview_Save" xml:space="preserve"><value>保存</value></data>
<data name="Preview_Discard" xml:space="preserve"><value>放弃</value></data>
<!-- Toasts -->
<data name="Toast_CaptureSaved" xml:space="preserve"><value>截图已保存</value></data>
<data name="Toast_CaptureFailed" xml:space="preserve"><value>截图失败</value></data>
<data name="Toast_SettingsImported" xml:space="preserve"><value>设置已导入</value></data>
<data name="Toast_SettingsExported" xml:space="preserve"><value>设置已导出</value></data>
<data name="Toast_Error" xml:space="preserve"><value>错误</value></data>
<!-- Tray menu -->
<data name="Tray_ShowWindow" xml:space="preserve"><value>显示 CaptureImage</value></data>
<data name="Tray_OpenFolder" xml:space="preserve"><value>打开截图文件夹</value></data>
<data name="Tray_Exit" xml:space="preserve"><value>退出</value></data>
</root>
@@ -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);
}
}
+189
View File
@@ -0,0 +1,189 @@
<?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>
<!-- Theme: System / Light / Dark. ItemTemplate binds to ThemeOption.DisplayLabel
(already localized in the VM by RebuildThemeOptions). -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding ThemeLabel}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
FontSize="{StaticResource FontSizeSmall}" />
<ComboBox ItemsSource="{Binding SupportedThemes}"
SelectedItem="{Binding SelectedTheme, Mode=TwoWay}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DisplayLabel}" />
</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}" />
<StackPanel Spacing="2">
<CheckBox Content="{Binding AutoSwitchOnAltTabLabel}"
IsChecked="{Binding AutoSwitchOnAltTab, Mode=TwoWay}" />
<TextBlock Text="{Binding AutoSwitchOnAltTabHint}"
FontSize="{StaticResource FontSizeCaption}"
TextWrapping="Wrap"
Margin="28,0,0,0"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
<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"),
};
}
@@ -139,14 +137,14 @@ public sealed partial class AboutViewModel : ViewModelBase
var full = Path.Combine(basePath, relativePath);
if (!File.Exists(full))
{
_logger.LogWarning("Document not found: {Path}", full);
_logger.LogWarning("Document not found at {Path}.", full);
return;
}
Process.Start(new ProcessStartInfo(full) { UseShellExecute = true });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to open document {Path}.", relativePath);
_logger.LogError(ex, "Couldn't open the document at {Path}.", relativePath);
}
}
@@ -158,7 +156,7 @@ public sealed partial class AboutViewModel : ViewModelBase
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to open URL {Url}.", url);
_logger.LogError(ex, "Couldn't open the link {Url}.", url);
}
}
}
@@ -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;
@@ -25,6 +20,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
private readonly IProcessDetector _detector;
private readonly IProcessWatcher _watcher;
private readonly IForegroundWindowWatcher _foregroundWatcher;
private readonly IHotkeyService _hotkeys;
private readonly ICaptureEngine _captureEngine;
private readonly IReadOnlyList<IImageEncoder> _encoders;
@@ -79,6 +75,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
public DashboardViewModel(
IProcessDetector detector,
IProcessWatcher watcher,
IForegroundWindowWatcher foregroundWatcher,
IHotkeyService hotkeys,
ICaptureEngine captureEngine,
IEnumerable<IImageEncoder> encoders,
@@ -92,6 +89,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
{
_detector = detector;
_watcher = watcher;
_foregroundWatcher = foregroundWatcher;
_hotkeys = hotkeys;
_captureEngine = captureEngine;
_encoders = new List<IImageEncoder>(encoders).AsReadOnly();
@@ -111,6 +109,8 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
_watcher.Start();
_hotkeys.Triggered += OnHotkeyTriggered;
_settings.Changed += OnSettingsChanged;
_foregroundWatcher.ForegroundChanged += OnForegroundChanged;
ApplyAutoSwitchSetting();
Localization.PropertyChanged += OnLocalizationChanged;
@@ -164,7 +164,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to enumerate capture targets.");
_logger.LogError(ex, "Couldn't load the list of windows. Try clicking Refresh again.");
}
finally
{
@@ -341,7 +341,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Capture engine threw.");
_logger.LogError(ex, "Picture capture failed: the capture engine reported an error.");
_stateMachine.Fire(CaptureTrigger.ErrorOccurred);
_toasts.ShowError(Localization["Toast_CaptureFailed"], ex.Message);
return;
@@ -377,6 +377,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);
@@ -391,7 +392,7 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Save path threw unexpectedly.");
_logger.LogError(ex, "Picture capture failed while saving: {Reason}", ex.Message);
_stateMachine.Fire(CaptureTrigger.ErrorOccurred);
_toasts.ShowError(Localization["Toast_CaptureFailed"], ex.Message);
}
@@ -485,6 +486,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)
@@ -500,6 +515,79 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
{
UpdateStatusForState();
}
ApplyAutoSwitchSetting();
}
private void ApplyAutoSwitchSetting()
{
var enabled = _settings.Current.Capture.AutoSwitchOnAltTab;
if (enabled && !_foregroundWatcher.IsRunning)
{
_foregroundWatcher.Start();
}
else if (!enabled && _foregroundWatcher.IsRunning)
{
_foregroundWatcher.Stop();
}
}
private void OnForegroundChanged(object? sender, nint hwnd)
{
// Watcher runs on a thread-pool timer; marshal to the UI thread before touching
// SelectedTarget so binding updates land on the dispatcher.
_dispatcher.Post(() =>
{
if (_disposed) return;
if (!_settings.Current.Capture.AutoSwitchOnAltTab) return;
foreach (var vm in Targets)
{
if (vm.Target.WindowHandle == hwnd)
{
if (!ReferenceEquals(SelectedTarget, vm))
{
SelectedTarget = vm;
_logger.LogDebug(
"Auto-switched target to PID {Pid} ({Name}).",
vm.ProcessId, vm.DisplayName);
}
return;
}
}
// No match — keep the current selection. Clearing it would surprise users
// who Alt-Tab to apps that are filtered out of the target list (Explorer,
// Settings, etc.).
});
}
/// <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()
@@ -509,6 +597,8 @@ public sealed partial class DashboardViewModel : ViewModelBase, IDisposable
_hotkeys.Triggered -= OnHotkeyTriggered;
_watcher.Changed -= OnProcessChanged;
_settings.Changed -= OnSettingsChanged;
_foregroundWatcher.ForegroundChanged -= OnForegroundChanged;
_foregroundWatcher.Stop();
_stateMachine.StateChanged -= OnStateChanged;
Localization.PropertyChanged -= OnLocalizationChanged;
_pendingRefresh?.Cancel();
@@ -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;
@@ -197,7 +193,7 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to open logs folder {Path}.", folder);
_logger.LogWarning(ex, "Couldn't open the logs folder at {Path}.", folder);
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
@@ -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;
@@ -2,6 +2,7 @@ using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
@@ -32,6 +33,8 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
public ObservableCollection<CultureInfo> SupportedCultures { get; }
public ObservableCollection<ThemeOption> SupportedThemes { get; } = new();
public ObservableCollection<ImageFormat> SupportedFormats { get; } =
new(new[] { ImageFormat.Png, ImageFormat.Jpeg, ImageFormat.Webp, ImageFormat.Tiff });
@@ -46,6 +49,9 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
[ObservableProperty]
private CultureInfo _selectedCulture;
[ObservableProperty]
private ThemeOption? _selectedTheme;
[ObservableProperty]
private ImageFormat _defaultFormat;
@@ -64,6 +70,9 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
[ObservableProperty]
private bool _previewBeforeSave;
[ObservableProperty]
private bool _autoSwitchOnAltTab;
[ObservableProperty]
private bool _minimizeToTray;
@@ -87,6 +96,7 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
public string TitleLabel => Localization["Settings_Title"];
public string LanguageLabel => Localization["Settings_Language"];
public string ThemeLabel => Localization["Settings_Theme"];
public string HotkeyLabel => Localization["Settings_Hotkey"];
public string HotkeyHint => Localization["Settings_HotkeyHint"];
public string FormatLabel => Localization["Settings_Format"];
@@ -98,6 +108,8 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
public string BrowseTooltip => Localization["Settings_BrowseTooltip"];
public string FileNameTemplateLabel => Localization["Settings_FileNameTemplate"];
public string PreviewBeforeSaveLabel => Localization["Settings_PreviewBeforeSave"];
public string AutoSwitchOnAltTabLabel => Localization["Settings_AutoSwitchOnAltTab"];
public string AutoSwitchOnAltTabHint => Localization["Settings_AutoSwitchOnAltTabHint"];
public string MinimizeToTrayLabel => Localization["Settings_MinimizeToTray"];
public string SoundEnabledLabel => Localization["Settings_SoundEnabled"];
public string ImportLabel => Localization["Settings_Import"];
@@ -125,6 +137,8 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
SupportedCultures = new ObservableCollection<CultureInfo>(localization.SupportedCultures);
_selectedCulture = FindCulture(settings.Current.Culture) ?? SupportedCultures[0];
RebuildThemeOptions();
Hydrate();
_settings.Changed += OnSettingsStoreChanged;
@@ -149,10 +163,12 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
if (e.PropertyName is "Item[]" or nameof(ILocalizationService.CurrentCulture))
{
OnPropertyChanged(nameof(Localization));
RebuildThemeOptions();
// Plain-property refresh for every localized label the view binds to —
// indexer-path bindings don't wake reliably on Localization-reference ping.
OnPropertyChanged(nameof(TitleLabel));
OnPropertyChanged(nameof(LanguageLabel));
OnPropertyChanged(nameof(ThemeLabel));
OnPropertyChanged(nameof(HotkeyLabel));
OnPropertyChanged(nameof(HotkeyHint));
OnPropertyChanged(nameof(FormatLabel));
@@ -164,6 +180,8 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
OnPropertyChanged(nameof(BrowseTooltip));
OnPropertyChanged(nameof(FileNameTemplateLabel));
OnPropertyChanged(nameof(PreviewBeforeSaveLabel));
OnPropertyChanged(nameof(AutoSwitchOnAltTabLabel));
OnPropertyChanged(nameof(AutoSwitchOnAltTabHint));
OnPropertyChanged(nameof(MinimizeToTrayLabel));
OnPropertyChanged(nameof(SoundEnabledLabel));
OnPropertyChanged(nameof(ImportLabel));
@@ -202,12 +220,14 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
{
var current = _settings.Current;
SelectedCulture = FindCulture(current.Culture) ?? SupportedCultures[0];
SelectedTheme = FindTheme(current.Theme) ?? SupportedThemes[0];
DefaultFormat = current.Capture.DefaultFormat;
JpegQuality = current.Capture.JpegQuality;
WebpQuality = current.Capture.WebpQuality;
OutputDirectory = current.Capture.OutputDirectory;
FileNameTemplate = current.Capture.FileNameTemplate;
PreviewBeforeSave = current.Capture.PreviewBeforeSave;
AutoSwitchOnAltTab = current.Capture.AutoSwitchOnAltTab;
MinimizeToTray = current.UI.MinimizeToTray;
SoundEnabled = current.UI.SoundEnabled;
// Fall back to the first supported value if the persisted string doesn't match —
@@ -227,6 +247,44 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
if (_suppressPush || value is null) return;
_settings.Update(s => s with { Culture = value.Name });
Localization.SetCulture(value);
_logger.LogInformation("Language switched to {Code} ({Name}).", value.Name, value.NativeName);
}
partial void OnSelectedThemeChanged(ThemeOption? value)
{
if (_suppressPush || value is null) return;
_settings.Update(s => s with { Theme = value.Code });
_logger.LogInformation("Theme switched to {Theme}.", value.Code);
}
private ThemeOption? FindTheme(string code)
{
foreach (var t in SupportedThemes)
{
if (t.Code.Equals(code, StringComparison.OrdinalIgnoreCase))
{
return t;
}
}
return null;
}
private void RebuildThemeOptions()
{
var keepCode = SelectedTheme?.Code;
SupportedThemes.Clear();
SupportedThemes.Add(new ThemeOption("System", Localization["Settings_Theme_System"]));
SupportedThemes.Add(new ThemeOption("Light", Localization["Settings_Theme_Light"]));
SupportedThemes.Add(new ThemeOption("Dark", Localization["Settings_Theme_Dark"]));
// After a culture switch the bound SelectedTheme reference points at a stale
// option — rebind by Code so the ComboBox shows the right entry.
if (keepCode is not null)
{
_suppressPush = true;
try { SelectedTheme = FindTheme(keepCode) ?? SupportedThemes[0]; }
finally { _suppressPush = false; }
}
}
partial void OnDefaultFormatChanged(ImageFormat value)
@@ -265,6 +323,13 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
_settings.Update(s => s with { Capture = s.Capture with { PreviewBeforeSave = value } });
}
partial void OnAutoSwitchOnAltTabChanged(bool value)
{
if (_suppressPush) return;
_settings.Update(s => s with { Capture = s.Capture with { AutoSwitchOnAltTab = value } });
_logger.LogInformation("Auto-switch on Alt-Tab {State}.", value ? "enabled" : "disabled");
}
partial void OnMinimizeToTrayChanged(bool value)
{
if (_suppressPush) return;
@@ -275,6 +340,7 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
{
if (_suppressPush) return;
_settings.Update(s => s with { UI = s.UI with { SoundEnabled = value } });
_logger.LogInformation("Capture sound {State}.", value ? "enabled" : "disabled");
}
partial void OnSelectedLogLevelChanged(string value)
@@ -298,7 +364,7 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to open settings file.");
_logger.LogWarning(ex, "Couldn't open the settings file.");
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
@@ -318,7 +384,7 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Settings export failed.");
_logger.LogError(ex, "Couldn't export settings.");
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
@@ -334,7 +400,7 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Settings import failed.");
_logger.LogError(ex, "Couldn't import settings.");
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
@@ -0,0 +1,6 @@
namespace CaptureImage.ViewModels.Settings;
public sealed record ThemeOption(string Code, string DisplayLabel)
{
public override string ToString() => DisplayLabel;
}
@@ -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;
@@ -113,7 +111,7 @@ public sealed partial class UpdateViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Update check failed.");
_logger.LogError(ex, "Couldn't check for updates.");
Status = UpdateStatus.Failed;
}
finally
@@ -141,7 +139,7 @@ public sealed partial class UpdateViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Update download failed.");
_logger.LogError(ex, "Couldn't download the update.");
Status = UpdateStatus.Failed;
}
finally
@@ -162,7 +160,7 @@ public sealed partial class UpdateViewModel : ViewModelBase, IDisposable
}
catch (Exception ex)
{
_logger.LogError(ex, "Update install failed.");
_logger.LogError(ex, "Couldn't install the update.");
Status = UpdateStatus.Failed;
IsBusy = false;
}
@@ -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();
}
}
@@ -0,0 +1,47 @@
using CaptureImage.Infrastructure.Processes;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace CaptureImage.Infrastructure.Tests.Processes;
/// <summary>
/// Smoke tests for <see cref="Win32ForegroundWindowWatcher"/> lifecycle. Verifies that
/// construction, idempotent stop, and disposal don't throw — the actual SetWinEventHook
/// path needs a UI thread with a message pump and is exercised manually during QA.
/// </summary>
public class Win32ForegroundWindowWatcherTests
{
[Fact]
public void NewInstance_IsNotRunning()
{
using var watcher = new Win32ForegroundWindowWatcher(
NullLogger<Win32ForegroundWindowWatcher>.Instance);
watcher.IsRunning.Should().BeFalse();
}
[Fact]
public void Stop_WithoutStart_IsNoOp()
{
using var watcher = new Win32ForegroundWindowWatcher(
NullLogger<Win32ForegroundWindowWatcher>.Instance);
var act = () => watcher.Stop();
act.Should().NotThrow();
watcher.IsRunning.Should().BeFalse();
}
[Fact]
public void Dispose_IsIdempotent()
{
var watcher = new Win32ForegroundWindowWatcher(
NullLogger<Win32ForegroundWindowWatcher>.Instance);
watcher.Dispose();
var act = () => watcher.Dispose();
act.Should().NotThrow();
}
}
@@ -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>();
}
}
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more