10 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 6a21c531f6 chore(release): 2.0.0 (#23)
* chore(release): 2.0.0

- Version 2.0.0 in Directory.Build.props (the release workflow checks the tag against it).
- CHANGELOG: the v2 notes become [2.0.0] - 2026-10-19 under a new empty [Unreleased], plus the
  fix for settings missing from the file losing their defaults.
- Dependabot: open-pull-requests-limit back to 5 (NuGet) and 3 (Actions) now that the rewrite
  has landed; the config notes how to re-lock a NuGet update on Windows.
- ui-tests is now a required check on main; CLAUDE.md, CONTRIBUTING and the workflow comment
  say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: stop the release and deadcode jobs on any failing command

On Windows runners a multi-line pwsh step only fails when its last native command
fails. The release build ran restore, build and test before `dotnet tool restore`,
so a failing test could still produce a release; the deadcode job had the same
shape. Each command now runs in its own step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): list the end-to-end UI tests among the required checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:05:41 +07:00
poli0981andClaude Opus 5.5 7d68be7c7f feat!: CaptureImage 2.0 — WPF UI, per-mode hotkeys, multi-monitor, HDR, library, game profiles (#22)
* refactor(core)!: v2 capture model, settings v3, profiles, coordinator

- remove the WinUI projects (replaced by WPF in this branch); resx files and
  ResxLocalizationService move to ViewModels so they stay framework-agnostic
- capture model: CaptureMode (Window/Region/Monitor), CaptureSource,
  CaptureOptions, MonitorInfo/HdrInfo, PixelRect; frames carry a pixel format
  (BGRA8 or scRGB FP16) so HDR captures flow through the pipeline
- HdrToneMapper (scRGB -> sRGB with a C1-continuous highlight shoulder),
  FrameOperations (crop, force opaque)
- AppSettings v3: one hotkey per mode, HDR/PNG/cursor/window-frame options,
  start-with-Windows, arm-on-startup, game profiles; unknown fields round-trip
  via JsonExtensionData; SettingsMigrator moves v1/v2 files forward
- GameProfile + ProfileResolver (exe path > exe name > Steam AppId)
- FileNameStrategy: fixed Windows-invalid set, strips bidi/zero-width
  characters, guards CON/NUL/COM1..., caps length, working {counter}, {Mode}
- CaptureFileWriter: encode off-thread to .tmp, move without overwrite, retry on
  name races, optional JPEG XR HDR sidecar
- CaptureCoordinator replaces the Stateless state machine and the duplicated
  save pipeline in DashboardViewModel: one capture at a time (busy requests are
  ignored instead of throwing), cancellable countdown/selection/preview,
  frozen-snapshot region capture across monitors, profile auto-arm
- interfaces for the WinEvent watcher, RegisterHotKey service, display/HDR
  info, region selector, library, shell, sound, autostart, diagnostics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(infra)!: RegisterHotKey, WinEvent watcher, WGC monitor/HDR capture, WIC

- hotkeys: Win32 RegisterHotKey on a dedicated message-loop thread (no global
  keyboard *and mouse* hook any more), MOD_NOREPEAT, real conflict detection,
  temporary keys for the region overlay; SharpHook and HotkeyConflictSniffer gone
- window list: SetWinEventHook (create/destroy/show/hide/rename/minimize/
  foreground) replaces WMI polling every 2 s; TargetCatalog runs off the UI thread,
  skips cloaked windows and reads exe paths with QueryFullProcessImageName (works
  for elevated games); bounded LRU icon cache
- DisplayService: monitors in physical pixels with DPI, HDR state per output via
  IDXGIOutput6 on every adapter, SDR white level via DisplayConfig
- WgcCaptureEngine: window and monitor sources, BGRA8 or FP16 HDR, client-area /
  ContentSize crop on the GPU, cancellable timeout, late frames disposed, device
  lost -> recreate and retry once, no RCW leaks (vtable interop), safe readback
- encoders: SkiaSharp (PNG with selectable zlib level, JPEG 4:4:4 at q>=90, WebP)
  without extra copies or premultiplied-alpha transparency; WIC for TIFF and the
  JPEG XR HDR sidecar
- JsonSettingsStore v3: real atomic replace, serialized writes, backups of
  corrupt/older/newer files, v1 file adopted from the install folder, validated
  import that rejects UNC output folders
- CaptureLibraryService (index + WIC thumbnails + Recycle Bin), ShellService,
  SoundService, PerformanceModeService (EcoQoS), AutostartService,
  DiagnosticsExporter, OCR from BGRA frames with cached engines, Velopack 1.2
  WaitExitThenApplyUpdates, log path redaction, VDF depth limit
- packages: + Microsoft.Windows.CsWin32 (build-time), Vortice.Direct2D1 (WIC);
  - SharpHook, Stateless, System.Management, System.IO.Abstractions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(viewmodels)!: v2 view models for the WPF shell

Rewrite the view-model layer against the v2 Core abstractions, with no
framework or OS calls inside view models:

- Shell (tray tooltip, arm/disarm, capture per mode, exit through
  IAppLifetime), Dashboard (in-place window list refreshed by WinEvent
  notifications only while visible, target lock, per-hotkey status),
  Library (lazy thumbnails, filters, copy/OCR/pin/delete to Recycle Bin),
  Profiles (editor, create from a Dashboard window), Settings (write-
  through, per-mode hotkey recorder with conflict checks, import/export,
  reset, diagnostics), Logs (batched, paused, filtered), Update (localized
  status, cancellable check/download, apply on exit), About, Preview.
- Coordinator gains SuspendHotkeys() so the recorder receives combinations
  that are currently registered.
- IImageDecoder + WIC implementation for library copy/OCR/pin.
- Localization service uses source-generated logging, narrows its catch
  and can match the OS language to a shipped culture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(ui)!: WPF + WPF UI shell, tray, overlays and 11-language strings

Replace the WinUI 3 front end with WPF on .NET 10 and WPF UI 4.3:

- CaptureImage.UI: FluentWindow + NavigationView (Dashboard, Library,
  Profiles, Settings, Logs, Update, About) with pages resolved from DI,
  {loc:Tr} live localization, RTL + per-window language, WPF UI themes
  (System/Light/Dark/High contrast), snackbar in the window and
  non-activating, capture-excluded toast pop-ups when it isn't in front.
- Region selection: one frozen overlay per monitor placed in physical
  pixels at the monitor's DPI; Esc/Enter also registered as temporary
  hotkeys so they work while a game holds the keyboard.
- Preview window, pinned thumbnails, clipboard (bitmap + PNG), dialogs,
  hotkey recorder (Alt combos, Print Screen key-up).
- Tray icon (H.NotifyIcon.Wpf) with an armed indicator; re-added after
  Explorer restarts.
- CaptureImage.App: Velopack hooks first, per-user single instance over a
  CurrentUserOnly pipe, Serilog (async file + in-memory, user paths
  redacted), validated container, --data-dir / --instance-id /
  --minimized / --smoke-test / --screenshots, PerMonitorV2 + long paths
  manifest, multi-size app icon, commit recorded for "2.0.0 (abc1234)".
- Strings: 306 keys translated into all 11 languages; tests compare key
  sets per culture without fallback, check placeholders and that every
  key the code uses exists and every key is used.
- Settings records keep unknown JSON fields with a settable
  ExtensionData (the source generator can't bind init-only ones).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(ui)!: view-model and FlaUI suites, WPF publish smoke, stricter analyzers

- 135 view-model tests (settings write-through and reload, hotkey recorder
  with suspension, conflicts and validation, in-place window list,
  profiles, library filters and delete, log viewer batching, update flow,
  shell tray state, About links and third-party coverage, preview/OCR).
- CaptureImage.App.UiTests: FlaUI end-to-end tests against the real exe
  with a temporary data folder and instance id (navigation, arming,
  language switch, Arabic RTL, hotkey recorder, hide to tray + second
  launch). They skip unless CAPTUREIMAGE_UI_TESTS=1; new `ui-tests` job.
- CI publish-smoke publishes framework-dependent, runs --smoke-test with
  page screenshots (uploaded as an artifact) and checks the payload;
  deadcode now covers the UI and App projects.
- Release: framework-dependent publish + smoke test, vpk --framework
  net10-x64-desktop and --icon. Package .pdb/.xml stay out of the
  installer (publish 143 MB -> 51 MB, Setup ~28 MB).
- src/ builds with AnalysisMode=Recommended (warnings are errors);
  CA1716/CA1873 off with reasons, CA1822 off for bound view models.
- Test projects moved to the "tests" solution folder; Dependabot groups
  and the license ignore list follow the new dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: redundant casts and an unused P/Invoke result found by InspectCode

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ui): hide and exit after Closing returns; let sign-out close the app

Hiding or shutting down from inside Window.Closing can throw ("while a
Window is closing"), and tray Exit / Windows sign-out went through
Application.Shutdown without allowing the main window to close. Defer the
hide/exit, route IAppLifetime through App.RequestExit and allow close on
SessionEnding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): v2.0 notes under Unreleased

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(logging): render enums without JSON quotes in the log file and viewer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): give the startup and shutdown log lines a source context

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(ui): drop the sleep-and-retry temp cleanup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ui): keep running when the tray icon can't be created

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(infra): extract window icons with Win32 and WIC instead of System.Drawing

IconExtractor now takes the executable's own 48 px icon with SHDefExtractIcon
(falling back to the shell icon from SHGetFileInfo) and encodes it to PNG with
the WIC factory the app already uses. That removes the last System.Drawing.Common
reference and its central pin, which NuGet's package pruning resolved differently
on Linux than on Windows and broke the locked restore of the audit and license jobs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ui): expose pages to UI Automation as named panes

WPF creates no automation peer for Page, so the pages' automation ids and titles
never reached UI Automation: screen readers had no region to announce and the UI
tests could not find a page. Each page now creates a pane peer named after its
localized title.

The language UI test also waits for the debounced settings write instead of
reading settings.json once, which raced on the CI runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(core): v2 Core test suite

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the audit and license checks on Windows runners

NuGet prunes the WPF projects' Windows Desktop packages (System.Drawing.Common,
System.Diagnostics.EventLog, ...) only when restoring on Windows, so a locked
restore on Linux could never match the lock files. Both jobs now restore exactly
like the build job. The license job's restore is split so a failed package
restore can't be masked by the tool restore that follows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: v2 README, contributor guides, legal texts and contacts

- README, ARCHITECTURE, RELEASING, dev_env and pc_spec (+ Vietnamese) describe the WPF app,
  per-mode hotkeys, library, profiles, HDR, the framework-dependent installer and the new data
  folder; new screenshots rendered from seeded demo data (no personal windows or paths).
- PRIVACY, TERMS, DISCLAIMER, THIRD_PARTY_NOTICES and NOTICE match what v2 does and ships
  (clipboard, OCR, WinEvent hook, named pipe, library index, autostart, diagnostics export).
- New CONTRIBUTING, CODE_OF_CONDUCT, SUPPORT and CODEOWNERS; issue and PR templates updated.
- Contacts: contact@poli0981.dev and https://poli0981.dev/links, plus the role aliases
  (security@, privacy@, legal@, copyright@, dmca@, takedown@, code@, sponsor@, games@, collab@,
  press@) where each one belongs.
- CLAUDE.md covers the v2 layout, required checks, release steps, the Windows-only restore and
  how README screenshots are made.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(infra): v2 Infrastructure test suite

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address the SonarCloud findings on the v2 branch

- S2190: LocalizationSource.FlowDirection shared its name with the FlowDirection enum it
  returns, which reads as a recursive property; it is now CurrentFlowDirection.
- S8949: the coordinator's hotkey and auto-arm paths pass CancellationToken.None explicitly
  (a hotkey capture has no caller to cancel it; CancelCurrent() still stops it).
- S6640: unsafe code is how the Infrastructure assembly talks to Win32, Direct3D and WinRT; the
  rule is acknowledged once for that assembly with a justification instead of per call site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:52:30 +07:00
poli0981andClaude Opus 5.5 c649442a3a chore!: .NET 10 foundation, required CI quality gates, hardened release pipeline (#21)
* chore(build)!: move to .NET 10 LTS, refresh dependencies, enforce LF + SPDX headers

.NET 9 reaches end of support on 2026-11-10 and this machine only has .NET 10
SDKs, so the repo no longer built locally.

- global.json: SDK 10.0.401 (latestFeature) + Microsoft.Testing.Platform runner
- all projects retargeted to net10.0 / net10.0-windows10.0.22621.0
- Directory.Build.props: single version source (App no longer overrides it),
  TreatWarningsAsErrors everywhere, lock files + locked restore in CI,
  NuGetAudit (all, low), EnableWindowsTargeting (Dependabot evaluated every
  Windows-TFM project as "not compatible" without it), XML docs on so IDE0005
  runs in build
- packages: Microsoft.Extensions 10.0.13, Serilog 4.4.0 (+ sinks/extensions),
  CommunityToolkit.Mvvm 8.4.2, Stateless 5.20.1, Vortice 3.8.3, SkiaSharp
  4.153.1, Velopack 1.2.161 (DownloadUpdatesAsync lost ignoreDeltas;
  CheckForUpdatesAsync now honours cancellation via WaitAsync), WinAppSDK last
  1.8 patch
- security: drop SixLabors.ImageSharp 3.1.12 (GHSA-j3p4-wp97-rph4,
  GHSA-j9gm-c75j-xc9q, GHSA-jjfr-hcj7-qf5w high; GHSA-gwg2-r3hj-4w44,
  GHSA-wmxv-xphr-5c9g moderate) — TIFF now goes through the built-in WIC
  encoder (opaque, LZW)
- removed unused references: M.E.Hosting/Localization/Options/DI.Abstractions
  where unused, Serilog sinks in Infrastructure, SkiaSharp.NativeAssets.Win32
  (transitive), CsWinRT, Microsoft.Win32.Registry, H.NotifyIcon,
  Hosting.Abstractions
- tests: xunit 2 -> xunit.v3 4.0.2 (MTP v2), FluentAssertions 6 ->
  AwesomeAssertions 9 (FA >= 8 is commercially licensed), NSubstitute 6,
  coverlet -> Microsoft.Testing.Extensions.CodeCoverage; tests pass the xunit
  cancellation token
- .gitattributes: eol=lf everywhere (matches .editorconfig); .gitignore now
  ignores .idea/ and .claude/
- .editorconfig: SPDX header template (IDE0073) and IDE0161/0065/0005/0051/
  0052/0059/0060 enforced in build; headers added to every C# file, whitespace
  normalised; dead IID field and unused parameter/field removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: required quality gates, hardened release pipeline, working Dependabot

New required checks (one job each, no path filters so they always report):
- build: locked restore, Release build with warnings as errors, tests on
  Microsoft.Testing.Platform with Cobertura coverage summarised in the job summary
- format: `dotnet format whitespace` + style subset (SPDX header, file-scoped
  namespaces, using placement, unnecessary usings)
- deadcode: JetBrains InspectCode gated on file-local dead/redundant-code rules
  (WinUI projects excluded until they are replaced)
- audit: `dotnet list package --vulnerable --include-transitive` parsed by a gate
  script (the command itself always exits 0)
- license: nuget-license allowlist for the shipped app's dependency closure
- publish-smoke: publishes the app and verifies the payload (.pri/.xbf, legal docs)
- pr-title (Conventional Commits), dependency-review (vulnerabilities of any
  severity + non-free licenses), workflow-lint (actionlint + zizmor), docs
  (markdownlint + offline lychee); weekly external link check and OpenSSF
  Scorecard are informational

Release workflow:
- version taken from the tag through env + SemVer regex (removes the
  `${{ github.event.inputs.version }}` script injection) and checked against
  Directory.Build.props; prerelease derived from the version
- vpk pinned through the tool manifest (was unpinned while the library was
  0.0.1053); full packages only, so the previous release's 100 MB package is no
  longer re-uploaded; release notes come from CHANGELOG (the in-app update page
  showed none); identical packId/title/shortcuts/mainExe
- CycloneDX SBOM, SHA256SUMS of this version's assets, build-provenance
  attestations; release is created as a draft via gh (no third-party action with
  a write token); workflow_dispatch can rebuild an existing tag or dry-run

Other workflows: every action pinned to a commit SHA; least-privilege
permissions per job; notify-ci-failure ignores fork pull requests (they could post
their commit message to Discord) and all callers pass only the secrets they need
instead of `secrets: inherit`; announce-release now fires because releases are
published with a user token; discussion-welcome pinned and lists security@.
Removed .github/scripts/discord_notify.py (unused; the reusable workflows carry
their own copy).

Dependabot: EnableWindowsTargeting fixes the "not compatible" evaluation;
dead avalonia group removed; ecosystems grouped (incl. Velopack + vpk), 3-day
cooldown, tool manifest covered; version-update PRs paused (limit 0) until the
2.0.0 release.

Repo tooling: .config/dotnet-tools.json (vpk, InspectCode, nuget-license,
ReportGenerator, CycloneDX), markdownlint + lychee configs, RuntimeIdentifiers
win-x64 for stable lock files, CLAUDE.md for AI assistants, markdown lint fixes,
and the remaining InspectCode findings in Core/Infrastructure/ViewModels fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: fix first-run findings of the new gates

- dependency-review: drop Commons-Clause from deny-licenses (not an SPDX id)
- docs: disable markdownlint MD060 (table pipe alignment) introduced in
  markdownlint 0.41, which the CI action ships
- Dependabot cooldown 3 -> 7 days (zizmor dependabot-cooldown audit)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: quote InspectCode arguments, force HTTPS for actionlint download

- PowerShell splits a dash-prefixed native argument at its first period, so
  -o=inspectcode.sarif reached InspectCode as two arguments ('Specify only one
  solution file'); arguments are now quoted
- curl in workflow-lint refuses non-HTTPS protocols and redirects (SonarCloud
  githubactions:S6506)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 08:02:41 +07:00
dependabot[bot] 726f3076d7 chore(ci): Bump actions/setup-dotnet from 5 to 6 (#19)
Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 5 to 6.
- [Commits](https://github.com/actions/setup-dotnet/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/setup-dotnet
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-07 16:19:49 +07:00
dependabot[bot] 61582eaf45 chore(deps): Bump the test-tooling group with 1 update (#20)
Bumps coverlet.collector from 10.0.1 to 10.1.0

---
updated-dependencies:
- dependency-name: coverlet.collector
  dependency-version: 10.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: test-tooling
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-07 16:18:46 +07:00
dependabot[bot] 90381a0e71 chore(ci): Bump actions/checkout from 6 to 7 (#18)
Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-25 21:13:49 +07:00
dependabot[bot] de7d4ee57e chore(deps): Bump the test-tooling group with 1 update (#17)
Bumps coverlet.collector from 10.0.0 to 10.0.1

---
updated-dependencies:
- dependency-name: coverlet.collector
  dependency-version: 10.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: test-tooling
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-21 22:06:24 +07:00
dependabot[bot] 297de450b3 chore(ci): Bump actions/github-script from 7 to 9 (#16)
Bumps [actions/github-script](https://github.com/actions/github-script) from 7 to 9.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v7...v9)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-version: '9'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-18 21:32:46 +07:00
dependabot[bot] d80ae48174 chore(deps): Bump coverlet.collector from 8.0.1 to 10.0.0 (#8)
---
updated-dependencies:
- dependency-name: coverlet.collector
  dependency-version: 10.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: test-tooling
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-14 09:25:12 +07:00
poli0981 d01293f1a4 Hotfix v1.5.1
Hotfix mini-cycle — CI hardening, supply-chain SHA pinning, dev-env docs, About page Social/Donate/Report Bug, notify-* filter narrowing, discussion-welcome workflow. 7 milestone commits preserved.
2026-05-11 20:38:22 +07:00
412 changed files with 33294 additions and 17404 deletions

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
{
"version": 1,
"isRoot": true,
"tools": {
"vpk": {
"version": "1.2.161",
"commands": [
"vpk"
],
"rollForward": false
},
"jetbrains.resharper.globaltools": {
"version": "2026.2.3.1",
"commands": [
"jb"
],
"rollForward": false
},
"nuget-license": {
"version": "4.0.18",
"commands": [
"nuget-license"
],
"rollForward": false
},
"dotnet-reportgenerator-globaltool": {
"version": "5.5.11",
"commands": [
"reportgenerator"
],
"rollForward": false
},
"cyclonedx": {
"version": "6.3.1",
"commands": [
"dotnet-CycloneDX"
],
"rollForward": false
}
}
}
+26 -6
View File
@@ -23,12 +23,28 @@ csharp_using_directive_placement = outside_namespace:warning
dotnet_sort_system_directives_first = true
dotnet_separate_import_directive_groups = false
# Nullable
dotnet_diagnostic.CS8600.severity = warning
dotnet_diagnostic.CS8601.severity = warning
dotnet_diagnostic.CS8602.severity = warning
dotnet_diagnostic.CS8603.severity = warning
dotnet_diagnostic.CS8618.severity = warning
# License header on every C# file (IDE0073 is enforced during build).
file_header_template = SPDX-License-Identifier: GPL-3.0-or-later\nCopyright (c) CaptureImage Contributors
dotnet_diagnostic.IDE0073.severity = warning
# Style rules enforced during build (EnforceCodeStyleInBuild + TreatWarningsAsErrors).
# The ":warning" suffix on the options above is honored only by IDEs; these lines make
# the compiler report them too.
dotnet_diagnostic.IDE0161.severity = warning # file-scoped namespace
dotnet_diagnostic.IDE0065.severity = warning # using directives outside the namespace
dotnet_diagnostic.IDE0005.severity = warning # unnecessary using (needs GenerateDocumentationFile)
dotnet_diagnostic.IDE0051.severity = warning # unused private member
dotnet_diagnostic.IDE0052.severity = warning # private member assigned but never read
dotnet_diagnostic.IDE0059.severity = warning # value assigned but never used
dotnet_diagnostic.IDE0060.severity = warning # unused parameter
dotnet_code_quality_unused_parameters = non_public
# src/ builds with AnalysisMode=Recommended (src/Directory.Build.props). Rules switched off:
# CA1716 flags names that are keywords in other .NET languages (IWindowWatcher.Stop is "Stop"
# in VB); this is a C#-only app. CA1873 flags argument evaluation in log calls; the ones left
# run once per startup or per error, and LoggerMessage methods check IsEnabled themselves.
dotnet_diagnostic.CA1716.severity = none
dotnet_diagnostic.CA1873.severity = none
# Code style - var
csharp_style_var_for_built_in_types = true:suggestion
@@ -43,3 +59,7 @@ csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_between_query_expression_clauses = true
# View models: XAML binds to instance properties even when they return constants.
[src/CaptureImage.ViewModels/**.cs]
dotnet_diagnostic.CA1822.severity = none
+32 -41
View File
@@ -1,45 +1,36 @@
# Normalize line endings for all text files — Git stores LF internally and
# checks out CRLF on Windows automatically for *.cs / *.csproj / *.md / etc.
# This avoids the "CRLF will be replaced by LF" warning on every commit.
* text=auto
# Store text as LF in the repository *and* check it out as LF, regardless of the
# local core.autocrlf setting (this dev box and GitHub's Windows runners both
# default to true). .editorconfig says end_of_line = lf and the CI `format` job
# runs `dotnet format --verify-no-changes`, which enforces it.
* text=auto eol=lf
# Files that must stay LF regardless of platform.
*.sh text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
Dockerfile text eol=lf
*.gitattributes text eol=lf
*.gitignore text eol=lf
# Windows batch files must keep CRLF.
*.bat text eol=crlf
*.cmd text eol=crlf
# Files that must stay CRLF (Windows scripts).
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
# Source / config files — auto is fine but declaring explicit makes intent obvious.
*.cs text diff=csharp
*.csproj text
*.sln text
*.props text
*.targets text
*.json text
*.xml text
*.config text
*.resx text
*.axaml text
# Diff drivers.
*.cs text diff=csharp
*.md text diff=markdown
# Binaries — never touch.
*.dll binary
*.pdb binary
*.exe binary
*.so binary
*.dylib binary
*.png binary
*.jpg binary
*.jpeg binary
*.webp binary
*.tiff binary
*.ico binary
*.nupkg binary
*.snupkg binary
*.zip binary
*.dll binary
*.exe binary
*.pdb binary
*.so binary
*.dylib binary
*.nupkg binary
*.zip binary
*.ico binary
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.bmp binary
*.webp binary
*.tif binary
*.tiff binary
*.jxr binary
*.ttf binary
*.otf binary
*.woff binary
*.woff2 binary
+2
View File
@@ -0,0 +1,2 @@
# Every change is reviewed by the maintainer.
* @poli0981
+43 -35
View File
@@ -6,16 +6,19 @@ body:
- type: markdown
attributes:
value: |
Thanks for taking the time to report a bug. Please fill in every
field — bug reports missing environment or repro details usually
cannot be acted on.
Thanks for taking the time to report a bug. Reports with the version, Windows build and
steps to reproduce are the ones that get fixed.
**Tip:** in the app, set **Settings → Advanced → Minimum log level** to **Debug**,
reproduce the problem, then use **Export diagnostics** and attach the zip below (user
paths are removed automatically).
- type: textarea
id: summary
attributes:
label: Summary
description: One-sentence description of what's wrong.
placeholder: "Capturing Elden Ring produces an all-black PNG."
description: One sentence describing what's wrong.
placeholder: "Region captures of my second monitor are shifted to the left."
validations:
required: true
@@ -23,12 +26,12 @@ body:
id: repro
attributes:
label: Steps to reproduce
description: Numbered steps from a clean launch of CaptureImage.
description: Numbered steps, starting from opening CaptureImage.
placeholder: |
1. Start Elden Ring in borderless windowed mode.
2. Open CaptureImage and select "Elden Ring" from the Dashboard.
3. Click Arm, focus Elden Ring, press Ctrl+Shift+F12.
4. Observe the resulting PNG in Pictures\CaptureImage.
1. Start the game in borderless windowed mode on my second monitor (150% scaling).
2. Click Arm on the Dashboard.
3. Press Ctrl+Shift+F11 and drag an area.
4. Open the saved PNG.
validations:
required: true
@@ -36,7 +39,6 @@ body:
id: expected
attributes:
label: Expected behavior
placeholder: "The PNG should contain the game frame."
validations:
required: true
@@ -44,7 +46,18 @@ body:
id: actual
attributes:
label: Actual behavior
placeholder: "The PNG is 1920x1080 but every pixel is (0,0,0,255)."
validations:
required: true
- type: dropdown
id: mode
attributes:
label: Capture mode
options:
- "Window (Ctrl+Shift+F12 by default)"
- "Region (Ctrl+Shift+F11 by default)"
- "Screen (Ctrl+Shift+F10 by default)"
- "Not about capturing (UI, settings, library, update…)"
validations:
required: true
@@ -52,8 +65,8 @@ body:
id: version
attributes:
label: CaptureImage version
description: "See About tab. Example: `1.0.0`"
placeholder: "1.0.0"
description: "Shown in the title bar and on the About page, e.g. `2.0.0 (abc1234)`."
placeholder: "2.0.0 (abc1234)"
validations:
required: true
@@ -61,45 +74,40 @@ body:
id: windows
attributes:
label: Windows version
description: "Run `winver` — example: `Windows 11 Pro 24H2 (26100.2454)`"
description: "Run `winver`, e.g. `Windows 11 Pro 24H2 (26100.2454)`."
validations:
required: true
- type: input
id: gpu
id: displays
attributes:
label: GPU + driver version
description: "Example: `RTX 4070 / NVIDIA 566.14`"
label: Displays and graphics
description: "Number of monitors, their scaling, whether HDR is on, GPU and driver."
placeholder: "2 monitors (100% + 150%), HDR on the first, RTX 4070 / 566.14"
- type: dropdown
id: capture-api
- type: input
id: game
attributes:
label: Which capture engine produced the bug?
options:
- "Windows.Graphics.Capture (primary)"
- "PrintWindow fallback"
- "Both"
- "Not sure"
validations:
required: true
label: Game or application
description: "Name, and whether it runs windowed, borderless or exclusive full screen."
- type: textarea
id: logs
attributes:
label: Relevant log snippet
label: Diagnostics or log excerpt
description: |
Paste the relevant window from `%LocalAppData%\CaptureImage\logs\captureimg-<date>.log`.
Please redact anything sensitive (window titles of other apps, file paths in your home).
Attach the zip from **Export diagnostics**, or paste the relevant lines from
`%LocalAppData%\poli0981\CaptureImage\logs\captureimage-<date>.log`.
render: text
- type: checkboxes
id: preflight
attributes:
label: Pre-flight checks
label: Before submitting
options:
- label: I have searched existing issues for a duplicate.
- label: I searched existing issues for a duplicate.
required: true
- label: I have read `docs/legal/DISCLAIMER.md §2` (capture limitations) and the bug is not an expected limitation.
- label: I read the capture limitations in `docs/legal/DISCLAIMER.md` (section 2) and this isn't one of them.
required: true
- label: This is NOT a security vulnerability (those go through Security Advisories, not issues).
- label: This is not a security vulnerability (those go to `security@poli0981.dev` or a private advisory).
required: true
+6 -3
View File
@@ -2,7 +2,10 @@ blank_issues_enabled: false
contact_links:
- name: Security vulnerability
url: https://github.com/poli0981/captureimg/security/advisories/new
about: Please report security issues privately via GitHub Security Advisories, not public issues.
- name: Question / discussion
about: Report security issues privately (or email security@poli0981.dev), never in a public issue.
- name: Questions and ideas
url: https://github.com/poli0981/captureimg/discussions
about: For questions and general discussion, open a Discussion instead of an issue.
about: Ask questions and discuss ideas in GitHub Discussions.
- name: Other ways to reach the maintainer
url: https://poli0981.dev/links
about: General contact is contact@poli0981.dev; all channels are listed here.
+45 -10
View File
@@ -1,8 +1,15 @@
version: 2
# NuGet updates only work because Directory.Build.props sets
# EnableWindowsTargeting=true — Dependabot's updater runs on Linux and otherwise
# reports every newer version as "not compatible" with the Windows TFMs.
#
# The updater restores on Linux, where NuGet prunes the WPF projects' Windows
# Desktop packages differently: if a PR fails `restore --locked-mode`, run
# `dotnet restore CaptureImage.sln --force-evaluate` on Windows and push the
# lock files.
updates:
# NuGet — the actual runtime + build dependencies. Weekly cadence; grouped
# minor/patch bumps so we don't get a PR per package when .NET rolls.
- package-ecosystem: nuget
directory: "/"
schedule:
@@ -10,6 +17,8 @@ updates:
day: monday
time: "07:00"
timezone: Asia/Ho_Chi_Minh
cooldown:
default-days: 7
open-pull-requests-limit: 5
commit-message:
prefix: "chore(deps)"
@@ -17,25 +26,45 @@ updates:
labels:
- dependencies
groups:
avalonia:
patterns:
- "Avalonia*"
microsoft-extensions:
patterns:
- "Microsoft.Extensions.*"
serilog:
patterns:
- "Serilog*"
skiasharp:
patterns:
- "SkiaSharp*"
vortice:
patterns:
- "Vortice.*"
velopack:
# The library and the `vpk` tool in .config/dotnet-tools.json must move together.
patterns:
- "Velopack"
- "vpk"
wpf-ui:
patterns:
- "WPF-UI*"
- "H.NotifyIcon*"
- "CommunityToolkit.Mvvm"
win32-interop:
patterns:
- "Microsoft.Windows.CsWin32"
test-tooling:
patterns:
- "xunit*"
- "FluentAssertions"
- "AwesomeAssertions"
- "NSubstitute"
- "Microsoft.NET.Test.Sdk"
- "coverlet.*"
- "Microsoft.Testing.*"
- "FlaUI*"
dev-tools:
patterns:
- "jetbrains.resharper.globaltools"
- "nuget-license"
- "dotnet-reportgenerator-globaltool"
- "cyclonedx"
# GitHub Actions workflow files themselves. Dependabot bumps action
# versions when upstream releases.
- package-ecosystem: github-actions
directory: "/"
schedule:
@@ -43,9 +72,15 @@ updates:
day: monday
time: "07:00"
timezone: Asia/Ho_Chi_Minh
cooldown:
default-days: 7
open-pull-requests-limit: 3
commit-message:
prefix: "chore(ci)"
labels:
- dependencies
- ci
groups:
github-actions:
patterns:
- "*"
+12
View File
@@ -0,0 +1,12 @@
[
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Zlib",
"0BSD",
"Unlicense",
"LGPL-2.1-or-later",
"LGPL-3.0-or-later"
]
+1
View File
@@ -0,0 +1 @@
[]
+20 -39
View File
@@ -1,52 +1,33 @@
<!-- Thanks for contributing to CaptureImage! Please fill in every section. -->
<!-- markdownlint-disable-file MD041 -->
<!-- Thanks for contributing to CaptureImage! The PR title must follow Conventional Commits,
e.g. "fix(capture): keep alpha opaque" — it becomes the squash-commit subject. -->
## Summary
<!-- One or two sentences about what this PR does and why. -->
## Type of change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation only
- [ ] Build / CI / release infrastructure
- [ ] Refactoring (no functional change)
<!-- What does this change and why? -->
## Related issues
<!-- Reference with `Fixes #123` / `Closes #456` / `Refs #789`. -->
<!-- Fixes #123 / Closes #456 / Refs #789 -->
## Testing
<!--
Describe how you verified the change. Minimum:
- `dotnet build CaptureImage.sln` and `dotnet test CaptureImage.sln` locally
- Manual repro of the bug (for fixes) or the new workflow (for features)
<!-- How did you verify it? For UI changes, add screenshots
(`CaptureImage.App.exe --screenshots <dir> --data-dir <temp>` renders every page). -->
For UI changes, attach screenshots or a short GIF.
-->
- [ ] `dotnet build CaptureImage.sln` passes with 0 warnings / 0 errors
- [ ] `dotnet test CaptureImage.sln` passes all existing tests
- [ ] New tests added for new logic (if applicable)
- [ ] Manual smoke test performed (describe below)
## AI assistance disclosure
<!--
Check if the diff was materially generated with AI help. This does NOT
disqualify the PR — it just helps reviewers focus their attention. See
`docs/CONTRIBUTORS.md` for the project's AI assistance policy.
-->
- [ ] This change was produced with significant AI assistance
- [ ] This change is human-authored (no meaningful AI involvement)
- [ ] `dotnet build CaptureImage.sln -c Release` passes (warnings are errors)
- [ ] `dotnet test --solution CaptureImage.sln -c Release` passes
- [ ] New or changed behavior is covered by tests
- [ ] Tried it in the app (describe what you checked)
## Checklist
- [ ] I have read [`docs/CONTRIBUTORS.md`](../docs/CONTRIBUTORS.md) and agree to license this contribution under GPL-3.0-or-later.
- [ ] I have updated `CHANGELOG.md` under the appropriate section.
- [ ] I have updated localization resources if the UI changed (`Strings.resx` + `.vi.resx` + `.ar.resx`).
- [ ] My commits follow conventional-commits style (`feat(...)`, `fix(...)`, `docs(...)`, etc.).
- [ ] I have not committed secrets, credentials, or personal screenshots.
- [ ] I read [`CONTRIBUTING.md`](../CONTRIBUTING.md) and license this contribution under GPL-3.0-or-later.
- [ ] User-visible text is in all 11 `Strings*.resx` files (or I asked for help translating).
- [ ] `CHANGELOG.md` has an entry under `[Unreleased]` for user-visible changes.
- [ ] No secrets, credentials or personal screenshots are included.
- [ ] AI assistance, if any, is mentioned below.
## AI assistance
<!-- e.g. "Drafted with Claude Code, reviewed and tested by me", or "None". -->
-658
View File
@@ -1,658 +0,0 @@
"""
Discord webhook notification helper — phase 2.
Extends phase 1 with four new commands:
python discord_notify.py release # phase 1: release announcement
python discord_notify.py failure # phase 1: generic CI failure
python discord_notify.py deploy # phase 2: deploy success/fail
python discord_notify.py release-build # phase 2: release pipeline build status
python discord_notify.py dependabot-summary # phase 2: org-wide dependabot digest
python discord_notify.py weekly-digest # phase 2: org-wide weekly activity
Stdlib-only. Drop into .github/scripts/ in any repo.
"""
from __future__ import annotations
import json
import os
import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# ---------- Embed colors ----------
COLOR_RELEASE = 0x57F287 # green
COLOR_FAILURE = 0xED4245 # red
COLOR_PRERELEASE = 0xFEE75C # yellow
COLOR_DEPLOY_OK = 0x3BA55D # darker green (distinct from release)
COLOR_DEPLOY_FAIL = 0xE74C3C # darker red
COLOR_BUILD_OK = 0x5865F2 # blurple — neutral build success
COLOR_BUILD_FAIL = 0xED4245
COLOR_DEPENDABOT = 0xFAA61A # orange
COLOR_DIGEST = 0x9B59B6 # purple
# ---------- Truncation limits ----------
MAX_NOTES_CHARS = 1500
MAX_FIELD_VALUE = 1000
MAX_ASSETS_LISTED = 5
MAX_DIGEST_REPOS_PER_FIELD = 8
# ---------- Helpers ----------
def _post_webhook(url: str, payload: dict) -> bool:
"""POST a JSON payload to a Discord webhook. Returns True on 2xx."""
if not url:
print("[SKIP] No webhook URL provided.")
return False
url = url.replace("https://discordapp.com/", "https://discord.com/")
if "/webhooks/" in url and "/api/webhooks/" not in url:
url = url.replace("/webhooks/", "/api/webhooks/")
url = url.rstrip("/")
body = json.dumps(payload).encode("utf-8")
req = Request(
url,
data=body,
headers={
"Content-Type": "application/json",
"User-Agent": "poli0981-cicd/2.0 (+https://github.com/poli0981)",
},
)
try:
with urlopen(req, timeout=30) as resp:
print(f"[OK] Discord webhook posted (HTTP {resp.status}).")
return True
except HTTPError as e:
body_text = e.read().decode("utf-8", errors="replace")
print(f"[ERROR] Discord webhook: {e.code} — {body_text}")
return False
except URLError as e:
print(f"[ERROR] Discord webhook: {e}")
return False
def _gh_api(path: str, token: str, method: str = "GET", params: dict | None = None) -> dict | list:
"""Call GitHub REST API. Returns parsed JSON."""
base = "https://api.github.com"
url = f"{base}{path}"
if params:
url += "?" + urlencode(params)
req = Request(
url,
method=method,
headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "poli0981-cicd/2.0",
},
)
try:
with urlopen(req, timeout=30) as resp:
return json.loads(resp.read())
except HTTPError as e:
print(f"[ERROR] GitHub API {method} {path}: {e.code} — {e.read().decode('utf-8', errors='replace')}")
raise
except URLError as e:
print(f"[ERROR] GitHub API {method} {path}: {e}")
raise
def _gh_search(query: str, token: str, kind: str = "issues") -> list:
"""Run a GitHub search. Returns the items list (paginated, capped at 100)."""
result = _gh_api(f"/search/{kind}", token, params={"q": query, "per_page": 100})
if isinstance(result, dict):
return result.get("items", [])
return []
def _truncate(text: str, limit: int, suffix: str = "…") -> str:
if not text or len(text) <= limit:
return text or ""
cut = text[: limit - len(suffix)]
last_break = max(cut.rfind("\n"), cut.rfind(". "))
if last_break > limit * 0.6:
cut = cut[:last_break]
return cut.rstrip() + suffix
def _env(name: str, default: str = "") -> str:
return os.environ.get(name, default).strip()
def _required(name: str) -> str:
v = _env(name)
if not v:
print(f"[ERROR] Required env var not set: {name}")
sys.exit(1)
return v
# ---------- Phase 1: Release announcement ----------
def build_release_embed() -> dict:
repo = _required("GITHUB_REPOSITORY")
repo_name = repo.split("/", 1)[1]
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
tag = _required("RELEASE_TAG")
name = _env("RELEASE_NAME") or tag
body = _env("RELEASE_BODY")
html_url = _env("RELEASE_URL") or f"{server_url}/{repo}/releases/tag/{tag}"
is_prerelease = _env("RELEASE_PRERELEASE", "false").lower() == "true"
assets_raw = _env("RELEASE_ASSETS_JSON", "[]")
try:
assets = json.loads(assets_raw) if assets_raw else []
except json.JSONDecodeError:
assets = []
color = COLOR_PRERELEASE if is_prerelease else COLOR_RELEASE
badge = " (pre-release)" if is_prerelease else ""
description = _truncate(body, MAX_NOTES_CHARS) if body else "*No release notes provided.*"
fields = []
if assets:
priority_order = (".msi", ".exe", ".dmg", ".AppImage", ".deb", ".rpm", ".zip")
def asset_priority(a: dict) -> int:
n = a.get("name", "").lower()
for i, ext in enumerate(priority_order):
if n.endswith(ext.lower()):
return i
return len(priority_order)
sorted_assets = sorted(assets, key=asset_priority)[:MAX_ASSETS_LISTED]
asset_lines = []
for a in sorted_assets:
n = a.get("name", "asset")
u = a.get("browser_download_url") or a.get("url", "")
size_mb = a.get("size", 0) / (1024 * 1024) if a.get("size") else 0
size_str = f" ({size_mb:.1f} MB)" if size_mb > 0.1 else ""
asset_lines.append(f"• [{n}]({u}){size_str}")
if len(assets) > MAX_ASSETS_LISTED:
asset_lines.append(f"• … +{len(assets) - MAX_ASSETS_LISTED} more on the release page")
fields.append({
"name": "📥 Downloads",
"value": _truncate("\n".join(asset_lines), MAX_FIELD_VALUE),
"inline": False,
})
embed = {
"title": f"🚀 {repo_name} {tag}{badge}",
"url": html_url,
"description": description,
"color": color,
"fields": fields,
"footer": {"text": f"{repo} • {name}" if name != tag else repo},
"timestamp": _env("RELEASE_PUBLISHED_AT") or None,
}
return {k: v for k, v in embed.items() if v}
def post_release() -> int:
embed = build_release_embed()
repo = _required("GITHUB_REPOSITORY")
tag = _required("RELEASE_TAG")
webhooks = [w.strip() for w in _required("DISCORD_WEBHOOKS").split(",") if w.strip()]
payload = {"username": "Release Bot", "embeds": [embed]}
if _env("DISCORD_CONTENT"):
payload["content"] = _env("DISCORD_CONTENT")
print(f"[INFO] Announcing {repo}@{tag} to {len(webhooks)} webhook(s).")
failures = sum(1 for url in webhooks if not _post_webhook(url, payload))
if failures == len(webhooks):
return 1
return 0
# ---------- Phase 1: Generic CI failure ----------
def build_failure_embed() -> dict:
repo = _required("GITHUB_REPOSITORY")
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
workflow_name = _env("WORKFLOW_NAME", "Unknown workflow")
run_id = _required("RUN_ID")
run_number = _env("RUN_NUMBER", "?")
run_attempt = _env("RUN_ATTEMPT", "1")
branch = _env("BRANCH", "")
commit_sha = _env("COMMIT_SHA", "")
commit_short = commit_sha[:7] if commit_sha else "?"
commit_msg = _env("COMMIT_MESSAGE", "").splitlines()[0] if _env("COMMIT_MESSAGE") else ""
actor = _env("ACTOR", "")
event = _env("EVENT_NAME", "")
run_url = f"{server_url}/{repo}/actions/runs/{run_id}"
commit_url = f"{server_url}/{repo}/commit/{commit_sha}" if commit_sha else None
fields = [{"name": "Workflow", "value": f"`{workflow_name}` (run #{run_number}, attempt {run_attempt})", "inline": False}]
if branch:
fields.append({"name": "Branch", "value": f"`{branch}`", "inline": True})
if event:
fields.append({"name": "Trigger", "value": f"`{event}`", "inline": True})
if actor:
fields.append({"name": "Actor", "value": f"@{actor}", "inline": True})
if commit_sha:
commit_line = f"[`{commit_short}`]({commit_url})"
if commit_msg:
commit_line += f" — {_truncate(commit_msg, 100)}"
fields.append({"name": "Commit", "value": commit_line, "inline": False})
return {
"title": f"❌ CI failed: {repo}",
"url": run_url,
"description": f"**[View run logs →]({run_url})**",
"color": COLOR_FAILURE,
"fields": fields,
"footer": {"text": repo},
}
def post_failure() -> int:
embed = build_failure_embed()
webhook = _required("DISCORD_CI_WEBHOOK")
return 0 if _post_webhook(webhook, {"username": "CI Bot", "embeds": [embed]}) else 1
# ---------- Phase 2: Deploy alert ----------
def post_deploy() -> int:
"""
Post a deploy success/fail alert.
Distinct from generic CI failure: includes the deployed URL when known,
and uses 🌐 / 🚫 icons so the channel scan reads as deploys, not random builds.
Env:
DISCORD_CI_WEBHOOK — same channel as failure alerts (per user choice)
DEPLOY_STATUS — 'success' | 'failure'
DEPLOY_TARGET — e.g. 'GitHub Pages', 'Cloudflare Pages'
DEPLOY_URL — optional; live site URL when status=success
WORKFLOW_NAME, RUN_ID, BRANCH, COMMIT_SHA, COMMIT_MESSAGE, ACTOR — context
"""
repo = _required("GITHUB_REPOSITORY")
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
status = _env("DEPLOY_STATUS", "failure").lower()
target = _env("DEPLOY_TARGET", "deploy")
deploy_url = _env("DEPLOY_URL", "")
workflow_name = _env("WORKFLOW_NAME", "?")
run_id = _required("RUN_ID")
run_number = _env("RUN_NUMBER", "?")
branch = _env("BRANCH", "")
commit_sha = _env("COMMIT_SHA", "")
commit_short = commit_sha[:7] if commit_sha else "?"
commit_msg = _env("COMMIT_MESSAGE", "").splitlines()[0] if _env("COMMIT_MESSAGE") else ""
actor = _env("ACTOR", "")
run_url = f"{server_url}/{repo}/actions/runs/{run_id}"
commit_url = f"{server_url}/{repo}/commit/{commit_sha}" if commit_sha else None
if status == "success":
icon, color, verb = "🌐", COLOR_DEPLOY_OK, "deployed"
title = f"{icon} {target} deploy OK: {repo}"
else:
icon, color, verb = "🚫", COLOR_DEPLOY_FAIL, "deploy failed"
title = f"{icon} {target} deploy FAILED: {repo}"
description = f"**[View run logs →]({run_url})**"
if status == "success" and deploy_url:
description = f"**[Open live site →]({deploy_url})** • [run logs]({run_url})"
fields = [{"name": "Workflow", "value": f"`{workflow_name}` (run #{run_number})", "inline": False}]
if branch:
fields.append({"name": "Branch", "value": f"`{branch}`", "inline": True})
if actor:
fields.append({"name": "Actor", "value": f"@{actor}", "inline": True})
if commit_sha:
commit_line = f"[`{commit_short}`]({commit_url})"
if commit_msg:
commit_line += f" — {_truncate(commit_msg, 100)}"
fields.append({"name": "Commit", "value": commit_line, "inline": False})
embed = {
"title": title,
"url": run_url,
"description": description,
"color": color,
"fields": fields,
"footer": {"text": repo},
}
webhook = _required("DISCORD_CI_WEBHOOK")
return 0 if _post_webhook(webhook, {"username": "Deploy Bot", "embeds": [embed]}) else 1
# ---------- Phase 2: Release pipeline build status ----------
def post_release_build() -> int:
"""
Post a release-pipeline build status (Velopack / Tauri matrix etc.).
Both success and failure post — channel is #release-pipeline (low-volume,
only fires during release tag pushes).
Env:
DISCORD_RELEASE_PIPELINE_WEBHOOK — webhook for #release-pipeline
BUILD_STATUS — 'success' | 'failure' | 'cancelled'
BUILD_PLATFORM — e.g. 'win-x64', 'macos-14', 'ubuntu-latest'
BUILD_PACKAGER — optional; e.g. 'Velopack', 'Tauri'
RELEASE_TAG — the tag that triggered the build
WORKFLOW_NAME, RUN_ID, BRANCH, ACTOR
"""
repo = _required("GITHUB_REPOSITORY")
repo_name = repo.split("/", 1)[1]
server_url = _env("GITHUB_SERVER_URL", "https://github.com")
status = _env("BUILD_STATUS", "failure").lower()
platform = _env("BUILD_PLATFORM", "?")
packager = _env("BUILD_PACKAGER", "")
tag = _env("RELEASE_TAG", "")
workflow_name = _env("WORKFLOW_NAME", "?")
run_id = _required("RUN_ID")
run_url = f"{server_url}/{repo}/actions/runs/{run_id}"
if status == "success":
icon, color = "✅", COLOR_BUILD_OK
verb = "OK"
elif status == "cancelled":
icon, color = "⚠️", COLOR_PRERELEASE
verb = "cancelled"
else:
icon, color = "❌", COLOR_BUILD_FAIL
verb = "FAILED"
packager_str = f" {packager}" if packager else ""
title_tag = f" {tag}" if tag else ""
title = f"{icon} {repo_name}{title_tag} —{packager_str} {platform} {verb}"
fields = [{"name": "Workflow", "value": f"`{workflow_name}`", "inline": False}]
if tag:
fields.append({"name": "Tag", "value": f"`{tag}`", "inline": True})
fields.append({"name": "Platform", "value": f"`{platform}`", "inline": True})
if packager:
fields.append({"name": "Packager", "value": packager, "inline": True})
embed = {
"title": title,
"url": run_url,
"description": f"**[View build logs →]({run_url})**",
"color": color,
"fields": fields,
"footer": {"text": repo},
}
webhook = _required("DISCORD_RELEASE_PIPELINE_WEBHOOK")
return 0 if _post_webhook(webhook, {"username": "Build Bot", "embeds": [embed]}) else 1
# ---------- Phase 2: Dependabot consolidator ----------
def _list_org_repos(owner: str, token: str) -> list[dict]:
"""List all repos owned by `owner` (user or org). Paginated, capped at 200."""
repos: list[dict] = []
for page in range(1, 3): # 100 per page × 2 pages = 200 max
# `/users/{owner}/repos` works for users; for orgs use `/orgs/{owner}/repos`.
# Try user endpoint first, fall back to org if 404.
try:
page_repos = _gh_api(f"/users/{owner}/repos", token, params={"per_page": 100, "page": page, "type": "owner"})
except HTTPError:
page_repos = _gh_api(f"/orgs/{owner}/repos", token, params={"per_page": 100, "page": page})
if not isinstance(page_repos, list) or not page_repos:
break
repos.extend(page_repos)
if len(page_repos) < 100:
break
return repos
def post_dependabot_summary() -> int:
"""
Daily Dependabot summary across all repos.
Lists open PRs authored by 'dependabot[bot]', grouped by repo. If zero PRs,
posts a quiet 'all clean' message (configurable).
Env:
DISCORD_DEPENDABOT_WEBHOOK — webhook for #dependabot
OPS_GH_TOKEN — PAT with `repo` scope (or fine-grained read across all repos)
GH_OWNER — GitHub username (e.g. 'poli0981')
QUIET_WHEN_EMPTY — 'true' to skip posting when zero PRs (default: false)
"""
webhook = _required("DISCORD_DEPENDABOT_WEBHOOK")
token = _required("OPS_GH_TOKEN")
owner = _required("GH_OWNER")
quiet_when_empty = _env("QUIET_WHEN_EMPTY", "false").lower() == "true"
# Use search API to find all open dependabot PRs across owner's repos in one call.
# Search is rate-limited at 30 req/min for authenticated users — well under that.
query = f"is:open is:pr author:app/dependabot user:{owner}"
print(f"[INFO] Searching: {query}")
items = _gh_search(query, token)
print(f"[INFO] Found {len(items)} open Dependabot PR(s).")
if not items and quiet_when_empty:
print("[INFO] No PRs and QUIET_WHEN_EMPTY=true; skipping post.")
return 0
# Group by repo
by_repo: dict[str, list[dict]] = defaultdict(list)
for item in items:
# repository_url is "https://api.github.com/repos/{owner}/{name}"
repo_url = item.get("repository_url", "")
repo_full = repo_url.rsplit("/repos/", 1)[-1] if "/repos/" in repo_url else "unknown"
by_repo[repo_full].append(item)
fields = []
for repo_full in sorted(by_repo.keys()):
prs = by_repo[repo_full]
# Sort: oldest first within a repo, so stale ones are visible
prs.sort(key=lambda p: p.get("created_at", ""))
lines = []
for pr in prs[:5]: # cap per repo to keep field under 1024
title = _truncate(pr.get("title", ""), 80)
number = pr.get("number", "?")
url = pr.get("html_url", "")
created = pr.get("created_at", "")
try:
age_days = (datetime.now(timezone.utc) - datetime.fromisoformat(created.replace("Z", "+00:00"))).days
age_str = f" ({age_days}d)" if age_days >= 1 else " (today)"
except (ValueError, AttributeError):
age_str = ""
lines.append(f"• [#{number}]({url}) {title}{age_str}")
if len(prs) > 5:
lines.append(f"• … +{len(prs) - 5} more")
fields.append({
"name": f"{repo_full} ({len(prs)})",
"value": _truncate("\n".join(lines), MAX_FIELD_VALUE),
"inline": False,
})
# Discord caps embeds at 25 fields; truncate gracefully
if len(fields) >= 24 and len(by_repo) > 24:
remaining_repos = len(by_repo) - 24
remaining_prs = sum(len(by_repo[r]) for r in sorted(by_repo.keys())[24:])
fields.append({
"name": "…and more",
"value": f"+{remaining_prs} PR(s) in {remaining_repos} other repo(s)",
"inline": False,
})
break
if items:
title = f"🤖 Dependabot: {len(items)} open PR(s) across {len(by_repo)} repo(s)"
description = "Daily summary of open dependency-update PRs."
else:
title = "🤖 Dependabot: all clean"
description = "No open dependency-update PRs across any repo. ✨"
embed = {
"title": title,
"description": description,
"color": COLOR_DEPENDABOT,
"fields": fields,
"footer": {"text": f"{owner} • daily summary"},
"timestamp": datetime.now(timezone.utc).isoformat(),
}
return 0 if _post_webhook(webhook, {"username": "Dependabot Digest", "embeds": [embed]}) else 1
# ---------- Phase 2: Weekly digest ----------
def post_weekly_digest() -> int:
"""
Weekly activity digest. Aggregates last 7 days of:
- merged PRs
- closed issues
- releases published
- commits to default branches
Posted to #announcements (configurable).
Env:
DISCORD_DIGEST_WEBHOOK — webhook for #announcements
OPS_GH_TOKEN — PAT with read access
GH_OWNER — owner username
"""
webhook = _required("DISCORD_DIGEST_WEBHOOK")
token = _required("OPS_GH_TOKEN")
owner = _required("GH_OWNER")
since = (datetime.now(timezone.utc) - timedelta(days=7)).strftime("%Y-%m-%d")
print(f"[INFO] Aggregating activity since {since} for {owner}")
# Use search for merged PRs and closed issues — fastest cross-repo aggregation
merged_prs = _gh_search(f"user:{owner} is:pr is:merged merged:>={since}", token)
closed_issues = _gh_search(f"user:{owner} is:issue is:closed closed:>={since}", token)
# Releases: list per repo via the repos endpoint, filter by published_at locally.
# GitHub search doesn't index releases, so this is unavoidable.
repos = _list_org_repos(owner, token)
releases_by_repo: dict[str, list[dict]] = defaultdict(list)
since_dt = datetime.now(timezone.utc) - timedelta(days=7)
for repo in repos:
repo_full = repo.get("full_name", "")
if repo.get("archived") or repo.get("disabled"):
continue
try:
rels = _gh_api(f"/repos/{repo_full}/releases", token, params={"per_page": 10})
if isinstance(rels, list):
for r in rels:
pub = r.get("published_at")
if not pub:
continue
try:
pub_dt = datetime.fromisoformat(pub.replace("Z", "+00:00"))
except ValueError:
continue
if pub_dt >= since_dt:
releases_by_repo[repo_full].append(r)
except HTTPError:
continue # skip repos we can't read
# Top-active repos (by PR + issue count)
repo_activity: dict[str, int] = defaultdict(int)
for pr in merged_prs:
repo_full = pr.get("repository_url", "").rsplit("/repos/", 1)[-1]
repo_activity[repo_full] += 1
for iss in closed_issues:
repo_full = iss.get("repository_url", "").rsplit("/repos/", 1)[-1]
repo_activity[repo_full] += 1
fields = []
# Summary numbers
total_releases = sum(len(rs) for rs in releases_by_repo.values())
summary_lines = [
f"• **{len(merged_prs)}** PR(s) merged",
f"• **{len(closed_issues)}** issue(s) closed",
f"• **{total_releases}** release(s) published",
f"• Activity in **{len(repo_activity)}** repo(s)",
]
fields.append({
"name": "📊 Last 7 days",
"value": "\n".join(summary_lines),
"inline": False,
})
# Releases list
if releases_by_repo:
rel_lines = []
for repo_full in sorted(releases_by_repo.keys()):
for r in releases_by_repo[repo_full]:
tag = r.get("tag_name", "?")
url = r.get("html_url", "")
rel_lines.append(f"• [{repo_full} {tag}]({url})")
fields.append({
"name": f"🚀 Releases ({total_releases})",
"value": _truncate("\n".join(rel_lines), MAX_FIELD_VALUE),
"inline": False,
})
# Top active repos
if repo_activity:
top_repos = sorted(repo_activity.items(), key=lambda x: x[1], reverse=True)[:MAX_DIGEST_REPOS_PER_FIELD]
repo_lines = [f"• **{repo}**: {count} change(s)" for repo, count in top_repos]
fields.append({
"name": "🔥 Most active",
"value": _truncate("\n".join(repo_lines), MAX_FIELD_VALUE),
"inline": False,
})
embed = {
"title": f"📅 Weekly digest — week of {since}",
"description": f"Activity across @{owner}'s repos.",
"color": COLOR_DIGEST,
"fields": fields,
"footer": {"text": f"{owner} • weekly"},
"timestamp": datetime.now(timezone.utc).isoformat(),
}
return 0 if _post_webhook(webhook, {"username": "Weekly Digest", "embeds": [embed]}) else 1
# ---------- Entry point ----------
def main() -> int:
if len(sys.argv) < 2:
print("Usage: discord_notify.py <release|failure|deploy|release-build|dependabot-summary|weekly-digest>")
return 2
cmd = sys.argv[1].lower()
handlers = {
"release": post_release,
"failure": post_failure,
"deploy": post_deploy,
"release-build": post_release_build,
"dependabot-summary": post_dependabot_summary,
"weekly-digest": post_weekly_digest,
}
handler = handlers.get(cmd)
if not handler:
print(f"[ERROR] Unknown command: {cmd}")
return 2
return handler()
if __name__ == "__main__":
sys.exit(main())
+58
View File
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (c) CaptureImage Contributors
#
# Fails the CI `deadcode` job when JetBrains InspectCode reports dead or redundant
# code. Only file-local rules are gated: the `*.Global` variants produce false
# positives in a XAML + DI app (members used only from XAML bindings or resolved by
# the container), so they are listed in the job summary but never fail the build.
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $Sarif,
# Repository-relative path prefixes whose findings are ignored, separated by ';' or ','
# (a single string, because `pwsh -File` does not parse arrays).
[string] $ExcludePath = ''
)
$ErrorActionPreference = 'Stop'
$gatedRules = @(
'UnusedMember.Local', 'UnusedType.Local', 'UnusedParameter.Local',
'UnusedVariable', 'UnusedVariable.Compiler', 'NotAccessedVariable',
'NotAccessedField.Local', 'UnusedField.Compiler', 'UnusedAutoPropertyAccessor.Local',
'UnusedMethodReturnValue.Local', 'UnusedMemberInSuper.Local',
'NotAccessedPositionalProperty.Local', 'EmptyNamespace',
'RedundantUsingDirective', 'RedundantCast', 'RedundantSuppressNullableWarningExpression'
)
$reportedRules = @('UnusedMember.Global', 'UnusedType.Global', 'UnusedMethodReturnValue.Global')
$excluded = @($ExcludePath -split '[;,]' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$doc = Get-Content -Raw -LiteralPath $Sarif | ConvertFrom-Json
$results = @($doc.runs | ForEach-Object { $_.results })
$failures = @()
$informational = @()
foreach ($r in $results) {
$loc = $r.locations[0].physicalLocation
$path = $loc.artifactLocation.uri
if ($excluded | Where-Object { $path.StartsWith($_, [StringComparison]::OrdinalIgnoreCase) }) { continue }
$entry = [pscustomobject]@{ Rule = $r.ruleId; Path = $path; Line = $loc.region.startLine; Message = $r.message.text }
if ($gatedRules -contains $r.ruleId) { $failures += $entry }
elseif ($reportedRules -contains $r.ruleId) { $informational += $entry }
}
$summary = @(
'## InspectCode — dead code', '',
"Gated findings: **$($failures.Count)** · informational (``*.Global``): $($informational.Count)", ''
)
if ($failures.Count -gt 0) {
$summary += '| Rule | Location | Message |', '|---|---|---|'
foreach ($f in $failures) {
$summary += "| ``$($f.Rule)`` | ``$($f.Path):$($f.Line)`` | $($f.Message -replace '\|', '\|') |"
Write-Output "::error file=$($f.Path),line=$($f.Line),title=$($f.Rule)::$($f.Message)"
}
}
if ($env:GITHUB_STEP_SUMMARY) { $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8 }
else { $summary | Write-Output }
if ($failures.Count -gt 0) { exit 1 }
+46
View File
@@ -0,0 +1,46 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (c) CaptureImage Contributors
#
# `dotnet list package --vulnerable` exits 0 even when it finds vulnerable packages,
# so the CI `audit` job feeds its JSON output to this script, which fails on any
# finding (direct or transitive, any severity) and lists them in the job summary.
[CmdletBinding()]
param([Parameter(Mandatory)] [string] $Report)
$ErrorActionPreference = 'Stop'
$doc = Get-Content -Raw -LiteralPath $Report | ConvertFrom-Json
$rows = @()
foreach ($project in @($doc.projects)) {
foreach ($framework in @($project.frameworks)) {
foreach ($kind in 'topLevelPackages', 'transitivePackages') {
foreach ($package in @($framework.$kind)) {
foreach ($vuln in @($package.vulnerabilities)) {
if (-not $vuln) { continue }
$rows += [pscustomobject]@{
Project = [IO.Path]::GetFileNameWithoutExtension($project.path)
Package = $package.id
Version = $package.resolvedVersion
Severity = $vuln.severity
Advisory = $vuln.advisoryurl
}
}
}
}
}
}
$rows = @($rows | Sort-Object Package, Version, Advisory -Unique)
$summary = @('## NuGet vulnerability audit', '', "Vulnerable packages: **$($rows.Count)**", '')
if ($rows.Count -gt 0) {
$summary += '| Package | Version | Severity | Advisory | Project |', '|---|---|---|---|---|'
foreach ($r in $rows) {
$summary += "| $($r.Package) | $($r.Version) | $($r.Severity) | $($r.Advisory) | $($r.Project) |"
Write-Output "::error title=Vulnerable package::$($r.Package) $($r.Version) ($($r.Severity)) $($r.Advisory)"
}
}
if ($env:GITHUB_STEP_SUMMARY) { $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8 }
else { $summary | Write-Output }
if ($rows.Count -gt 0) { exit 1 }
+10 -9
View File
@@ -1,5 +1,8 @@
name: Announce Release to Discord
# Fires when a release is published. Releases are created as drafts by
# release.yml and published by the maintainer (`gh release edit --draft=false`),
# so this event is raised by a user token and actually triggers.
on:
release:
types: [published]
@@ -10,18 +13,16 @@ on:
required: true
type: string
# Reusable announce-release.yml only needs `contents: read` to fetch
# release metadata via the gh CLI.
permissions:
contents: read
permissions: {}
jobs:
announce:
# Pinned to commit SHA instead of @main — guards against a malicious or
# accidental push to poli0981/.github landing in our release pipeline
# silently. Dependabot bumps this weekly via the github-actions ecosystem
# rule in .github/dependabot.yml.
permissions:
contents: read
# Reusable workflows are pinned to a commit of poli0981/.github.
uses: poli0981/.github/.github/workflows/announce-release.yml@e973e2f15725356653ef07539016670ad2733f83
with:
tag_override: ${{ inputs.tag || '' }}
secrets: inherit
secrets:
DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }}
DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }}
+313 -32
View File
@@ -1,60 +1,341 @@
name: CI
# Build + test CaptureImage on every push to main and every pull request.
# Runs on windows-latest because the Infrastructure project targets
# net9.0-windows10.0.22621.0 and the WGC integration tests require a real
# desktop session with Windows 11 22H2 SDK.
# Minimum permissions required to checkout the repo and run dotnet
# build/test. No package writes, no release uploads, no PR comments.
permissions:
contents: read
# Every job name below is a required status check on `main` (repository ruleset).
# Keep job ids stable and never add `paths:` filters here: a required check that
# does not report leaves the pull request waiting forever.
on:
push:
branches: [ main ]
branches: [main]
pull_request:
branches: [ main ]
branches: [main]
workflow_dispatch:
# Cancel in-progress runs for the same ref when a new commit lands.
permissions: {}
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
build-test:
runs-on: windows-latest
timeout-minutes: 20
env:
DOTNET_NOLOGO: "true"
DOTNET_CLI_TELEMETRY_OPTOUT: "true"
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "true"
NUGET_PACKAGES: ${{ github.workspace }}/.nuget/packages
jobs:
build:
name: build
runs-on: windows-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0 # full history so MinVer / git describe works later
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@v5
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
# Honor global.json; avoids drift between local + CI.
global-json-file: global.json
cache: true
cache-dependency-path: "**/packages.lock.json"
- name: Print .NET version
run: dotnet --info
- name: Restore (locked)
run: dotnet restore CaptureImage.sln --locked-mode
- name: Restore
run: dotnet restore CaptureImage.sln
- name: Build (Release, warnings as errors)
run: dotnet build CaptureImage.sln -c Release --no-restore
- name: Build (Release, no restore)
run: dotnet build CaptureImage.sln -c Release --no-restore /p:TreatWarningsAsErrors=true /p:WarningsAsErrors=nullable
- name: Test (Microsoft.Testing.Platform + coverage)
run: >
dotnet test --solution CaptureImage.sln -c Release --no-build
--results-directory TestResults
--coverage --coverage-output-format cobertura
--report-xunit-trx
- name: Test
run: dotnet test CaptureImage.sln -c Release --no-build --logger "trx;LogFileName=test-results.trx" --results-directory ./TestResults
- name: Upload test results
- name: Coverage summary
if: always()
uses: actions/upload-artifact@v7
shell: pwsh
run: |
dotnet tool restore
dotnet reportgenerator "-reports:TestResults/*.cobertura.xml" "-targetdir:coverage-report" `
"-reporttypes:MarkdownSummaryGithub;Cobertura" "-assemblyfilters:+CaptureImage.*;-CaptureImage.*.Tests"
if (Test-Path coverage-report/SummaryGithub.md) {
Get-Content coverage-report/SummaryGithub.md | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
- name: Upload test results + coverage
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: test-results
path: ./TestResults/**/*.trx
path: |
TestResults/**/*.trx
coverage-report/**
retention-days: 14
format:
name: format
runs-on: windows-latest
timeout-minutes: 20
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
cache: true
cache-dependency-path: "**/packages.lock.json"
- name: Restore (locked)
run: dotnet restore CaptureImage.sln --locked-mode
- name: Whitespace / line endings
run: dotnet format whitespace CaptureImage.sln --no-restore --verify-no-changes
# Unused-member rules (IDE0051/0052/…) are enforced by the compiler in `build`,
# where XAML-generated code is visible; `dotnet format` cannot see it.
- name: Code style (SPDX header, namespaces, usings)
run: >
dotnet format style CaptureImage.sln --no-restore --verify-no-changes
--diagnostics IDE0073 IDE0161 IDE0065 IDE0005
deadcode:
name: deadcode
runs-on: windows-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
cache: true
cache-dependency-path: "**/packages.lock.json"
# One command per step: a pwsh step only fails when its last native command does.
- name: Restore
run: dotnet restore CaptureImage.sln --locked-mode
- name: Build
run: dotnet build CaptureImage.sln -c Release --no-restore
- name: Restore tools
run: dotnet tool restore
# Quoted: PowerShell splits a dash-prefixed native argument at its first period.
- name: JetBrains InspectCode
run: >
dotnet jb inspectcode CaptureImage.sln "--output=inspectcode.sarif" "--format=Sarif"
"--severity=SUGGESTION" "--properties:Configuration=Release" --no-build
- name: Gate on dead / redundant code
shell: pwsh
run: ./.github/scripts/inspectcode-gate.ps1 -Sarif inspectcode.sarif
- name: Upload InspectCode report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: inspectcode
path: inspectcode.sarif
retention-days: 14
# audit and license restore on Windows like the build: NuGet prunes the WPF projects'
# Windows Desktop packages only there, so a Linux restore can't match the lock files.
audit:
name: audit
runs-on: windows-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
- name: Restore (locked)
run: dotnet restore CaptureImage.sln --locked-mode
- name: Vulnerable packages (direct + transitive)
shell: pwsh
run: |
dotnet list CaptureImage.sln package --vulnerable --include-transitive --format json --output-version 1 > vulnerable.json
./.github/scripts/vulnerability-gate.ps1 -Report vulnerable.json
- name: Deprecated / outdated packages (report only)
if: always()
shell: pwsh
run: |
"## Deprecated packages`n" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
'```' | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
dotnet list CaptureImage.sln package --deprecated --include-transitive | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
'```' | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
license:
name: license
runs-on: windows-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
- name: Restore (locked)
run: dotnet restore CaptureImage.sln --locked-mode
- name: Restore tools
run: dotnet tool restore
# Only the shipped app's dependency closure is checked against the allowlist —
# build/test-only tooling never reaches users.
- name: Licenses of shipped dependencies
run: >
dotnet nuget-license -i src/CaptureImage.App/CaptureImage.App.csproj -t
-a .github/license/allowed-licenses.json
-ignore .github/license/ignored-packages.json
-o Markdown -fo license-report.md
- name: License report
if: always()
shell: pwsh
run: |
if (Test-Path license-report.md) {
"## Licenses of shipped dependencies`n" | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
Get-Content license-report.md | Out-File $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
publish-smoke:
name: publish-smoke
runs-on: windows-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
cache: true
cache-dependency-path: "**/packages.lock.json"
- name: Publish app (same switches as the release workflow)
run: >
dotnet publish src/CaptureImage.App/CaptureImage.App.csproj
-c Release -r win-x64 --self-contained false
-o publish
- name: Verify published payload
shell: pwsh
run: |
$required = @(
'CaptureImage.App.exe', 'CaptureImage.App.dll', 'CaptureImage.App.runtimeconfig.json',
'Wpf.Ui.dll', 'LICENSE', 'NOTICE',
'docs/legal/DISCLAIMER.md', 'docs/legal/PRIVACY.md', 'docs/legal/TERMS.md',
'docs/legal/THIRD_PARTY_NOTICES.md', 'docs/CONTRIBUTORS.md',
'vi/CaptureImage.ViewModels.resources.dll', 'ar/CaptureImage.ViewModels.resources.dll'
)
$missing = $required | Where-Object { -not (Test-Path (Join-Path publish $_)) }
if ($missing) { $missing | ForEach-Object { "::error title=publish-smoke::missing $_" }; exit 1 }
$size = (Get-ChildItem publish -Recurse -File | Measure-Object Length -Sum).Sum / 1MB
"publish-smoke: payload OK ({0:N1} MB)" -f $size
# Starts the published app with a throwaway data folder, opens every page,
# saves a screenshot of each and exits 0 (non-zero on any failure).
- name: Smoke test the published app
shell: pwsh
run: |
$data = Join-Path $env:RUNNER_TEMP 'smoke-data'
$shots = Join-Path $env:RUNNER_TEMP 'screenshots'
$app = Start-Process -FilePath publish/CaptureImage.App.exe -PassThru `
-ArgumentList @('--screenshots', $shots, '--data-dir', $data, '--instance-id', 'ci')
if (-not $app.WaitForExit(180000)) { $app.Kill(); "::error title=publish-smoke::the app did not exit within 3 minutes"; exit 1 }
Get-ChildItem (Join-Path $data 'logs') -Filter *.log | Get-Content
if ($app.ExitCode -ne 0) { "::error title=publish-smoke::smoke test exited with $($app.ExitCode)"; exit 1 }
$pages = @(Get-ChildItem $shots -Filter *.png).Count
if ($pages -lt 7) { "::error title=publish-smoke::expected 7 page screenshots, got $pages"; exit 1 }
"smoke test OK: $pages pages"
- name: Upload page screenshots
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: screenshots
path: ${{ runner.temp }}/screenshots
retention-days: 14
if-no-files-found: ignore
# End-to-end UI tests (FlaUI) against the real app.
ui-tests:
name: ui-tests
runs-on: windows-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
cache: true
cache-dependency-path: "**/packages.lock.json"
- name: Restore + build
run: |
dotnet restore CaptureImage.sln --locked-mode
dotnet build tests/CaptureImage.App.UiTests/CaptureImage.App.UiTests.csproj -c Release --no-restore
- name: UI tests (FlaUI)
env:
CAPTUREIMAGE_UI_TESTS: "1"
run: >
dotnet test --project tests/CaptureImage.App.UiTests/CaptureImage.App.UiTests.csproj
-c Release --no-build --results-directory TestResults-ui --report-xunit-trx
- name: Upload UI test results
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ui-test-results
path: TestResults-ui/**
retention-days: 14
if-no-files-found: ignore
+40
View File
@@ -0,0 +1,40 @@
name: Dependency review
# Blocks pull requests that introduce a vulnerable dependency (any severity) or a
# dependency under a license that cannot be combined with GPL-3.0-or-later.
# `dependency-review` is a required status check.
on:
pull_request:
branches: [main]
permissions: {}
concurrency:
group: dependency-review-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
dependency-review:
name: dependency-review
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
pull-requests: write # summary comment on failure
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Review dependency changes
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
with:
fail-on-severity: low
license-check: true
deny-licenses: >-
SSPL-1.0, BUSL-1.1, Elastic-2.0, CC-BY-NC-1.0, CC-BY-NC-2.0, CC-BY-NC-2.5,
CC-BY-NC-3.0, CC-BY-NC-4.0, CC-BY-NC-SA-4.0, CC-BY-NC-ND-4.0,
JSON, CPOL-1.02
comment-summary-in-pr: on-failure
+9 -6
View File
@@ -17,13 +17,14 @@ on:
# `discussions: write` is the only scope required to add a discussion comment
# via the GraphQL `addDiscussionComment` mutation. Default everything else to
# read so a compromised step can't push code or open releases.
permissions:
contents: read
discussions: write
permissions: {}
jobs:
welcome:
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
discussions: write
# Skip greetings for OWNER / COLLABORATOR / MEMBER — the maintainer and
# any future collaborators don't need a venue cheat-sheet on their own
# threads.
@@ -34,7 +35,7 @@ jobs:
steps:
- name: Add welcome comment
uses: actions/github-script@v7
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const body = [
@@ -43,15 +44,17 @@ jobs:
"**Tiếng Việt**",
"",
"- Báo lỗi (crash, capture lỗi, OCR sai, hotkey không hoạt động): dùng nút **About → Report a bug** ngay trong app, hoặc mở [bug-report template](https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml). Issue tracker yêu cầu các field (Windows build, GPU, log snippet) cần để debug nhanh.",
"- Lỗi bảo mật (security vulnerability): **không** post công khai — báo riêng qua [GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new).",
"- Lỗi bảo mật (security vulnerability): **không** post công khai — báo riêng qua [GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new) hoặc email **security@poli0981.dev**.",
"- Câu hỏi sử dụng, ý tưởng, show & tell: bạn đang ở đúng chỗ rồi.",
"",
"**English**",
"",
"- Bug reports (crash, broken capture, OCR mistakes, hotkey not firing): use the **About → Report a bug** button in-app, or open the [bug-report template](https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml). The issue tracker requires the fields (Windows build, GPU, log snippet) needed to debug.",
"- Security vulnerabilities: please **don't** post publicly — file privately via [GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new).",
"- Security vulnerabilities: please **don't** post publicly — report privately via [GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new) or email **security@poli0981.dev**.",
"- Usage questions, ideas, show & tell: you're in the right place.",
"",
"Other ways to reach the maintainer: **contact@poli0981.dev** · https://poli0981.dev/links",
"",
"_posted automatically by [.github/workflows/discussion-welcome.yml](https://github.com/poli0981/captureimg/blob/main/.github/workflows/discussion-welcome.yml)_"
].join("\n");
+74
View File
@@ -0,0 +1,74 @@
name: Docs
# Markdown lint + link check. `docs` is a required status check and runs on every
# pull request; it only checks links inside the repository (offline) so external
# outages never block a merge. External links are checked weekly and reported.
on:
pull_request:
branches: [main]
push:
branches: [main]
schedule:
- cron: "17 3 * * 1" # Mondays 03:17 UTC
workflow_dispatch:
permissions: {}
concurrency:
group: docs-${{ github.ref }}
cancel-in-progress: true
jobs:
docs:
name: docs
if: github.event_name != 'schedule'
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: markdownlint
uses: DavidAnson/markdownlint-cli2-action@21c1be1b93ad9ed58fa840aacc3f279cde2a72ff # v24.2.0
with:
globs: |
**/*.md
!LICENSE
!**/bin/**
!**/obj/**
- name: Links inside the repository
uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0
with:
args: --config lychee.toml --offline --no-progress .
fail: true
output: lychee-offline.md
jobSummary: true
external-links:
name: external-links
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: All links (report only)
uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0
with:
args: >-
--config lychee.toml --no-progress --max-concurrency 4
--accept 200,206,429 .
fail: false
output: lychee-external.md
jobSummary: true
+17 -15
View File
@@ -1,25 +1,27 @@
name: Notify CI Failures
# Previously listened to `workflows: ["*"]`, which fired this caller on every
# workflow completion in the repo — every release run, every announce run,
# every notify run itself — and the Actions tab filled with skipped entries.
# Narrowed to the single workflow this is supposed to monitor: ci.yml (name
# "CI"). The job-level `if` further skips successful CI runs so the reusable
# isn't pulled in on green builds.
# Posts failed CI runs on `main` to Discord through the shared notifier in
# poli0981/.github. Only pushes made in this repository qualify — a fork's pull
# request also reports `head_branch == 'main'`, and its commit message must never
# reach the Discord channel.
on:
workflow_run:
workflow_run: # zizmor: ignore[dangerous-triggers] — read-only; no checkout of the triggering ref
workflows: ["CI"]
types: [completed]
# REQUIRED: declare permissions matching the reusable workflow's needs.
# Reusable needs `actions: read` to inspect workflow_run details.
permissions:
contents: read
actions: read
permissions: {}
jobs:
notify:
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
# Pinned to commit SHA — see comment in announce-release.yml.
if: >-
github.event.workflow_run.conclusion == 'failure'
&& github.event.workflow_run.event == 'push'
&& github.event.workflow_run.head_branch == 'main'
&& github.event.workflow_run.head_repository.full_name == github.repository
permissions:
contents: read
actions: read
# Reusable workflows are pinned to a commit of poli0981/.github.
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@e973e2f15725356653ef07539016670ad2733f83
secrets: inherit
secrets:
DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }}
+11 -11
View File
@@ -1,21 +1,21 @@
name: Notify Release Pipeline
# Previously listened to `workflows: ["*"]`. Narrowed to the actual release
# build workflow ("Release" — release.yml) so the Actions tab no longer fills
# with skipped runs after every CI / notify completion. announce-release.yml
# is intentionally NOT included here — it already posts to Discord on its own,
# routing it through this notifier too would double-post.
# Reports the outcome of each Release workflow run to Discord. The public release
# announcement itself comes from announce-release.yml when the draft is published.
on:
workflow_run:
workflow_run: # zizmor: ignore[dangerous-triggers] — read-only; no checkout of the triggering ref
workflows: ["Release"]
types: [completed]
permissions:
contents: read
actions: read
permissions: {}
jobs:
notify:
# Pinned to commit SHA — see comment in announce-release.yml.
if: github.event.workflow_run.head_repository.full_name == github.repository
permissions:
contents: read
actions: read
# Reusable workflows are pinned to a commit of poli0981/.github.
uses: poli0981/.github/.github/workflows/notify-release-pipeline.yml@e973e2f15725356653ef07539016670ad2733f83
secrets: inherit
secrets:
DISCORD_RELEASE_PIPELINE_WEBHOOK: ${{ secrets.DISCORD_RELEASE_PIPELINE_WEBHOOK }}
+41
View File
@@ -0,0 +1,41 @@
name: PR lint
# Squash merges use the pull request title as the commit subject, so the title must
# follow Conventional Commits. `pr-title` is a required status check.
on:
pull_request:
types: [opened, edited, synchronize, reopened]
permissions: {}
concurrency:
group: pr-lint-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
pr-title:
name: pr-title
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read
steps:
- name: Conventional Commits title
uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6.1.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
types: |
feat
fix
perf
refactor
docs
test
build
ci
chore
revert
style
requireScope: false
+200 -133
View File
@@ -1,176 +1,243 @@
name: Release
# 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.
# Builds a release from a `vX.Y.Z[-pre]` tag and uploads it as a DRAFT GitHub
# Release. Velopack clients (`prerelease: false`) never see drafts, so the
# maintainer can verify the assets before publishing with
# `gh release edit <tag> --draft=false` — publishing with a user token also fires
# `release: published`, which runs announce-release.yml.
#
# Code signing is NOT performed yet (SignPath application was declined).
# The installer will trigger Windows SmartScreen "Unknown publisher" until
# a signing cert is available. Users can verify the build manually by
# comparing SHA256 sums — see docs/RELEASING.md §5.
# Re-running for an existing tag (the tag ruleset forbids moving tags) works through
# workflow_dispatch: it checks out the requested tag with the workflow as it is on
# the default branch. `dry_run` builds and packs without touching any release.
#
# Code signing is not available yet (SignPath declined the application); every
# asset gets a SHA-256 checksum and a GitHub build-provenance attestation instead.
on:
push:
tags:
- "v*"
tags: ["v*"]
workflow_dispatch:
inputs:
version:
description: "Version to release (without leading v, e.g. 1.0.0)"
tag:
description: "Existing release tag to build, e.g. v2.0.0"
required: true
type: string
dry_run:
description: "Build and pack only (no GitHub Release)"
type: boolean
default: true
permissions: {}
concurrency:
group: release-${{ github.ref }}
group: release-${{ inputs.tag || github.ref_name }}
cancel-in-progress: false
permissions:
contents: write # needed to create a GitHub Release
env:
DOTNET_NOLOGO: "true"
DOTNET_CLI_TELEMETRY_OPTOUT: "true"
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "true"
# Must stay identical across releases so installed copies keep updating and
# existing shortcuts stay valid.
PACK_ID: CaptureImage
PACK_TITLE: CaptureImage
MAIN_EXE: CaptureImage.App.exe
CHANNEL: win
# Installed by Setup / the updater when missing (the app is framework-dependent).
RUNTIME: net10-x64-desktop
jobs:
release:
build:
name: build
runs-on: windows-latest
timeout-minutes: 30
env:
PACK_ID: CaptureImage
MAIN_EXE: CaptureImage.App.exe
timeout-minutes: 45
permissions:
contents: read
outputs:
tag: ${{ steps.version.outputs.tag }}
version: ${{ steps.version.outputs.version }}
prerelease: ${{ steps.version.outputs.prerelease }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Resolve version
- name: Resolve and validate the tag
id: version
shell: pwsh
env:
EVENT_NAME: ${{ github.event_name }}
INPUT_TAG: ${{ inputs.tag }}
REF_NAME: ${{ github.ref_name }}
run: |
if ($env:GITHUB_REF -like "refs/tags/v*") {
$v = $env:GITHUB_REF -replace "^refs/tags/v", ""
} elseif ("${{ github.event.inputs.version }}" -ne "") {
$v = "${{ github.event.inputs.version }}"
} else {
throw "No tag and no manual version supplied."
}
Write-Host "Resolved version: $v"
"version=$v" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
$tag = if ($env:EVENT_NAME -eq 'workflow_dispatch') { $env:INPUT_TAG } else { $env:REF_NAME }
$semver = '^v(?<v>(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?)$'
if ($tag -notmatch $semver) { throw "Not a SemVer release tag: '$tag'" }
$version = $Matches.v
"tag=$tag" | Out-File $env:GITHUB_OUTPUT -Append -Encoding utf8
"version=$version" | Out-File $env:GITHUB_OUTPUT -Append -Encoding utf8
"prerelease=$($version.Contains('-').ToString().ToLowerInvariant())" | Out-File $env:GITHUB_OUTPUT -Append -Encoding utf8
- name: Checkout the tag
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: refs/tags/${{ steps.version.outputs.tag }}
persist-credentials: false
- name: Tag must match Directory.Build.props
shell: pwsh
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
[xml]$props = Get-Content Directory.Build.props
$declared = @($props.Project.PropertyGroup | ForEach-Object { $_.Version } | Where-Object { $_ })[0]
if ($declared -ne $env:VERSION) { throw "Tag version $env:VERSION does not match Directory.Build.props ($declared)." }
# No NuGet cache here: a poisoned cache must never reach release binaries.
- name: Setup .NET
uses: actions/setup-dotnet@v5
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
- name: Restore + test
run: |
dotnet restore CaptureImage.sln
dotnet test CaptureImage.sln -c Release --logger "trx;LogFileName=test-results.trx" --results-directory ./TestResults
# One command per step: a pwsh step only fails when its last native command does.
- name: Restore
run: dotnet restore CaptureImage.sln --locked-mode
- 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.
- name: Build
run: dotnet build CaptureImage.sln -c Release --no-restore
- name: Test
run: dotnet test --solution CaptureImage.sln -c Release --no-build
- name: Restore tools
run: dotnet tool restore
# Framework-dependent: Setup installs the .NET Desktop Runtime when it is missing.
- name: Publish app
run: >
dotnet publish src/CaptureImage.App/CaptureImage.App.csproj
-c Release
-r win-x64
--self-contained
/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
-o ./publish
-c Release -r win-x64 --self-contained false
-o publish
- name: Install Velopack CLI
run: dotnet tool install --global vpk
- name: Add dotnet tools to PATH
- name: Smoke test the published app
shell: pwsh
run: echo "$env:USERPROFILE\.dotnet\tools" | Out-File -FilePath $env:GITHUB_PATH -Append
- name: Download previous release (for delta generation)
# Velopack only emits a *-delta.nupkg when it finds a previous full package
# in --outputDir. Fetching the last GitHub release before pack gives the
# Update tab a working incremental path from n-1 → n. Safe to continue-on-error:
# a first-ever release has nothing to download and we just publish full.
shell: pwsh
continue-on-error: true
run: |
New-Item -ItemType Directory -Force -Path ./releases | Out-Null
vpk download github --repoUrl https://github.com/${{ github.repository }} --outputDir ./releases --channel win
$data = Join-Path $env:RUNNER_TEMP 'smoke-data'
$app = Start-Process -FilePath publish/CaptureImage.App.exe -PassThru `
-ArgumentList @('--smoke-test', '--data-dir', $data, '--instance-id', 'release')
if (-not $app.WaitForExit(180000)) { $app.Kill(); throw 'The app did not exit within 3 minutes.' }
if ($app.ExitCode -ne 0) {
Get-ChildItem (Join-Path $data 'logs') -Filter *.log | Get-Content
throw "Smoke test exited with $($app.ExitCode)."
}
- name: Release notes from CHANGELOG
shell: pwsh
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
$lines = Get-Content CHANGELOG.md
$start = [Array]::FindIndex($lines, [Predicate[string]] { param($l) $l -match "^## \[$([regex]::Escape($env:VERSION))\]" })
if ($start -lt 0) { throw "CHANGELOG.md has no section for $env:VERSION." }
$end = [Array]::FindIndex($lines, $start + 1, [Predicate[string]] { param($l) $l -match '^## \[' })
if ($end -lt 0) { $end = $lines.Length }
$lines[($start + 1)..($end - 1)] | Out-File release-notes.md -Encoding utf8
- name: Velopack pack
# --channel win produces the modern releases.win.json manifest alongside the
# legacy RELEASES file, which is what Velopack clients >= 0.0.900 poll for.
# --delta BestSize keeps the hotfix payload small (typical v1.1.0 → v1.1.1
# delta is a few MB vs the ~55 MB full).
run: >
vpk pack
--packId ${{ env.PACK_ID }}
--packVersion ${{ steps.version.outputs.version }}
--packDir ./publish
--mainExe ${{ env.MAIN_EXE }}
--outputDir ./releases
--channel win
--delta BestSize
- name: Compute SHA256 sums
shell: pwsh
env:
VERSION: ${{ steps.version.outputs.version }}
# Full packages only: deltas need the previous package and are not worth the
# extra moving parts for this app's size.
run: |
$outDir = "./releases"
Get-ChildItem $outDir -File | ForEach-Object {
$hash = (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLower()
"$hash $($_.Name)" | Out-File -FilePath "$outDir\SHA256SUMS.txt" -Append -Encoding utf8
}
Get-Content "$outDir\SHA256SUMS.txt"
dotnet vpk pack --packId $env:PACK_ID --packVersion $env:VERSION --packTitle $env:PACK_TITLE `
--packAuthors "poli0981 and contributors" --packDir publish --mainExe $env:MAIN_EXE `
--channel $env:CHANNEL --shortcuts "Desktop,StartMenuRoot" --delta None `
--framework $env:RUNTIME --icon src/CaptureImage.UI/Assets/CaptureImage.ico `
--releaseNotes release-notes.md --outputDir releases
- name: Upload release artifacts
uses: actions/upload-artifact@v7
- name: Collect assets, SBOM and checksums
shell: pwsh
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
New-Item -ItemType Directory dist | Out-Null
Get-ChildItem releases -File | Copy-Item -Destination dist
dotnet CycloneDX src/CaptureImage.App/CaptureImage.App.csproj --output dist `
--filename "CaptureImage-$env:VERSION-sbom.cdx.json" --output-format Json `
--set-name CaptureImage --set-version $env:VERSION --exclude-test-projects
Push-Location dist
Get-ChildItem -File | Sort-Object Name | ForEach-Object {
"$((Get-FileHash $_.Name -Algorithm SHA256).Hash.ToLowerInvariant()) $($_.Name)"
} | Out-File SHA256SUMS.txt -Encoding utf8
Get-Content SHA256SUMS.txt
Pop-Location
- name: Release body
shell: pwsh
env:
VERSION: ${{ steps.version.outputs.version }}
REPOSITORY: ${{ github.repository }}
run: |
$body = @(
"## CaptureImage v$env:VERSION", '',
(Get-Content release-notes.md -Raw), '',
'### Downloads',
'- **`CaptureImage-win-Setup.exe`** — installer (per-user). Windows 11 22H2 or later; installs the .NET 10 Desktop Runtime if it is missing.',
'- **`CaptureImage-win-Portable.zip`** — extract-and-run build without installer (needs the [.NET 10 Desktop Runtime](https://dotnet.microsoft.com/download/dotnet/10.0)).',
'- **`*-full.nupkg`**, **`releases.win.json`** — update feed used by the in-app updater.',
'- **`SHA256SUMS.txt`**, **`*-sbom.cdx.json`** — checksums and CycloneDX SBOM.', '',
'### Verify the download',
'The installer is not code-signed yet, so Windows SmartScreen shows "Unknown publisher".',
'Check the checksum or the build-provenance attestation before running it:', '',
'```powershell',
'Get-FileHash -Algorithm SHA256 .\CaptureImage-win-Setup.exe # compare with SHA256SUMS.txt',
"gh attestation verify .\CaptureImage-win-Setup.exe --repo $env:REPOSITORY",
'```'
)
$body | Out-File release-body.md -Encoding utf8
- name: Upload release payload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: captureimage-release-${{ steps.version.outputs.version }}
path: ./releases/**
name: release-${{ steps.version.outputs.version }}
path: |
dist/**
release-body.md
retention-days: 30
if-no-files-found: error
- name: Create / update GitHub Release
uses: softprops/action-gh-release@v3
if: startsWith(github.ref, 'refs/tags/v')
publish:
name: publish
needs: build
if: github.event_name == 'push' || !inputs.dry_run
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write # create / update the draft release
id-token: write # build provenance
attestations: write
steps:
- name: Download release payload
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: CaptureImage v${{ steps.version.outputs.version }}
tag_name: ${{ github.ref_name }}
draft: false
prerelease: false
generate_release_notes: true
files: |
./releases/*.exe
./releases/*.nupkg
./releases/*.zip
./releases/RELEASES
./releases/releases.*.json
./releases/SHA256SUMS.txt
body: |
## CaptureImage v${{ steps.version.outputs.version }}
name: release-${{ needs.build.outputs.version }}
Lightweight Windows screen capture for games without a built-in screenshot key.
- name: Attest build provenance
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: dist/*
### 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.
### Unsigned installer notice
This release is **not code-signed** yet (OSS signing application
pending). Windows SmartScreen will show an "Unknown publisher"
warning on first run. To verify the installer is unmodified:
1. Download `SHA256SUMS.txt` from this release.
2. Run `Get-FileHash -Algorithm SHA256 Setup.exe` in PowerShell.
3. Compare with the entry in `SHA256SUMS.txt`.
### Changelog
See [CHANGELOG.md](https://github.com/poli0981/captureimg/blob/v${{ steps.version.outputs.version }}/CHANGELOG.md).
- name: Create or update the draft release
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
TAG: ${{ needs.build.outputs.tag }}
VERSION: ${{ needs.build.outputs.version }}
PRERELEASE: ${{ needs.build.outputs.prerelease }}
run: |
set -euo pipefail
if gh release view "$TAG" >/dev/null 2>&1; then
gh release edit "$TAG" --notes-file release-body.md
gh release upload "$TAG" dist/* --clobber
else
flags=(--draft --verify-tag --title "CaptureImage v$VERSION" --notes-file release-body.md)
if [ "$PRERELEASE" = "true" ]; then flags+=(--prerelease); fi
gh release create "$TAG" "${flags[@]}" dist/*
fi
+43
View File
@@ -0,0 +1,43 @@
name: OpenSSF Scorecard
# Supply-chain posture report (branch protection, pinned dependencies, token
# permissions, …). Results are published to the Scorecard API and code scanning.
on:
push:
branches: [main]
schedule:
- cron: "41 4 * * 2" # Tuesdays 04:41 UTC
branch_protection_rule:
workflow_dispatch:
permissions: {}
jobs:
scorecard:
name: scorecard
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
actions: read
security-events: write # upload SARIF to code scanning
id-token: write # publish results to the Scorecard API
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run analysis
uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
with:
results_file: scorecard.sarif
results_format: sarif
publish_results: true
- name: Upload to code scanning
uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
with:
sarif_file: scorecard.sarif
category: scorecard
+52
View File
@@ -0,0 +1,52 @@
name: Workflow lint
# Syntax (actionlint) and security (zizmor) checks for everything under
# .github/workflows. Runs on every pull request because `workflow-lint` is a
# required status check — a path filter would leave unrelated PRs waiting.
on:
pull_request:
branches: [main]
push:
branches: [main]
permissions: {}
concurrency:
group: workflow-lint-${{ github.ref }}
cancel-in-progress: true
env:
ACTIONLINT_VERSION: "1.7.12"
jobs:
workflow-lint:
name: workflow-lint
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: actionlint
run: |
set -euo pipefail
base="https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}"
tarball="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz"
curl --proto "=https" --proto-redir "=https" --tlsv1.2 -fsSLO "${base}/${tarball}"
curl --proto "=https" --proto-redir "=https" --tlsv1.2 -fsSLO "${base}/actionlint_${ACTIONLINT_VERSION}_checksums.txt"
grep " ${tarball}\$" "actionlint_${ACTIONLINT_VERSION}_checksums.txt" | sha256sum -c -
tar -xzf "${tarball}" actionlint
./actionlint -color
- name: zizmor
uses: zizmorcore/zizmor-action@85b2b9fb8e3325e7a23d7d0a9d7ba5ae0f999e3e # v0.7.1
with:
version: "1.31.1"
advanced-security: false
annotations: true
persona: regular
+9 -6
View File
@@ -30,11 +30,11 @@ UpgradeLog*.XML
_UpgradeReport_Files/
_Pvt_Extensions/
# Rider / JetBrains (keep .idea for user, but ignore transient files)
.idea/workspace.xml
.idea/tasks.xml
.idea/shelf/
.idea/httpRequests/
# Rider / JetBrains — per-user IDE state, never committed.
.idea/
# Claude Code local state (session settings, worktrees).
.claude/
# Visual Studio Code
.vscode/
@@ -50,9 +50,12 @@ _Pvt_Extensions/
packages/
!packages/build/
# Test results
# Test results / coverage / build logs
TestResults/
coverage*.xml
*.cobertura.xml
coverage-report/
*.binlog
*.trx
*.coverage
*.coveragexml
+17
View File
@@ -0,0 +1,17 @@
{
// markdownlint rules for the CI `docs` job (https://github.com/DavidAnson/markdownlint).
"config": {
"default": true,
// Prose is wrapped by hand; tables and URLs make a hard limit impractical.
"MD013": false,
// README / docs use small bits of inline HTML (badges, <details>, <br>).
"MD033": false,
// Keep a Changelog repeats "### Added/Fixed/Changed" under every release.
"MD024": { "siblings_only": true },
// Bold lead-ins ("**Heads-up:** …") are intentional, not headings.
"MD036": false,
// Pipe alignment inside tables is cosmetic and churns on every edit.
"MD060": false
},
"ignores": ["LICENSE", "**/bin/**", "**/obj/**", "artifacts/**", "TestResults/**", "node_modules/**"]
}
+90 -2
View File
@@ -7,6 +7,93 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [2.0.0] - 2026-10-19
CaptureImage 2.0 is a rewrite of the app around the same idea: arm the hotkeys, press one in
your game, get a clean screenshot. Settings from 1.x are carried over automatically.
### Highlights
- **New interface** built with WPF and [WPF UI](https://github.com/lepoco/wpfui): Fluent design,
Mica, light / dark / high-contrast themes that follow Windows, resizable window that remembers
its position.
- **Three capture modes, each with its own hotkey** — Window (`Ctrl+Shift+F12`), Region
(`Ctrl+Shift+F11`) and Screen (`Ctrl+Shift+F10`). Region freezes every monitor and lets you drag
an area (a click takes the whole screen); Screen captures the monitor under the mouse pointer.
Works across monitors with different scaling.
- **HDR screenshots** — on HDR displays the full HDR frame is captured and tone-mapped to a normal
image; the original can be kept next to it as JPEG XR (`.jxr`).
- **Capture library** — browse every capture with thumbnails, filter by game or HDR, open, show in
folder, copy the image or its path, extract text (OCR), pin it on screen or move it to the
Recycle Bin.
- **Game profiles** — per-game output folder, format, file name template and HDR setting, matched
by executable path, executable name or Steam AppId. A profile can arm the hotkeys (and lock the
game window) as soon as the game comes to the front. Create one from the Dashboard in one click.
- **Start with Windows**, start minimized to the tray, arm on startup, export diagnostics,
import / export / reset settings.
- **11 languages** with every string translated, following the Windows display language on first
run; Arabic is laid out right to left.
### Changed
- Runs on **.NET 10 (LTS)**. The app is now framework-dependent: Setup (and the in-app updater)
installs the .NET 10 Desktop Runtime when it is missing, so the first update from 1.x may ask for
permission once. The installer shrank from about 100 MB to about 28 MB.
- **Hotkeys use the Windows `RegisterHotKey` API** and are registered only while armed. There is no
global keyboard or mouse hook any more, and while disarmed your key combinations reach other
apps untouched. Conflicts with other apps are detected and shown.
- The window list follows Windows events instead of polling WMI every two seconds.
- Settings, logs, the library index and thumbnails live in
`%LocalAppData%\poli0981\CaptureImage`, outside the installer's folder, so reinstalling never
wipes them. The 1.x `settings.json` is copied (the old file is left as it was) and migrated to
the new format.
- Notifications appear inside the window when it is in front, otherwise as a small pop-up that
never takes focus from a game and never shows up in screenshots.
- The tray icon shows a red dot while the hotkeys are armed; its menu can capture in every mode.
- The version is shown the same way everywhere, e.g. `2.0.0 (abc1234)`.
- Logs hide your user-profile path; window titles are logged only at the Debug level.
### Fixed
- Pressing Esc while selecting a region reported "Capture failed"; pressing the hotkey again during
a countdown could crash the app; an error during preview could leave it stuck.
- Captures could come out partly transparent, a new capture could overwrite an existing file, and
encoding ran on the UI thread (the window froze while saving 4K images).
- Region selection worked only on the primary monitor and was offset at scaling other than 100%.
- After a graphics-driver reset, captures failed until the app was restarted; a few native objects
leaked with every capture.
- Settings were not written atomically; a damaged file or one from a newer version was replaced by
defaults without a backup; unknown fields were dropped; importing skipped validation and accepted
network (UNC) paths.
- Notifications were invisible while the app was in the tray; the Import / Export buttons did
nothing; "Start minimized" was ignored; the app had no icon.
- A second Windows user running the app filled the log with warnings; the foreground-window
watcher could crash on exit.
- "Install update" ended the process without saving settings or removing the tray icon, and
release notes never reached the Update page.
- File names now avoid reserved device names (`CON`, `NUL`, …), invisible bidirectional and
zero-width characters, and names that are too long.
- Settings missing from the settings file — such as options added by an update — were turned off
or set to zero instead of taking their default values.
### Removed
- WinUI 3 / Windows App SDK, SharpHook, WMI, Stateless, ImageSharp and System.IO.Abstractions.
- "Auto-switch target on Alt+Tab": the Window hotkey captures the window in front unless you lock
one on the Dashboard.
- The list of social profiles in About; other channels are listed at <https://poli0981.dev/links>.
### Project
- Required pull-request checks: build and tests (with coverage), formatting, dead code, vulnerable
and incompatibly licensed dependencies, a smoke test of the published app, end-to-end UI tests,
PR title, dependency review, workflow lint and documentation links. CodeQL (extended queries), OpenSSF Scorecard and
SonarCloud also review every change.
- Releases ship a CycloneDX SBOM, SHA-256 checksums and GitHub build-provenance attestations, and are
published as drafts first.
- About and the documentation list the project contacts: `contact@poli0981.dev` and
<https://poli0981.dev/links>.
## [1.5.1] - 2026-05-11
Hotfix cycle. CI hardening, supply-chain pinning of reusable
@@ -259,6 +346,7 @@ auto-update users hit this on the first launch after Velopack restart.
### 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
@@ -574,7 +662,7 @@ intact.
surface).
- New `tests/CaptureImage.ViewModels.Tests/Preview/PreviewViewModelTests.cs`
covering the v1.1.2 M1 fix: Localization PropertyChanged forwarding
+ Dispose detachment.
- Dispose detachment.
## [1.1.1] - 2026-04-20
@@ -964,7 +1052,7 @@ Major shell rewire landing everything the spec calls "polish".
- `IconExtractor` — extracts the associated icon for an executable and encodes as
PNG bytes, cached by path.
- `GameDetector` (`IProcessDetector`) — composes WindowEnumerator + IconExtractor
+ ISteamDetector into a single `EnumerateTargetsAsync()` call.
- ISteamDetector into a single `EnumerateTargetsAsync()` call.
- `WmiProcessWatcher` (`IProcessWatcher`) — WMI `__InstanceCreationEvent` /
`__InstanceDeletionEvent` subscription over `Win32_Process`, 2s poll window.
- `AvaloniaUIDispatcher` — `IUIThreadDispatcher` implementation over
+115
View File
@@ -0,0 +1,115 @@
# CLAUDE.md
Guidance for AI coding assistants (Claude Code and similar) working in this repository. Human
contributors: see [CONTRIBUTING.md](CONTRIBUTING.md).
## What this is
CaptureImage — a tray-resident, hotkey-driven Windows screenshot tool for games
(Windows.Graphics.Capture + Direct3D 11). C# on **.NET 10**, WPF + WPF UI 4.x, GPL-3.0-or-later.
Solo maintainer: poli0981, who communicates in Vietnamese.
## Build, test, run
```powershell
dotnet restore CaptureImage.sln # lock files; CI uses --locked-mode
dotnet build CaptureImage.sln -c Release # warnings are errors; src/ uses AnalysisMode=Recommended
dotnet test --solution CaptureImage.sln -c Release --no-build # Microsoft.Testing.Platform (global.json)
dotnet run --project src/CaptureImage.App -c Release -- --data-dir .\.devdata --instance-id dev
```
- SDK pinned in `global.json` (10.0.401, `latestFeature`). Tests are xunit.v3 on
Microsoft.Testing.Platform: use `--report-xunit-trx` and
`--coverage --coverage-output-format cobertura` (there is no `--logger trx`).
- **Never run a dev build against real user data.** Always pass `--data-dir <temp>` and
`--instance-id <name>`; the installed app keeps its data in `%LocalAppData%\poli0981\CaptureImage`
(1.x kept it in `%LocalAppData%\CaptureImage`).
- `--smoke-test` opens every page and exits 0; `--screenshots <dir>` also writes a PNG per page
(handy for checking UI changes without driving the mouse).
- UI tests (`tests/CaptureImage.App.UiTests`, FlaUI) move the mouse and type; they skip unless
`CAPTUREIMAGE_UI_TESTS=1`. Don't run them on the maintainer's desktop.
- Local tools (`dotnet tool restore`): `vpk`, `jb` (InspectCode), `nuget-license`,
`reportgenerator`, `dotnet-CycloneDX`.
## Layout and layering rules
```text
src/CaptureImage.Core net10.0 — models, abstractions, settings migration, CaptureCoordinator; no Windows APIs
src/CaptureImage.Infrastructure Windows implementations (WGC/D3D11, RegisterHotKey, WinEvent, WIC/Skia, settings, Velopack, Serilog)
src/CaptureImage.ViewModels CommunityToolkit.Mvvm view models + Resources/Strings (11 languages); no UI-framework types
src/CaptureImage.UI WPF + WPF UI: App.xaml, windows, pages, overlays, toasts, tray, UI services
src/CaptureImage.App Main: Velopack hooks, single instance, Serilog, DI composition root
tests/* Core, Infrastructure, ViewModels tests + App.UiTests (FlaUI)
```
- Core and ViewModels stay free of UI-framework and `Windows.*` references; view models talk to
Core abstractions only (no `Process.Start`, file I/O or WPF types).
- Every resx key must exist in all 11 `Strings*.resx` files with the same `{0}` placeholders, and
every key must be used — `LocalizationCompletenessTests` enforces both.
- Central Package Management: versions live only in `Directory.Packages.props`; after changing
references run `dotnet restore --force-evaluate` and commit the `packages.lock.json` files.
- The version lives only in `Directory.Build.props` (`<Version>`).
## Code conventions
- Every `.cs` file starts with the SPDX header (IDE0073):
`// SPDX-License-Identifier: GPL-3.0-or-later` / `// Copyright (c) CaptureImage Contributors`.
- LF line endings (`.gitattributes` `eol=lf`), file-scoped namespaces, usings outside the namespace,
no unused members or usings (enforced at build), `[LoggerMessage]` source-generated logging.
- Run `dotnet format` only with the CI subsets: `dotnet format whitespace` and
`dotnet format style --diagnostics IDE0073 IDE0161 IDE0065 IDE0005`. A plain `dotnet format`
deletes XAML event handlers.
- Pass `CancellationToken`s through (SonarCloud S8949); tests use
`TestContext.Current.CancellationToken` (xUnit1051).
## Pitfalls already hit
- System.Text.Json source generation treats `init` properties as constructor parameters, so a
`[JsonExtensionData]` property must have a plain `set`.
- WPF UI: setting `Style` on a `ui:CardControl` (or `BasedOn="{StaticResource {x:Type …}}"`)
replaces its implicit style and hides header/icon — use `Margin` etc. instead. Pages need
`ScrollViewer.CanContentScroll="False"` or `NavigationView` wraps them in a ScrollViewer (lists lose
virtualization). `TitleBar.Header` replaces the title text. `NavigationViewItem` has no UIA Invoke
pattern.
- Never `Hide()`/`Close()`/`Shutdown()` from inside `Window.Closing`; defer with the dispatcher.
Exits go through `App.RequestExit()`.
- WPF projects exclude `System.IO` from implicit usings (`Path` clashes with `System.Windows.Shapes`).
## Pull requests and CI
- `main` is protected by a ruleset: PR required, signed commits, linear history, squash merge only
(PR title = commit subject, Conventional Commits), branch up to date, no bypass. Release tags `v*`
can't be moved or deleted.
- Required checks: `build`, `format`, `deadcode` (InspectCode, file-local rules), `audit`,
`license` (shipped dependencies vs `.github/license/allowed-licenses.json`), `publish-smoke`
(publish + `--smoke-test` + page screenshots artifact), `pr-title`, `dependency-review`,
`workflow-lint` (actionlint + zizmor), `docs` (markdownlint + offline lychee), `ui-tests` (FlaUI
against the built app), plus CodeQL via the code-scanning rule.
- Never add `paths:` filters to a workflow that provides a required check. Actions are pinned to
full commit SHAs with a `# vX.Y.Z` comment.
- SonarCloud (automatic analysis, project `poli0981_captureimg`) comments on PRs — fix what it
reports.
- Dependabot NuGet updates rely on `EnableWindowsTargeting=true` in `Directory.Build.props` (the
updater runs on Linux).
- NuGet prunes the WPF projects' Windows Desktop packages (System.Drawing.Common, EventLog, …) only
when restoring on Windows, so a Linux restore never matches the lock files. Jobs that restore run
on `windows-latest`; if a Dependabot PR fails `--locked-mode`, re-run
`dotnet restore CaptureImage.sln --force-evaluate` on Windows and push the lock files.
- README screenshots come from `--screenshots` with seeded demo data, rendered on a separate,
hidden desktop — never from a personal desktop, whose window titles show up on the Dashboard.
## Releases
1. Bump `<Version>` in `Directory.Build.props`; rename `## [Unreleased]` in `CHANGELOG.md` to
`## [x.y.z] - date` (it becomes the release and in-app update notes).
2. After the PR merges: `git tag -s vX.Y.Z -m "…"` and push the tag.
3. `release.yml` builds, tests, publishes framework-dependent, smoke-tests, packs with Velopack
(`packId CaptureImage`, `mainExe CaptureImage.App.exe`, channel `win`, `--framework
net10-x64-desktop` — never change the first three), attaches SBOM, SHA256SUMS and provenance
attestations, and creates a **draft** release.
4. Verify the draft (see `docs/RELEASING.md`), then `gh release edit vX.Y.Z --draft=false`.
## Contacts used in docs and the About page
`contact@poli0981.dev` (general) and <https://poli0981.dev/links>; role aliases at the same domain:
security@, privacy@, legal@, copyright@, dmca@, takedown@, code@, sponsor@, games@, collab@, press@.
+18
View File
@@ -0,0 +1,18 @@
# Code of Conduct
CaptureImage follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).
In short: be respectful and welcoming, assume good intent, give and accept constructive feedback
gracefully, and focus on what is best for the community. Harassment, insults, personal or political
attacks, sexualized language or imagery, and publishing others' private information are not
acceptable — in issues, discussions, pull requests, reviews or any other project space.
## Reporting
If you experience or witness unacceptable behavior, contact the maintainer at
`contact@poli0981.dev`. Reports are handled confidentially. The maintainer may remove, edit or
reject comments, commits, issues and other contributions that violate this code, and may
temporarily or permanently ban contributors for behavior they consider inappropriate, following the
enforcement guidelines of the Contributor Covenant.
This code applies in all project spaces and when someone represents the project in public.
+93
View File
@@ -0,0 +1,93 @@
# Contributing to CaptureImage
Thanks for wanting to help! Bug reports, translations, documentation fixes and code are all welcome.
Please follow the [Code of Conduct](CODE_OF_CONDUCT.md).
## Ways to help
- **Report a bug or suggest a feature** with the issue templates (see [`SUPPORT.md`](SUPPORT.md)).
- **Proofread a translation.** The user interface is translated into 11 languages, mostly with AI
assistance. Strings live in `src/CaptureImage.ViewModels/Resources/Strings/Strings.<language>.resx`
(English is `Strings.resx`). Keep every `{0}`-style placeholder and the names in `{Game}`-style
file-name tokens unchanged.
- **Fix a bug or build a feature.** For anything larger than a small fix, please open an issue or a
discussion first so we can agree on the approach.
## Development setup
- Windows 11 22H2 or later, 64-bit.
- The .NET 10 SDK version pinned in [`global.json`](global.json).
- Any editor; JetBrains Rider and Visual Studio 2026 both work.
```bash
dotnet build CaptureImage.sln -c Release
dotnet test --solution CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release -- --data-dir ./.devdata --instance-id dev
```
Use `--data-dir` and `--instance-id` so a development copy never touches your real settings or a
copy you have installed. [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) explains how the projects fit
together.
End-to-end UI tests move the mouse and type, so they only run with `CAPTUREIMAGE_UI_TESTS=1`:
```bash
CAPTUREIMAGE_UI_TESTS=1 dotnet test --project tests/CaptureImage.App.UiTests -c Release
```
## Pull requests
Every pull request must pass the required checks before it can be merged (squash merge only):
- **build** — warnings are errors, the recommended .NET analyzers are on for `src/`, all tests pass.
- **format** — `dotnet format whitespace` and the style rules below.
- **deadcode** — JetBrains InspectCode finds no unused or redundant code.
- **audit** / **license** — no vulnerable packages; shipped dependencies use a GPL-compatible
license.
- **publish-smoke** — the published app starts and opens every page.
- **ui-tests** — end-to-end tests drive the built app through UI Automation (FlaUI).
- **pr-title** — the title follows [Conventional Commits](https://www.conventionalcommits.org/), e.g.
`fix(capture): keep alpha opaque` or `feat(ui)!: …` for breaking changes.
- **dependency-review**, **workflow-lint**, **docs**.
Conventions:
- Every C# file starts with the SPDX header:
```csharp
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
```
- File-scoped namespaces, `using` directives outside the namespace, no unused usings.
- Logging uses source-generated `[LoggerMessage]` methods.
- Every user-visible string is a resource key with a translation in all 11 `.resx` files (a test
checks this). Add the English text and, if you can't translate, ask in the pull request.
- Packages are managed centrally in `Directory.Packages.props` with lock files; after changing a
dependency run `dotnet restore --force-evaluate` and commit the updated `packages.lock.json` files.
- Commits must be signed (GPG or SSH) — the `main` branch requires verified signatures.
Before pushing, the quick local check is:
```bash
dotnet build CaptureImage.sln -c Release
dotnet test --solution CaptureImage.sln -c Release
dotnet format whitespace CaptureImage.sln --verify-no-changes
dotnet format style CaptureImage.sln --verify-no-changes --diagnostics IDE0073 IDE0161 IDE0065 IDE0005
```
## AI-assisted contributions
AI tools are fine to use. Please mention it in the pull request, review everything you submit as if
you wrote it, and make sure it builds and passes the tests. Commits with meaningful AI authorship
should carry a `Co-Authored-By` trailer naming the model.
## License
By contributing you agree that your work is released under the
[GPL-3.0-or-later](LICENSE) license, and that you have the right to license it. Contributors are
listed in [`docs/CONTRIBUTORS.md`](docs/CONTRIBUTORS.md).
## Contact
Questions about contributing: `code@poli0981.dev`, or open a discussion.
+47 -47
View File
@@ -11,19 +11,19 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.Infrastructure
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.ViewModels", "src\CaptureImage.ViewModels\CaptureImage.ViewModels.csproj", "{0F060F46-7782-4686-8C12-56261A2876D6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.UI", "src\CaptureImage.UI\CaptureImage.UI.csproj", "{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.App", "src\CaptureImage.App\CaptureImage.App.csproj", "{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.Core.Tests", "tests\CaptureImage.Core.Tests\CaptureImage.Core.Tests.csproj", "{41DC8750-7186-494E-80BC-845C5071DF8F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.Infrastructure.Tests", "tests\CaptureImage.Infrastructure.Tests\CaptureImage.Infrastructure.Tests.csproj", "{679C3869-EE49-4A76-ADF2-431430B781E1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.ViewModels.Tests", "tests\CaptureImage.ViewModels.Tests\CaptureImage.ViewModels.Tests.csproj", "{65E8FCC7-53C0-4793-925F-3AB562EFC562}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.UI", "src\CaptureImage.UI\CaptureImage.UI.csproj", "{B151D050-4DEC-46A5-BB62-97578B2359BC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.App", "src\CaptureImage.App\CaptureImage.App.csproj", "{7885E645-F1F9-42EC-808A-69E1433FFCC9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.UI.Tests", "tests\CaptureImage.UI.Tests\CaptureImage.UI.Tests.csproj", "{C4E037B1-D055-4C6C-AAAF-3D814665D077}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptureImage.App.UiTests", "tests\CaptureImage.App.UiTests\CaptureImage.App.UiTests.csproj", "{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -71,30 +71,6 @@ Global
{0F060F46-7782-4686-8C12-56261A2876D6}.Release|x64.Build.0 = Release|Any CPU
{0F060F46-7782-4686-8C12-56261A2876D6}.Release|x86.ActiveCfg = Release|Any CPU
{0F060F46-7782-4686-8C12-56261A2876D6}.Release|x86.Build.0 = Release|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Debug|x64.ActiveCfg = Debug|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Debug|x64.Build.0 = Debug|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Debug|x86.ActiveCfg = Debug|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Debug|x86.Build.0 = Debug|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Release|Any CPU.Build.0 = Release|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Release|x64.ActiveCfg = Release|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Release|x64.Build.0 = Release|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Release|x86.ActiveCfg = Release|Any CPU
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3}.Release|x86.Build.0 = Release|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Debug|x64.ActiveCfg = Debug|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Debug|x64.Build.0 = Debug|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Debug|x86.ActiveCfg = Debug|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Debug|x86.Build.0 = Debug|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Release|Any CPU.Build.0 = Release|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Release|x64.ActiveCfg = Release|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Release|x64.Build.0 = Release|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Release|x86.ActiveCfg = Release|Any CPU
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3}.Release|x86.Build.0 = Release|Any CPU
{41DC8750-7186-494E-80BC-845C5071DF8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{41DC8750-7186-494E-80BC-845C5071DF8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{41DC8750-7186-494E-80BC-845C5071DF8F}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -131,18 +107,42 @@ Global
{65E8FCC7-53C0-4793-925F-3AB562EFC562}.Release|x64.Build.0 = Release|Any CPU
{65E8FCC7-53C0-4793-925F-3AB562EFC562}.Release|x86.ActiveCfg = Release|Any CPU
{65E8FCC7-53C0-4793-925F-3AB562EFC562}.Release|x86.Build.0 = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x64.ActiveCfg = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x64.Build.0 = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x86.ActiveCfg = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Debug|x86.Build.0 = Debug|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|Any CPU.Build.0 = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x64.ActiveCfg = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x64.Build.0 = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x86.ActiveCfg = Release|Any CPU
{C4E037B1-D055-4C6C-AAAF-3D814665D077}.Release|x86.Build.0 = Release|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Debug|x64.ActiveCfg = Debug|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Debug|x64.Build.0 = Debug|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Debug|x86.ActiveCfg = Debug|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Debug|x86.Build.0 = Debug|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Release|Any CPU.Build.0 = Release|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Release|x64.ActiveCfg = Release|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Release|x64.Build.0 = Release|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Release|x86.ActiveCfg = Release|Any CPU
{B151D050-4DEC-46A5-BB62-97578B2359BC}.Release|x86.Build.0 = Release|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Debug|x64.ActiveCfg = Debug|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Debug|x64.Build.0 = Debug|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Debug|x86.ActiveCfg = Debug|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Debug|x86.Build.0 = Debug|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Release|Any CPU.Build.0 = Release|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Release|x64.ActiveCfg = Release|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Release|x64.Build.0 = Release|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Release|x86.ActiveCfg = Release|Any CPU
{7885E645-F1F9-42EC-808A-69E1433FFCC9}.Release|x86.Build.0 = Release|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Debug|Any CPU.Build.0 = Debug|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Debug|x64.ActiveCfg = Debug|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Debug|x64.Build.0 = Debug|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Debug|x86.ActiveCfg = Debug|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Debug|x86.Build.0 = Debug|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Release|Any CPU.ActiveCfg = Release|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Release|Any CPU.Build.0 = Release|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Release|x64.ActiveCfg = Release|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Release|x64.Build.0 = Release|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Release|x86.ActiveCfg = Release|Any CPU
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -151,11 +151,11 @@ Global
{BE4B464E-F2AD-445F-A40A-1C8D9EF6CF5E} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{56963B42-4D6F-441F-9283-576526FF517A} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{0F060F46-7782-4686-8C12-56261A2876D6} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{B443C8B4-AD41-4016-BF6E-7F1C9FF4ABC3} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{19A8672D-1A5F-4120-A66E-F6BD2C8431E3} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{41DC8750-7186-494E-80BC-845C5071DF8F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{679C3869-EE49-4A76-ADF2-431430B781E1} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{65E8FCC7-53C0-4793-925F-3AB562EFC562} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{C4E037B1-D055-4C6C-AAAF-3D814665D077} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{41DC8750-7186-494E-80BC-845C5071DF8F} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{679C3869-EE49-4A76-ADF2-431430B781E1} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{65E8FCC7-53C0-4793-925F-3AB562EFC562} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{B151D050-4DEC-46A5-BB62-97578B2359BC} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{7885E645-F1F9-42EC-808A-69E1433FFCC9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{30BE110B-1E5E-4FBB-B498-4B68D11A0D97} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
EndGlobal
+36 -12
View File
@@ -1,36 +1,60 @@
<Project>
<PropertyGroup>
<!-- Language / compiler -->
<PropertyGroup Label="Language / compiler">
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningsAsErrors>nullable</WarningsAsErrors>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisLevel>latest</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<!-- Needed so IDE0005 (unnecessary using) is reported by the compiler, not only in the IDE.
CS1591 (missing XML doc on public members) stays muted below. -->
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<!-- Deterministic + source link friendly -->
<PropertyGroup Label="Reproducible restore + build">
<Deterministic>true</Deterministic>
<ContinuousIntegrationBuild Condition="'$(CI)' == 'true'">true</ContinuousIntegrationBuild>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<RestoreLockedMode Condition="'$(CI)' == 'true'">true</RestoreLockedMode>
<!-- Dependabot's NuGet updater runs on Linux. Without this, every Windows-TFM project fails
to evaluate there and every newer package version is reported "not compatible", so no
update PR is ever opened. Harmless on Windows. -->
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<!-- The app ships for win-x64 only. Declaring the RID for every project keeps each
packages.lock.json identical between a plain `dotnet restore` and the
`dotnet publish -r win-x64` restore, so locked mode works for both. -->
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
</PropertyGroup>
<!-- Assembly / product info -->
<PropertyGroup Label="Supply chain">
<NuGetAudit>true</NuGetAudit>
<NuGetAuditMode>all</NuGetAuditMode>
<NuGetAuditLevel>low</NuGetAuditLevel>
</PropertyGroup>
<PropertyGroup Label="Version (single source of truth — the release workflow checks the tag against it)">
<Version>2.0.0</Version>
<AssemblyVersion>$([System.Text.RegularExpressions.Regex]::Match('$(Version)', '^\d+\.\d+\.\d+').Value).0</AssemblyVersion>
<FileVersion>$(AssemblyVersion)</FileVersion>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
</PropertyGroup>
<PropertyGroup Label="Product metadata">
<Product>CaptureImage</Product>
<Company>CaptureImage Contributors</Company>
<Authors>poli0981 and contributors</Authors>
<Copyright>Copyright (c) CaptureImage Contributors. Licensed under GPL-3.0-or-later.</Copyright>
<Version>1.0.0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<NeutralLanguage>en</NeutralLanguage>
<!-- Repository metadata — lands in the assembly manifest and the About tab. -->
<RepositoryUrl>https://github.com/poli0981/captureimg</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageProjectUrl>https://github.com/poli0981/captureimg</PackageProjectUrl>
<PackageLicenseExpression>GPL-3.0-or-later</PackageLicenseExpression>
</PropertyGroup>
<!-- Repo-wide suppressions -->
<PropertyGroup Label="Repo-wide suppressions">
<!-- CA1014: CLSCompliant attribute is meaningless for an app. CS1591: XML docs on every
public member are not required. -->
<NoWarn>$(NoWarn);CA1014;CS1591</NoWarn>
</PropertyGroup>
+27 -58
View File
@@ -5,83 +5,52 @@
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
<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 Label="WPF UI">
<PackageVersion Include="WPF-UI" Version="4.3.0" />
<PackageVersion Include="H.NotifyIcon.Wpf" Version="2.4.1" />
</ItemGroup>
<ItemGroup Label="MVVM">
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
</ItemGroup>
<ItemGroup Label="DI / Hosting / Localization">
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Localization" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="9.0.0" />
</ItemGroup>
<ItemGroup Label="Tray">
<PackageVersion Include="H.NotifyIcon.WinUI" Version="2.2.0" />
<PackageVersion Include="H.NotifyIcon" Version="2.2.0" />
</ItemGroup>
<ItemGroup Label="Hotkeys">
<PackageVersion Include="SharpHook" Version="5.3.9" />
</ItemGroup>
<ItemGroup Label="State machine">
<PackageVersion Include="Stateless" Version="5.15.0" />
<ItemGroup Label="Microsoft.Extensions">
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />
</ItemGroup>
<ItemGroup Label="Logging">
<PackageVersion Include="Serilog" Version="4.2.0" />
<PackageVersion Include="Serilog.Extensions.Hosting" Version="9.0.0" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageVersion Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageVersion Include="Serilog" Version="4.4.0" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="10.0.0" />
<PackageVersion Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageVersion Include="Serilog.Sinks.Async" Version="2.1.0" />
</ItemGroup>
<ItemGroup Label="Windows interop + D3D11">
<PackageVersion Include="Microsoft.Windows.CsWinRT" Version="2.2.0" />
<PackageVersion Include="Vortice.Direct3D11" Version="3.6.2" />
<PackageVersion Include="Vortice.DXGI" Version="3.6.2" />
<PackageVersion Include="System.Management" Version="9.0.0" />
<PackageVersion Include="Microsoft.Win32.Registry" Version="5.0.0" />
<PackageVersion Include="System.Drawing.Common" Version="9.0.0" />
</ItemGroup>
<ItemGroup Label="Filesystem abstractions (for tests)">
<PackageVersion Include="System.IO.Abstractions" Version="21.2.1" />
<ItemGroup Label="Windows interop: Direct3D 11, DXGI, WIC, Win32 P/Invoke">
<PackageVersion Include="Vortice.Direct3D11" Version="3.8.3" />
<PackageVersion Include="Vortice.DXGI" Version="3.8.3" />
<PackageVersion Include="Vortice.Direct2D1" Version="3.8.3" />
<PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.363" />
</ItemGroup>
<ItemGroup Label="Imaging">
<PackageVersion Include="SkiaSharp" Version="3.119.2" />
<PackageVersion Include="SkiaSharp.NativeAssets.Win32" Version="3.119.2" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" />
<PackageVersion Include="SkiaSharp" Version="4.153.1" />
</ItemGroup>
<ItemGroup Label="Auto-update">
<PackageVersion Include="Velopack" Version="0.0.1053" />
<ItemGroup Label="Auto-update (keep in lockstep with the vpk tool in .config/dotnet-tools.json)">
<PackageVersion Include="Velopack" Version="1.2.161" />
</ItemGroup>
<ItemGroup Label="Tests">
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageVersion Include="FluentAssertions" Version="6.12.2" />
<PackageVersion Include="NSubstitute" Version="5.3.0" />
<PackageVersion Include="System.IO.Abstractions.TestingHelpers" Version="21.2.1" />
<PackageVersion Include="coverlet.collector" Version="8.0.1" />
<PackageVersion Include="xunit.v3" Version="4.0.2" />
<PackageVersion Include="AwesomeAssertions" Version="9.6.0" />
<PackageVersion Include="NSubstitute" Version="6.2.0" />
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.12.0" />
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.11.0" />
<PackageVersion Include="FlaUI.UIA3" Version="5.0.0" />
</ItemGroup>
</Project>
+60 -38
View File
@@ -4,48 +4,70 @@ Copyright (c) CaptureImage Contributors
This product is licensed under the GNU General Public License v3.0 or later (GPL-3.0-or-later).
See LICENSE for the full license text.
Contact: contact@poli0981.dev (copyright: copyright@poli0981.dev, legal: legal@poli0981.dev)
================================================================================
Third-party components
================================================================================
This product includes software developed by third parties. The following table
lists every runtime dependency together with its upstream license. All listed
licenses are compatible with distribution under GPL-3.0-or-later.
This product includes the following third-party packages. All of them are licensed under terms
compatible with GPL-3.0-or-later. Details and project links: docs/legal/THIRD_PARTY_NOTICES.md.
Package SPDX license
--------------------------------------- -----------------
Avalonia MIT
Avalonia.Desktop MIT
Avalonia.Themes.Fluent MIT
Avalonia.Fonts.Inter MIT
Avalonia.Diagnostics MIT
CommunityToolkit.Mvvm MIT
Microsoft.Extensions.DependencyInjection MIT
Microsoft.Extensions.Hosting MIT
Microsoft.Extensions.Localization MIT
Microsoft.Extensions.Logging MIT
Microsoft.Extensions.Options MIT
H.NotifyIcon MIT
SharpHook MIT
Stateless Apache-2.0
Serilog Apache-2.0
Serilog.Extensions.Hosting Apache-2.0
Serilog.Extensions.Logging Apache-2.0
Serilog.Sinks.Console Apache-2.0
Serilog.Sinks.File Apache-2.0
Serilog.Sinks.Async Apache-2.0
Microsoft.Windows.CsWinRT MIT
Vortice.Direct3D11 MIT
Vortice.DXGI MIT
System.Management MIT
SixLabors.ImageSharp (>= 3.1) Apache-2.0
Velopack MIT
SkiaSharp (transitive via Avalonia) MIT
Inter font (transitive via Avalonia) OFL-1.1
Package SPDX license
------------------------------------------------------- ------------
CommunityToolkit.Mvvm MIT
H.GeneratedIcons.System.Drawing MIT
H.NotifyIcon MIT
H.NotifyIcon.Wpf MIT
Microsoft.Extensions.Configuration MIT
Microsoft.Extensions.Configuration.Abstractions MIT
Microsoft.Extensions.Configuration.Binder MIT
Microsoft.Extensions.Configuration.CommandLine MIT
Microsoft.Extensions.Configuration.EnvironmentVariables MIT
Microsoft.Extensions.Configuration.FileExtensions MIT
Microsoft.Extensions.Configuration.Json MIT
Microsoft.Extensions.Configuration.UserSecrets MIT
Microsoft.Extensions.DependencyInjection MIT
Microsoft.Extensions.DependencyInjection.Abstractions MIT
Microsoft.Extensions.Diagnostics MIT
Microsoft.Extensions.Diagnostics.Abstractions MIT
Microsoft.Extensions.FileProviders.Abstractions MIT
Microsoft.Extensions.FileProviders.Physical MIT
Microsoft.Extensions.FileSystemGlobbing MIT
Microsoft.Extensions.Hosting MIT
Microsoft.Extensions.Hosting.Abstractions MIT
Microsoft.Extensions.Logging MIT
Microsoft.Extensions.Logging.Abstractions MIT
Microsoft.Extensions.Logging.Configuration MIT
Microsoft.Extensions.Logging.Console MIT
Microsoft.Extensions.Logging.Debug MIT
Microsoft.Extensions.Logging.EventLog MIT
Microsoft.Extensions.Logging.EventSource MIT
Microsoft.Extensions.Options MIT
Microsoft.Extensions.Options.ConfigurationExtensions MIT
Microsoft.Extensions.Primitives MIT
Serilog Apache-2.0
Serilog.Extensions.Logging Apache-2.0
Serilog.Sinks.Async Apache-2.0
Serilog.Sinks.File Apache-2.0
SharpGen.Runtime MIT
SharpGen.Runtime.COM MIT
SkiaSharp MIT
SkiaSharp.NativeAssets.Win32 MIT
Velopack MIT
Vortice.Direct2D1 MIT
Vortice.Direct3D11 MIT
Vortice.DirectX MIT
Vortice.DXGI MIT
Vortice.Mathematics MIT
WPF-UI MIT
WPF-UI.Abstractions MIT
Test-only dependencies are not redistributed with the binary and are omitted.
Also used at runtime: the .NET 10 Desktop Runtime (MIT), the Windows SDK projection for .NET
(MIT) and the Fluent System Icons font embedded in WPF UI (MIT).
Full license texts for Apache-2.0, MIT, and OFL-1.1 can be retrieved from:
- https://www.apache.org/licenses/LICENSE-2.0.txt
- https://opensource.org/licenses/MIT
- https://openfontlicense.org/open-font-license-official-text/
Build and test tools are not redistributed with the binary and are omitted.
License texts:
- https://opensource.org/license/mit
- https://www.apache.org/licenses/LICENSE-2.0
+128 -159
View File
@@ -1,225 +1,194 @@
# CaptureImage
[![CI](https://github.com/poli0981/captureimg/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/captureimg/actions/workflows/ci.yml)
[![Latest release](https://img.shields.io/github/v/release/poli0981/captureimg?include_prereleases&sort=semver)](https://github.com/poli0981/captureimg/releases)
[![Latest release](https://img.shields.io/github/v/release/poli0981/captureimg?sort=semver)](https://github.com/poli0981/captureimg/releases)
[![License: GPL-3.0](https://img.shields.io/badge/License-GPL--3.0--or--later-blue.svg)](LICENSE)
[![.NET 9](https://img.shields.io/badge/.NET-9.0-512BD4.svg)](https://dotnet.microsoft.com/en-us/download/dotnet/9.0)
[![.NET 10](https://img.shields.io/badge/.NET-10.0-512BD4.svg)](https://dotnet.microsoft.com/download/dotnet/10.0)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/poli0981/captureimg/badge)](https://securityscorecards.dev/viewer/?uri=github.com/poli0981/captureimg)
A lightweight Windows screen-capture tool for games that don't ship a
built-in screenshot feature. Tray-resident, hotkey-driven, fast, and
gentle on resources.
A lightweight Windows screenshot tool for games that don't have their own screenshot key.
It sits in the tray, stays out of the way, and takes a clean capture when you press a hotkey.
> **One-line pitch:** pick a target window from a list, press
> `Ctrl+Shift+F12`, and your PNG lands in `Pictures\CaptureImage\`. That's it.
> **In one line:** click **Arm**, press `Ctrl+Shift+F12` in your game, and the PNG is in
> `Pictures\CaptureImage`.
## Why
Many games — especially older ones, smaller indie titles, emulators,
and anything outside Steam — don't bundle a screenshot key. The Windows
built-in options (Snipping Tool, Xbox Game Bar, `Print Screen`) either
don't work on fullscreen DirectX surfaces or require interrupting your
session. The heavy alternatives (OBS, ShareX) are overkill when all you
want is _one frame of a specific window, now, into a file_.
Many games — older titles, small indie games, emulators, anything outside Steam — have no
screenshot key. Print Screen, the Snipping Tool and the Xbox Game Bar either miss full-screen
DirectX surfaces or pull you out of the game, and OBS or ShareX are a lot of machinery when all you
want is _one frame of one window, now, in a file_.
CaptureImage fills that gap. It uses the same `Windows.Graphics.Capture`
API that OBS Studio uses for its Game Capture source, ships as a small
tray app, and stays out of your way until you press the hotkey.
CaptureImage uses `Windows.Graphics.Capture` — the API behind OBS Studio's window capture — from a
small tray app that does nothing until you press a hotkey.
## Features
- **Windows.Graphics.Capture** engine — hardware-accelerated, works with
DX11/DX12/Vulkan windowed and borderless titles, same API OBS uses.
- **PrintWindow fallback** for legacy windowed apps that WGC refuses.
- **Live Dashboard** — every visible top-level window with an icon and
title, refreshed in real time via WMI process events.
- **Steam warning badge** — if a capture target lives under a Steam
library, a small badge reminds you that F12 screenshots are available
via the Steam Overlay, and that some anti-cheat titles may block
external capture.
- **Arm + global hotkey** — default `Ctrl+Shift+F12`, rebind in Settings
(full hotkey editor is M6+).
- **Preview gate** — optional; show each capture, click Save or Discard.
- **4 output formats** — PNG, JPEG, WebP, TIFF, with per-format quality.
- **Local, private by default** — no telemetry, no cloud, no account.
Update check is the only network call, and only when you click the
button. See [`docs/legal/PRIVACY.md`](docs/legal/PRIVACY.md).
- **Tray icon + minimize-to-tray**, runtime-generated so no binary
asset to ship yet.
- **Toasts, preview dialog, real-time log drawer** in the UI.
- **Localized** — English, Vietnamese, Arabic (with live RTL mirroring).
Translations are machine-assisted — see
[`docs/legal/DISCLAIMER.md §4`](docs/legal/DISCLAIMER.md).
- **Velopack auto-update** from GitHub Releases. Security policy below.
- **Three capture modes, three hotkeys**
- **Window** (`Ctrl+Shift+F12`) — the window in front, or the one you locked on the Dashboard.
- **Region** (`Ctrl+Shift+F11`) — freezes every screen and lets you drag an area; a click takes
the whole screen.
- **Screen** (`Ctrl+Shift+F10`) — the monitor under the mouse pointer.
- **Works on every monitor**, at any scaling, including mixed-DPI setups.
- **HDR** — on HDR displays the full HDR frame is captured and tone-mapped to a normal image; the
original can be kept as a JPEG XR (`.jxr`) file next to it.
- **Library** — every capture with thumbnails; filter by game or HDR; open, show in folder, copy
the image or path, extract text (OCR), pin on screen, move to the Recycle Bin.
- **Game profiles** — per-game folder, format, file name and HDR settings, matched by executable
path, executable name or Steam AppId. A profile can arm the hotkeys and lock the game window as
soon as the game comes to the front.
- **PNG, JPEG, WebP or TIFF**, with quality / compression settings and a file-name template
(`{Game}`, `{Process}`, `{Mode}`, date and time, `{counter}`).
- **Optional preview** before saving, countdown (3 / 5 / 10 s), copy to the clipboard, open the
folder after saving, pin a floating thumbnail.
- **Stays out of your game** — hotkeys are registered only while armed (no keyboard or mouse hook),
notifications never take focus and never appear in your screenshots, and the app drops to
Windows' efficiency mode while it idles in the tray.
- **Steam badge** on windows of Steam games (some anti-cheat titles block external capture; Steam's
own F12 screenshot works there).
- **11 languages** — English, Tiếng Việt, العربية (right to left), 日本語, 简体中文, 한국어, Español,
Français, Deutsch, Português (Brasil), Русский. Translations are machine-assisted — see
[`docs/legal/DISCLAIMER.md`](docs/legal/DISCLAIMER.md).
- **Light, dark and high-contrast themes**, following Windows by default.
- **Start with Windows**, start minimized, arm on startup.
- **Private by default** — no telemetry, no account, no cloud. The only network request is the
update check. See [`docs/legal/PRIVACY.md`](docs/legal/PRIVACY.md).
- **In-app updates** from GitHub Releases (Velopack).
## Screenshots
Captured with CaptureImage itself — yes, we eat our own dog food.
| Dashboard | Settings | About |
| Dashboard | Library | Settings |
|:-:|:-:|:-:|
| ![Dashboard — target list with Steam badge](docs/screenshots/dashboard.png) | ![Settings — hotkey recorder + format + language](docs/screenshots/settings.png) | ![About — version, licenses, legal docs](docs/screenshots/about.png) |
| ![Dashboard — armed status, per-mode hotkeys and the window list](docs/screenshots/dashboard.png) | ![Library — captures with thumbnails and actions](docs/screenshots/library.png) | ![Settings — hotkeys per capture mode](docs/screenshots/settings.png) |
| Update | Log viewer | RTL (Arabic) |
| Game profiles | About | Arabic (right to left) |
|:-:|:-:|:-:|
| ![Update — Velopack check / download / install with live log](docs/screenshots/update.png) | ![Log viewer — live Serilog ring buffer](docs/screenshots/logviewer.png) | ![RTL — dashboard mirrored for Arabic culture](docs/screenshots/rtl-dashboard.png) |
| ![Profiles — per-game overrides and auto-arm](docs/screenshots/profiles.png) | ![About — version, contact, legal documents](docs/screenshots/about.png) | ![Settings in Arabic, mirrored right to left](docs/screenshots/rtl-settings.png) |
## Requirements
- **Windows 11 22H2 or later** (build 10.0.22621+). Required by the
`Windows.Graphics.Capture` API. Older Windows 10 builds will not run.
- For the Steam badge to appear: Steam installed with at least one
library. Otherwise the badge is simply absent.
- **Windows 11 22H2 or later** (build 22621+), 64-bit.
- **.NET 10 Desktop Runtime** — installed automatically by Setup and by the in-app updater when it
is missing. The portable zip needs it installed
([download](https://dotnet.microsoft.com/download/dotnet/10.0)).
## Install
Download `Setup.exe` from the
[latest GitHub Release](https://github.com/poli0981/captureimg/releases).
Velopack installs the app into `%LocalAppData%\CaptureImage\` — no admin
prompt, no registry spam, no background service.
Download **`CaptureImage-win-Setup.exe`** from the
[latest release](https://github.com/poli0981/captureimg/releases/latest). It installs per user into
`%LocalAppData%\CaptureImage` — no administrator rights, no service. Prefer no installer? Use
**`CaptureImage-win-Portable.zip`**.
### Unsigned installer — SmartScreen warning
Updating from 1.x? Use **Update** inside the app (or run the new Setup). Your settings are copied to
the new data folder and migrated; the old file is left untouched.
**Heads-up:** CaptureImage is not yet code-signed (see
[`docs/legal/DISCLAIMER.md §7`](docs/legal/DISCLAIMER.md)). On first run
Windows SmartScreen will show:
### Unsigned installer — SmartScreen
> Windows protected your PC · Unknown publisher · Don't run
To proceed, click **More info** → **Run anyway**. If you want to verify
the download is unmodified, the release page includes `SHA256SUMS.txt`:
CaptureImage is not code-signed yet, so Windows SmartScreen may say _"Windows protected your PC ·
Unknown publisher"_. Click **More info → Run anyway**. To check the download first, compare its
SHA-256 with `SHA256SUMS.txt` on the release page, or verify the build provenance:
```powershell
Get-FileHash -Algorithm SHA256 .\Setup.exe
# Compare the output with the entry in SHA256SUMS.txt on the release page.
Get-FileHash -Algorithm SHA256 .\CaptureImage-win-Setup.exe
gh attestation verify .\CaptureImage-win-Setup.exe --repo poli0981/captureimg
```
## Usage
1. Launch CaptureImage — a 960×600 window opens.
2. The **Dashboard** shows every visible top-level window on your desktop
with its icon, title, and — for Steam games — a warning badge.
3. Click the target you want to capture.
4. Click **Arm**. The global hotkey listener starts.
5. Alt-Tab to the target, press **`Ctrl+Shift+F12`**.
6. If preview is enabled (Settings → Preview before save), a dialog
shows the captured frame. Click Save or Discard.
7. The PNG (or JPEG/WebP/TIFF, your choice) lands in
`%USERPROFILE%\Pictures\CaptureImage\` with a time-stamped filename.
8. A toast appears bottom-right confirming the save.
1. Start CaptureImage. The **Dashboard** shows the hotkeys and every window you can capture.
2. Click **Arm**. While armed the three hotkeys belong to CaptureImage; click **Disarm** (or use the
tray menu) to give them back. Turn on **Arm when CaptureImage starts** in Settings to skip this
step.
3. In your game press **`Ctrl+Shift+F12`** (window), **`Ctrl+Shift+F11`** (region) or
**`Ctrl+Shift+F10`** (screen). Change them in **Settings → Hotkeys**.
4. The image is saved to `Pictures\CaptureImage` (change it in Settings, or per game with a
profile) and shows up in the **Library**.
Close-to-tray is on by default — click the X, the window hides, the
tray icon stays. Quit via the tray menu's Exit item.
Tips:
- **Lock a window** on the Dashboard to capture it even when something else is in front — or let a
game profile lock it for you.
- **Create profile** on the Dashboard turns the selected game into a profile in one click.
- Closing the window keeps CaptureImage in the tray; quit from the tray menu.
- A game that swallows registered hotkeys (rare) can still be captured with **Capture region** or
**Capture screen** from the tray menu, optionally with a countdown.
- Settings, logs and the library index are kept in `%LocalAppData%\poli0981\CaptureImage`.
**Settings → Advanced → Export diagnostics** creates a zip for bug reports (user paths removed).
## Build from source
You need the **.NET 10 SDK** (the exact version is pinned in [`global.json`](global.json)) on
Windows 11.
```bash
git clone https://github.com/poli0981/captureimg.git
cd captureimg
dotnet restore
dotnet build CaptureImage.sln -c Release
dotnet test CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release
dotnet test --solution CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release -- --data-dir ./.devdata --instance-id dev
```
The build needs:
- **.NET 9 SDK** — the repo's `global.json` pins the exact version.
- **Windows 10.0.22621 SDK** (or newer) for the WinRT projections the
capture engine uses. Install via the Visual Studio Installer
("Windows 11 SDK (10.0.22621.x)") or directly from
<https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/>.
`--data-dir` and `--instance-id` keep a development copy away from your real settings and from a
copy you have installed. `--smoke-test` opens every page and exits; `--screenshots <dir>` also saves
a PNG of each page.
## Repository layout
```
```text
src/
CaptureImage.Core Pure domain (models, abstractions, state machine,
pipeline). Portable net9.0, no Windows ties.
CaptureImage.Infrastructure Windows implementations: capture engine, process
watcher, Steam detector, hotkeys, settings, logging,
Velopack updater. net9.0-windows10.0.22621.0.
CaptureImage.ViewModels MVVM layer — reusable across UI frameworks, no
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.
CaptureImage.Core Capture model, settings and migration, profiles, file naming,
HDR tone mapping, the capture coordinator. net10.0, no Windows APIs.
CaptureImage.Infrastructure Windows implementations: Windows.Graphics.Capture + Direct3D 11,
RegisterHotKey, WinEvent window watcher, displays and HDR, WIC and
SkiaSharp encoders, library, settings store, OCR, Velopack, Serilog.
CaptureImage.ViewModels View models and the 11-language string resources (no UI framework).
CaptureImage.UI WPF + WPF UI: windows, pages, region overlays, toasts, tray icon.
CaptureImage.App Entry point: Velopack hooks, single instance, logging, composition.
tests/
CaptureImage.Core.Tests xUnit — 31 tests (state machine, file name
strategy, image format).
CaptureImage.Infrastructure.Tests xUnit — 37 tests (VDF parser, Steam scanner,
settings store, WGC integration).
CaptureImage.ViewModels.Tests Placeholder project for future VM tests.
docs/
CONTRIBUTORS.md Contributor list + AI-assistance policy.
RELEASING.md How to cut a release.
legal/
DISCLAIMER.md No-warranty, capture limits, AI-dev, translations.
PRIVACY.md What's read, what's written, what's on the network.
TERMS.md Plain-language restatement of GPL-3.0 obligations.
THIRD_PARTY_NOTICES.md Full dependency list + licenses.
CaptureImage.Core.Tests Domain logic, migration, coordinator (with fakes).
CaptureImage.Infrastructure.Tests Settings store, encoders, Steam, hotkeys, capture on real hardware.
CaptureImage.ViewModels.Tests View models and translation completeness.
CaptureImage.App.UiTests End-to-end UI tests (FlaUI), run in CI.
docs/ Architecture, releasing, legal documents, screenshots.
```
## Architecture
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for a one-page-per-layer
tour — layer rules, state-machine diagram, WGC capture pipeline sequence,
DI composition sketch, i18n + RTL flow, and Velopack update flow (all with
Mermaid diagrams rendered inline on GitHub).
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the design, with diagrams.
## Contributing
See [`docs/CONTRIBUTORS.md`](docs/CONTRIBUTORS.md) for the full
contribution flow. The short version:
1. Open an issue first for anything non-trivial.
2. Follow conventional-commits style (`feat(...)`, `fix(...)`, `docs(...)`).
3. Run `dotnet build` and `dotnet test` locally before opening the PR.
4. Disclose AI-assisted changes in the PR description (not required, but
helpful for reviewers).
**Translation help wanted.** The Vietnamese and Arabic language packs
are machine-assisted — native speakers who can proofread the `.resx`
files are warmly welcomed.
Bug reports, translations and pull requests are welcome — see [`CONTRIBUTING.md`](CONTRIBUTING.md).
Native speakers who can proofread a language file are especially appreciated.
## Security
Report vulnerabilities privately via
[GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new).
See [`SECURITY.md`](SECURITY.md) for the full policy, scope, and
response-time expectations.
Please report vulnerabilities privately through
[GitHub Security Advisories](https://github.com/poli0981/captureimg/security/advisories/new) or
`security@poli0981.dev`. See [`SECURITY.md`](SECURITY.md).
## Contact
- General: `contact@poli0981.dev`
- Other channels: <https://poli0981.dev/links>
- Collaboration: `collab@poli0981.dev` · Press: `press@poli0981.dev`
- Help and questions: [`SUPPORT.md`](SUPPORT.md)
## AI assistance
CaptureImage was developed with significant assistance from the
**Claude Opus 4.6** large language model, used through Claude Code,
during the 2026 development cycle. Every change was reviewed, accepted,
and tested by the human maintainer before landing. Commits with
meaningful AI authorship carry a `Co-Authored-By` trailer naming the
model. Full details in [`docs/CONTRIBUTORS.md`](docs/CONTRIBUTORS.md)
and [`docs/legal/DISCLAIMER.md §3`](docs/legal/DISCLAIMER.md).
CaptureImage is developed with substantial help from an AI coding assistant — Claude (Anthropic),
used through Claude Code — for code, tests and documentation. The maintainer reviews and tests every
change before it ships; commits with meaningful AI authorship carry a `Co-Authored-By` trailer.
Details in [`docs/CONTRIBUTORS.md`](docs/CONTRIBUTORS.md).
## Support the project
CaptureImage is free, open source, and developed solo. If it helps
you, consider supporting development:
- [GitHub Sponsors](https://github.com/sponsors/poli0981)
- [Ko-fi](https://ko-fi.com/skullmute)
- [Buy Me a Coffee](https://buymeacoffee.com/skullmute)
- [Patreon](https://patreon.com/skullmute)
The same destinations are wired into the repo's "Sponsor" button via
[`.github/FUNDING.yml`](.github/FUNDING.yml).
Bug reports go through the in-app **About → Report a bug** button or
[directly on GitHub](https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml).
CaptureImage is free and developed by one person. If it helps you:
[GitHub Sponsors](https://github.com/sponsors/poli0981) ·
[Ko-fi](https://ko-fi.com/skullmute) ·
[Buy Me a Coffee](https://buymeacoffee.com/skullmute) ·
[Patreon](https://patreon.com/skullmute). For sponsorship enquiries: `sponsor@poli0981.dev`.
## License
CaptureImage is distributed under the **GNU General Public License
v3.0 or later** (SPDX: `GPL-3.0-or-later`). See
[`LICENSE`](LICENSE) for the full text and
[`docs/legal/THIRD_PARTY_NOTICES.md`](docs/legal/THIRD_PARTY_NOTICES.md)
for attributions.
[GNU General Public License v3.0 or later](LICENSE) (SPDX: `GPL-3.0-or-later`). Third-party
components and their licenses are listed in
[`docs/legal/THIRD_PARTY_NOTICES.md`](docs/legal/THIRD_PARTY_NOTICES.md).
+50 -65
View File
@@ -1,90 +1,75 @@
# Security Policy
_Last updated: 2026-04-15_
_Last updated: 2026-10-19_
## Supported versions
CaptureImage has a single release line. Only the latest tagged release
on the `main` branch receives security updates.
Only the latest release receives security fixes.
| Version | Supported |
|---|---|
| Latest tagged release | ✅ |
| Older releases | ❌ |
| `main` branch (untagged) | ❌ |
| 2.x (latest release) | ✅ |
| 1.x and older | ❌ — update from inside the app or install the latest release |
| Unreleased `main` | ❌ |
## Reporting a vulnerability
**Please do not open a public issue for security problems.** Instead,
report privately via GitHub Security Advisories:
**Please don't open a public issue for security problems.** Report privately, either:
<https://github.com/poli0981/captureimg/security/advisories/new>
- through GitHub's private vulnerability reporting:
<https://github.com/poli0981/captureimg/security/advisories/new>, or
- by email to `security@poli0981.dev`.
Include as much of the following as you can:
Please include what you can of:
- Affected version(s) (tag name or commit hash).
- A description of the issue and the security impact (arbitrary code
execution, local privilege escalation, data exfiltration, etc.).
- Reproduction steps or a proof-of-concept.
- Your suggested fix, if any.
- Whether you want public credit in the advisory.
- the affected version (release tag or commit),
- what the issue is and its impact (code execution, privilege escalation, data leaving the
computer, …),
- steps or a proof of concept to reproduce it,
- a suggested fix, if you have one,
- whether and how you would like to be credited.
You should expect an acknowledgement within **7 days** and a triage
decision (fix plan + rough timeline) within **14 days**. CaptureImage
is a volunteer-run project — these are good-faith targets, not
guaranteed SLAs.
You can expect an acknowledgement within **7 days** and a triage decision (fix plan and rough
timeline) within **14 days**. CaptureImage is maintained by a volunteer, so these are good-faith
targets rather than guarantees.
## Scope — what counts as a security vulnerability
## In scope
- Arbitrary code execution triggered by opening a crafted settings file,
image, or update payload.
- Privilege escalation (anything that causes CaptureImage to acquire
more privileges than the user that launched it).
- Bypass of the capture-target selection (e.g. a way to make the app
capture a window the user did not select).
- Data exfiltration (anything that causes captured images, process
names, or settings to leave the user's machine without consent).
- Remote code execution via the Velopack update path (e.g. an attacker
who can MITM the GitHub Releases fetch and inject a malicious package).
- Memory safety issues in the Win32 / WinRT interop code that could be
exploited.
- Code execution triggered by a crafted settings file, image, library index or update package.
- CaptureImage gaining more privileges than the user who started it.
- Capturing a window or screen without the user's action, or captures, settings or logs leaving
the computer without consent.
- The update path: tampering with releases or the update feed, or installing a package that wasn't
published by this repository.
- The single-instance pipe or other local interfaces being usable by another user or process to
control the app.
- Memory-safety problems in the Win32 / WinRT / Direct3D interop code.
## Out of scope
## Out of scope (please file a normal bug report)
These are bugs, not security issues — please file them via a regular
bug report instead:
- A particular game can't be captured — see
[`docs/legal/DISCLAIMER.md`](docs/legal/DISCLAIMER.md), section 2.
- SmartScreen shows "unknown publisher" — the installer isn't code-signed yet; verify downloads as
described in the [README](README.md#unsigned-installer--smartscreen).
- An anti-cheat system flags the app — CaptureImage doesn't inject into or read from games, but we
can't control how anti-cheat software classifies capture tools.
- Translation, documentation or accessibility issues, and feature requests.
- A specific game cannot be captured (this is an expected limitation —
see [`docs/legal/DISCLAIMER.md §2`](docs/legal/DISCLAIMER.md)).
- The app crashes during startup on an unsupported Windows version.
- SmartScreen warns "Unknown publisher" on the installer (the binary is
intentionally not signed yet — see
[`docs/RELEASING.md`](docs/RELEASING.md) §5).
- Third-party anti-cheat software flags the app as untrusted. CaptureImage
does not inject into or read from game memory, but we cannot control
how any particular anti-cheat engine classifies capture tools.
- Missing localization, machine-translated strings, or other documentation
issues — these are tracked as normal bugs.
- Feature requests, even if they would improve user privacy.
## After you report
## What happens after you report
1. The maintainer acknowledges receipt of the advisory.
2. We reproduce the issue, identify the root cause, and draft a fix.
3. For non-trivial issues the fix lands on a private branch and is
reviewed before merging to `main`.
4. A new release is cut with the fix.
5. The advisory is made public, crediting the reporter (if they want
credit). CVE assignment may be requested for high-severity issues.
1. The report is acknowledged.
2. The issue is reproduced, the cause found and a fix prepared (privately for non-trivial issues).
3. A release with the fix is published.
4. The advisory is published, crediting you if you wish; a CVE may be requested for serious issues.
## Supply chain
CaptureImage depends on a large tree of open-source libraries (see
[`docs/legal/THIRD_PARTY_NOTICES.md`](docs/legal/THIRD_PARTY_NOTICES.md)).
Dependabot runs weekly to pick up upstream security advisories, and
pinned package versions in `Directory.Packages.props` are bumped as
needed.
- Dependencies are pinned centrally with lock files; Dependabot proposes updates after a cooldown,
and every pull request is checked for known-vulnerable and incompatibly licensed packages.
- GitHub Actions are pinned to full commit SHAs and linted with actionlint and zizmor; CodeQL,
OpenSSF Scorecard and SonarCloud review the code.
- Releases are built by GitHub Actions from signed tags and ship with SHA-256 checksums, a CycloneDX
SBOM and a build-provenance attestation (`gh attestation verify`).
If you find a vulnerability in one of CaptureImage's dependencies,
please report it upstream first. We will pick it up once the upstream
fix is released.
Vulnerabilities in a dependency should be reported upstream first; we will pick up the fixed
version once it is released.
+27
View File
@@ -0,0 +1,27 @@
# Getting help
CaptureImage is maintained by one volunteer. Here is where to go:
| You want to… | Go to |
|---|---|
| Ask a question or share an idea | [GitHub Discussions](https://github.com/poli0981/captureimg/discussions) |
| Report a bug | [Bug report](https://github.com/poli0981/captureimg/issues/new?template=bug_report.yml) — or **About → Report a bug** in the app |
| Suggest a feature | [Feature request](https://github.com/poli0981/captureimg/issues/new?template=feature_request.yml) |
| Report a security problem | Privately — see [`SECURITY.md`](SECURITY.md) (`security@poli0981.dev`) |
| Ask about privacy | `privacy@poli0981.dev` — see [`docs/legal/PRIVACY.md`](docs/legal/PRIVACY.md) |
| Raise a game-compatibility or anti-cheat concern (publishers, vendors) | `games@poli0981.dev` |
| Copyright, DMCA or takedown requests | `dmca@poli0981.dev` · `takedown@poli0981.dev` |
| Sponsor the project | `sponsor@poli0981.dev` or the links in the [README](README.md#support-the-project) |
| Anything else | `contact@poli0981.dev` · <https://poli0981.dev/links> |
## Before reporting a bug
1. Update to the [latest release](https://github.com/poli0981/captureimg/releases/latest) — it may
already be fixed.
2. In the app, open **Settings → Advanced**, set the log level to **Debug**, reproduce the problem,
then use **Export diagnostics**. The zip contains logs, settings and system information with your
user paths removed; attach it to the issue if you're comfortable with that.
3. For capture problems, say which game, whether it runs windowed, borderless or full screen, and
whether you use HDR or several monitors.
There is no paid support or guaranteed response time, but every report is read.
+171 -332
View File
@@ -1,358 +1,197 @@
# Architecture
This document is a one-page-per-layer tour of CaptureImage for people who
want to contribute, audit, or port the code. It is **not** the design
intent record — that lives in the per-milestone plan files under
`.claude/plans/`. This is the shape of the code as it stands on `main`.
CaptureImage 2.x is a .NET 10 WPF tray app. This page describes how it is put together; the
[README](../README.md) covers what it does.
Diagrams are Mermaid so GitHub renders them inline. Source paths are
clickable; line numbers drift, so I link to files rather than lines.
## 1. Layer rules
Five projects, four rules:
- **`CaptureImage.Core`** (net9.0) — pure domain. Models, abstractions,
state machine, pipeline. No platform references. **Depends on nothing.**
- **`CaptureImage.Infrastructure`** (net9.0-windows10.0.22621.0) — every
Windows-specific implementation: WGC capture, D3D11 interop, WMI
process watch, `RegisterHotKey` sniff, Velopack updater, Serilog sinks,
JSON settings. **Depends on Core.**
- **`CaptureImage.ViewModels`** (net9.0) — MVVM layer using
CommunityToolkit.Mvvm source generators. Platform-agnostic — these
types exist so the UI logic is testable without WinUI 3.
**Depends on Core only.**
- **`CaptureImage.UI`** (net9.0-windows10.0.22621.0) — WinUI 3 Pages +
UserControls, converters, resx localization, tray host, picker COM
interop. **Depends on Core + ViewModels.**
- **`CaptureImage.App`** (net9.0-windows10.0.22621.0) — the composition
root. `Program.cs` + [`CompositionRoot.cs`](../src/CaptureImage.App/CompositionRoot.cs).
Single point of DI wiring. **Depends on all four projects.**
## Layers
```mermaid
graph LR
App[CaptureImage.App<br/>net9.0-windows]
UI[CaptureImage.UI<br/>net9.0-windows · WinUI 3]
VM[CaptureImage.ViewModels<br/>net9.0 · MVVM]
Infra[CaptureImage.Infrastructure<br/>net9.0-windows · P/Invoke]
Core[CaptureImage.Core<br/>net9.0 · pure domain]
App --> UI
App --> Infra
App --> VM
App --> Core
UI --> VM
UI --> Core
VM --> Core
Infra --> Core
flowchart TD
App["CaptureImage.App<br/>entry point · composition root"]
UI["CaptureImage.UI<br/>WPF + WPF UI windows, pages, tray"]
VM["CaptureImage.ViewModels<br/>view models · string resources"]
Core["CaptureImage.Core<br/>models · abstractions · coordinator"]
Infra["CaptureImage.Infrastructure<br/>Win32 · WinRT · Direct3D · WIC · Serilog · Velopack"]
App --> UI
App --> Infra
UI --> VM
VM --> Core
Infra --> Core
```
**Why this shape:**
| Project | Target | Rules |
|---|---|---|
| Core | `net10.0` | No Windows APIs, no UI types. Everything Windows-specific is an interface here. |
| Infrastructure | `net10.0-windows10.0.22621.0` | Implements Core interfaces. P/Invoke through CsWin32 (`NativeMethods.txt`). |
| ViewModels | `net10.0` | CommunityToolkit.Mvvm. Talks only to Core abstractions; no WPF, no `Process.Start`, no file I/O. |
| UI | `net10.0-windows10.0.22621.0` | WPF + WPF UI. Implements the interactive abstractions (toasts, overlays, dialogs, clipboard). |
| App | `net10.0-windows10.0.22621.0` | `Main`, Velopack hooks, single instance, logging, dependency injection. |
- `Core` stays portable so the domain logic is trivially testable. The
Core test project runs on plain `net9.0`, no Windows 11 SDK needed.
- `ViewModels` stays off `net9.0-windows` so the type system stays
portable — VM tests run on plain `net9.0` without dragging in WinAppSDK
or WinRT projections.
- `Infrastructure` is the only project that touches `Windows.*`. If a
future milestone ports to another desktop platform, that's the project
that gets replaced.
All services are singletons registered in `CaptureImage.App/Composition/ServiceRegistration.cs`
(Core + Infrastructure) and `CaptureImage.UI/UiServiceCollectionExtensions.cs` (UI, view models,
pages). The container validates the whole graph when it is built.
## 2. Capture state machine
## Startup and shutdown
Every screenshot flows through a single
[`CaptureStateMachine`](../src/CaptureImage.Core/StateMachine/CaptureStateMachine.cs)
backed by the `Stateless` library. `DashboardViewModel` fires triggers;
the machine decides whether the preview step is visited based on a
live-checked `Func<bool> previewEnabled`.
1. `VelopackApp.Build().Run()` — install / update / uninstall hooks run before anything else; the
uninstall hook removes the "Start with Windows" entry.
2. Command line: `--data-dir`, `--instance-id`, `--minimized`, `--smoke-test`, `--screenshots`.
3. Single instance per Windows session, user and instance id: a named mutex plus a
`CurrentUserOnly` pipe. A second launch asks the first copy to show its window and exits.
4. Serilog: an async rolling file in `<data>\logs` and an in-memory ring buffer for the Logs page;
user-profile paths are replaced by `%USERPROFILE%`.
5. Settings are loaded (and migrated), the host starts the WinEvent window watcher, and the WPF
`App` applies language and theme, creates the main window and the tray icon, and arms the
hotkeys if the user asked for that.
6. On exit the tray icon is removed, the hotkeys are released, the host stops, pending settings are
written and the log is flushed — including when an update restarts the app.
## Data
Everything the app writes lives in `%LocalAppData%\poli0981\CaptureImage` (or `--data-dir`):
| Path | Content |
|---|---|
| `settings.json` | Settings, schema version 3. Written atomically (temp file + replace); damaged files and files from a newer version are backed up before defaults are used; unknown fields are kept. |
| `library.json` | Index of saved captures (newest first, at most 2,000). |
| `thumbnails\` | JPEG thumbnails for the Library, named by a hash of the image path. |
| `logs\` | `captureimage-<date>.log`, 14 days, 10 MB per file. |
The 1.x settings file (`%LocalAppData%\CaptureImage\settings.json`, inside the Velopack install
folder) is copied on first start and migrated: the old single hotkey goes to the capture mode that
was in use, the other modes get their defaults, and options that no longer exist are dropped.
## Capturing
```mermaid
sequenceDiagram
participant Hotkey as Win32HotkeyService
participant Coord as CaptureCoordinator
participant Engine as WgcCaptureEngine
participant UI as Overlays / preview
participant Writer as CaptureFileWriter
Hotkey->>Coord: Triggered(mode)
Coord->>Coord: resolve target and profile, countdown
Coord->>Engine: CaptureAsync(window or monitor)
Engine-->>Coord: frame (BGRA8 or FP16 HDR)
opt Region
Coord->>UI: SelectAsync(frozen monitors)
UI-->>Coord: rectangle or cancel
end
opt Preview before save
Coord->>UI: ShowAsync(frame)
UI-->>Coord: save or discard
end
Coord->>Writer: SaveAsync(frame, HDR original)
Writer-->>Coord: CaptureRecord
Coord->>Coord: library, clipboard, sound, toast, pin
```
### Hotkeys and arming
- `Win32HotkeyService` registers one hotkey per capture mode with `RegisterHotKey` (window handle
`NULL`, `MOD_NOREPEAT`) on its own message-loop thread. Keys are registered **only while armed**,
because a registered combination never reaches any other application.
- Registration results (registered, conflict, invalid) are shown on the Dashboard and in Settings.
- While the hotkey recorder in Settings is listening, the coordinator suspends the hotkeys so the
current combination can be pressed again.
- During region selection Esc and Enter are registered temporarily, so they work even when a
full-screen game keeps the keyboard focus.
### Coordinator
`CaptureCoordinator` (Core) runs one capture at a time; a second request while one is running is
ignored. Every request ends in exactly one outcome — saved, copied, cancelled, discarded, busy or
failed — and failures are always reported with a localized message.
```mermaid
stateDiagram-v2
[*] --> Idle
Idle --> TargetsSelected: SelectTargets
TargetsSelected --> Idle: ClearTargets
TargetsSelected --> Armed: Arm
Armed --> TargetsSelected: Disarm
Armed --> Idle: ClearTargets
Armed --> Capturing: HotkeyPressed
Capturing --> Previewing: FrameCaptured\n(previewEnabled=true)
Capturing --> Saving: FrameCaptured\n(previewEnabled=false)
Capturing --> Failed: ErrorOccurred
Previewing --> Saving: PreviewAccepted
Previewing --> Armed: PreviewRejected
Saving --> Complete: Saved
Saving --> Failed: ErrorOccurred
Complete --> Armed: Reset
Complete --> Idle: ClearTargets
Failed --> Armed: Reset
Failed --> Idle: ClearTargets
[*] --> Idle
Idle --> Countdown: countdown set
Idle --> Capturing
Countdown --> Capturing
Capturing --> Selecting: region
Selecting --> Capturing: area chosen
Capturing --> Previewing: preview on
Capturing --> Saving
Previewing --> Saving: save
Countdown --> Idle: cancel
Selecting --> Idle: Esc / right click
Previewing --> Idle: discard
Saving --> Idle
```
**Rules of the road:**
- **Window**: the locked window, otherwise the foreground window. A game profile with auto-arm arms
the hotkeys (and locks its window) when the game comes to the front.
- **Screen**: the monitor under the mouse pointer.
- **Region**: every monitor is captured first; the overlays show those frozen frames, so the result
is exactly what was on screen when the key was pressed.
- Transitions are driven by explicit triggers, never by timers. The
viewmodel is the only thing allowed to call `Fire`.
- `Capturing → Saving/Previewing` uses `PermitDynamic` so the preview
toggle is consulted at transition time. Changing the toggle while
armed affects the *next* capture, not any in-flight one.
- `Failed` and `Complete` both route back to `Armed` on `Reset` so the
user can fire another shot without re-selecting a target.
- `StateChanged` fires on whatever thread drove the trigger.
`DashboardViewModel` marshals to the UI thread before touching
bindings.
### Windows.Graphics.Capture
Tests cover every legal transition and assert illegal ones throw —
[`CaptureStateMachineTests`](../tests/CaptureImage.Core.Tests/StateMachine/CaptureStateMachineTests.cs).
- One Direct3D 11 device (hardware, WARP as fallback) is shared by all captures and recreated once
when the driver reports a lost device.
- Frames are read back through a staging texture; window captures are cropped to the client area
unless the window frame is wanted, and alpha is forced opaque.
- On an HDR display the frame pool uses `R16G16B16A16Float` (scRGB). `HdrToneMapper` maps it to
sRGB using the display's SDR white level (knee at 0.8 of white, exponential shoulder), and the
untouched HDR frame can be saved as JPEG XR.
- Monitors, DPI and HDR state come from `EnumDisplayMonitors`, DXGI (`IDXGIOutput6`) and
`DisplayConfigGetDeviceInfo`.
## 3. WGC capture pipeline
### Saving
The primary engine is
[`WindowsGraphicsCaptureEngine`](../src/CaptureImage.Infrastructure/Capture/WindowsGraphicsCaptureEngine.cs),
an on-demand single-frame pipeline. It uses the same
`Windows.Graphics.Capture` API that OBS Studio uses for Game Capture.
Hardware-accelerated, works with DX11/DX12/Vulkan windowed and
borderless-fullscreen titles.
- PNG (zlib level by "PNG compression"), JPEG and WebP are encoded with SkiaSharp; TIFF and JPEG XR
with Windows Imaging Component.
- File names come from the template (`FileNameStrategy`): invalid, control and invisible
formatting characters are replaced, reserved device names are avoided, names are capped at 120
characters.
- The image is written to a temporary file and moved into place **without overwriting**; on a name
collision the next counter is tried.
## User interface
- `MainWindow` is a WPF UI `FluentWindow` with a `NavigationView`; pages come from the container
and only the visible page refreshes in the background (window list, logs, library).
- Strings are bound with `{loc:Tr Key}`, a live binding to the resource service; switching language
updates every window in place, including right-to-left layout for Arabic. Keys and placeholders
are checked against all 11 languages by tests.
- Notifications use a snackbar while the main window is in front, otherwise a small topmost window
that is never activated and is excluded from screen capture (`WDA_EXCLUDEFROMCAPTURE`) — the same
applies to region overlays, the preview and pinned thumbnails.
- Region overlays are placed over each monitor in physical pixels and show the frozen frame at the
monitor's DPI, so one image pixel is one screen pixel; the selection is converted back to physical
pixels.
- The tray icon (H.NotifyIcon) shows a red dot while armed and is re-added after Explorer restarts.
- The main window hides to the tray while it idles and the process then runs in Windows' efficiency
mode (EcoQoS), lifted during captures.
## Updates
```mermaid
sequenceDiagram
participant VM as DashboardViewModel
participant Eng as WindowsGraphicsCaptureEngine
participant Interop as CaptureItemInterop
participant D3D as D3D11DeviceManager
participant WGC as Windows.Graphics.Capture
participant Tex as Staging Texture
VM->>Eng: CaptureAsync(target, ct)
Eng->>Interop: CreateForWindow(HWND)
Interop-->>Eng: GraphicsCaptureItem
Eng->>D3D: Get()
D3D-->>Eng: (ID3D11Device, context)
Eng->>WGC: CreateFreeThreaded(framePool)
Eng->>WGC: CreateCaptureSession(item)
Note over Eng,WGC: IsBorderRequired=false<br/>IsCursorCaptureEnabled=false
Eng->>WGC: StartCapture()
WGC-->>Eng: FrameArrived (async)
Eng->>Tex: CreateTexture2D(STAGING + CPU_READ)
Eng->>Tex: CopyResource(gpu → staging)
Eng->>Tex: Map(READ)
Eng-->>VM: CapturedFrame(w, h, stride, bytes)
Note over Eng: Dispose session<br/>Dispose framePool<br/>Dispose staging + gpu texture
participant User
participant App as CaptureImage
participant GH as GitHub Releases
participant Up as Velopack Update.exe
User->>App: Update → Check
App->>GH: releases.win.json
GH-->>App: newer version + notes
User->>App: Download, then Install and restart
App->>Up: WaitExitThenApplyUpdates
App->>App: normal shutdown (settings, tray, logs)
Up->>Up: install runtime if missing, apply package
Up->>App: restart new version
```
**Invariants:**
The package id (`CaptureImage`), executable name (`CaptureImage.App.exe`), channel (`win`) and
shortcuts never change, so installed copies keep updating. See [RELEASING.md](RELEASING.md).
- Exactly one frame per call. The framepool is `numberOfBuffers: 1` and
the session is disposed as soon as the first frame arrives.
- 2-second `FrameTimeout`. Games that never render (minimized, stalled)
surface as `CaptureError.NoFrameArrived`.
- BGRA8 only — pixel format is pinned so the encoder layer doesn't need
a format negotiation step. The Skia/ImageSharp wrappers accept BGRA
directly.
- Win11 22H2+ only. That's the minimum OS for the
`IsBorderRequired = false` flag to actually hide the yellow capture
frame. Older builds still work but show the frame.
## Quality gates
**Fallback path:** if WGC itself fails (legacy GDI-only apps, some
emulators), the orchestrator retries with
[`PrintWindowFallback`](../src/CaptureImage.Infrastructure/Capture/PrintWindowFallback.cs)
which calls `PrintWindow(hwnd, hdc, PW_RENDERFULLCONTENT)`. Slower,
subject to HDCP, but wide compatibility.
## 4. DI composition
[`CompositionRoot.BuildServices`](../src/CaptureImage.App/CompositionRoot.cs)
is the only place DI registrations live. No scanning, no convention, no
assembly-level attributes — everything the runtime sees is explicit in
one file.
```mermaid
graph LR
subgraph "Cross-cutting"
Log[ILogger*]
FS[IFileSystem]
Dispatcher[IUIThreadDispatcher]
Loc[ILocalizationService]
end
subgraph "Domain services"
Settings[ISettingsStore]
Steam[ISteamDetector]
Procs[IProcessWatcher<br/>IProcessDetector]
Cap[ICaptureEngine]
Encoders[IImageEncoder × 2]
Hotkey[IHotkeyService<br/>IHotkeyConflictSniffer]
Update[IUpdateService]
Orch[CaptureOrchestrator]
end
subgraph "UI services"
Toast[IToastService]
Preview[IPreviewPresenter]
Tray[ITrayIconHost]
Nav[INavigationService]
end
subgraph "ViewModels (singletons)"
Main[MainWindowViewModel]
Dash[DashboardViewModel]
Set[SettingsViewModel]
Hk[HotkeyBindingViewModel]
About[AboutViewModel]
Upd[UpdateViewModel]
LogVM[LogViewerViewModel]
end
Dash --> Settings
Dash --> Procs
Dash --> Orch
Dash --> Hotkey
Orch --> Cap
Orch --> Encoders
Orch --> FS
Set --> Settings
Set --> Loc
Set --> Hk
Hk --> Settings
Hk --> Hotkey
```
**Lifetimes:** every service and every viewmodel is a singleton. There
is no request scope — the app is one long-running desktop process with
a single window. `validateScopes: true` is on so DI misuse fails loudly
at startup.
**Startup order:**
1. `VelopackApp.Build().Run()` — must be the first line of `Main` so
Velopack can handle `--squirrel-install`, `--squirrel-firstrun`, etc.
before WinUI 3 spins up.
2. Serilog configured (file sink + in-memory ring buffer for the log
drawer).
3. `BuildServices(inMemorySink)` — container built.
4. `ISettingsStore.LoadAsync()` — settings file read before any VM that
depends on them is resolved.
5. `Microsoft.UI.Xaml.Application.Start(...)` — installs a
`DispatcherQueueSynchronizationContext` on the freshly-minted UI
thread, then constructs the `App` instance which `OnLaunched` shows
the main window.
## 5. i18n + RTL
Resources live as three sibling `.resx` files under
[`src/CaptureImage.UI/Resources/Strings/`](../src/CaptureImage.UI/Resources/Strings):
`Strings.resx` (en-US, neutral), `Strings.vi.resx`, `Strings.ar.resx`.
MSBuild compiles them to satellite assemblies at build time. No
Designer-generated wrapper — we use `ResourceManager` directly.
```mermaid
sequenceDiagram
participant User
participant Settings as SettingsViewModel
participant Loc as ResxLocalizationService
participant RM as ResourceManager
participant XAML as WinUI 3 bindings
User->>Settings: Pick "العربية" in Language dropdown
Settings->>Loc: SetCulture(ar-SA)
Loc->>Loc: CurrentCulture = ar-SA<br/>CurrentFlowDirection = RightToLeft
Loc-->>XAML: PropertyChanged("Item[]")
XAML->>Loc: this["Settings_Hotkey"]
Loc->>RM: GetString(key, ar-SA)
RM-->>Loc: "مفتاح اختصار الالتقاط"
Loc-->>XAML: string
XAML-->>User: window mirrors + text flips
```
**Key properties:**
- `PropertyChanged("Item[]")` is the magic indexer-binding refresh
signal. WinUI 3 picks it up reliably for direct `{Binding Localization[Key]}`
paths; computed `XLabel` properties on each VM (the pattern adopted in
v1.1.2 to work around an Avalonia compiled-binding quirk) carry forward
for live culture switching.
- `MainWindow.xaml` binds `FlowDirection` on its root Grid to
`Localization.CurrentFlowDirection` via `FlowDirectionConverter` (a
static IValueConverter declared at App.xaml `Application.Resources`
scope). Arabic, Hebrew, Farsi, Urdu — any two-letter language code in
the RTL set — mirrors the whole tree.
- No app restart required. Every VM that stores localized text holds
only the key, looks up via the indexer, and refreshes on the
`PropertyChanged` broadcast.
- Translations for VI and AR are machine-assisted today — see
[`docs/legal/DISCLAIMER.md §4`](legal/DISCLAIMER.md). Native-speaker
review is the next milestone's ask.
## 6. Update flow (Velopack)
[`VelopackUpdateService`](../src/CaptureImage.Infrastructure/Update/VelopackUpdateService.cs)
wraps Velopack's `UpdateManager` pointed at the GitHub Releases source.
Everything is explicit — no background timer, no silent upgrades. The
user clicks **Check for updates**, optionally **Download**, optionally
**Install and restart**.
```mermaid
sequenceDiagram
participant Main as Program.Main
participant Velo as VelopackApp
participant User
participant UI as UpdateView
participant VM as UpdateViewModel
participant Svc as VelopackUpdateService
participant GH as GitHub Releases
participant Mgr as UpdateManager
Main->>Velo: Build().Run(args)
Note over Velo: Handles --squirrel-install,<br/>--squirrel-firstrun etc.<br/>then returns to caller
Main->>Main: Application.Start(...)
User->>UI: Click "Check for updates"
UI->>VM: CheckCommand
VM->>Svc: CheckAsync()
Svc->>Mgr: CheckForUpdatesAsync()
Mgr->>GH: GET /releases/latest
GH-->>Mgr: UpdateInfo (or null)
Mgr-->>Svc: UpdateInfo
Svc-->>VM: UpdateCheckResult
VM-->>UI: Status + version + release notes
User->>UI: Click "Download"
UI->>VM: DownloadCommand
VM->>Svc: DownloadAsync(progress)
Svc->>Mgr: DownloadUpdatesAsync(IProgress<int>)
Mgr->>GH: GET /releases/.../CaptureImage-full.nupkg
GH-->>Mgr: stream
Mgr-->>Svc: done
Svc-->>VM: Status=ReadyToInstall
User->>UI: Click "Install & restart"
UI->>VM: InstallCommand
VM->>Svc: ApplyAndRestart()
Svc->>Mgr: ApplyUpdatesAndRestart()
Note over Mgr: Velopack spawns Update.exe,<br/>kills current process,<br/>swaps files, relaunches
```
**Development-mode caveat:** when the app is launched via
`dotnet run` (not from a Velopack-installed location), `UpdateManager`
reports `IsInstalled = false` and the service returns
`UpdateStatus.Unavailable`. The update tab still renders, it just tells
you updates are disabled and why. Release builds installed via `Setup.exe`
have `IsInstalled = true` and the full flow works.
**Unsigned installer today.** Velopack can sign the installer if given a
cert; CaptureImage doesn't have one yet (SignPath application was
declined for v1.0). Users see Windows SmartScreen's "Unknown publisher"
warning on first run. Integrity is still verifiable via the
`SHA256SUMS.txt` published alongside every release.
---
## See also
- [`docs/RELEASING.md`](RELEASING.md) — how releases are cut and
published.
- [`docs/CONTRIBUTORS.md`](CONTRIBUTORS.md) — contribution flow, AI
assistance policy, translation hand-off.
- [`docs/legal/`](legal) — disclaimers, privacy, third-party notices.
- The `Co-Authored-By` commit trailers naming Claude Opus 4.7 — see
the git log for per-milestone design notes that influenced this
architecture.
Every pull request runs: build with warnings as errors and the recommended .NET analyzers; unit,
view-model and integration tests with coverage; formatting and SPDX headers; JetBrains InspectCode
(dead and redundant code); vulnerable and incompatibly licensed dependencies; a publish of the app
followed by a smoke test that opens every page; PR title; dependency review; workflow lint
(actionlint, zizmor); Markdown lint and link check. End-to-end UI tests (FlaUI), CodeQL, OpenSSF
Scorecard and SonarCloud run as well.
+32 -69
View File
@@ -1,91 +1,54 @@
# Contributors
_Last updated: 2026-04-15_
_Last updated: 2026-10-19_
## Maintainer
- **poli0981** — project owner, design decisions, code review, release
management. All commits are signed off by the maintainer before landing
in the default branch.
- **poli0981** — project owner: design decisions, code review, releases. Every change is reviewed and
accepted by the maintainer before it lands on `main`.
## AI assistance
Development of CaptureImage was carried out with significant assistance
from the **Claude Opus 4.6** large language model (Anthropic), used
through Claude Code, during the 2026 development cycle. This assistance
was pair-programming-style: the maintainer drove requirements, chose
trade-offs, and reviewed every change, while the model generated code,
unit tests, XAML layouts, P/Invoke signatures, commit messages, and
documentation (including the file you are reading now).
CaptureImage is developed with substantial help from an AI coding assistant — **Claude
(Anthropic), used through Claude Code**. The work is pair-programming style: the maintainer sets the
requirements, chooses the trade-offs and reviews every change, while the assistant drafts code,
tests, Windows interop, user-interface layouts, translations, commit messages and documentation
(including this file).
Commits where AI authored significant portions of the diff carry the
trailer:
Commits where the assistant wrote a significant part of the change carry a trailer such as:
```
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
```text
Co-Authored-By: Claude <model name> <noreply@anthropic.com>
```
This follows the git convention documented at
<https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors>.
The co-author trailer is an attribution mechanism; it does not give the
model any copyright over the output — per Anthropic's usage terms and
current US Copyright Office guidance, AI-generated material is not
copyrightable by the model itself. The resulting project is licensed
under **GPL-3.0-or-later** by the human maintainer and contributors.
If this distinction matters for your use case (for example, your
organization prohibits shipping AI-assisted code in production), please
audit the git history. Every commit's full diff is available via
`git show` and the co-author trailer is visible in the commit message.
following GitHub's
[multiple-authors convention](https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors).
The trailer is attribution only; the project is licensed under **GPL-3.0-or-later** by its human
maintainer and contributors. If AI-assisted code matters for your use (for example, a policy against
shipping it), the full history is available with `git log` and `git show`.
## How to contribute
Contributions are welcome. The general flow is:
1. Open an issue describing the bug or feature before starting work on
anything non-trivial. A short discussion avoids duplicated effort.
2. Fork the repository and create a feature branch from `main`.
3. Keep commits small and focused. Use conventional-commits style:
`feat(m5): …`, `fix(capture): …`, `docs(legal): …`, etc.
4. Run `dotnet build CaptureImage.sln` and `dotnet test CaptureImage.sln`
locally. Every PR must ship with the full suite passing.
5. For UI changes, include before/after screenshots or a short video.
6. If your change was AI-assisted, say so in the PR description — it
helps reviewers focus their attention.
7. Open a pull request.
By submitting a contribution, you agree that it can be distributed under
GPL-3.0-or-later as part of CaptureImage (see [TERMS.md](legal/TERMS.md)
§5).
See [`CONTRIBUTING.md`](../CONTRIBUTING.md) for the development setup, the required checks and the
conventions. By contributing you agree that your work is distributed under GPL-3.0-or-later as part
of CaptureImage (see [`legal/TERMS.md`](legal/TERMS.md), section 5).
## Translation help wanted
The Vietnamese (`vi-VN`) and Arabic (`ar-SA`) language packs were
produced with machine assistance. Native speakers who can review the
shipped strings are warmly invited to open a PR against
`src/CaptureImage.UI/Resources/Strings/Strings.*.resx`. Small
improvements are welcome — please submit the smallest possible diff and
explain the reasoning for each string change in the PR body.
All 11 languages were produced or completed with AI assistance. Native speakers who can review the
strings in `src/CaptureImage.ViewModels/Resources/Strings/Strings.*.resx` are warmly invited to
open a pull request — small, focused changes with a short reason per string are easiest to review.
## Acknowledgements
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:
CaptureImage is built on open-source work; the full list with licenses is in
[`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md). Special thanks to:
- 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`.
- The **Velopack** team for making installer + updater flow for desktop
.NET apps genuinely easy.
- The **Vortice.Windows** team for high-quality, actively-maintained
Direct3D/DXGI bindings.
- The **SharpHook** team for cross-platform global keyboard hooks that
"just work" on .NET.
- **WPF UI** (lepo.co) for the Fluent controls the 2.x interface is built with.
- **H.NotifyIcon** for the tray icon.
- **OBS Studio**, whose public Windows Graphics Capture code was a useful reference.
- **Velopack** for the installer and updater.
- **Vortice.Windows** for Direct3D, DXGI and WIC bindings, and **SkiaSharp** for image encoding.
- **Serilog** and **CommunityToolkit.Mvvm**.
- **Avalonia UI** (versions 1.0–1.2) and **WinUI 3 / Windows App SDK** (1.3–1.5), the frameworks
earlier versions of CaptureImage were built on.
+67 -154
View File
@@ -1,176 +1,89 @@
# Releasing CaptureImage
_Last updated: 2026-04-15_
_Last updated: 2026-10-19 (CaptureImage 2.0)_
This document describes how to cut a new release of CaptureImage end to
end: tagging, CI/CD, verifying the installer, and what to tell users
about the unsigned-binary warning.
Releases are built by [`.github/workflows/release.yml`](../.github/workflows/release.yml) from a
signed tag and published as a **draft** first. Nothing reaches users until a maintainer publishes
the draft.
## 1. Prerequisites
## 1. Prepare the release pull request
You need:
1. Make sure `main` is green.
2. On a branch (e.g. `chore/release-2.1.0`):
- set `<Version>` in [`Directory.Build.props`](../Directory.Build.props) — the single source of
the version; the release workflow refuses a tag that doesn't match it;
- rename `## [Unreleased]` in [`CHANGELOG.md`](../CHANGELOG.md) to `## [2.1.0] - YYYY-MM-DD` and
add a new empty `## [Unreleased]` above it. The workflow uses this section as the release notes
shown in the app and on GitHub.
3. Open the pull request, let the required checks pass, squash-merge.
- Push access to <https://github.com/poli0981/captureimg>.
- The working tree on `main` is clean and all tests pass locally:
```powershell
dotnet build CaptureImage.sln -c Release /p:TreatWarningsAsErrors=true
dotnet test CaptureImage.sln -c Release
```
- `CHANGELOG.md` has an entry for the release under `[Unreleased]`.
Move the entries into a new `## [1.0.0] - 2026-MM-DD` section before
tagging — the CI release workflow does not rewrite the file.
## 2. Tag
## 2. Cutting a release
Tags must be signed (the `main` branch and `v*` tags are protected by rulesets; tags can't be moved
or deleted once pushed).
Releases are cut by pushing a tag. The tag triggers
[`.github/workflows/release.yml`](../.github/workflows/release.yml) which
builds, tests, publishes a single-file self-contained Win64 build, wraps
it with Velopack, computes SHA256 checksums, and uploads everything as a
GitHub Release.
```powershell
# Update the version number in the source metadata.
# (Directory.Build.props already sets <Version> to the target release.)
# Commit the CHANGELOG bump.
git add CHANGELOG.md
git commit -m "chore(release): CaptureImage v1.0.0"
# Create and push the tag. Use an annotated tag with a release message.
git tag -a v1.0.0 -m "CaptureImage v1.0.0"
git push origin main
git push origin v1.0.0
```bash
git switch main
git pull --ff-only
git tag -s v2.1.0 -m "CaptureImage v2.1.0"
git push origin v2.1.0
```
Within a minute or two, GitHub Actions should show a `Release` workflow
running. Total build time is about 8–12 minutes on a `windows-latest`
runner.
The workflow then:
When the workflow finishes:
1. checks the tag is SemVer and equals `<Version>`;
2. restores with lock files, builds, runs all tests;
3. publishes the app (framework-dependent, `win-x64`) and runs it with `--smoke-test`;
4. packs it with Velopack (`vpk`, same version as the library): package id `CaptureImage`, main
executable `CaptureImage.App.exe`, channel `win`, shortcuts on the desktop and Start menu, the
.NET 10 Desktop Runtime as a prerequisite, full packages only;
5. adds a CycloneDX SBOM and `SHA256SUMS.txt`, attests build provenance, and creates or updates a
**draft** release with all assets.
- A new GitHub Release appears under
<https://github.com/poli0981/captureimg/releases>.
- It contains `Setup.exe`, the Velopack `.nupkg`, the `RELEASES`
manifest, and `SHA256SUMS.txt`.
- A workflow artifact bundle is also uploaded as a backup.
> Never change the package id, executable name, channel or shortcut set — installed copies would
> stop updating or end up with duplicate shortcuts.
## 3. If the workflow fails mid-run
## 3. Verify the draft
Do NOT manually create a release with the broken artifacts. Instead:
- [ ] Assets: `CaptureImage-win-Setup.exe`, `CaptureImage-win-Portable.zip`,
`CaptureImage-<version>-full.nupkg`, `releases.win.json`, `assets.win.json`, `RELEASES`,
`SHA256SUMS.txt`, `CaptureImage-<version>-sbom.cdx.json`.
- [ ] `gh attestation verify CaptureImage-win-Setup.exe --repo poli0981/captureimg` succeeds.
- [ ] On a clean machine or Windows Sandbox: Setup installs (and installs the .NET runtime if
missing), the app starts, About shows the new version.
- [ ] Update path: install the previous release, then apply the new package
(`Update.exe apply --package <full.nupkg>` in the install folder, or the in-app updater once
published) — settings are kept and migrated.
- [ ] The portable zip starts with `--smoke-test --data-dir <temp>` and exits 0.
1. Investigate the failure in the Actions tab.
2. Delete the broken tag both locally and on GitHub:
```powershell
git tag -d v1.0.0
git push --delete origin v1.0.0
```
3. Fix the underlying problem on `main`.
4. Re-tag and re-push.
## 4. Publish
This keeps the GitHub Releases page as a trustworthy source of truth —
every release there was produced by a clean, green workflow run.
## 4. Post-release checklist
After the release publishes, verify by hand:
- [ ] `Setup.exe` downloads from the Release page.
- [ ] `Setup.exe` installs to `%LocalAppData%\CaptureImage\app-<version>\`
(Velopack default).
- [ ] First launch opens the main window without crashing.
- [ ] `About` tab shows the new version number.
- [ ] The `Update` tab can hit GitHub and reports the installed version
matches the latest release.
- [ ] `%LocalAppData%\CaptureImage\logs\captureimg-<today>.log` contains
`"Velopack update service initialized: installed=True"`.
Also update `docs/CONTRIBUTORS.md` if new contributors landed during the
cycle, and post a short release note in GitHub Discussions if the user
community wants one.
## 5. Unsigned installer — Windows SmartScreen
**CaptureImage is currently NOT code-signed.** The project applied to
<https://signpath.io>'s free OSS program and was declined in the first
round. Until a signing certificate is available, every download will
trigger Windows SmartScreen:
> Windows protected your PC
> Microsoft Defender SmartScreen prevented an unrecognized app from
> starting. Running this app might put your PC at risk.
Users can proceed via **More info** → **Run anyway**, but many will
reasonably refuse. To mitigate:
1. The GitHub Release description links to the `SHA256SUMS.txt` file
and explains how to verify the download:
```powershell
Get-FileHash -Algorithm SHA256 Setup.exe
# Compare the output with the hash listed in SHA256SUMS.txt
```
2. [`docs/legal/DISCLAIMER.md §7`](legal/DISCLAIMER.md) explicitly
documents the unsigned state and the SmartScreen warning so users
know it is expected, not a compromise.
3. When SmartScreen "Unknown publisher" warnings decrease over time
(SmartScreen learns reputation from download volume + age), we
re-evaluate whether manual signing is worth the cost.
### When signing becomes available
- [ ] Re-apply to SignPath.io with a more polished project description,
public download count, and signed commits history.
- [ ] Alternatively, purchase an Azure Trusted Signing subscription
(~$10/month) or a cheap EV cert from a CA that issues to individuals.
- [ ] Add a `SIGN_EXE` step to `.github/workflows/release.yml` after
`vpk pack` that calls `signtool sign` on `Setup.exe` and every
intermediate `.nupkg` contents.
- [ ] Re-run `vpk pack` with the signed binaries so the installer embeds
the signed files.
- [ ] Update `docs/legal/DISCLAIMER.md §7` to remove the unsigned note.
- [ ] Update this file's §5 to describe the signing step.
## 6. Manual release (emergency only)
If CI is down and you must cut a release by hand, run locally:
```powershell
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:Version=1.0.0 `
-o .\publish
dotnet tool install --global vpk
vpk pack `
--packId CaptureImage `
--packVersion 1.0.0 `
--packDir .\publish `
--mainExe CaptureImage.App.exe `
--outputDir .\releases
Get-ChildItem .\releases -File | ForEach-Object {
(Get-FileHash $_ -Algorithm SHA256).Hash.ToLower() + " " + $_.Name
} | Out-File .\releases\SHA256SUMS.txt -Encoding utf8
# Create the Release manually via the GitHub web UI and attach every
# file from .\releases\ including SHA256SUMS.txt.
```bash
gh release edit v2.1.0 --draft=false
```
Prefer CI over manual releases — every manual release is one more
build environment to audit.
Publishing with your own token triggers `release: published`, which runs the announcement workflow.
Installed copies see the update on their next check.
## 7. Version policy
## 5. When something goes wrong
CaptureImage uses [Semantic Versioning](https://semver.org) with one
practical twist: as long as the app is pre-1.0 internally (i.e. the
user community is tiny), breaking changes between 1.x.y releases are
still avoided, and API changes in the plugin surface (once that exists)
are flagged in `CHANGELOG.md` as **BREAKING**.
- **The workflow failed** — fix the problem on `main`, then re-run it for the same tag with
**Actions → Release → Run workflow** (`tag: v2.1.0`, `dry_run: false`). It checks out the tag with
the workflow from `main`, so a broken tag doesn't need to be moved. Use `dry_run: true` to build
and pack without touching the release.
- **A bad release was published** — publish a fixed patch release; don't delete the old one (users
may be mid-update). Mark the bad one as pre-release or edit its notes if needed.
- `MAJOR` bumps when the capture engine gains or loses a backend.
- `MINOR` bumps for new user-visible features.
- `PATCH` bumps for bug fixes and security updates.
## 6. Code signing
Velopack deltas are generated automatically by `vpk pack` — users on an
older version will get a diff download instead of the full installer.
The installer isn't Authenticode-signed yet (the SignPath application was declined), so SmartScreen
warns about an unknown publisher. Users can verify downloads with `SHA256SUMS.txt` or the
build-provenance attestation — see [`legal/DISCLAIMER.md`](legal/DISCLAIMER.md), section 7. When a
certificate becomes available (SignPath, Azure Artifact Signing or a CA), sign with `vpk pack
--signTemplate` / `--azureTrustedSignFile` and update the disclaimer.
## 7. Versioning
[Semantic Versioning](https://semver.org): **major** for breaking changes to behavior, settings or
supported systems; **minor** for new features; **patch** for fixes. Pre-releases use a suffix
(`v2.1.0-beta.1`) and are marked as pre-releases automatically; the in-app updater ignores them.
+31 -52
View File
@@ -1,74 +1,53 @@
# Development environment
This document lists the toolchain versions used to build, test, and
release CaptureImage. Hardware reference: [`docs/pc_spec.md`](pc_spec.md).
Vietnamese mirror: [`docs/i18n/vi/dev_env.md`](i18n/vi/dev_env.md).
The toolchain used to build, test and release CaptureImage. Hardware reference:
[`pc_spec.md`](pc_spec.md). Vietnamese version: [`i18n/vi/dev_env.md`](i18n/vi/dev_env.md).
## Toolchains
## Toolchain
| Toolchain | Version | Purpose |
|-------------|----------------------------------------|-----------------------------------------------|
| **.NET SDK**| 9.0 (exact version pinned in [`global.json`](../global.json)) | Primary build / test runtime |
| **Python** | 3.12 | Release scripting, Discord notification helper (`.github/scripts/discord_notify.py`) |
| **Node.js** | ≥ 22 LTS | Future docs site / web companion tooling |
| **Rust** | stable, via `rustup` | Reserved for future native helpers (none in v1.5.x) |
| **Git** | recent (≥ 2.40) | Source control |
| **GPG** | any version supporting Ed25519 | Commit + tag signing — `commit.gpgsign=true` is set repo-wide; tag signing required per [`docs/RELEASING.md`](RELEASING.md) |
| Tool | Version | Purpose |
|---|---|---|
| **.NET SDK** | 10.0 (exact feature band pinned in [`global.json`](../global.json)) | Build, test, run |
| **Windows** | 11 22H2 or later | Required by the WPF app and `Windows.Graphics.Capture` |
| **Git** | 2.40 or later | Source control |
| **GPG** | with Ed25519 support | Signed commits and tags (required on `main` and for release tags) |
| **GitHub CLI** (`gh`) | recent | Pull requests, releases, attestation checks |
| **Node.js** | 22 LTS or later | `markdownlint-cli2` for the docs check (optional locally) |
The CI runner uses `actions/setup-dotnet@v5` with `global-json-file:
global.json`, so the local and CI .NET versions are guaranteed to
match — see [`.github/workflows/ci.yml`](../.github/workflows/ci.yml).
The Windows SDK projections come from NuGet with the target framework
(`net10.0-windows10.0.22621.0`); no separate Windows SDK install is needed. CI uses
`actions/setup-dotnet` with `global-json-file: global.json`, so local and CI SDKs match.
## IDE setup
.NET tools used by CI are pinned in [`.config/dotnet-tools.json`](../.config/dotnet-tools.json) and
installed with `dotnet tool restore`: `vpk` (Velopack), JetBrains InspectCode, `nuget-license`,
ReportGenerator and CycloneDX.
Primary: **JetBrains Rider 2026.x** (paid lineup). Recommended Rider
plugins:
## Editors
- *.NET Core User Secrets* (built in)
- *Markdown* (built in)
- *Resource Bundle Editor* — handy when editing the 11 `.resx`
locale files at once
([`src/CaptureImage.UI/Resources/Strings/`](../src/CaptureImage.UI/Resources/Strings/))
- **JetBrains Rider** (primary) — the ReSharper inspections match the `deadcode` CI check.
- **Visual Studio 2026** or **Visual Studio Code** with the C# Dev Kit also work.
Sibling JetBrains IDEs used on adjacent projects: **PyCharm**,
**WebStorm**, **RustRover**.
Secondary: **Visual Studio Code** with the C# Dev Kit extension for
quick edits.
## Windows SDK
WinUI 3 + `Windows.Graphics.Capture` projections require the
**Windows 11 22H2 SDK** (10.0.22621). Install via the Visual Studio
Installer ("Windows 11 SDK (10.0.22621.x)") or directly from
<https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/>.
## Build / test / run
## Build, test, run
```powershell
git clone https://github.com/poli0981/captureimg.git
cd captureimg
dotnet restore
dotnet build CaptureImage.sln -c Release
dotnet test CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release
dotnet test --solution CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release -- --data-dir .\.devdata --instance-id dev
```
The CI commands are a literal mirror of the above plus
`/p:TreatWarningsAsErrors=true /p:WarningsAsErrors=nullable` — run
the same locally before opening a PR.
Warnings are errors and `src/` uses the recommended .NET analyzers, so a clean local build means the
CI build will compile too. See [`CONTRIBUTING.md`](../CONTRIBUTING.md) for the formatting commands
and the full list of required checks.
## Release tooling
- **Velopack** (`vpk` CLI) — packaging + delta updates.
- **`gh`** (GitHub CLI) — creating Releases, uploading artifacts,
fetching SHAs (the reusable-workflow pin lookup in
[`docs/RELEASING.md`](RELEASING.md)).
- See [`docs/RELEASING.md`](RELEASING.md) for the end-to-end cycle.
Releases are produced by GitHub Actions from signed tags — see [`RELEASING.md`](RELEASING.md).
## Related documents
- [`docs/pc_spec.md`](pc_spec.md) — hardware reference.
- [`docs/ARCHITECTURE.md`](ARCHITECTURE.md) — software architecture.
- [`docs/CONTRIBUTORS.md`](CONTRIBUTORS.md) — contribution policy.
- [`README.md`](../README.md) — project overview.
- [`pc_spec.md`](pc_spec.md) — hardware reference.
- [`ARCHITECTURE.md`](ARCHITECTURE.md) — how the app is built.
- [`CONTRIBUTORS.md`](CONTRIBUTORS.md) — contributors and AI-assistance policy.
- [`../README.md`](../README.md) — project overview.
+33 -56
View File
@@ -1,77 +1,54 @@
# Môi trường phát triển
Tài liệu này liệt kê các phiên bản toolchain dùng để build, test
và release CaptureImage. Tham chiếu phần cứng:
[`pc_spec.md`](pc_spec.md). Bản tiếng Anh:
[`docs/dev_env.md`](../../dev_env.md).
Bộ công cụ dùng để build, test và phát hành CaptureImage. Tham chiếu phần cứng:
[`pc_spec.md`](pc_spec.md). Bản tiếng Anh: [`dev_env.md`](../../dev_env.md).
## Toolchain
## Công cụ
| Toolchain | Version | Purpose |
|-------------|----------------------------------------|-----------------------------------------------|
| **.NET SDK**| 9.0 (pin chính xác trong [`global.json`](../../../global.json)) | Build + test runtime chính |
| **Python** | 3.12 | Release scripting, Discord notification helper (`.github/scripts/discord_notify.py`) |
| **Node.js** | ≥ 22 LTS | Docs site / web companion tooling tương lai |
| **Rust** | stable, qua `rustup` | Dự phòng cho native helper tương lai (chưa có trong v1.5.x) |
| **Git** | mới (≥ 2.40) | Source control |
| **GPG** | bất kỳ phiên bản nào hỗ trợ Ed25519 | Ký commit + tag — `commit.gpgsign=true` được bật repo-wide; tag signing là bắt buộc theo [`docs/RELEASING.md`](../../RELEASING.md) |
| Công cụ | Phiên bản | Mục đích |
|---|---|---|
| **.NET SDK** | 10.0 (feature band cụ thể được pin trong [`global.json`](../../../global.json)) | Build, test, chạy |
| **Windows** | 11 22H2 trở lên | Bắt buộc cho app WPF và `Windows.Graphics.Capture` |
| **Git** | 2.40 trở lên | Quản lý mã nguồn |
| **GPG** | có hỗ trợ Ed25519 | Ký commit và tag (bắt buộc trên `main` và cho tag phát hành) |
| **GitHub CLI** (`gh`) | bản mới | Pull request, phát hành, kiểm tra attestation |
| **Node.js** | 22 LTS trở lên | `markdownlint-cli2` cho bước kiểm tra docs (không bắt buộc khi làm local) |
CI runner dùng `actions/setup-dotnet@v5` với `global-json-file:
global.json`, nên phiên bản .NET local và CI đảm bảo khớp nhau —
xem [`.github/workflows/ci.yml`](../../../.github/workflows/ci.yml).
Các projection của Windows SDK được lấy từ NuGet theo target framework
(`net10.0-windows10.0.22621.0`); không cần cài Windows SDK riêng. CI dùng `actions/setup-dotnet` với
`global-json-file: global.json`, nên SDK ở máy local và CI luôn khớp nhau.
## Cấu hình IDE
Các .NET tool mà CI dùng được pin trong
[`.config/dotnet-tools.json`](../../../.config/dotnet-tools.json) và cài bằng `dotnet tool restore`:
`vpk` (Velopack), JetBrains InspectCode, `nuget-license`, ReportGenerator và CycloneDX.
Chính: **JetBrains Rider 2026.x** (paid lineup). Plugin Rider khuyến
nghị:
## Trình soạn thảo
- *.NET Core User Secrets* (có sẵn)
- *Markdown* (có sẵn)
- *Resource Bundle Editor* — tiện khi edit 11 file `.resx` locale
cùng lúc
([`src/CaptureImage.UI/Resources/Strings/`](../../../src/CaptureImage.UI/Resources/Strings/))
- **JetBrains Rider** (chính) — các inspection của ReSharper khớp với bước kiểm tra `deadcode`
trên CI.
- **Visual Studio 2026** hoặc **Visual Studio Code** với C# Dev Kit cũng dùng được.
JetBrains IDE anh em dùng trên các project lân cận: **PyCharm**,
**WebStorm**, **RustRover**.
Phụ: **Visual Studio Code** với extension C# Dev Kit cho các edit
nhanh.
## Windows SDK
WinUI 3 + projection của `Windows.Graphics.Capture` yêu cầu
**Windows 11 22H2 SDK** (10.0.22621). Cài qua Visual Studio
Installer ("Windows 11 SDK (10.0.22621.x)") hoặc trực tiếp từ
<https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/>.
## Build / test / run
## Build, test, chạy
```powershell
git clone https://github.com/poli0981/captureimg.git
cd captureimg
dotnet restore
dotnet build CaptureImage.sln -c Release
dotnet test CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release
dotnet test --solution CaptureImage.sln -c Release
dotnet run --project src/CaptureImage.App -c Release -- --data-dir .\.devdata --instance-id dev
```
Lệnh trên CI là mirror chính xác của các lệnh trên, có thêm
`/p:TreatWarningsAsErrors=true /p:WarningsAsErrors=nullable` —
chạy y hệt ở local trước khi mở PR.
Warning được coi là lỗi và `src/` bật bộ analyzer khuyến nghị của .NET, nên build sạch ở local nghĩa
là bước build trên CI cũng biên dịch được. Xem [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) để biết
các lệnh format và toàn bộ danh sách check bắt buộc.
## Release tooling
## Công cụ phát hành
- **Velopack** (`vpk` CLI) — packaging + delta update.
- **`gh`** (GitHub CLI) — tạo Release, upload artifact, fetch SHA
(lookup SHA của reusable-workflow pin trong
[`docs/RELEASING.md`](../../RELEASING.md)).
- Xem [`docs/RELEASING.md`](../../RELEASING.md) cho chu trình end-to-end.
Bản phát hành được GitHub Actions tạo từ tag đã ký — xem [`RELEASING.md`](../../RELEASING.md).
## Tài liệu liên quan
- [`pc_spec.md`](pc_spec.md) — tham chiếu phần cứng (bản VI).
- [`docs/ARCHITECTURE.md`](../../ARCHITECTURE.md) — kiến trúc phần
mềm (EN, chưa có bản VI).
- [`docs/CONTRIBUTORS.md`](../../CONTRIBUTORS.md) — chính sách đóng
góp (EN, chưa có bản VI).
- [`README.md`](../../../README.md) — tổng quan project.
- [`pc_spec.md`](pc_spec.md) — cấu hình phần cứng.
- [`ARCHITECTURE.md`](../../ARCHITECTURE.md) — kiến trúc của app.
- [`CONTRIBUTORS.md`](../../CONTRIBUTORS.md) — người đóng góp và chính sách hỗ trợ AI.
- [`README.md`](../../../README.md) — tổng quan dự án.
+5 -5
View File
@@ -12,14 +12,14 @@ Bản tiếng Anh: [`docs/pc_spec.md`](../../pc_spec.md).
| Component | Details |
|-------------|-------------------------------------------------------------------|
| **OS** | Windows 11 Pro 25H2 Insider Preview (Dev Channel), build 26300.8376 |
| **OS** | Windows 11 Pro Insider Preview, build 29648 |
| **CPU** | Intel Core i7-14700KF |
| **GPU** | NVIDIA GeForce RTX 5080 (16 GB VRAM) |
| **RAM** | 32 GB DDR5 |
| **Storage** | 1 TB SSD |
| **IDE** | JetBrains 2026.x paid lineup (Rider cho repo này; PyCharm / WebStorm / RustRover cho các project anh em) + Visual Studio Code |
Việc dùng Windows Insider Dev Channel là có chủ đích — CaptureImage
Việc dùng bản Windows Insider là có chủ đích — CaptureImage
khai thác bề mặt API mới nhất của `Windows.Graphics.Capture` và
hưởng lợi khi chạy trên build đi trước stable, nhờ vậy regression
trên các phiên bản public sắp tới được phát hiện sớm.
@@ -35,14 +35,14 @@ Khi phần đó được triển khai, browser test trên mobile sẽ chạy tr
Browser test trên iOS: **Chrome**, **Brave**.
> **Ghi chú.** Bản thân CaptureImage là một desktop application
> Windows 11 (WinUI 3 / Windows App SDK), không có build iOS / web.
> Windows 11 (WPF trên .NET 10), không có build iOS / web.
> Các thiết bị mobile ở trên được liệt kê để minh bạch về test fleet
> tổng thể của maintainer; không dùng để validate CaptureImage.
## Tài liệu liên quan
- [`dev_env.md`](dev_env.md) — phiên bản toolchain (Python, Node,
Rust, Git) và cấu hình IDE (bản VI).
- [`dev_env.md`](dev_env.md) — phiên bản toolchain (.NET SDK, Git,
GPG, Node.js) và cấu hình IDE (bản VI).
- [`README.md` § Requirements](../../../README.md#requirements) —
yêu cầu runtime cho người dùng cuối (Windows 11 22H2+, không yêu
cầu GPU cụ thể).
+78 -122
View File
@@ -1,158 +1,114 @@
# Disclaimer
_Last updated: 2026-04-15_
_Last updated: 2026-10-19 (CaptureImage 2.0)_
This document describes the known limitations of **CaptureImage** and the
caveats that apply to its development, translations, and licensing. Please
read it before using the application in any production or archival setting.
This document describes the known limitations of **CaptureImage** and the caveats that apply to its
development, translations and licensing. Please read it before relying on the application.
## 1. No warranty
CaptureImage is licensed under the **GNU General Public License v3.0 or
later** (see [`LICENSE`](../../LICENSE)). Under Sections 15 and 16 of that
license, the software is provided **"AS IS"**, without warranty of any kind,
express or implied, including but not limited to the warranties of
merchantability, fitness for a particular purpose, and non-infringement.
CaptureImage is licensed under the **GNU General Public License v3.0 or later** (see
[`LICENSE`](../../LICENSE)). Under sections 15 and 16 of that license the software is provided
**"AS IS"**, without warranty of any kind, express or implied, including the warranties of
merchantability, fitness for a particular purpose and non-infringement.
The author(s) and contributors shall not be held liable for any claim,
damages, or other liability, whether in an action of contract, tort, or
otherwise, arising from, out of, or in connection with the software or the
use or other dealings in the software — including, without limitation:
The authors and contributors are not liable for any claim, damages or other liability arising from
the software or its use — including, without limitation:
- lost or corrupted screenshots,
- game crashes, anti-cheat bans, or account suspensions caused by third-party
software interacting with a title's process,
- data loss resulting from disk full errors, abrupt shutdowns, or failed
atomic file writes, or
- any consequence of running an unsigned binary, a self-built binary, or a
binary downloaded from an unofficial source.
- game crashes, anti-cheat actions or account suspensions involving third-party software that
interacts with a game,
- data loss from full disks or abrupt shutdowns, or
- any consequence of running an unsigned, self-built or unofficially distributed binary.
**Use at your own risk.**
## 2. Capture support is not universal
CaptureImage is designed to capture the visible surface of a target window
using the Windows `Windows.Graphics.Capture` API, with an optional GDI
`PrintWindow` fallback for legacy windowed applications. **It does not, and
by design cannot, capture every application or game.** Known limitations
include, without limitation:
CaptureImage captures windows and screens with the Windows `Windows.Graphics.Capture` API. **It
does not, and by design cannot, capture every application or game.** Known limitations include:
1. **DRM / protected content.** Applications that mark their swap chain as
protected (DRM movie players, secure conferencing, some banking apps) will
produce either an all-black frame or a `ProtectedContent` error. This is a
Windows-level restriction, not a bug in CaptureImage.
2. **Exclusive-fullscreen Direct3D 9 titles.** Some older games that refuse
to register with the Desktop Window Manager cannot be captured by
Windows.Graphics.Capture. The GDI fallback may return a black frame for
these as well.
3. **Anti-cheat protected titles.** Games protected by kernel-mode anti-cheat
systems (VAC, EAC, BattlEye, Vanguard, etc.) may block external capture
tools, or — in rare cases — treat such tools as untrusted and apply
account sanctions. CaptureImage is **not** a cheat and does not read game
memory or inject code, but anti-cheat heuristics are outside our control.
If a given title's anti-cheat flags this tool, **stop using it with that
title immediately** and report the incident via the project's issue
tracker.
4. **High-DPI / multi-monitor mismatches.** When a target window spans two
monitors with different scale factors, the captured frame may include
scaling artifacts at the monitor boundary.
5. **Layered / transparent windows.** Capture fidelity for windows that rely
heavily on layered composition (e.g. some overlays, screen reader
highlights) is best-effort and may omit overlay effects.
6. **Minimized or occluded windows.** A minimized window has no live surface
to capture. Windows.Graphics.Capture may deliver a stale cached frame,
the last-rendered bitmap, or time out with `NoFrameArrived`.
1. **Protected content.** Windows that mark their content as protected (DRM video, some
conferencing and banking apps) produce a black image or a "protected content" error. This is a
Windows restriction.
2. **Exclusive full-screen games.** Some older games that bypass the desktop compositor cannot be
captured, and the region overlays and notifications cannot appear above them. Borderless or
windowed mode usually works.
3. **Anti-cheat.** Games protected by kernel-level anti-cheat (VAC, EAC, BattlEye, Vanguard and
others) may block external capture. CaptureImage does not read game memory or inject code, but
anti-cheat decisions are outside our control. If a game's anti-cheat objects to CaptureImage,
**stop using it with that game** and tell us (§8).
4. **Hotkeys.** While armed, the capture hotkeys are registered with Windows, so the game and other
apps do not receive those key combinations; disarm to give them back. A few games read the
keyboard in a way that bypasses registered hotkeys — use the tray menu's region or screen capture
there.
5. **HDR.** HDR captures are tone-mapped to a standard image using the display's SDR white level.
Colors and highlights are an approximation of what an HDR display shows; keep the JPEG XR original
if exact HDR data matters.
6. **Minimized windows** have nothing to capture; restore the window first.
7. **Mixed-DPI setups.** A window spanning monitors with different scaling may show scaling seams in
its capture.
If a specific title does not work, please file an issue describing the game,
its graphics API, whether it runs windowed / borderless / fullscreen, and
whether the `PrintWindow` fallback was also unable to capture it.
If a game does not work, please open an issue with the game, its graphics API, and whether it runs
windowed, borderless or full screen.
## 3. Development was AI-assisted
## 3. Development is AI-assisted
The implementation of CaptureImage was carried out with significant
assistance from the **Claude Opus 4.6** large language model (Anthropic),
used through Claude Code, during the 2026 development cycle. AI assistance
included — but was not limited to — code generation, unit test drafting,
architectural design proposals, Win32 / WinRT interop troubleshooting,
P/Invoke signature authoring, XAML layout, commit message drafting, and
documentation writing (including this disclaimer).
CaptureImage is developed with substantial help from an AI coding assistant — Claude (Anthropic),
used through Claude Code — for code, tests, Windows interop, user-interface layout, translations,
commit messages and documentation (including this disclaimer).
Every change was reviewed, accepted, and tested by a human maintainer
before landing in version control. However, AI-assisted code may still
contain subtle errors, non-idiomatic patterns, or references to APIs that
behave differently than the model expected. Users and downstream
distributors should treat the source as they would any other community
contribution: **read it, audit it, and run the tests before shipping.**
Commits authored with AI assistance carry a `Co-Authored-By` trailer that
names the model. Git history is the authoritative record.
The maintainer reviews, tests and accepts every change before it is released. AI-assisted code can
still contain subtle mistakes, so treat the source as you would any community contribution: read
it, audit it and run the tests before you depend on it. Commits with meaningful AI authorship carry
a `Co-Authored-By` trailer; the git history is the authoritative record.
## 4. Translations are machine-assisted
CaptureImage ships with localized strings for English (`en-US`),
Vietnamese (`vi-VN`), and Arabic (`ar-SA`). The Arabic translation in
particular was produced with assistance from the same AI model; the
Vietnamese strings were reviewed by a native speaker but still pass
through an automated generation step.
Consequences:
- Terminology may not match native conventions in every locale.
- Some technical jargon (e.g. "hotkey", "toast", "frame") is deliberately
kept in English because it is more recognizable to developers than any
localized equivalent.
- Right-to-left layouts (Arabic) are verified for structural mirroring but
copy may still sound machine-translated.
Native speakers willing to proofread any shipped language are warmly
invited to open a pull request — see [`CONTRIBUTORS.md`](../CONTRIBUTORS.md).
The user interface is available in English, Vietnamese, Arabic, Japanese, Simplified Chinese,
Korean, Spanish, French, German, Brazilian Portuguese and Russian. Except where a native speaker has
reviewed them, the translations were produced with AI assistance. Terminology may not match native
conventions everywhere, and some technical words (for example "hotkey") are kept as users commonly
know them. Native speakers who can proofread a language are very welcome — see
[`CONTRIBUTING.md`](../../CONTRIBUTING.md).
## 5. Trademarks
"Steam", "Dota", "Counter-Strike", "Windows", "DirectX",
"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
endorsement by, the respective trademark holders.
Microsoft, Windows, DirectX, .NET, Steam, Valve, GitHub, WPF UI, Velopack, SkiaSharp, Serilog and
other names that appear in the source code, documentation or user interface are trademarks of their
respective owners, used only to identify them. No affiliation or endorsement is implied.
## 6. No legal advice
This disclaimer summarizes the project's intent in plain language and is
**not** a substitute for the actual license text. Where this document
conflicts with [`LICENSE`](../../LICENSE), the license text controls. If
you need legal certainty about your use of CaptureImage — for example
because you intend to redistribute it, bundle it with another product, or
integrate it into a commercial offering — consult a qualified attorney in
your jurisdiction.
This disclaimer summarizes the project's intent in plain language and does not replace the license.
Where it conflicts with [`LICENSE`](../../LICENSE), the license controls. If you need legal certainty
— for example to redistribute or bundle CaptureImage — consult a lawyer in your jurisdiction.
## 7. Unsigned installer — SmartScreen warning
## 7. Unsigned installer — SmartScreen
Until a code-signing certificate is available, the installer (`Setup.exe`
produced by Velopack) is **not Authenticode-signed**. Windows SmartScreen
will show the "Unknown publisher" warning on first run:
Until a code-signing certificate is available, the installer `CaptureImage-win-Setup.exe` is **not
Authenticode-signed**, and Windows SmartScreen shows an "unknown publisher" warning on first run.
That alone does not mean the file was altered. To verify a download:
> Windows protected your PC · Microsoft Defender SmartScreen prevented
> an unrecognized app from starting.
1. Download `SHA256SUMS.txt` from the same release page.
2. Compute the hash of your download and compare:
This is expected, not a sign that the binary has been tampered with. To
verify the download is authentic:
1. Download `SHA256SUMS.txt` from the same GitHub Release page.
2. Compute the hash of your downloaded `Setup.exe`:
```powershell
Get-FileHash -Algorithm SHA256 .\Setup.exe
Get-FileHash -Algorithm SHA256 .\CaptureImage-win-Setup.exe
```
3. Compare the output against the entry in `SHA256SUMS.txt`.
Only then click **More info** → **Run anyway** in SmartScreen. If the
hashes do not match, **do not run the installer** and report the
discrepancy via a GitHub Security Advisory.
3. Or verify the GitHub build-provenance attestation:
The project's application to <https://signpath.io> (free OSS code
signing) was declined in the first round. Until it is accepted or an
alternative signing path becomes available, every release ships under
these terms. Re-signing old releases is not planned — each release is
the authoritative artifact at its point in time.
```powershell
gh attestation verify .\CaptureImage-win-Setup.exe --repo poli0981/captureimg
```
Only then choose **More info → Run anyway**. If the hashes don't match, **do not run the file** and
report it to `security@poli0981.dev` or through a GitHub security advisory.
## 8. Contact
- Game publishers and anti-cheat vendors with concerns about CaptureImage: `games@poli0981.dev`.
- Copyright, DMCA or takedown requests: `dmca@poli0981.dev` (or `takedown@poli0981.dev`).
- Other legal questions: `legal@poli0981.dev`.
- Everything else: `contact@poli0981.dev` · <https://poli0981.dev/links>.
+74 -87
View File
@@ -1,114 +1,101 @@
# Privacy Policy
_Last updated: 2026-04-15_
_Last updated: 2026-10-19 (CaptureImage 2.0)_
This policy describes what data **CaptureImage** reads from your computer,
what it stores, and what it sends over the network. It applies to the
official builds distributed from the project's GitHub Releases page.
This policy describes what **CaptureImage** reads on your computer, what it stores, and what it
sends over the network. It applies to the official builds published on the project's
[GitHub Releases](https://github.com/poli0981/captureimg/releases) page.
## Summary
- CaptureImage is a **local, offline-first** desktop application.
- It **does not** collect telemetry, analytics, usage metrics, crash
reports, or any personal information.
- It does not create an account, ask for credentials, or authenticate you
with any service.
- The only network access the app performs is the **update check** against
a configured GitHub repository's Releases API (see §3), and only when you
explicitly enable auto-check in Settings or click "Check for updates".
- Optional cloud upload providers (Google Drive, Dropbox) are **post-1.0
stretch features** and are not present in this release.
- CaptureImage is a **local, offline** desktop application.
- It collects **no telemetry, analytics, usage statistics or crash reports**, and has no account
or sign-in.
- The only network access is the **update check and download** against GitHub Releases (§3).
- Captures stay on your computer unless you move them yourself.
## 1. Data the app reads from your machine
To build the list of capture targets and to save your settings, the app
reads the following on each launch or when you refresh the Dashboard:
## 1. What the app reads
| Source | What is read | Why |
|---|---|---|
| Running processes | Process IDs, process names, executable paths, main window handles and titles | Populate the Dashboard list; resolve a target HWND for capture |
| Executable icons | The associated icon of each target's `.exe` | Display next to each target in the Dashboard |
| Windows registry | `HKLM\SOFTWARE\Valve\Steam\InstallPath` (32- and 64-bit views) | Locate the Steam install directory |
| File system | `steamapps\libraryfolders.vdf` and `steamapps\appmanifest_*.acf` under every detected Steam library | Attribute capture targets to Steam games so the warning badge can be shown |
| File system | `%LocalAppData%\CaptureImage\settings.json` | Load your persisted preferences |
| File system | The captured window's pixel buffer via Direct3D11 / GDI | Produce the output image |
| Open windows | Window handles, titles, process ids, process names and executable paths, from Windows window events (`SetWinEventHook`) and process queries | The Dashboard window list, game profiles and auto-arm |
| Executable icons | The icon of each listed program | Shown next to each window |
| Displays | Monitor positions, scaling (DPI), HDR state and SDR white level | Multi-monitor capture and HDR tone mapping |
| Screen contents | The pixels of the window, monitor or area being captured — **only when you press a capture hotkey or click a capture button** | To produce the screenshot |
| Steam | `HKCU\Software\Valve\Steam\SteamPath` or `HKLM\SOFTWARE\Valve\Steam\InstallPath`, then `libraryfolders.vdf` and `appmanifest_*.acf` | The Steam badge and Steam AppId matching in profiles |
| Image files | Pictures in your capture output folders | The Library index and its thumbnails |
| Settings | `settings.json` in the data folder (§2); on the first start of 2.x, the 1.x file in `%LocalAppData%\CaptureImage` is copied | Your preferences |
None of this data leaves your machine. Everything is kept in memory for the
duration of the process, except settings and the captures you explicitly
save.
Keyboard input is **not** monitored. The capture hotkeys are registered with Windows
(`RegisterHotKey`) only while you have them armed; Windows then tells the app when one of those
exact combinations is pressed. While the hotkey recorder in Settings is open, it reads the keys you
press in that field.
## 2. Data the app writes to your machine
**Text recognition (OCR)** runs on your device with the Windows OCR engine, only when you click
**Extract text**; the recognized text is copied to your clipboard and is not stored.
| Location | What is written | Retention |
## 2. What the app writes
| Location | Content | Kept until |
|---|---|---|
| `%LocalAppData%\CaptureImage\settings.json` | Your preferences (language, hotkey, format, quality sliders, output folder, toggles) | Until you delete the file or uninstall the app |
| `%LocalAppData%\CaptureImage\logs\captureimg-YYYYMMDD.log` | Diagnostic log: process list, capture events, errors, settings changes | Rolling daily; max 14 files, 10 MB each |
| Your chosen output folder (default: `%USERPROFILE%\Pictures\CaptureImage\`) | The PNG / JPEG / WebP / TIFF files you capture | Until you delete them |
| `%LocalAppData%\poli0981\CaptureImage\settings.json` (and `settings.*.bak.json` backups made before a reset or when a file can't be read) | Your preferences and game profiles | You reset them or delete the folder |
| `%LocalAppData%\poli0981\CaptureImage\library.json` | Path, time, size, format and game name of each capture | The capture is deleted or the folder is removed |
| `%LocalAppData%\poli0981\CaptureImage\thumbnails\` | Small JPEG previews for the Library | You delete the folder |
| `%LocalAppData%\poli0981\CaptureImage\logs\` | Diagnostic log (§2.1) | 14 daily files, at most 10 MB each |
| Your output folder (default `Pictures\CaptureImage`) | Your captures, and the `.jxr` HDR original when that option is on | You delete them |
| Clipboard | A capture, a file path or recognized text — when you choose to copy, or when the clipboard mode is on | The next thing you copy |
| `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` → `CaptureImage` | The command that starts the app with Windows — only when **Start with Windows** is on | You turn the option off or uninstall |
Logs are written in plain text and contain only information the app
already knows about your local environment (process names, window titles,
file paths, error stacks). They do **not** contain window contents, pixel
data, or personal information from your documents.
Deleting a capture in the Library moves it (and its HDR original) to the **Recycle Bin**.
### 2.1 Logs
Logs contain what the app does: settings changes, capture results with file names and sizes,
hotkey registrations, errors. Your user-profile path is replaced by `%USERPROFILE%`, and window
titles are only logged at the **Debug** level. Logs never contain pixels or the content of your
documents.
### 2.2 Diagnostics export
**Settings → Advanced → Export diagnostics** creates a zip with recent logs, your settings and
system information (Windows and .NET versions, graphics adapter, monitors, scaling and HDR state),
with user paths removed. It is saved where you choose and is never sent anywhere by the app —
attach it to a bug report only if you want to.
### 2.3 Local communication
A second copy of the app talks to the first through a local named pipe that only your Windows
account can open, to bring the existing window forward. Nothing leaves the computer.
## 3. Network access
The only built-in network access is the **update check**, and only when
both of the following are true:
The app connects to the internet only to **check for and download updates**:
1. `UiSettings.AutoCheck` is enabled (off by default) **or** you click the
"Check for updates" button manually.
2. You are connected to the internet.
- when you open the **Update** page (one check per session) or click **Check for updates**, it
downloads the release list (`releases.win.json`) from this project's GitHub Releases over HTTPS;
- when you click **Download**, it downloads the update package from GitHub.
The update check performs an HTTPS GET against the GitHub Releases API for
the configured repository. No cookies, headers, or identifiers are sent
beyond the standard `User-Agent` that the .NET HTTP client adds, and
Velopack's default metadata. GitHub may log the request in its own access
logs under GitHub's privacy policy — CaptureImage does not control or
receive those logs.
No identifiers, cookies or system information are sent beyond what any HTTPS request carries (your
IP address and a standard user agent). GitHub may log these requests under
[its own privacy statement](https://docs.github.com/site-policy/privacy-policies/github-general-privacy-statement).
If an update is available, clicking **Download** issues a second HTTPS
request to GitHub's Releases CDN for the package bytes. Download progress
is kept entirely in memory.
When the .NET Desktop Runtime is missing, Setup and the updater download it from Microsoft.
Links in the About page open in your browser; the app itself does not fetch them.
CaptureImage does **not**:
CaptureImage does **not** send crash reports, contact analytics or license servers, upload
captures, or collect hardware identifiers.
- Send crash reports.
- Ping any analytics or metrics endpoint.
- Upload any captured image anywhere automatically.
- Check in with a license server.
- Phone home with system information, hardware fingerprints, or GUIDs.
## 4. Your choices
## 4. Optional cloud upload (future)
- Disarm the hotkeys at any time; nothing is captured without your action.
- Delete `%LocalAppData%\poli0981\CaptureImage` to remove settings, the library index, thumbnails
and logs. Uninstalling removes the program and the "Start with Windows" entry; your captures and
the data folder stay until you delete them.
- The source code is public under GPL-3.0, so every behavior above can be checked.
The project plan includes optional cloud upload providers (Google Drive,
Dropbox) as a post-1.0 stretch feature. If/when those land, they will be
**off by default**, documented separately in this file, and require the
user to:
Changes to this policy are listed in [`CHANGELOG.md`](../../CHANGELOG.md) and in the date above.
1. Explicitly enable the provider in Settings.
2. Complete an OAuth authorization flow that grants the app access to a
single folder.
3. Opt in per-capture or via a global toggle.
## 5. Contact
No cloud upload code is present or compiled into the binary in this
release.
## 5. Your rights
Because no data leaves your machine, there is nothing for the project to
delete, export, or access on request. You can:
- Delete `%LocalAppData%\CaptureImage\` to clear all settings and logs.
- Uninstall the app via its installer or by deleting its folder.
- Review the source code on GitHub — the project is licensed under
GPL-3.0 so every network call is auditable.
If a future release changes this policy, the changes will be noted in
[`CHANGELOG.md`](../../CHANGELOG.md) and in the `Last updated` field at the
top of this file.
## 6. Contact
CaptureImage is a volunteer-run open-source project. Privacy questions can
be raised as GitHub issues on the repository. There is no dedicated
privacy officer, data processing agreement, or paid support channel.
Privacy questions: `privacy@poli0981.dev`. Other channels: <https://poli0981.dev/links>.
CaptureImage is a volunteer open-source project with no paid support.
+48 -73
View File
@@ -1,107 +1,82 @@
# Terms of Use
_Last updated: 2026-04-15_
_Last updated: 2026-10-19 (CaptureImage 2.0)_
These terms describe the relationship between the CaptureImage project and
the people who download, run, and redistribute the software. They are
written in plain English for readability. The authoritative legal text is
the **GNU General Public License v3.0 or later**; these terms do not add
obligations beyond it.
These terms describe the relationship between the CaptureImage project and the people who download,
run and redistribute the software. They are written in plain language; the authoritative legal text
is the **GNU General Public License v3.0 or later**, and these terms add no obligations beyond it.
## 1. The software is free software
CaptureImage is free software as defined by the Free Software Foundation.
You have the four essential freedoms:
CaptureImage is free software as defined by the Free Software Foundation. You have the four
essential freedoms:
1. The freedom to **run** the program, for any purpose.
2. The freedom to **study** how the program works, and **adapt** it to
your needs. Access to the source code is a precondition for this.
3. The freedom to **redistribute** copies so you can help others.
4. The freedom to **distribute modified versions** to others. By doing
this you can give the whole community a chance to benefit from your
changes. Access to the source code is a precondition for this.
1. to **run** the program, for any purpose;
2. to **study** how it works and **adapt** it to your needs;
3. to **redistribute** copies;
4. to **distribute modified versions**.
These freedoms come with the obligations described in the
[GPL-3.0-or-later license text](../../LICENSE). The most important
obligation for downstream users and distributors is: **if you distribute
the software, whether modified or not, you must make the complete
corresponding source code available under the same license.**
These freedoms come with the obligations in the [GPL-3.0-or-later license text](../../LICENSE). The
most important one for distributors: **if you distribute the software, modified or not, you must
make the complete corresponding source code available under the same license.**
## 2. By running CaptureImage, you agree that
- You have read and understood the [DISCLAIMER](DISCLAIMER.md) and the
[PRIVACY POLICY](PRIVACY.md).
- You will **not** use the software to violate the Terms of Service of any
third-party game, application, platform, or service. In particular:
- You will not use it to produce content that violates another party's
copyright, trademark, or other intellectual property rights.
- You will not use it as a component of a cheat, exploit, or similar
tool that breaks anti-cheat rules on an online service.
- You will not capture or distribute images of other people without
their consent where such consent is required by the laws of your
jurisdiction.
- You understand that the software is provided **"AS IS"** under the
GPL-3.0, without warranty of any kind, and that the authors and
contributors are not liable for damages resulting from its use.
- You will not hold the project, its contributors, or the AI systems that
assisted in its development responsible for outcomes caused by your own
use of the software.
- You have read the [Disclaimer](DISCLAIMER.md) and the [Privacy Policy](PRIVACY.md).
- You will **not** use the software to break the terms of service of any game, application,
platform or service — in particular you will not:
- produce or distribute content that infringes someone else's copyright, trademark or other
rights;
- use it as part of a cheat, exploit or tool that circumvents anti-cheat rules;
- capture or share images of other people without the consent your local law requires.
- The software is provided **"AS IS"** under the GPL-3.0, without warranty of any kind, and the
authors and contributors are not liable for damages resulting from its use.
- You will not hold the project, its contributors or the AI systems that assisted its development
responsible for the outcomes of your own use of the software.
If you do not agree with any of the above, please do not install or run
the software.
If you do not agree, please do not install or run the software.
## 3. Trademarks
"CaptureImage" is used as the project's internal name. No trademark
registration is claimed. You may fork the project and rename your fork
freely, subject to the GPL's attribution requirements.
"CaptureImage" is the project's name; no trademark registration is claimed. You may fork the project
and rename your fork, 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, 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
Third-party names that appear in the source code, documentation, user interface or release notes
(including Microsoft, Windows, DirectX, .NET, Steam, Valve, GitHub, WPF UI, Velopack, SkiaSharp and
Serilog) belong to their owners and are used only for identification and interoperability. No
endorsement is implied.
## 4. No support obligation
CaptureImage is maintained by volunteers. Nothing in these terms obliges
any contributor to respond to issues, fix bugs, answer questions, merge
pull requests, or ship updates on any particular schedule. Paid support,
commercial licensing, or service-level agreements are **not** offered.
CaptureImage is maintained by volunteers. Nothing in these terms obliges any contributor to answer
questions, fix bugs, merge pull requests or ship updates on any schedule. Paid support, commercial
licensing and service-level agreements are not offered.
## 5. Contributions
Contributions submitted via pull requests are accepted under the same
license as the project itself. By submitting a contribution you represent
that:
Contributions are accepted under the project's license. By submitting one you confirm that:
1. You have the right to license your contribution under GPL-3.0-or-later.
2. Your contribution does not knowingly infringe on any third party's
intellectual property rights.
3. You are comfortable with your contribution being listed in
[`CONTRIBUTORS.md`](../CONTRIBUTORS.md) and in git history.
1. you have the right to license it under GPL-3.0-or-later;
2. it does not knowingly infringe anyone's intellectual property; and
3. you are fine with being credited in [`CONTRIBUTORS.md`](../CONTRIBUTORS.md) and the git history.
If your contribution was generated with AI assistance, please say so in
the pull request description so it can be reviewed with that context in
mind.
If AI tools helped you write a contribution, please say so in the pull request. See
[`CONTRIBUTING.md`](../../CONTRIBUTING.md).
## 6. Termination
Your rights under the GPL-3.0 license terminate automatically if you fail
to comply with the license (see GPL-3.0 Section 8). These terms do not
add additional termination conditions.
Your rights under the GPL-3.0 end automatically if you do not comply with it (GPL-3.0 section 8).
These terms add no other termination conditions.
## 7. Governing law
These terms, the GPL-3.0 license, and any dispute arising from them are
interpreted under the law of the jurisdiction of the downstream user —
there is no central governing jurisdiction imposed by the project because
the project does not sell, transfer, or control distribution.
The project does not sell or control distribution and imposes no governing jurisdiction; these
terms and the license are interpreted under the law that applies to you.
## 8. Contact
The project's primary contact point is its GitHub repository's issue
tracker. Security-sensitive reports that should not be disclosed publicly
may be sent by opening a private security advisory on GitHub.
- Legal questions about these terms: `legal@poli0981.dev`
- Copyright and DMCA notices: `copyright@poli0981.dev` · `dmca@poli0981.dev`
- Takedown requests for content in this repository: `takedown@poli0981.dev`
- Security issues: see [`SECURITY.md`](../../SECURITY.md)
- Anything else: `contact@poli0981.dev` · <https://poli0981.dev/links>
+88 -93
View File
@@ -1,105 +1,100 @@
# Third-party Notices
_Last updated: 2026-04-15_
_Last updated: 2026-10-19 (CaptureImage 2.0)_
CaptureImage is built on top of several open-source components. This file
lists every runtime and build dependency together with its upstream license
and project URL. A shorter version is in the repository root [`NOTICE`](../../NOTICE) file.
CaptureImage is built on open-source components. This file lists every package that ships with
the app, with its license and upstream project; the short form is the repository root
[`NOTICE`](../../NOTICE). The list is generated from the app's dependency graph with
[nuget-license](https://github.com/sensslen/nuget-license), and the `license` CI check keeps it
within licenses compatible with **GPL-3.0-or-later**.
All listed licenses are **compatible with distribution under the
GNU General Public License v3.0 or later**, which is the license the
CaptureImage binary is distributed under.
## User interface
## Runtime dependencies
| Package | Version | License | Project |
|---|---|---|---|
| CommunityToolkit.Mvvm | 8.4.2 | MIT | <https://github.com/CommunityToolkit/dotnet> |
| H.GeneratedIcons.System.Drawing | 2.4.1 | MIT | <https://github.com/HavenDV/H.NotifyIcon> |
| H.NotifyIcon | 2.4.1 | MIT | <https://github.com/HavenDV/H.NotifyIcon> |
| H.NotifyIcon.Wpf | 2.4.1 | MIT | <https://github.com/HavenDV/H.NotifyIcon> |
| WPF-UI | 4.3.0 | MIT | <https://github.com/lepoco/wpfui> |
| WPF-UI.Abstractions | 4.3.0 | MIT | <https://github.com/lepoco/wpfui> |
### UI framework
## Capture, imaging and Windows interop
| Package | License | Upstream |
| Package | Version | License | Project |
|---|---|---|---|
| SharpGen.Runtime | 2.4.2-beta | MIT | <https://github.com/SharpGenTools/SharpGenTools> |
| SharpGen.Runtime.COM | 2.4.2-beta | MIT | <https://github.com/SharpGenTools/SharpGenTools> |
| SkiaSharp | 4.153.1 | MIT | <https://github.com/mono/SkiaSharp> |
| SkiaSharp.NativeAssets.Win32 | 4.153.1 | MIT | <https://github.com/mono/SkiaSharp> |
| Vortice.Direct2D1 | 3.8.3 | MIT | <https://github.com/amerkoleci/Vortice.Windows> |
| Vortice.Direct3D11 | 3.8.3 | MIT | <https://github.com/amerkoleci/Vortice.Windows> |
| Vortice.DirectX | 3.8.3 | MIT | <https://github.com/amerkoleci/Vortice.Windows> |
| Vortice.DXGI | 3.8.3 | MIT | <https://github.com/amerkoleci/Vortice.Windows> |
| Vortice.Mathematics | 2.1.0 | MIT | <https://github.com/amerkoleci/Vortice.Mathematics> |
## Hosting, dependency injection and configuration
| Package | Version | License | Project |
|---|---|---|---|
| Microsoft.Extensions.Configuration | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Configuration.Abstractions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Configuration.Binder | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Configuration.CommandLine | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Configuration.EnvironmentVariables | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Configuration.FileExtensions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Configuration.Json | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Configuration.UserSecrets | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.DependencyInjection | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.DependencyInjection.Abstractions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Diagnostics | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Diagnostics.Abstractions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.FileProviders.Abstractions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.FileProviders.Physical | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.FileSystemGlobbing | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Hosting | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Hosting.Abstractions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging.Abstractions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging.Configuration | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging.Console | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging.Debug | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging.EventLog | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging.EventSource | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Options | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Options.ConfigurationExtensions | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Primitives | 10.0.13 | MIT | <https://github.com/dotnet/runtime> |
## Logging
| Package | Version | License | Project |
|---|---|---|---|
| Serilog | 4.4.0 | Apache-2.0 | <https://serilog.net/> |
| Serilog.Extensions.Logging | 10.0.0 | Apache-2.0 | <https://github.com/serilog/serilog-extensions-logging> |
| Serilog.Sinks.Async | 2.1.0 | Apache-2.0 | <https://serilog.net/> |
| Serilog.Sinks.File | 7.0.0 | Apache-2.0 | <https://github.com/serilog/serilog-sinks-file> |
## Updates
| Package | Version | License | Project |
|---|---|---|---|
| Velopack | 1.2.161 | MIT | <https://github.com/velopack/velopack> |
## Platform components
| Component | License | Project |
|---|---|---|
| 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> |
| .NET 10 Desktop Runtime (installed separately by Setup when missing) | MIT | <https://github.com/dotnet/runtime> |
| Windows SDK projection for .NET (`Microsoft.Windows.SDK.NET`, C#/WinRT) | MIT | <https://github.com/microsoft/CsWinRT> |
| Fluent System Icons (font embedded in WPF UI) | MIT | <https://github.com/microsoft/fluentui-system-icons> |
### MVVM + DI + logging
Build and test tools (CsWin32, xUnit, AwesomeAssertions, NSubstitute, FlaUI, JetBrains
InspectCode, ReportGenerator, CycloneDX, Velopack's `vpk`) are not distributed with the app.
| Package | License | Upstream |
|---|---|---|
| CommunityToolkit.Mvvm | MIT | <https://github.com/CommunityToolkit/dotnet> |
| Microsoft.Extensions.DependencyInjection | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Hosting | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Localization | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Logging | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Extensions.Options | MIT | <https://github.com/dotnet/runtime> |
| Serilog | Apache 2.0 | <https://github.com/serilog/serilog> |
| Serilog.Extensions.Hosting | Apache 2.0 | <https://github.com/serilog/serilog-extensions-hosting> |
| Serilog.Extensions.Logging | Apache 2.0 | <https://github.com/serilog/serilog-extensions-logging> |
| Serilog.Sinks.Console | Apache 2.0 | <https://github.com/serilog/serilog-sinks-console> |
| Serilog.Sinks.File | Apache 2.0 | <https://github.com/serilog/serilog-sinks-file> |
| Serilog.Sinks.Async | Apache 2.0 | <https://github.com/serilog/serilog-sinks-async> |
## License texts
### Capture pipeline (Windows)
- MIT: <https://opensource.org/license/mit>
- Apache-2.0: <https://www.apache.org/licenses/LICENSE-2.0>
| Package | License | Upstream |
|---|---|---|
| Vortice.Direct3D11 | MIT | <https://github.com/amerkoleci/Vortice.Windows> |
| Vortice.DXGI | MIT | <https://github.com/amerkoleci/Vortice.Windows> |
| Microsoft.Windows.CsWinRT (runtime only) | MIT | <https://github.com/microsoft/CsWinRT> |
| SixLabors.ImageSharp (>= 3.1) | Apache 2.0 | <https://github.com/SixLabors/ImageSharp> |
| System.Drawing.Common | MIT | <https://github.com/dotnet/runtime> |
| System.Management | MIT | <https://github.com/dotnet/runtime> |
| Microsoft.Win32.Registry | MIT | <https://github.com/dotnet/runtime> |
| System.IO.Abstractions | MIT | <https://github.com/TestableIO/System.IO.Abstractions> |
### Hotkeys + state machine + updater
| Package | License | Upstream |
|---|---|---|
| SharpHook | MIT | <https://github.com/TolikPylypchuk/SharpHook> |
| libuiohook (bundled with SharpHook) | GPL-3.0 / LGPL-3.0 | <https://github.com/kwhat/libuiohook> |
| Stateless | Apache 2.0 | <https://github.com/dotnet-state-machine/stateless> |
| Velopack | MIT | <https://github.com/velopack/velopack> |
### Test-only (not redistributed)
| Package | License |
|---|---|
| xUnit | Apache 2.0 |
| xunit.runner.visualstudio | Apache 2.0 |
| Microsoft.NET.Test.Sdk | MIT |
| FluentAssertions (version 6.x) | Apache 2.0 |
| NSubstitute | BSD-3-Clause |
| System.IO.Abstractions.TestingHelpers | MIT |
| coverlet.collector | MIT |
## libuiohook + GPL compatibility note
SharpHook wraps the native `libuiohook` library, which is dual-licensed
under GPL-3.0 and LGPL-3.0. CaptureImage is itself distributed under
GPL-3.0-or-later, so this is compatible. Downstream redistributors of
CaptureImage must therefore also respect the libuiohook license terms
when redistributing the compiled binary.
## Full license texts
The full text of every license referenced above is available from:
- GNU GPL v3.0: <https://www.gnu.org/licenses/gpl-3.0.txt> — shipped as [`LICENSE`](../../LICENSE) in this repository.
- GNU LGPL v3.0: <https://www.gnu.org/licenses/lgpl-3.0.txt>
- Apache License 2.0: <https://www.apache.org/licenses/LICENSE-2.0.txt>
- MIT License: <https://opensource.org/licenses/MIT>
- BSD 3-Clause: <https://opensource.org/licenses/BSD-3-Clause>
- SIL Open Font License 1.1: <https://openfontlicense.org/open-font-license-official-text/>
Per the Apache 2.0 license terms (Section 4), this file serves as the
required notice for Apache-licensed components.
## Reporting a missing attribution
If you ship a downstream copy of CaptureImage and discover that a
dependency is missing from this list, please open a pull request or issue
with the package name, version, and upstream license. We aim to keep this
list complete at every tagged release.
Each package's own license file and copyright notice are available from its project page and
inside the NuGet package.
+5 -5
View File
@@ -12,14 +12,14 @@ A Vietnamese mirror of this document lives at
| Component | Details |
|-------------|-------------------------------------------------------------------|
| **OS** | Windows 11 Pro 25H2 Insider Preview (Dev Channel), build 26300.8376 |
| **OS** | Windows 11 Pro Insider Preview, build 29648 |
| **CPU** | Intel Core i7-14700KF |
| **GPU** | NVIDIA GeForce RTX 5080 (16 GB VRAM) |
| **RAM** | 32 GB DDR5 |
| **Storage** | 1 TB SSD |
| **IDE** | JetBrains 2026.x paid lineup (Rider for this repo; PyCharm / WebStorm / RustRover for sibling projects) + Visual Studio Code |
The Windows Insider Dev Channel build is intentional — CaptureImage
The Windows Insider build is intentional — CaptureImage
exercises the latest `Windows.Graphics.Capture` surface area and
benefits from running on builds ahead of stable so regressions on
upcoming public releases are caught early.
@@ -35,14 +35,14 @@ work lands, mobile browser testing is performed on:
Browsers under test on iOS: **Chrome**, **Brave**.
> **Note.** CaptureImage itself is a Windows 11 desktop application
> (WinUI 3 / Windows App SDK) and has no iOS / web build. The mobile
> (WPF on .NET 10) and has no iOS / web build. The mobile
> devices above are listed for transparency about the maintainer's
> overall test fleet; they are not used to validate CaptureImage.
## Related documents
- [`docs/dev_env.md`](dev_env.md) — toolchain versions (Python, Node,
Rust, Git) and IDE configuration.
- [`docs/dev_env.md`](dev_env.md) — toolchain versions (.NET SDK, Git,
GPG, Node.js) and IDE configuration.
- [`README.md` § Requirements](../README.md#requirements) — end-user
runtime requirements (Windows 11 22H2+, no specific GPU needed).
- [`docs/ARCHITECTURE.md`](ARCHITECTURE.md) — software architecture.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

+5 -2
View File
@@ -1,7 +1,10 @@
{
"sdk": {
"version": "9.0.312",
"rollForward": "latestPatch",
"version": "10.0.401",
"rollForward": "latestFeature",
"allowPrerelease": false
},
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
+5
View File
@@ -0,0 +1,5 @@
# lychee link-checker settings for the CI `docs` job.
# Build output (bin/obj) contains copies of the legal docs whose relative links only
# resolve in the repository layout.
exclude_path = ["bin", "obj", "artifacts", "TestResults", "node_modules"]
include_fragments = "full"
-58
View File
@@ -1,58 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Application
x:Class="CaptureImage.App.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="using:CaptureImage.UI.Converters">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
</ResourceDictionary.MergedDictionaries>
<!-- Globally-available converters. Declared at Application scope so any view's
{StaticResource X} lookup walks up the chain and finds them — local
Element.Resources scope hits a forward-reference issue when the host
element uses the converter on its own properties. See
feedback_winui3_resource_scope.md. -->
<conv:FlowDirectionConverter x:Key="FlowDirectionConverter" />
<conv:BytesToBitmapConverter x:Key="BytesToBitmapConverter" />
<conv:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<conv:InvertedBoolToVisibilityConverter x:Key="InvertedBoolToVisibilityConverter" />
<conv:NotNullToVisibilityConverter x:Key="NotNullToVisibilityConverter" />
<conv:ToastKindToBrushConverter x:Key="ToastKindToBrushConverter" />
<!-- Design tokens — port of the v1.2 Avalonia design-system comment block.
Keep the same scale (4/8/12/16/24 px spacing, 4/8 px corner radius) so the
view ports stay visually consistent with the v1.2 baseline.
FontFamily : Segoe UI Variable (Fluent 2 default — explicit for clarity).
Inter is dropped; Win11 native font carries the Fluent look.
FontSize : 11 (caption) / 12 (small) / 13 (body) / 14 (body-strong) /
16 (subtitle) / 22 (title).
CornerRadius: 8 px for cards/borders/containers, 4 px for inline pills.
Spacing : 4 / 8 / 12 / 16 / 24 px scale.
Contrast : secondary text uses TextFillColorSecondaryBrush, not
Opacity=0.6 — the theme brush keeps WCAG AA on light/dark.
-->
<FontFamily x:Key="BodyFontFamily">Segoe UI Variable Display</FontFamily>
<x:Double x:Key="FontSizeCaption">11</x:Double>
<x:Double x:Key="FontSizeSmall">12</x:Double>
<x:Double x:Key="FontSizeBody">13</x:Double>
<x:Double x:Key="FontSizeBodyStrong">14</x:Double>
<x:Double x:Key="FontSizeSubtitle">16</x:Double>
<x:Double x:Key="FontSizeTitle">22</x:Double>
<x:Double x:Key="SpacingXSmall">4</x:Double>
<x:Double x:Key="SpacingSmall">8</x:Double>
<x:Double x:Key="SpacingMedium">12</x:Double>
<x:Double x:Key="SpacingLarge">16</x:Double>
<x:Double x:Key="SpacingXLarge">24</x:Double>
<CornerRadius x:Key="PillCornerRadius">4</CornerRadius>
<CornerRadius x:Key="CardCornerRadius">8</CornerRadius>
</ResourceDictionary>
</Application.Resources>
</Application>
-81
View File
@@ -1,81 +0,0 @@
using CaptureImage.App.SingleInstance;
using CaptureImage.Core.Abstractions;
using CaptureImage.UI.Services;
using CaptureImage.UI.Views;
using CaptureImage.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Serilog;
namespace CaptureImage.App;
/// <summary>
/// WinUI 3 Application root. Holds the static <see cref="Services"/> handle so view-models
/// resolved from XAML data templates can reach the DI container; <see cref="OnLaunched"/>
/// binds the UI dispatcher and shows the first window.
/// </summary>
public partial class App : Application
{
/// <summary>
/// Service provider populated by <c>Program.Main</c> before <see cref="Application.Start"/>
/// returns. View-models and converters resolve through this.
/// </summary>
public static IServiceProvider? Services { get; set; }
private Window? _window;
private ActivationListener? _activationListener;
public App()
{
InitializeComponent();
UnhandledException += OnUnhandledException;
}
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
var services = Services
?? throw new InvalidOperationException(
"App.Services must be assigned before Application.Start runs.");
// Bind the WinUI 3 dispatcher now that we are on the UI thread.
var dispatcher = services.GetRequiredService<WinUIThreadDispatcher>();
dispatcher.Bind(DispatcherQueue.GetForCurrentThread());
var vm = services.GetRequiredService<MainWindowViewModel>();
var mainWindow = new MainWindow();
mainWindow.SetViewModel(vm);
// Stash the main window on a UI-side static accessor so Pages (which can't
// reference back into CaptureImage.App) can reach the host HWND for
// FolderPicker / FilePicker InitializeWithWindow calls.
WindowHostHelper.MainWindow = mainWindow;
_window = mainWindow;
// Apply persisted theme before first paint, then keep it in sync with settings.
var settings = services.GetRequiredService<ISettingsStore>();
mainWindow.ApplyTheme(settings.Current.Theme);
settings.Changed += (_, _) => mainWindow.ApplyTheme(settings.Current.Theme);
_window.Activate();
// Tray host attaches to the live Window. M1 ships a no-op stub; M6 wires the real
// H.NotifyIcon.WindowsAppSDK implementation.
var tray = services.GetRequiredService<ITrayIconHost>();
tray.Initialize(_window);
// Listen for ACTIVATE messages from secondary launches so a double-click on
// the shortcut restores this instance instead of orphaning a new one. The
// listener owns its own background task; disposed via the IServiceProvider
// chain at shutdown (registered just below).
_activationListener = ActivationListener.Start(
_window,
services.GetRequiredService<IUIThreadDispatcher>());
_window.Closed += (_, _) => _activationListener?.Dispose();
}
private static void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "Unhandled exception on UI dispatcher.");
e.Handled = true;
}
}
+35 -47
View File
@@ -2,36 +2,33 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows10.0.22621.0</TargetFramework>
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
<SupportedOSPlatformVersion>10.0.22621.0</SupportedOSPlatformVersion>
<UseWPF>true</UseWPF>
<EnableDefaultApplicationDefinition>false</EnableDefaultApplicationDefinition>
<RootNamespace>CaptureImage.App</RootNamespace>
<!-- Keep the v1 executable name: Velopack updates and shortcuts point at it. -->
<AssemblyName>CaptureImage.App</AssemblyName>
<UseWindowsForms>false</UseWindowsForms>
<UseWpf>false</UseWpf>
<UseWinUI>true</UseWinUI>
<EnableMsixTooling>false</EnableMsixTooling>
<WindowsPackageType>None</WindowsPackageType>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
<Platforms>x64</Platforms>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<DefineConstants>$(DefineConstants);DISABLE_XAML_GENERATED_MAIN</DefineConstants>
<Version>1.5.1</Version>
<StartupObject>CaptureImage.App.Program</StartupObject>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationIcon>..\CaptureImage.UI\Assets\CaptureImage.ico</ApplicationIcon>
<!-- [LibraryImport] (AllowSetForegroundWindow) generates unsafe marshalling code. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Only ship satellite assemblies for the UI languages we translate. -->
<SatelliteResourceLanguages>en;vi;ar;ja;zh-Hans;ko;es;fr;de;pt-BR;ru</SatelliteResourceLanguages>
<!-- XML docs are for the IDE, not the installed app. -->
<PublishDocumentationFiles>false</PublishDocumentationFiles>
<PublishReferencesDocumentationFiles>false</PublishReferencesDocumentationFiles>
</PropertyGroup>
<ItemGroup>
<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" />
<PackageReference Include="Serilog.Sinks.Console" />
<PackageReference Include="Serilog.Sinks.File" />
<PackageReference Include="Serilog.Sinks.Async" />
<PackageReference Include="Serilog.Sinks.File" />
<PackageReference Include="Velopack" />
</ItemGroup>
<ItemGroup>
@@ -41,34 +38,7 @@
<ProjectReference Include="..\CaptureImage.UI\CaptureImage.UI.csproj" />
</ItemGroup>
<!-- 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>
<!-- Legal documents ship next to the executable; About opens them (publish-smoke checks they exist). -->
<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" />
@@ -79,4 +49,22 @@
<Content Include="..\..\NOTICE" Link="NOTICE" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<!-- Packages' debug symbols stay out of the installer (SkiaSharp alone adds a 90 MB native .pdb);
our own .pdb files ship so crash logs have line numbers. -->
<Target Name="DropPackageSymbolsFromPublish" AfterTargets="ComputeResolvedFilesToPublishList">
<ItemGroup>
<ResolvedFileToPublish Remove="@(ResolvedFileToPublish)" Condition="'%(Extension)' == '.pdb' And '%(ResolvedFileToPublish.NuGetPackageId)' != ''" />
</ItemGroup>
</Target>
<!-- Record the commit (SourceLink fills SourceRevisionId) so About and diagnostics show "2.0.0 (abc1234)". -->
<Target Name="EmbedSourceRevision" BeforeTargets="GetAssemblyAttributes" DependsOnTargets="InitializeSourceControlInformation">
<ItemGroup Condition="'$(SourceRevisionId)' != ''">
<AssemblyAttribute Include="System.Reflection.AssemblyMetadataAttribute">
<_Parameter1>SourceRevisionId</_Parameter1>
<_Parameter2>$(SourceRevisionId)</_Parameter2>
</AssemblyAttribute>
</ItemGroup>
</Target>
</Project>
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using System.IO;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Paths;
using CaptureImage.Core.Pipeline;
using CaptureImage.Infrastructure.Capture;
using CaptureImage.Infrastructure.Diagnostics;
using CaptureImage.Infrastructure.Imaging;
using CaptureImage.Infrastructure.Library;
using CaptureImage.Infrastructure.Logging;
using CaptureImage.Infrastructure.Ocr;
using CaptureImage.Infrastructure.Platform;
using CaptureImage.Infrastructure.Settings;
using CaptureImage.Infrastructure.Steam;
using CaptureImage.Infrastructure.Update;
using CaptureImage.Infrastructure.Win32;
using CaptureImage.Infrastructure.Windowing;
using CaptureImage.ViewModels.Localization;
using CaptureImage.ViewModels.Services;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog.Core;
namespace CaptureImage.App.Composition;
/// <summary>Core and Infrastructure services (the UI layer registers its own in CaptureImage.UI).</summary>
internal static class ServiceRegistration
{
public static IServiceCollection AddCaptureImageCore(
this IServiceCollection services,
AppPaths paths,
LoggingLevelSwitch levelSwitch,
InMemorySink logBuffer)
{
services.AddSingleton(paths);
services.AddSingleton(TimeProvider.System);
services.AddSingleton(AppInfo.FromAssembly(typeof(Program).Assembly));
services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);
services.AddSingleton<ILocalizationService, ResxLocalizationService>();
services.AddSingleton<ILogBufferSource>(logBuffer);
services.AddSingleton<ILogLevelSwitcher>(new SerilogLogLevelSwitcher(levelSwitch));
// A --data-dir run (tests, CI smoke) never adopts the real v1 settings.
services.AddSingleton<ISettingsStore>(sp => new JsonSettingsStore(
paths,
sp.GetRequiredService<ILogger<JsonSettingsStore>>(),
paths.IsOverridden ? null : AppPaths.LegacySettingsFile));
services.AddSingleton<IHotkeyService, Win32HotkeyService>();
services.AddSingleton<IWindowWatcher, WinEventWindowWatcher>();
services.AddSingleton<IconExtractor>();
services.AddSingleton<ISteamDetector>(sp => new SteamLibraryScanner(sp.GetRequiredService<ILogger<SteamLibraryScanner>>()));
services.AddSingleton<ITargetCatalog, TargetCatalog>();
services.AddSingleton<IDisplayService, DisplayService>();
services.AddSingleton<D3D11DeviceManager>();
services.AddSingleton<ICaptureEngine, WgcCaptureEngine>();
services.AddSingleton<IImageEncoder, SkiaImageEncoder>();
services.AddSingleton<IImageEncoder, WicImageEncoder>();
services.AddSingleton<IImageDecoder, WicImageDecoder>();
services.AddSingleton(new FileNameStrategy(File.Exists));
services.AddSingleton<CaptureFileWriter>();
services.AddSingleton<ICaptureLibrary, CaptureLibraryService>();
services.AddSingleton<IShellService, ShellService>();
services.AddSingleton<ISoundService, SoundService>();
services.AddSingleton<IPerformanceModeService, PerformanceModeService>();
services.AddSingleton<IAutostartService, AutostartService>();
services.AddSingleton<IDiagnosticsExporter, DiagnosticsExporter>();
services.AddSingleton<IUpdateService, VelopackUpdateService>();
services.AddSingleton<IOcrService, WindowsOcrService>();
services.AddSingleton<CaptureCoordinator>();
services.AddHostedService<WindowWatcherService>();
return services;
}
}
/// <summary>Starts the WinEvent window watcher with the host and stops it on shutdown.</summary>
internal sealed class WindowWatcherService(IWindowWatcher watcher) : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
watcher.Start();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
watcher.Stop();
return Task.CompletedTask;
}
}
-121
View File
@@ -1,121 +0,0 @@
using System.IO.Abstractions;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Pipeline;
using CaptureImage.Infrastructure.Capture;
using CaptureImage.Infrastructure.Hotkeys;
using CaptureImage.Infrastructure.Imaging;
using CaptureImage.Infrastructure.Logging;
using CaptureImage.Infrastructure.Ocr;
using CaptureImage.Infrastructure.Processes;
using CaptureImage.Infrastructure.Settings;
using CaptureImage.Infrastructure.Steam;
using CaptureImage.Infrastructure.Update;
using CaptureImage.UI.Localization;
using CaptureImage.UI.Services;
using CaptureImage.ViewModels;
using CaptureImage.ViewModels.About;
using CaptureImage.ViewModels.Dashboard;
using CaptureImage.ViewModels.Logs;
using CaptureImage.ViewModels.Navigation;
using CaptureImage.ViewModels.Settings;
using CaptureImage.ViewModels.Update;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Extensions.Logging;
namespace CaptureImage.App;
/// <summary>
/// Builds the DI container for the app. Kept as a single file so it's easy to see every binding.
/// </summary>
internal static class CompositionRoot
{
public static IServiceProvider BuildServices(InMemorySink inMemorySink, LoggingLevelSwitch loggingLevelSwitch)
{
var services = new ServiceCollection();
// --- Logging ------------------------------------------------------------
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.AddProvider(new SerilogLoggerProvider(Log.Logger, dispose: false));
// MEL's minimum level needs to sit at Trace/Debug so it never filters events
// before they reach Serilog — the real gating happens in the LoggingLevelSwitch.
builder.SetMinimumLevel(LogLevel.Trace);
});
// The same InMemorySink instance is both the Serilog sink AND the log buffer source
// used by the log viewer VM.
services.AddSingleton(inMemorySink);
services.AddSingleton<ILogBufferSource>(inMemorySink);
// Expose the Serilog level switch so Settings can mutate it live. Wrap it in the
// ILogLevelSwitcher abstraction so ViewModels don't take a Serilog dependency.
services.AddSingleton(loggingLevelSwitch);
services.AddSingleton<ILogLevelSwitcher, SerilogLogLevelSwitcher>();
// --- Cross-cutting -----------------------------------------------------
services.AddSingleton<IFileSystem, FileSystem>();
// 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 ----------------------------------------------------------
services.AddSingleton<ISettingsStore, JsonSettingsStore>();
// --- Steam detection ---------------------------------------------------
services.AddSingleton<ISteamRootLocator, RegistrySteamRootLocator>();
services.AddSingleton<ISteamDetector, SteamLibraryScanner>();
// --- Process / window enumeration --------------------------------------
services.AddSingleton<WindowEnumerator>();
services.AddSingleton<IconExtractor>();
services.AddSingleton<IProcessDetector, GameDetector>();
services.AddSingleton<IProcessWatcher, WmiProcessWatcher>();
services.AddSingleton<IForegroundWindowWatcher, Win32ForegroundWindowWatcher>();
// --- Capture engine + encoders -----------------------------------------
services.AddSingleton<D3D11DeviceManager>();
services.AddSingleton<ICaptureEngine, WindowsGraphicsCaptureEngine>();
services.AddSingleton<PrintWindowFallback>();
services.AddSingleton<IImageEncoder, SkiaImageEncoder>();
services.AddSingleton<IImageEncoder, ImageSharpTiffEncoder>();
services.AddSingleton<FileNameStrategy>(_ =>
new FileNameStrategy(File.Exists));
services.AddSingleton<CaptureOrchestrator>();
// --- Hotkeys -----------------------------------------------------------
services.AddSingleton<IHotkeyService, SharpHookHotkeyService>();
services.AddSingleton<IHotkeyConflictSniffer, HotkeyConflictSniffer>();
// --- Updates -----------------------------------------------------------
services.AddSingleton<IUpdateService, VelopackUpdateService>();
// --- UI-side services (toasts, preview, tray) --------------------------
services.AddSingleton<IToastService, ToastService>();
services.AddSingleton<IPreviewPresenter, PreviewPresenter>();
services.AddSingleton<ITrayIconHost, TrayIconHost>();
services.AddSingleton<IClipboardService, WinAppSDKClipboardService>();
services.AddSingleton<IPinnedThumbnailHost, PinnedThumbnailHost>();
services.AddSingleton<IOcrService, WindowsOcrService>();
services.AddSingleton<IRegionCaptureService, WindowsRegionCaptureService>();
// --- Navigation --------------------------------------------------------
services.AddSingleton<INavigationService, NavigationService>();
// --- View models -------------------------------------------------------
services.AddSingleton<MainWindowViewModel>();
services.AddSingleton<DashboardViewModel>();
services.AddSingleton<UpdateViewModel>();
services.AddSingleton<HotkeyBindingViewModel>();
services.AddSingleton<SettingsViewModel>();
services.AddSingleton<AboutViewModel>();
services.AddSingleton<LogViewerViewModel>();
return services.BuildServiceProvider(validateScopes: true);
}
}
-85
View File
@@ -1,85 +0,0 @@
using CaptureImage.Core.Logging;
using CaptureImage.Infrastructure.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.App;
/// <summary>
/// Central Serilog configuration. Creates the in-memory ring buffer sink once, exposes it
/// so the DI container can hand it to the log viewer, and wires console + rolling file.
/// </summary>
internal static class LoggingSetup
{
/// <summary>
/// Returns the root directory under <c>%LocalAppData%\CaptureImage</c>, creating it if needed.
/// </summary>
public static string GetAppDataDir()
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CaptureImage");
Directory.CreateDirectory(dir);
return dir;
}
public static string GetLogsDir() => LogPaths.GetLogsDirectory();
/// <summary>
/// Build the Serilog root logger together with the in-memory sink and the runtime
/// level switch, and assign the logger to <see cref="Log.Logger"/>. Both are returned
/// so the DI container can register them — the sink drives the log viewer, the switch
/// drives the Settings → Log Level picker.
/// </summary>
/// <remarks>
/// The switch boots at <see cref="LogEventLevel.Debug"/> so early-startup telemetry is
/// always captured; <c>Program.Main</c> narrows it to the user's configured value once
/// <c>ISettingsStore.LoadAsync</c> has finished.
/// </remarks>
public static (InMemorySink Sink, LoggingLevelSwitch LevelSwitch) Initialize()
{
var logPath = Path.Combine(GetLogsDir(), "captureimg-.log");
var sink = new InMemorySink();
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Debug);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.WithProperty("App", "CaptureImage")
.Enrich.With(new CallerPropertyDefaultsEnricher())
.WriteTo.Console()
.WriteTo.Sink(sink)
.WriteTo.Async(a => a.File(
path: logPath,
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 14,
fileSizeLimitBytes: 10L * 1024 * 1024,
rollOnFileSizeLimit: true,
shared: false,
// {File}:{Line} shows caller context injected by CallerAwareLoggerExtensions.
// Missing on legacy call sites — Serilog prints a bare ":" then, so keep the
// template consistent and accept that one cosmetic artifact until those are
// migrated. {Properties:j} still JSON-dumps every non-templated property.
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] ({File}:{Line}) {Message:lj} {Properties:j}{NewLine}{Exception}"))
.CreateLogger();
return (sink, levelSwitch);
}
/// <summary>
/// Map the persisted <c>LogLevel</c> string (one of <c>Debug</c> / <c>Information</c> /
/// <c>Warning</c> / <c>Error</c>) to a <see cref="LogEventLevel"/>. Unknown strings
/// fall back to <see cref="LogEventLevel.Information"/>.
/// </summary>
public static LogEventLevel ParseLevel(string? value) => value?.Trim().ToLowerInvariant() switch
{
"debug" => LogEventLevel.Debug,
"information" => LogEventLevel.Information,
"info" => LogEventLevel.Information,
"warning" => LogEventLevel.Warning,
"warn" => LogEventLevel.Warning,
"error" => LogEventLevel.Error,
_ => LogEventLevel.Information,
};
}
-121
View File
@@ -1,121 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="CaptureImage.App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:CaptureImage.UI.Views"
xmlns:controls="using:CaptureImage.UI.Controls"
mc:Ignorable="d">
<Grid x:Name="Root"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={StaticResource FlowDirectionConverter}}">
<Grid.RowDefinitions>
<!-- Title-bar drag region. Reserve 48 px so the OS-drawn caption buttons
(minimize / maximize / close) don't overlap the NavigationView pane
header, the LogViewer drawer, or any Page content. AppTitleBar is
marked as the window's title bar via Window.SetTitleBar in code-behind. -->
<RowDefinition Height="48" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Grid.Row="0" x:Name="AppTitleBar" Background="Transparent" />
<!-- Body grid: 2 columns so the LogViewer drawer can sit in a dedicated 480 px
column on the trailing edge instead of relying on HorizontalAlignment="Right",
which WinUI 3 doesn't honour reliably on first measure (the drawer would
render on the leading edge until a window resize forced a relayout). -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="480" />
</Grid.ColumnDefinitions>
<NavigationView
Grid.ColumnSpan="2"
x:Name="NavView"
IsBackButtonVisible="Collapsed"
IsSettingsVisible="False"
PaneDisplayMode="Left"
OpenPaneLength="220"
MenuItemsSource="{Binding NavItems}"
SelectedItem="{Binding SelectedNavItem, Mode=TwoWay}"
SelectionChanged="NavView_SelectionChanged">
<NavigationView.PaneHeader>
<StackPanel Margin="12,8,12,8">
<TextBlock
Text="{Binding AppTitle}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeTitle}"
FontWeight="SemiBold" />
<TextBlock
Text="{Binding AppVersion}"
FontFamily="{StaticResource BodyFontFamily}"
FontSize="{StaticResource FontSizeCaption}"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Margin="0,4,0,0" />
</StackPanel>
</NavigationView.PaneHeader>
<NavigationView.MenuItemTemplate>
<DataTemplate>
<NavigationViewItem Content="{Binding Label}">
<NavigationViewItem.Icon>
<FontIcon
Glyph="{Binding IconGlyph}"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" />
</NavigationViewItem.Icon>
</NavigationViewItem>
</DataTemplate>
</NavigationView.MenuItemTemplate>
<NavigationView.PaneFooter>
<Button
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Margin="8,4,8,16"
Padding="12,8"
Background="Transparent"
BorderThickness="0"
Command="{Binding ToggleLogViewerCommand}"
ToolTipService.ToolTip="{Binding LogToggleTooltip}"
AutomationProperties.Name="{Binding LogToggleTooltip}">
<StackPanel Orientation="Horizontal" Spacing="12">
<FontIcon
Glyph="&#xE9F9;"
FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets"
FontSize="16" />
<TextBlock
Text="{Binding LogToggleLabel}"
FontFamily="{StaticResource BodyFontFamily}"
VerticalAlignment="Center" />
</StackPanel>
</Button>
</NavigationView.PaneFooter>
<Frame x:Name="ContentFrame" />
</NavigationView>
<!-- Log viewer drawer overlay — pinned to Column 1 (trailing edge under LTR,
leading under RTL — FlowDirection mirrors). Stays in the visual tree
always so the slide-in Composition animation has something to act on
every toggle. Initial collapsed state (Offset = ±48 px X, Opacity = 0,
IsHitTestVisible = false) is set in MainWindow.OnRootLoaded. -->
<views:LogViewerView
Grid.Column="1"
x:Name="LogDrawer"
DataContext="{Binding LogViewer}" />
<!-- Toast overlay — anchored bottom of the trailing edge column. Spans both
columns so MaxWidth + alignment can position it freely. -->
<controls:ToastHost
Grid.ColumnSpan="2"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Margin="0,0,20,20"
IsHitTestVisible="True" />
</Grid>
</Grid>
</Window>
-177
View File
@@ -1,177 +0,0 @@
using System.ComponentModel;
using System.Numerics;
using CaptureImage.UI.Theming;
using CaptureImage.UI.Views;
using CaptureImage.ViewModels;
using CaptureImage.ViewModels.Navigation;
using Microsoft.UI;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Hosting;
using Microsoft.UI.Xaml.Media;
using Windows.Graphics;
using WinRT.Interop;
namespace CaptureImage.App;
public sealed partial class MainWindow : Window
{
// Logical dimensions carried over from v1.2-M7. AppWindow.Resize takes physical
// pixels — DPI scaling refinement is deferred to v1.4 polish.
private const int InitialWidth = 1200;
private const int InitialHeight = 720;
// How far the drawer is pushed off-screen when collapsed. Matches v1.2's translateX(48px).
// The sign flips under RTL so the drawer always slides in toward its anchored edge.
private const float DrawerOffsetX = 48f;
// Show/hide timing matches v1.2-M7 (220 ms slide, 180 ms fade, CircularEaseOut-ish).
private static readonly TimeSpan SlideDuration = TimeSpan.FromMilliseconds(220);
private static readonly TimeSpan FadeDuration = TimeSpan.FromMilliseconds(180);
public MainWindow()
{
InitializeComponent();
Title = "CaptureImage";
SystemBackdrop = new MicaBackdrop { Kind = MicaKind.Base };
ExtendsContentIntoTitleBar = true;
SetTitleBar(AppTitleBar);
var hwnd = WindowNative.GetWindowHandle(this);
var windowId = Win32Interop.GetWindowIdFromWindow(hwnd);
var appWindow = AppWindow.GetFromWindowId(windowId);
appWindow.Resize(new SizeInt32(InitialWidth, InitialHeight));
if (appWindow.Presenter is OverlappedPresenter presenter)
{
presenter.IsMaximizable = false;
presenter.IsResizable = false;
}
Root.Loaded += OnRootLoaded;
}
public MainWindowViewModel? ViewModel { get; private set; }
/// <summary>
/// Apply the persisted theme preference to the window root. <c>System</c> falls back
/// to <see cref="ElementTheme.Default"/> which lets the OS theme drive everything,
/// including Mica. Called at startup and whenever <c>ISettingsStore.Changed</c> fires.
/// Safe to call from any thread — <see cref="ThemeApplicator"/> hops to the dispatcher.
/// </summary>
public void ApplyTheme(string theme) => ThemeApplicator.Apply(Content as FrameworkElement, theme);
public void SetViewModel(MainWindowViewModel vm)
{
if (ViewModel is not null)
{
ViewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
ViewModel = vm;
Root.DataContext = vm;
vm.PropertyChanged += OnViewModelPropertyChanged;
if (vm.SelectedNavItem is { } first)
{
NavigateToNavItem(first);
}
}
private void OnRootLoaded(object sender, RoutedEventArgs e)
{
// Enable the Composition `Translation` property on the drawer's visual. WITHOUT
// this, animating Translation has no effect. WITH it, Translation is added on
// top of the layout-computed position — which is what we want: the drawer stays
// pinned to Grid.Column=1 (right 480 px) while Translation supplies the slide
// offset. Setting `visual.Offset` directly (the v1.3-M5 approach) OVERRODE
// layout position and made the drawer render from x=±48 absolute, ignoring its
// Grid cell.
ElementCompositionPreview.SetIsTranslationEnabled(LogDrawer, true);
var visual = ElementCompositionPreview.GetElementVisual(LogDrawer);
// Seed Translation to the collapsed offset; subsequent toggles animate via
// visual.StartAnimation("Translation", ...).
visual.Properties.InsertVector3("Translation", new Vector3(GetCollapsedOffsetX(), 0f, 0f));
visual.Opacity = 0f;
LogDrawer.IsHitTestVisible = false;
}
private float GetCollapsedOffsetX() =>
Root.FlowDirection == FlowDirection.RightToLeft ? -DrawerOffsetX : DrawerOffsetX;
private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (args.SelectedItem is NavItemViewModel item)
{
NavigateToNavItem(item);
}
}
private void NavigateToNavItem(NavItemViewModel item)
{
var pageType = item.Key switch
{
"dashboard" => typeof(DashboardPage),
"update" => typeof(UpdatePage),
"settings" => typeof(SettingsPage),
"about" => typeof(AboutPage),
_ => null,
};
if (pageType is not null && ContentFrame.CurrentSourcePageType != pageType)
{
ContentFrame.Navigate(pageType, App.Services);
}
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (ViewModel is null) return;
if (e.PropertyName == nameof(MainWindowViewModel.IsLogViewerVisible))
{
if (ViewModel.IsLogViewerVisible) ShowLogDrawer();
else HideLogDrawer();
}
}
private void ShowLogDrawer()
{
LogDrawer.IsHitTestVisible = true;
AnimateDrawer(targetTranslationX: 0f, targetOpacity: 1f);
}
private void HideLogDrawer()
{
AnimateDrawer(targetTranslationX: GetCollapsedOffsetX(), targetOpacity: 0f);
LogDrawer.IsHitTestVisible = false;
}
private void AnimateDrawer(float targetTranslationX, float targetOpacity)
{
var visual = ElementCompositionPreview.GetElementVisual(LogDrawer);
var compositor = visual.Compositor;
// CubicBezier(0.4, 0, 0.2, 1) — Material/Fluent decelerate. Visually
// indistinguishable from v1.2's Avalonia CircularEaseOut for sub-300ms motion.
var easing = compositor.CreateCubicBezierEasingFunction(
new Vector2(0.4f, 0f), new Vector2(0.2f, 1f));
// Animate Translation (an additive transform that respects layout) instead of
// Offset (which overrides layout). Target name "Translation" routes through the
// Properties dictionary set up in OnRootLoaded.
var translationAnim = compositor.CreateVector3KeyFrameAnimation();
translationAnim.InsertKeyFrame(1f, new Vector3(targetTranslationX, 0f, 0f), easing);
translationAnim.Duration = SlideDuration;
translationAnim.Target = "Translation";
visual.StartAnimation("Translation", translationAnim);
var opacityAnim = compositor.CreateScalarKeyFrameAnimation();
opacityAnim.InsertKeyFrame(1f, targetOpacity, easing);
opacityAnim.Duration = FadeDuration;
visual.StartAnimation("Opacity", opacityAnim);
}
}
+99 -142
View File
@@ -1,173 +1,130 @@
using CaptureImage.App.SingleInstance;
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using System.Globalization;
using System.IO;
using System.Windows.Threading;
using CaptureImage.App.Composition;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Paths;
using CaptureImage.Infrastructure.Logging;
using CaptureImage.Infrastructure.Platform;
using CaptureImage.UI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Velopack;
namespace CaptureImage.App;
internal static class Program
/// <summary>Entry point: Velopack hooks, single instance, logging, container, then the WPF app.</summary>
public static class Program
{
/// <summary>
/// Entry point.
/// </summary>
/// <remarks>
/// <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 WinUI 3 boots,
/// otherwise the installer will hang waiting for the previous instance to exit.
/// </remarks>
private static readonly TimeSpan ShutdownTimeout = TimeSpan.FromSeconds(5);
[STAThread]
public static int Main(string[] args)
{
VelopackApp.Build().Run();
// Velopack's install / update / uninstall hooks must run before anything else.
VelopackApp.Build()
.OnBeforeUninstallFastCallback(_ => AutostartService.RemoveForUninstall())
.Run();
// Single-instance guard runs AFTER Velopack hooks so installer/uninstaller
// launches (--squirrel-*) aren't blocked. If another instance owns the
// mutex, we ping it via named pipe (ActivationListener restores its
// window) and exit immediately without bringing up our own UI.
if (!SingleInstanceGuard.TryAcquire(out var instanceReleaser))
var options = StartupOptions.Parse(args);
var paths = AppPaths.FromCommandLine(args);
paths.EnsureCreated();
using var instance = new SingleInstance(options.InstanceId);
if (!instance.TryAcquire())
{
instance.SignalExisting();
return 0;
}
using var _instanceReleaser = instanceReleaser;
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);
var logBuffer = new InMemorySink();
Log.Logger = CreateLogger(paths, levelSwitch, logBuffer);
var log = Log.ForContext(typeof(Program));
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
log.Fatal(e.ExceptionObject as Exception, "Unhandled exception; CaptureImage is terminating.");
TaskScheduler.UnobservedTaskException += (_, e) =>
{
log.Error(e.Exception, "Unobserved task exception.");
e.SetObserved();
};
var (inMemorySink, loggingLevelSwitch) = LoggingSetup.Initialize();
RegisterGlobalExceptionHandlers();
var shutdownReason = "Normal";
try
{
Log.Information(
"CaptureImage starting. Version={Version} OS={OS} Culture={Culture} Args={Args}",
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0-dev",
System.Runtime.InteropServices.RuntimeInformation.OSDescription,
System.Globalization.CultureInfo.CurrentUICulture.Name,
args);
var services = CompositionRoot.BuildServices(inMemorySink, loggingLevelSwitch);
App.Services = services;
var settingsStore = services.GetRequiredService<ISettingsStore>();
settingsStore.LoadAsync().GetAwaiter().GetResult();
var configuredLevel = LoggingSetup.ParseLevel(settingsStore.Current.LogLevel);
loggingLevelSwitch.MinimumLevel = configuredLevel;
Log.Information("Log level set to {Level} from settings.", configuredLevel);
var localization = services.GetRequiredService<ILocalizationService>();
var cultureName = settingsStore.Current.Culture;
if (!string.IsNullOrWhiteSpace(cultureName))
{
try
{
var culture = System.Globalization.CultureInfo.GetCultureInfo(cultureName);
var supported = false;
foreach (var shipped in localization.SupportedCultures)
{
if (shipped.Name.Equals(culture.Name, StringComparison.OrdinalIgnoreCase))
{
supported = true;
break;
}
}
if (supported)
{
localization.SetCulture(culture);
}
else
{
Log.Warning(
"Persisted culture {Culture} is not a shipped language; falling back to default.",
cultureName);
}
}
catch (System.Globalization.CultureNotFoundException)
{
Log.Warning("Persisted culture {Culture} is unknown; falling back to default.", cultureName);
}
}
// WinUI 3 entry point. Application.Start blocks until the dispatcher exits. The
// callback runs once on the freshly-minted UI thread before any Window is shown
// — install a SynchronizationContext that flows back to that thread so async
// continuations land where bindings can see them.
Application.Start(p =>
{
var ctx = new DispatcherQueueSynchronizationContext(
DispatcherQueue.GetForCurrentThread());
SynchronizationContext.SetSynchronizationContext(ctx);
_ = new App();
});
return 0;
}
catch (Exception ex)
{
shutdownReason = "StartupCrash";
Log.Fatal(ex, "CaptureImage crashed during startup.");
return -1;
log.Information("CaptureImage {Version} starting (data: {DataDir}).", AppVersion(), paths.DataDirectory);
return Run(args, options, paths, levelSwitch, logBuffer, instance);
}
finally
{
try
{
if (App.Services is not null)
{
var store = App.Services.GetService<ISettingsStore>();
if (store is not null)
{
store.FlushAsync().GetAwaiter().GetResult();
}
}
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to flush settings on shutdown.");
}
// Dispose the DI container so every IDisposable singleton runs its cleanup —
// most importantly WmiProcessWatcher (WMI subscriptions on non-background
// threads), Win32ForegroundWindowWatcher (WinEventHook), and TrayIconHost.
// Without this, the process can't fully exit and Task Manager accumulates one
// zombie CaptureImage.exe per launch.
try
{
(App.Services as IDisposable)?.Dispose();
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to dispose service provider on shutdown.");
}
Log.Information("CaptureImage shutting down. Reason={Reason}", shutdownReason);
log.Information("CaptureImage exited.");
Log.CloseAndFlush();
}
}
private static void RegisterGlobalExceptionHandlers()
private static int Run(
string[] args,
StartupOptions options,
AppPaths paths,
LoggingLevelSwitch levelSwitch,
InMemorySink logBuffer,
SingleInstance instance)
{
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
var builder = Host.CreateEmptyApplicationBuilder(new HostApplicationBuilderSettings
{
var ex = e.ExceptionObject as Exception;
Log.Fatal(
ex,
"Unhandled AppDomain exception. IsTerminating={IsTerminating}",
e.IsTerminating);
if (e.IsTerminating)
{
Log.CloseAndFlush();
}
};
Args = args,
ContentRootPath = AppContext.BaseDirectory,
});
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.Logging.AddSerilog(Log.Logger, dispose: false);
builder.Services.AddCaptureImageCore(paths, levelSwitch, logBuffer);
builder.Services.AddCaptureImageUi(Dispatcher.CurrentDispatcher);
builder.ConfigureContainer(new DefaultServiceProviderFactory(new ServiceProviderOptions
{
ValidateOnBuild = true,
ValidateScopes = true,
}));
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error(e.Exception, "Unobserved task exception.");
e.SetObserved();
};
using var host = builder.Build();
var settings = host.Services.GetRequiredService<ISettingsStore>();
settings.LoadAsync().GetAwaiter().GetResult();
levelSwitch.MinimumLevel = SerilogLogLevelSwitcher.Parse(settings.Current.LogLevel);
host.StartAsync().GetAwaiter().GetResult();
var app = new UI.App(host.Services, new UiStartupOptions(options.StartMinimized, options.SmokeTest, options.ScreenshotDirectory));
instance.ShowRequested += (_, _) => app.Dispatcher.BeginInvoke(app.ShowMainWindow);
instance.StartListening();
var exitCode = app.Run();
host.StopAsync(ShutdownTimeout).GetAwaiter().GetResult();
settings.FlushAsync().GetAwaiter().GetResult();
return exitCode;
}
private static Logger CreateLogger(AppPaths paths, LoggingLevelSwitch levelSwitch, InMemorySink logBuffer) =>
new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.With(new UserPathRedactionEnricher())
.WriteTo.Async(sink => sink.File(
Path.Combine(paths.LogsDirectory, "captureimage-.log"),
formatProvider: CultureInfo.InvariantCulture,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext}: {Message:l}{NewLine}{Exception}",
fileSizeLimitBytes: 10L * 1024 * 1024,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
retainedFileCountLimit: 14))
.WriteTo.Sink(logBuffer)
.CreateLogger();
private static string AppVersion() => ViewModels.Services.AppInfo.FromAssembly(typeof(Program).Assembly).DisplayVersion;
}
+123
View File
@@ -0,0 +1,123 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
namespace CaptureImage.App;
/// <summary>
/// One running copy per user session and instance id. A second launch asks the first, over a
/// pipe only the same user can open, to show its window, then exits. The names differ from
/// v1, so a v1 copy that is still running doesn't swallow the request.
/// </summary>
internal sealed partial class SingleInstance : IDisposable
{
private const byte ShowCommand = 0x01;
private const int AsfwAny = -1;
private readonly string _name;
private Mutex? _mutex;
private CancellationTokenSource? _listening;
public SingleInstance(string instanceId)
{
using var identity = WindowsIdentity.GetCurrent();
using var process = Process.GetCurrentProcess();
var user = identity.User?.Value ?? Environment.UserName;
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(user)))[..12];
_name = $"CaptureImage.v2.{instanceId}.{process.SessionId}.{hash}";
}
/// <summary>Raised on a background thread when another launch asks for the window.</summary>
public event EventHandler? ShowRequested;
/// <summary>True when this is the first copy.</summary>
public bool TryAcquire()
{
var mutex = new Mutex(initiallyOwned: true, @"Local\" + _name, out var createdNew);
if (!createdNew)
{
mutex.Dispose();
return false;
}
_mutex = mutex;
return true;
}
/// <summary>Ask the first copy to show its window (best effort).</summary>
public void SignalExisting()
{
// The first copy is a background process; let it take the foreground for this request.
AllowSetForegroundWindow(AsfwAny);
try
{
using var client = new NamedPipeClientStream(".", _name, PipeDirection.Out, PipeOptions.CurrentUserOnly);
client.Connect(TimeSpan.FromSeconds(2));
client.WriteByte(ShowCommand);
client.Flush();
}
catch (Exception ex) when (ex is TimeoutException or IOException or UnauthorizedAccessException)
{
// The other copy is starting up or shutting down; nothing more to do.
}
}
public void StartListening()
{
_listening = new CancellationTokenSource();
var token = _listening.Token;
_ = Task.Run(() => ListenAsync(token), token);
}
public void Dispose()
{
_listening?.Cancel();
_listening?.Dispose();
if (_mutex is not null)
{
_mutex.ReleaseMutex();
_mutex.Dispose();
}
}
private async Task ListenAsync(CancellationToken cancellationToken)
{
var buffer = new byte[1];
while (!cancellationToken.IsCancellationRequested)
{
try
{
await using var server = new NamedPipeServerStream(
_name,
PipeDirection.In,
maxNumberOfServerInstances: 1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await server.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
if (await server.ReadAsync(buffer, cancellationToken).ConfigureAwait(false) == 1 && buffer[0] == ShowCommand)
{
ShowRequested?.Invoke(this, EventArgs.Empty);
}
}
catch (OperationCanceledException)
{
return;
}
catch (IOException)
{
// A client disconnected mid-message; wait a moment and listen again.
await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken).ConfigureAwait(false);
}
}
}
// The BOOL result is ignored: when the call isn't allowed the window simply flashes instead.
[LibraryImport("user32.dll")]
private static partial void AllowSetForegroundWindow(int processId);
}
@@ -1,115 +0,0 @@
using System.IO.Pipes;
using System.Runtime.InteropServices;
using CaptureImage.Core.Abstractions;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Serilog;
using WinRT.Interop;
namespace CaptureImage.App.SingleInstance;
/// <summary>
/// Background listener for the single-instance ACTIVATE pipe. When a secondary launch
/// fires <see cref="SingleInstanceGuard.ActivateMessage"/>, this brings the main window
/// back to the foreground — same restore sequence the tray icon uses
/// (<c>AppWindow.Show</c> + <c>ShowWindow(SW_RESTORE)</c> + <c>SetForegroundWindow</c>).
/// </summary>
internal sealed class ActivationListener : IDisposable
{
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;
private readonly Window _mainWindow;
private readonly IUIThreadDispatcher _dispatcher;
private readonly CancellationTokenSource _cts = new();
private readonly Task _loop;
private bool _disposed;
private ActivationListener(Window mainWindow, IUIThreadDispatcher dispatcher)
{
_mainWindow = mainWindow;
_dispatcher = dispatcher;
_loop = Task.Run(() => RunAsync(_cts.Token));
}
/// <summary>Start listening; returns the listener so it can be disposed on shutdown.</summary>
public static ActivationListener Start(Window mainWindow, IUIThreadDispatcher dispatcher)
=> new(mainWindow, dispatcher);
private async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(
pipeName: SingleInstanceGuard.PipeName,
direction: PipeDirection.In,
maxNumberOfServerInstances: 1,
transmissionMode: PipeTransmissionMode.Byte,
options: PipeOptions.Asynchronous);
await server.WaitForConnectionAsync(ct).ConfigureAwait(false);
using var reader = new StreamReader(server);
var line = await reader.ReadLineAsync(ct).ConfigureAwait(false);
if (string.Equals(line, SingleInstanceGuard.ActivateMessage, StringComparison.Ordinal))
{
_dispatcher.Post(RestoreWindow);
}
}
catch (OperationCanceledException)
{
// Shutdown — exit cleanly.
return;
}
catch (Exception ex)
{
Log.Warning(ex, "ActivationListener pipe iteration failed; will retry.");
// Avoid a hot loop if the pipe is in a bad state — yield briefly.
try { await Task.Delay(500, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
}
}
private void RestoreWindow()
{
try
{
var hwnd = WindowNative.GetWindowHandle(_mainWindow);
var windowId = Win32Interop.GetWindowIdFromWindow(hwnd);
var appWindow = AppWindow.GetFromWindowId(windowId);
// Mirror TrayIconHost.ShowMainWindow: AppWindow.Show un-hides if minimised
// to tray, ShowWindow(SW_RESTORE) un-minimises a taskbar-minimised window,
// and SetForegroundWindow forces Z-order to top even if another app has focus.
appWindow.Show();
ShowWindow(hwnd, SW_RESTORE);
_mainWindow.Activate();
SetForegroundWindow(hwnd);
Log.Debug("Main window restored from secondary launch ACTIVATE.");
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to restore main window on ACTIVATE.");
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { _cts.Cancel(); }
catch { /* swallow */ }
try { _loop.Wait(TimeSpan.FromSeconds(1)); }
catch { /* shutdown — best effort */ }
_cts.Dispose();
}
}
@@ -1,99 +0,0 @@
using System.IO.Pipes;
using Serilog;
namespace CaptureImage.App.SingleInstance;
/// <summary>
/// Per-user single-instance gate. The first process to call <see cref="TryAcquire"/>
/// wins the named mutex and returns a releaser to be held for the lifetime of the
/// app. Any subsequent launch fails the acquire, fires an ACTIVATE message at the
/// existing instance over a named pipe, and exits — the user perceives a restored
/// window instead of a duplicate process.
///
/// Mutex + pipe names are scoped to the local user session so two different OS
/// users on the same machine each get their own primary instance.
/// </summary>
internal static class SingleInstanceGuard
{
public const string PipeName = "CaptureImage.Activate";
public const string ActivateMessage = "ACTIVATE";
private static readonly string MutexName =
$"Local\\CaptureImage.SingleInstance.{Environment.UserName}";
/// <summary>
/// Try to become the primary instance. Returns true and yields a disposable
/// releaser when this process owns the mutex. Returns false if another instance
/// already holds it — in that case an ACTIVATE message is fired over the
/// named pipe (best effort) so the existing instance restores its window.
/// </summary>
public static bool TryAcquire(out IDisposable releaser)
{
var mutex = new Mutex(initiallyOwned: false, name: MutexName);
bool acquired;
try
{
// Short timeout — if another instance is alive it should already own the
// mutex; if it's hung we don't want to block startup waiting for it.
acquired = mutex.WaitOne(TimeSpan.FromMilliseconds(100), exitContext: false);
}
catch (AbandonedMutexException)
{
// Previous instance exited without releasing (crash, kill, etc.). The
// OS hands us ownership anyway — treat as acquired.
Log.Warning("Single-instance mutex was abandoned by a previous process; taking ownership.");
acquired = true;
}
if (acquired)
{
releaser = new MutexReleaser(mutex);
return true;
}
// Best-effort: poke the existing instance to restore its window. Failure
// here is non-fatal — even if the pipe send fails, the user can still
// click the tray icon to restore the running instance.
try
{
using var client = new NamedPipeClientStream(
serverName: ".",
pipeName: PipeName,
direction: PipeDirection.Out);
client.Connect(timeout: 1000);
using var writer = new StreamWriter(client) { AutoFlush = true };
writer.WriteLine(ActivateMessage);
Log.Information("Existing CaptureImage instance detected — sent ACTIVATE and exiting.");
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to ping existing instance over named pipe; user must restore manually.");
}
mutex.Dispose();
releaser = NoopReleaser.Instance;
return false;
}
private sealed class MutexReleaser : IDisposable
{
private Mutex? _mutex;
public MutexReleaser(Mutex mutex) => _mutex = mutex;
public void Dispose()
{
if (_mutex is null) return;
try { _mutex.ReleaseMutex(); }
catch (ApplicationException) { /* not owned — race on shutdown */ }
_mutex.Dispose();
_mutex = null;
}
}
private sealed class NoopReleaser : IDisposable
{
public static readonly NoopReleaser Instance = new();
public void Dispose() { }
}
}
+47
View File
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using System.IO;
namespace CaptureImage.App;
/// <summary>
/// Command-line switches: <c>--minimized</c> (start in the tray; "Start with Windows" uses it),
/// <c>--smoke-test</c> (open every page and exit 0 — CI), <c>--instance-id &lt;id&gt;</c>
/// (separate single-instance scope, so tests never talk to a copy the user is running) and
/// <c>--data-dir &lt;path&gt;</c> (read by <c>AppPaths</c>). <c>--screenshots &lt;dir&gt;</c> runs the
/// smoke test and saves a PNG of every page (docs, visual review in CI).
/// </summary>
internal sealed record StartupOptions(bool StartMinimized, bool SmokeTest, string InstanceId, string? ScreenshotDirectory)
{
private const int MaxInstanceIdLength = 32;
public static StartupOptions Parse(IReadOnlyList<string> args)
{
ArgumentNullException.ThrowIfNull(args);
var minimized = args.Any(a => string.Equals(a, "--minimized", StringComparison.OrdinalIgnoreCase));
var smokeTest = args.Any(a => string.Equals(a, "--smoke-test", StringComparison.OrdinalIgnoreCase));
var instanceId = "default";
string? screenshots = null;
for (var i = 0; i < args.Count - 1; i++)
{
if (string.Equals(args[i], "--instance-id", StringComparison.OrdinalIgnoreCase))
{
instanceId = Sanitize(args[i + 1]);
}
else if (string.Equals(args[i], "--screenshots", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(args[i + 1]))
{
screenshots = Path.GetFullPath(args[i + 1]);
}
}
return new StartupOptions(minimized, smokeTest || screenshots is not null, instanceId, screenshots);
}
/// <summary>Letters, digits, '-' and '_' only — the id becomes part of a mutex and pipe name.</summary>
private static string Sanitize(string value)
{
var clean = new string([.. value.Where(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_').Take(MaxInstanceIdLength)]);
return clean.Length == 0 ? "default" : clean;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="CaptureImage.App" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 and 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<!-- Per-monitor DPI v2: crisp UI on mixed-DPI setups; region overlays map 1:1 to screen pixels. -->
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<!-- Output folders and game paths can exceed MAX_PATH. -->
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*" />
</dependentAssembly>
</dependency>
</assembly>
+491
View File
@@ -0,0 +1,491 @@
{
"version": 2,
"dependencies": {
"net10.0-windows10.0.22621": {
"CommunityToolkit.Mvvm": {
"type": "Direct",
"requested": "[8.4.2, )",
"resolved": "8.4.2",
"contentHash": "WadCzGEc2U+3e20avRLng4qNtt4zoOGWrdUISqJWrHe3/FSnrYjuM5Sb4yQb09LhkBXrrI4Zt3dLKgRMbItsrg=="
},
"Microsoft.Extensions.Hosting": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "Q+hmPoDqeHipHyJcY7mDCQiLDUcn9jIgjoCThcgaOgjLTTT3ApTe8p6M2+twsDyfKuuCsKhSNlnNjaaggtXxRA==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.Configuration.CommandLine": "10.0.13",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.13",
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.13",
"Microsoft.Extensions.Configuration.Json": "10.0.13",
"Microsoft.Extensions.Configuration.UserSecrets": "10.0.13",
"Microsoft.Extensions.DependencyInjection": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Diagnostics": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Physical": "10.0.13",
"Microsoft.Extensions.Hosting.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Configuration": "10.0.13",
"Microsoft.Extensions.Logging.Console": "10.0.13",
"Microsoft.Extensions.Logging.Debug": "10.0.13",
"Microsoft.Extensions.Logging.EventLog": "10.0.13",
"Microsoft.Extensions.Logging.EventSource": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Serilog": {
"type": "Direct",
"requested": "[4.4.0, )",
"resolved": "4.4.0",
"contentHash": "ZC6Le3rr4TVJJjS4KsQAesxeF1EhW9qcZmmG7eP5Y2G3+gTGkJEUXkq4+tZNPtyp05I0wWOxnIjwtxFweJsObw=="
},
"Serilog.Extensions.Logging": {
"type": "Direct",
"requested": "[10.0.0, )",
"resolved": "10.0.0",
"contentHash": "vx0kABKl2dWbBhhqAfTOk53/i8aV/5VaT3a6il9gn72Wqs2pM7EK2OB6No6xdqK2IaY6Zf9gdjLuK9BVa2rT+Q==",
"dependencies": {
"Microsoft.Extensions.Logging": "10.0.0",
"Serilog": "4.2.0"
}
},
"Serilog.Sinks.Async": {
"type": "Direct",
"requested": "[2.1.0, )",
"resolved": "2.1.0",
"contentHash": "SnmRknWsSMgyo9wDXeZZCqSp48kkQYy44taSM6vcpxfiRICzSf09oLKEmVr0RCwQnfd8mJQ2WNN6nvhqf0RowQ==",
"dependencies": {
"Serilog": "4.1.0"
}
},
"Serilog.Sinks.File": {
"type": "Direct",
"requested": "[7.0.0, )",
"resolved": "7.0.0",
"contentHash": "fKL7mXv7qaiNBUC71ssvn/dU0k9t0o45+qm2XgKAlSt19xF+ijjxyA3R6HmCgfKEKwfcfkwWjayuQtRueZFkYw==",
"dependencies": {
"Serilog": "4.2.0"
}
},
"Velopack": {
"type": "Direct",
"requested": "[1.2.161, )",
"resolved": "1.2.161",
"contentHash": "OpHNacIumnkhaaX3ZlQ/TCR4YPOJvud2/PAOoWb6o+mIrLwIVA275I5wAgt4q/1O2VrJeDwR1qFQyqzG4lUArg=="
},
"H.GeneratedIcons.System.Drawing": {
"type": "Transitive",
"resolved": "2.4.1",
"contentHash": "gjYhuwHQzISqKhcNYaRdDhzKCoqLZii+6TTHP0MQf4Q9+H6z4f4A5Xu/j8B8XpFPQ1grCMlQYREvNyNJT9Q/Bg=="
},
"H.NotifyIcon": {
"type": "Transitive",
"resolved": "2.4.1",
"contentHash": "nNPgNzo5UHcWYpVLO3AsRlH8fKE9shBA7/WLpZrFZUFbzpKGcLnz15Kmg0pQ851aboAfm3YuHjYFsYQges/pyw==",
"dependencies": {
"H.GeneratedIcons.System.Drawing": "2.4.1"
}
},
"Microsoft.Extensions.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "DY4C2qzTt2lOIY3VoscBH/TCwTolI5DKOfgJLuI+k1QUvRNT5vTMS58AOerNiihdVRStO0wEpLeRWA8jytzHBQ==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Binder": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.CommandLine": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "RwdNZ9JdGs8eZmeL5qRe7ugp0Irk3KVkWpC/w1c8kjJwu1R4HvCXYz9kwHZxn45WiaRBG5lphQKtqnBaJOQC+Q==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.EnvironmentVariables": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "qJK2dm9/AxyPVfqqBaZtjkUFl2hnBR/CQnMJtSO5LdEoyATMqvZjeQVY+8l0oa6PM6qlVe28iMEyXIRQ0wyZjA==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.FileExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "kwC1DY55CsqPmDtJAz+7alD3G+gJcM+XwHSZrcRO8mJGYB9hRq1qC6ZH8DL0SPW9WtJ/Bae5ikzPic8SxSv6Vw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Physical": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Json": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "acCWM2+WR67kBAz6gAhD2zG+IZH9Q2VpKv5le7Msiu0vAMsnnLXpnV3BAzxd8/i+uOEo/dfb2XRYTynRVTDvEg==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.UserSecrets": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "kQ/Tx972unP+ueQL8SSninthIj6w6XP2o0VnJPFC5HQIimPMwEN704MOspEgDkmm4FUL5SuxLEU0bNiW4HEZFA==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Json": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Physical": "10.0.13"
}
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Diagnostics.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.FileProviders.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.FileProviders.Physical": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "U7HkgGCNPICN5k7NVK6dmLsSPSPeO/EbNcuxOl/5qdC9Ahjp9UZWKOvlnUC+rYurmoxIlwyv9e5j0BaQlTOELA==",
"dependencies": {
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.FileSystemGlobbing": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.FileSystemGlobbing": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "vQVzmAbnzlhXSXA2caYnlxtG9GXxEwtj5bODiWLu06A6iqeJmfBtlfKjuOSJGRy0/CFaNUrm7u9nxEUlljc2Rg=="
},
"Microsoft.Extensions.Hosting.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Console": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "i9rn0rHkiCxfNVbf4DRG7LOFcKPy/BioAxS07w6daWvIpLNRjskqDJcGGaYVFWndsq0iTRaS8Msry0t5fRYQug==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Configuration": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Debug": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yBig0DNMq+3UgliwxYlUC48dg0fPqvqI5B3ljzmLTrpR6maoKTOO5i9QnPgQUmQoaQWZMgu74fuF6oSDihb6pg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Logging.EventLog": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "OAK40lXhgMuvyNwvzW3fxLvvucN8yr5XS7dQRcPmtnPf+Pt1lpbMgao5T4Wa6VdFagtIeDZNgPtV5Ig4xstziQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Logging.EventSource": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "SxJu3oczk+TJtHvpgAmCVzEkzx69/obA6GZCbGrbqYqc981YOAyfEprySBdFX7Yc5qatHJKHNTlpGeeBAQkZcA==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "tmMJgdrE4uhf1JcNs9CV9moAHW+hmDuvgMiPpnQxarKaUxqI2eN33sYK5S4l9Uw+rG9PJvlm4qPxMhvolTDTaQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options.ConfigurationExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "ZjTwxzhiw2TMEzIbUDkMF0dfDB2I4NQgIfKD0ELu9/5Mk+SRGdKZcD0/lvBrRCAPo6KN2r0BW86MRancoyJkoA=="
},
"SharpGen.Runtime": {
"type": "Transitive",
"resolved": "2.4.2-beta",
"contentHash": "niTtWAUov1F7wZGAlVeEvW+Tnqvg5yTmhI7rxmYu2Utoyu2TbC9tWWpUpMs0PQg5lu5svoYpCAztNjxCqMFP/w=="
},
"SharpGen.Runtime.COM": {
"type": "Transitive",
"resolved": "2.4.2-beta",
"contentHash": "9lxDFMiepqo3lJQzMSjECCIONeCc2f3Drokgj6HtrTLZcJSftNgcLbD6/iXYj2iphkwgrZb1oLsDOZxoFZkawQ==",
"dependencies": {
"SharpGen.Runtime": "2.4.2-beta"
}
},
"SkiaSharp.NativeAssets.Win32": {
"type": "Transitive",
"resolved": "4.153.1",
"contentHash": "Yqg6rChTVh0BUE8QQxtOA3uUBnihfgID4yex/AvDa0+os2bVcBjmI3Qj9tnOB+R1hd/Jry1Gwl8qw5JI9HZG8Q=="
},
"Vortice.DirectX": {
"type": "Transitive",
"resolved": "3.8.3",
"contentHash": "nKwSavv0w5rDF7prSefqAVPDcTyqrfZxKFMVfttiXPfm62VdA/1d+b3PhCZpW4xO7jXczXDwjQdWgD1zGsvM8w==",
"dependencies": {
"SharpGen.Runtime": "2.4.2-beta",
"SharpGen.Runtime.COM": "2.4.2-beta",
"Vortice.Mathematics": "2.1.0"
}
},
"Vortice.Mathematics": {
"type": "Transitive",
"resolved": "2.1.0",
"contentHash": "KK+SjNSuKdP+zbavekubi+vaeb1Jo4k87ZF6CMkVWjr6RjJwc8peVtmgzXXDIMy4ZC3ZISyk3llY3q65ISOkBQ=="
},
"WPF-UI.Abstractions": {
"type": "Transitive",
"resolved": "4.3.0",
"contentHash": "7Kj9DmCCo4SOCd1jAiw4+EcMFP2nR8rLLvitAYzVtzbWToTsodkbie24+8x9C4LDLxkopWEUGX62szqqNy7oeg=="
},
"captureimage.core": {
"type": "Project",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "[10.0.13, )"
}
},
"captureimage.infrastructure": {
"type": "Project",
"dependencies": {
"CaptureImage.Core": "[1.5.1, )",
"Microsoft.Extensions.Logging.Abstractions": "[10.0.13, )",
"Serilog": "[4.4.0, )",
"SkiaSharp": "[4.153.1, )",
"Velopack": "[1.2.161, )",
"Vortice.DXGI": "[3.8.3, )",
"Vortice.Direct2D1": "[3.8.3, )",
"Vortice.Direct3D11": "[3.8.3, )"
}
},
"captureimage.ui": {
"type": "Project",
"dependencies": {
"CaptureImage.Core": "[1.5.1, )",
"CaptureImage.ViewModels": "[1.5.1, )",
"CommunityToolkit.Mvvm": "[8.4.2, )",
"H.NotifyIcon.Wpf": "[2.4.1, )",
"Microsoft.Extensions.DependencyInjection.Abstractions": "[10.0.13, )",
"Microsoft.Extensions.Logging.Abstractions": "[10.0.13, )",
"WPF-UI": "[4.3.0, )"
}
},
"captureimage.viewmodels": {
"type": "Project",
"dependencies": {
"CaptureImage.Core": "[1.5.1, )",
"CommunityToolkit.Mvvm": "[8.4.2, )",
"Microsoft.Extensions.DependencyInjection.Abstractions": "[10.0.13, )",
"Microsoft.Extensions.Logging.Abstractions": "[10.0.13, )"
}
},
"H.NotifyIcon.Wpf": {
"type": "CentralTransitive",
"requested": "[2.4.1, )",
"resolved": "2.4.1",
"contentHash": "aDfDSHCCOWgQoIvAApiog/MhriXibacqANQm+b5GaRCgRg92u5J2QcoW2C+wIblgxhtGx3o32/DCKWRR5C/KLw==",
"dependencies": {
"H.NotifyIcon": "2.4.1"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "CentralTransitive",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "4tnWU9vrU/A8NwYe9Z6wvieZ0EBb/uM82LAT+edNhdepOBWREZ7M7mzb941EIDPJaeOFdbVrDd5+7s9e89U6bQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "CentralTransitive",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.Logging": {
"type": "CentralTransitive",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "fqbiPy4nUp4H2XHKAVQXKN2y3T2h4cFIx1DAAgE6iY9OHkN/OA1cKFi+geJKRWGuX6pS5SFbsjIPWHJqrxE0eg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "CentralTransitive",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "aSZEhEig4fvNiw2zs8Z6NyDlniKtq6YjcF3DyHuqTEHcZ2VKA/6itMPZ+dW+yWABWExlDcQwwdbqX1Rcb7W8WQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"SkiaSharp": {
"type": "CentralTransitive",
"requested": "[4.153.1, )",
"resolved": "4.153.1",
"contentHash": "TghYLOUaP3q6rTjQw7U9uQaaXh8lEs9rfA1U7/VtmyAptVDtj/SmjtcWzFWmcC/VMWxe3QgbV9uyvqDL7ySFtQ==",
"dependencies": {
"SkiaSharp.NativeAssets.Win32": "4.153.1"
}
},
"Vortice.Direct2D1": {
"type": "CentralTransitive",
"requested": "[3.8.3, )",
"resolved": "3.8.3",
"contentHash": "SDHEmNUT3A4P8yj+g7q3AnRZ9fvqOOe/EoWjsgkHlQ3C9Tkc51rTeZXC9bQPySli+/lFTui8vMs9tpWZqf+AwQ==",
"dependencies": {
"SharpGen.Runtime": "2.4.2-beta",
"Vortice.DXGI": "3.8.3"
}
},
"Vortice.Direct3D11": {
"type": "CentralTransitive",
"requested": "[3.8.3, )",
"resolved": "3.8.3",
"contentHash": "JgFUswu2mgrSwcd0KRF2AnfeE5VbMEgcicmxPD1g2yXyomPIHbnX3wldBNHPOzzD0URC1WJ/pO1ymfi3imZwvg==",
"dependencies": {
"SharpGen.Runtime": "2.4.2-beta",
"Vortice.DXGI": "3.8.3"
}
},
"Vortice.DXGI": {
"type": "CentralTransitive",
"requested": "[3.8.3, )",
"resolved": "3.8.3",
"contentHash": "MbAUnTeQ6WD99ctAdrj5CQO2I7oaax0Kt2eVdWSUj0bYP9Ed0726+s7dIHe4+tqhpmINW/dcPt0mNtc72o+E0w==",
"dependencies": {
"SharpGen.Runtime": "2.4.2-beta",
"Vortice.DirectX": "3.8.3"
}
},
"WPF-UI": {
"type": "CentralTransitive",
"requested": "[4.3.0, )",
"resolved": "4.3.0",
"contentHash": "SIHhc8lIrhEQ/1cLFZN6Dtf8cqsLm4myBULj9obnacd9TyDs2vizhKYzRzTlcPEcnzb3L4EstvPN3M6kcXbJCA==",
"dependencies": {
"WPF-UI.Abstractions": "4.3.0"
}
}
},
"net10.0-windows10.0.22621/win-x64": {
"SkiaSharp.NativeAssets.Win32": {
"type": "Transitive",
"resolved": "4.153.1",
"contentHash": "Yqg6rChTVh0BUE8QQxtOA3uUBnihfgID4yex/AvDa0+os2bVcBjmI3Qj9tnOB+R1hd/Jry1Gwl8qw5JI9HZG8Q=="
}
}
}
}
@@ -1,16 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Capture;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Captures a single frame of a target window. The engine handles D3D/WinRT ceremony and
/// returns raw BGRA pixels — encoding is the encoder's responsibility (see <see cref="IImageEncoder"/>).
/// </summary>
/// <summary>Grabs a single frame from a window or a monitor.</summary>
public interface ICaptureEngine
{
/// <summary>
/// Capture one frame of the target's window. Throws <see cref="Errors.CaptureException"/>
/// with a stable <see cref="Errors.CaptureError"/> on any known-bad path.
/// Capture one frame. 8-bit frames always come back opaque. Failures are reported as
/// <see cref="Errors.CaptureException"/> with a specific <see cref="Errors.CaptureError"/>.
/// </summary>
Task<CapturedFrame> CaptureAsync(GameTarget target, CancellationToken cancellationToken = default);
Task<CapturedFrame> CaptureAsync(CaptureSource source, CaptureOptions options, CancellationToken cancellationToken = default);
}
/// <summary>Monitor layout, DPI and HDR state.</summary>
public interface IDisplayService
{
IReadOnlyList<MonitorInfo> GetMonitors();
MonitorInfo? GetMonitorForWindow(nint windowHandle);
MonitorInfo? GetMonitorAtCursor();
}
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Library;
namespace CaptureImage.Core.Abstractions;
/// <summary>Index of saved captures backing the Library page.</summary>
public interface ICaptureLibrary
{
/// <summary>The index changed (capture added or removed). Raised on any thread.</summary>
event EventHandler? Changed;
/// <summary>All known captures, newest first; files deleted outside the app are dropped.</summary>
Task<IReadOnlyList<CaptureRecord>> GetAllAsync(CancellationToken cancellationToken = default);
Task AddAsync(CaptureRecord record, CancellationToken cancellationToken = default);
/// <summary>Move the image (and its HDR sidecar) to the Recycle Bin and forget it.</summary>
Task<bool> DeleteAsync(CaptureRecord record, CancellationToken cancellationToken = default);
/// <summary>Path of a cached JPEG thumbnail (at most <paramref name="maxSize"/> px on the long edge).</summary>
Task<string?> GetThumbnailAsync(CaptureRecord record, int maxSize, CancellationToken cancellationToken = default);
}
@@ -1,22 +0,0 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Abstraction over the OS clipboard so portable code can copy a captured image
/// without taking a Windows.* / WinAppSDK dependency. The UI project supplies the
/// real implementation; tests can inject a fake.
/// </summary>
public interface IClipboardService
{
/// <summary>
/// Copy the given PNG-encoded image bytes to the clipboard as a bitmap.
/// Best-effort: returns <c>false</c> if the clipboard is locked or the data
/// can't be set (the caller may surface a toast but should not crash).
/// </summary>
Task<bool> CopyImageAsync(byte[] pngBytes, CancellationToken cancellationToken = default);
/// <summary>
/// Copy plain text to the clipboard. Used by the OCR pipeline to deliver extracted
/// text. Returns <c>false</c> on clipboard contention.
/// </summary>
bool CopyText(string text);
}
@@ -1,31 +0,0 @@
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,21 +0,0 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Platform-neutral test: is this hotkey binding already owned by another process?
/// Implementations perform a best-effort check (e.g. Windows <c>RegisterHotKey</c> sniff)
/// and immediately release any claim they take — they must never leave the combination
/// bound after the call returns.
/// </summary>
public interface IHotkeyConflictSniffer
{
/// <summary>
/// <c>true</c> if the combination is already registered by another process or the
/// shell; <c>false</c> if we successfully (and transiently) claimed it. Returning
/// <c>false</c> does not prove the combination will work — the Windows shell has
/// higher priority and consumes some combos before <c>RegisterHotKey</c> is consulted
/// (see <see cref="Validation.ReservedHotkeys"/>).
/// </summary>
bool IsConflicted(HotkeyBinding binding);
}
@@ -1,25 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Capture;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>Result of trying to register one global hotkey.</summary>
public enum HotkeyRegistrationStatus
{
/// <summary>The mode has no hotkey.</summary>
Unbound,
/// <summary>Registered with Windows; it fires while the service is active.</summary>
Registered,
/// <summary>Another application already owns the combination.</summary>
Conflict,
/// <summary>The binding is not a valid hotkey (see <see cref="HotkeyBinding.Validate"/>).</summary>
Invalid,
}
public sealed record HotkeyRegistration(CaptureMode Mode, HotkeyBinding Binding, HotkeyRegistrationStatus Status);
/// <summary>
/// Global (system-wide) hotkey listener. Subscribers are responsible for marshalling
/// to the UI thread — <see cref="Triggered"/> fires from whatever thread the hook uses.
/// System-wide hotkeys (Win32 <c>RegisterHotKey</c>). Keys are only registered while the
/// service is active, because a registered combination never reaches other applications.
/// </summary>
public interface IHotkeyService : IDisposable
{
/// <summary>Currently registered binding, or <c>null</c> if the service is stopped.</summary>
HotkeyBinding? CurrentBinding { get; }
/// <summary>A capture hotkey was pressed. Raised on a background thread.</summary>
event EventHandler<CaptureMode>? Triggered;
/// <summary>Fired whenever the registered binding matches the currently pressed keys.</summary>
event EventHandler? Triggered;
bool IsActive { get; }
IReadOnlyList<HotkeyRegistration> Registrations { get; }
/// <summary>(Re)register every bound mode; returns the per-mode result.</summary>
IReadOnlyList<HotkeyRegistration> Activate(HotkeySettings bindings);
void Deactivate();
/// <summary>
/// Start listening with the given binding. If the service is already listening, the
/// previous binding is replaced.
/// True when another application currently owns <paramref name="binding"/>. Bindings
/// held by this service are not reported as conflicts.
/// </summary>
void SetBinding(HotkeyBinding binding);
bool IsTakenByAnotherApp(HotkeyBinding binding);
/// <summary>Stop listening. Safe to call multiple times.</summary>
void Stop();
/// <summary>
/// Register extra keys for a short time (Esc / Enter while the region overlay is up, so
/// they work even if the overlay never gets keyboard focus). Dispose to release them.
/// </summary>
IDisposable RegisterTemporary(IReadOnlyList<HotkeyBinding> bindings, Action<HotkeyBinding> callback);
}
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>Loads saved images back into frames (library: copy, OCR, pin).</summary>
public interface IImageDecoder
{
/// <summary>
/// Decode <paramref name="path"/> into an opaque 8-bit frame. With
/// <paramref name="maxDimension"/> &gt; 0 the image is downscaled so its long edge fits.
/// Returns <c>null</c> when the file is missing or not a readable image.
/// </summary>
Task<CapturedFrame?> LoadAsync(string path, int maxDimension = 0, CancellationToken cancellationToken = default);
}
@@ -1,31 +1,44 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Encodes a <see cref="CapturedFrame"/> to a byte stream in a target <see cref="ImageFormat"/>.
/// Encoders may be format-specialized (SkiaSharp for PNG/JPEG/WebP, ImageSharp for TIFF);
/// the dispatcher picks the right one per request.
/// </summary>
/// <summary>PNG zlib effort.</summary>
public enum PngCompressionLevel
{
/// <summary>Fastest save, larger files.</summary>
Fast,
/// <summary>Default trade-off.</summary>
Balanced,
/// <summary>Smallest files, slowest save.</summary>
Smallest,
}
/// <summary>Text metadata embedded into saved images where the format supports it.</summary>
public sealed record ImageMetadata(string? Title, string Software, DateTimeOffset CapturedAt);
/// <summary>Per-save encoder options.</summary>
public sealed record EncoderSettings(
int JpegQuality = 90,
int WebpQuality = 85,
PngCompressionLevel PngCompression = PngCompressionLevel.Balanced,
ImageMetadata? Metadata = null);
/// <summary>Encodes a <see cref="CapturedFrame"/> into an image file stream.</summary>
public interface IImageEncoder
{
/// <summary>True if this encoder can handle <paramref name="format"/>.</summary>
bool Supports(ImageFormat format);
/// <summary>True if this encoder can write <paramref name="format"/> from <paramref name="pixelFormat"/> input.</summary>
bool Supports(ImageFormat format, FramePixelFormat pixelFormat);
/// <summary>
/// Encode <paramref name="frame"/> into <paramref name="destination"/>.
/// </summary>
/// <param name="frame">Raw BGRA source frame.</param>
/// <param name="format">Target format. Must be supported by this encoder.</param>
/// <param name="jpegQuality">1-100, used only when format is JPEG.</param>
/// <param name="webpQuality">1-100, used only when format is WebP.</param>
/// <param name="destination">Writable stream; flushed but not closed.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <summary>Encode into <paramref name="destination"/> (flushed, not closed).</summary>
Task EncodeAsync(
CapturedFrame frame,
ImageFormat format,
int jpegQuality,
int webpQuality,
EncoderSettings settings,
Stream destination,
CancellationToken cancellationToken = default);
}
@@ -0,0 +1,82 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Capture;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>A frozen picture of one monitor, shown by the region selector.</summary>
/// <param name="Monitor">The monitor that was captured.</param>
/// <param name="DisplayFrame">An 8-bit rendition of the monitor (tone-mapped when it was HDR).</param>
public sealed record MonitorSnapshot(MonitorInfo Monitor, CapturedFrame DisplayFrame);
/// <summary>The rectangle a user dragged, relative to the monitor's top-left corner (physical pixels).</summary>
public sealed record RegionSelection(MonitorInfo Monitor, PixelRect Area);
/// <summary>Full-screen overlays (one per monitor) for dragging a capture rectangle.</summary>
public interface IRegionSelector
{
/// <summary>The user's selection, or <c>null</c> when they cancelled (Esc, right click).</summary>
Task<RegionSelection?> SelectAsync(IReadOnlyList<MonitorSnapshot> snapshots, CancellationToken cancellationToken = default);
}
/// <summary>"Save this capture?" dialog shown when preview-before-save is enabled.</summary>
public interface IPreviewPresenter
{
/// <summary>True to save, false to discard.</summary>
Task<bool> ShowAsync(CapturedFrame frame, string title, CancellationToken cancellationToken = default);
}
/// <summary>Floating always-on-top thumbnails of recent captures.</summary>
public interface IPinnedThumbnailHost
{
void Show(CapturedFrame frame, string? filePath, string title);
}
public interface IClipboardService
{
Task<bool> CopyImageAsync(CapturedFrame frame, CancellationToken cancellationToken = default);
Task<bool> CopyTextAsync(string text, CancellationToken cancellationToken = default);
}
/// <summary>
/// Notifications. While the main window is visible they appear inside it; while the app sits
/// in the tray they appear as small non-activating pop-ups that never steal focus from a game.
/// </summary>
public interface IToastService
{
void Show(ToastKind kind, string title, string message, TimeSpan? duration = null);
}
public static class ToastServiceExtensions
{
public static void ShowSuccess(this IToastService toasts, string title, string message) =>
toasts.Show(ToastKind.Success, title, message);
public static void ShowError(this IToastService toasts, string title, string message) =>
toasts.Show(ToastKind.Error, title, message);
public static void ShowInfo(this IToastService toasts, string title, string message) =>
toasts.Show(ToastKind.Info, title, message);
public static void ShowWarning(this IToastService toasts, string title, string message) =>
toasts.Show(ToastKind.Warning, title, message);
}
/// <summary>Marshals work onto the UI thread.</summary>
public interface IUIThreadDispatcher
{
bool IsOnUIThread { get; }
/// <summary>Queue <paramref name="action"/>; runs inline when already on the UI thread.</summary>
void Post(Action action);
Task InvokeAsync(Action action);
Task<T> InvokeAsync<T>(Func<T> func);
/// <summary>Run an async function on the UI thread and observe its completion.</summary>
Task InvokeAsync(Func<Task> func);
}
@@ -1,12 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using System.ComponentModel;
using System.Globalization;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Direction of text flow for the UI. Maps 1:1 to Avalonia's
/// <c>Avalonia.Media.FlowDirection</c> but stays in the portable Core assembly so view models
/// don't have to reference Avalonia.
/// Direction of text flow for the UI. Maps 1:1 to WPF's <c>System.Windows.FlowDirection</c>
/// but stays in the portable Core assembly so view models don't reference the UI framework.
/// </summary>
public enum TextFlowDirection
{
@@ -16,8 +18,8 @@ public enum TextFlowDirection
/// <summary>
/// Runtime localization service. Exposes translated strings via the <see cref="this[string]"/>
/// indexer so XAML can bind to <c>{Binding [MyKey], Source={StaticResource Localizer}}</c> and
/// react to culture changes without a restart.
/// indexer so XAML can bind to <c>{Binding Localization[MyKey]}</c> and react to culture
/// changes without a restart.
/// </summary>
public interface ILocalizationService : INotifyPropertyChanged
{
@@ -43,8 +45,44 @@ public interface ILocalizationService : INotifyPropertyChanged
event EventHandler? CultureChanged;
/// <summary>
/// Switch the UI culture. Raises <see cref="PropertyChanged"/> for the indexer (so all
/// Switch the UI culture. Raises <see cref="System.ComponentModel.INotifyPropertyChanged.PropertyChanged"/> for the indexer (so all
/// bindings refresh) and <see cref="CultureChanged"/>.
/// </summary>
void SetCulture(CultureInfo culture);
}
public static class LocalizationServiceExtensions
{
/// <summary>Format a localized template with the current UI culture's number/date rules.</summary>
public static string Format(this ILocalizationService localization, string key, params object?[] args)
{
ArgumentNullException.ThrowIfNull(localization);
return string.Format(localization.CurrentCulture, localization[key], args);
}
/// <summary>
/// The shipped culture closest to <paramref name="requested"/>: the exact name, then the same
/// language (<c>vi</c> → <c>vi-VN</c>, <c>zh-CN</c> → <c>zh-Hans</c>), then English.
/// </summary>
public static CultureInfo MatchSupportedCulture(this ILocalizationService localization, CultureInfo? requested)
{
ArgumentNullException.ThrowIfNull(localization);
var supported = localization.SupportedCultures;
var fallback = supported.Count > 0 ? supported[0] : CultureInfo.GetCultureInfo("en-US");
if (requested is null || requested.Equals(CultureInfo.InvariantCulture))
{
return fallback;
}
for (var culture = requested; !culture.Equals(CultureInfo.InvariantCulture); culture = culture.Parent)
{
var exact = supported.FirstOrDefault(c => string.Equals(c.Name, culture.Name, StringComparison.OrdinalIgnoreCase));
if (exact is not null)
{
return exact;
}
}
return supported.FirstOrDefault(c => c.TwoLetterISOLanguageName == requested.TwoLetterISOLanguageName) ?? fallback;
}
}
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
@@ -1,3 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
namespace CaptureImage.Core.Abstractions;
/// <summary>
@@ -1,27 +1,33 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Result of an OCR pass over a captured image.
/// </summary>
/// <param name="Text">Extracted text in reading order. Empty if no glyphs were recognised.</param>
/// <param name="AverageConfidence">0.0–1.0; 0 if no engine was available.</param>
/// <param name="EngineAvailable">
/// <c>false</c> when the OS has no recognizer pack installed for the requested language
/// (and no usable fallback). UIs should disable the action and surface a hint.
/// </param>
public sealed record OcrResult(string Text, double AverageConfidence, bool EngineAvailable);
public enum OcrStatus
{
/// <summary>Text was recognized.</summary>
Success,
/// <summary>
/// Offline OCR. Wraps the OS-supplied <c>Windows.Media.Ocr</c> engine on the
/// implementation side; abstracted here so the portable VM layer can stay free of
/// WinRT references and test fakes can stub it.
/// </summary>
/// <summary>The engine ran but found no text.</summary>
NoText,
/// <summary>No OCR language pack is installed for the requested or user languages.</summary>
EngineUnavailable,
/// <summary>Recognition failed.</summary>
Failed,
}
public sealed record OcrResult(OcrStatus Status, string Text)
{
public static OcrResult Failed { get; } = new(OcrStatus.Failed, string.Empty);
}
/// <summary>Offline text recognition (Windows.Media.Ocr).</summary>
public interface IOcrService
{
/// <summary>
/// Recognise text from the given PNG-encoded image. <paramref name="languageTag"/>
/// is a BCP-47 hint (e.g. <c>en-US</c>); <c>null</c> defers to the user's profile
/// languages, falling back to en-US, then to <see cref="OcrResult.EngineAvailable"/>=false.
/// </summary>
Task<OcrResult> RecognizeAsync(byte[] pngBytes, string? languageTag, CancellationToken cancellationToken = default);
/// <summary>Recognize text in an 8-bit frame; large frames are downscaled to the engine's limit.</summary>
Task<OcrResult> RecognizeAsync(CapturedFrame frame, string? languageTag, CancellationToken cancellationToken = default);
}
@@ -1,17 +0,0 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Spawns a small always-on-top window holding a thumbnail of the most recent capture.
/// Each call creates a fresh window so users can keep multiple captures pinned and
/// compare them side-by-side. Implementation lives in the UI project.
/// </summary>
public interface IPinnedThumbnailHost
{
/// <summary>
/// Show a new pinned thumbnail. <paramref name="pngBytes"/> is the encoded image,
/// <paramref name="filePath"/> is the file the capture was written to (may be null
/// if clipboard-only mode skipped the save), and <paramref name="targetName"/> is
/// the display name shown in the title for context.
/// </summary>
void Show(byte[] pngBytes, string? filePath, string targetName);
}
@@ -1,23 +0,0 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Shows the user a preview of a captured frame and awaits their accept/reject decision.
/// </summary>
/// <remarks>
/// Declared in Core so the orchestrator / view models don't reference Avalonia. The UI
/// project provides an implementation that opens a modal <c>PreviewWindow</c>.
/// </remarks>
public interface IPreviewPresenter
{
/// <summary>
/// Show the preview dialog for <paramref name="frame"/>. The returned task completes
/// with <c>true</c> when the user accepts and <c>false</c> when they discard or close
/// the dialog without saving.
/// </summary>
Task<bool> ShowAsync(
CapturedFrame frame,
GameTarget target,
CancellationToken cancellationToken = default);
}
@@ -1,17 +0,0 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Enumerates candidate capture targets — processes with a visible top-level window.
/// Implementations combine window enumeration, process metadata, icon extraction,
/// and Steam attribution into a single call.
/// </summary>
public interface IProcessDetector
{
/// <summary>
/// Snapshot the current set of targets. Safe to call repeatedly; detectors
/// are expected to do their own caching for expensive lookups (icons, Steam metadata).
/// </summary>
Task<IReadOnlyList<GameTarget>> EnumerateTargetsAsync(CancellationToken cancellationToken = default);
}
@@ -1,22 +0,0 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Observes process create/destroy events so the Dashboard can stay live without polling.
/// Implementations raise <see cref="Changed"/> off the UI thread; subscribers are responsible
/// for marshalling to the UI via <see cref="IUIThreadDispatcher"/>.
/// </summary>
public interface IProcessWatcher : IDisposable
{
/// <summary>
/// Raised when a process starts or stops. May fire from an arbitrary thread.
/// </summary>
event EventHandler<ProcessChange>? Changed;
/// <summary>Begin observing. Safe to call multiple times; subsequent calls are no-ops.</summary>
void Start();
/// <summary>Stop observing. Can be restarted with <see cref="Start"/>.</summary>
void Stop();
}
@@ -1,13 +0,0 @@
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Capture an arbitrary rectangular region of the desktop. Implementations show an
/// overlay so the user can drag-select; <c>null</c> means the user cancelled (Esc /
/// click outside / overlay closed).
/// </summary>
public interface IRegionCaptureService
{
Task<CapturedFrame?> SelectAndCaptureAsync(CancellationToken cancellationToken = default);
}
@@ -1,56 +1,35 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Persistence for <see cref="AppSettings"/>. The orchestrator treats this as a live
/// cache — reads return the current in-memory copy, writes debounce to disk.
/// </summary>
/// <summary>Persisted user settings (<c>settings.json</c> in the data directory).</summary>
public interface ISettingsStore
{
/// <summary>
/// Current in-memory settings. Never <c>null</c>; defaults are returned before the first load.
/// </summary>
AppSettings Current { get; }
/// <summary>
/// Raised after <see cref="Current"/> has been mutated (via <see cref="Update"/>,
/// <see cref="LoadAsync"/>, or <see cref="ImportAsync"/>). Subscribers run on whatever
/// thread the change happened on.
/// </summary>
/// <summary>Raised after <see cref="Current"/> changes, on the thread that made the change.</summary>
event EventHandler? Changed;
/// <summary>Absolute path to the settings file on disk.</summary>
string SettingsFilePath { get; }
/// <summary>
/// Load settings from disk into <see cref="Current"/>. If the file does not exist or
/// fails to parse, defaults are used and a warning is logged. Safe to call repeatedly.
/// </summary>
/// <summary>Load (migrating older schemas and the v1 settings location) — call once at startup.</summary>
Task LoadAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Apply <paramref name="mutator"/> to a copy of <see cref="Current"/> and make it the
/// new current value. Writes are debounced — call this as often as you like, the disk
/// only sees one write per quiet window.
/// </summary>
/// <summary>Apply a change and schedule a debounced write.</summary>
void Update(Func<AppSettings, AppSettings> mutator);
/// <summary>
/// Force an immediate, non-debounced flush to disk. Use at app shutdown or before
/// import/export operations.
/// </summary>
/// <summary>Write pending changes now.</summary>
Task FlushAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Serialize the current settings to <paramref name="exportPath"/>. Existing files are
/// overwritten.
/// </summary>
Task ExportAsync(string exportPath, CancellationToken cancellationToken = default);
/// <summary>
/// Load + validate settings from <paramref name="importPath"/>, adopt them as the new
/// <see cref="Current"/>, and immediately flush. Throws on parse errors or unknown versions.
/// </summary>
/// <summary>Validate and apply a settings file exported earlier.</summary>
/// <exception cref="InvalidDataException">The file is not a valid settings document.</exception>
Task ImportAsync(string importPath, CancellationToken cancellationToken = default);
/// <summary>Back up the current file and restore defaults.</summary>
Task ResetAsync(CancellationToken cancellationToken = default);
}
@@ -1,22 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Maps executable paths to Steam application metadata. The user decided (see the plan file)
/// that Steam games get a <b>warning badge, not an ignore</b> — this service returns the
/// <see cref="SteamAppInfo"/> so the UI can render the badge; it does not filter anything out.
/// </summary>
/// <summary>Maps executables to installed Steam apps (for the Steam badge and profiles).</summary>
public interface ISteamDetector
{
/// <summary>
/// All Steam library roots discovered on this machine (empty if Steam is not installed).
/// </summary>
IReadOnlyList<SteamLibrary> Libraries { get; }
/// <summary>
/// Return the <see cref="SteamAppInfo"/> for the executable at <paramref name="executablePath"/>,
/// or <c>null</c> if the executable does not live under a Steam library.
/// </summary>
SteamAppInfo? TryGetAppInfo(string executablePath);
}
@@ -1,14 +0,0 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Locates the Steam client install directory. Production resolves from registry;
/// tests inject a fixed path.
/// </summary>
public interface ISteamRootLocator
{
/// <summary>
/// Absolute path to the Steam install directory (the folder that contains
/// <c>steamapps\libraryfolders.vdf</c>), or <c>null</c> if Steam is not installed.
/// </summary>
string? TryFindSteamRoot();
}
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
namespace CaptureImage.Core.Abstractions;
/// <summary>Shell integration (open files and folders, links, Recycle Bin).</summary>
public interface IShellService
{
/// <summary>Open a file with its default program, or a folder in Explorer.</summary>
bool Open(string path);
/// <summary>Open Explorer with <paramref name="filePath"/> selected.</summary>
bool RevealInExplorer(string filePath);
bool OpenUrl(Uri url);
/// <summary>Move a file to the Recycle Bin (never a permanent delete).</summary>
bool MoveToRecycleBin(string path);
}
public interface ISoundService
{
void PlayCaptureSound();
}
/// <summary>
/// Windows 11 "efficiency mode" (EcoQoS) while the app idles in the tray, lifted while a
/// capture runs so encoding isn't throttled.
/// </summary>
public interface IPerformanceModeService
{
void SetBackground(bool isBackground);
/// <summary>Temporarily run at normal priority; dispose to return to the previous mode.</summary>
IDisposable BeginForegroundWork();
}
/// <summary>"Start with Windows" (per-user Run key).</summary>
public interface IAutostartService
{
bool IsEnabled { get; }
/// <summary>Returns false if the registry could not be updated.</summary>
bool SetEnabled(bool enabled);
}
/// <summary>Bundles logs, settings and system information for a bug report.</summary>
public interface IDiagnosticsExporter
{
/// <summary>Write a zip to <paramref name="destinationPath"/> and return its path.</summary>
Task<string> ExportAsync(string destinationPath, CancellationToken cancellationToken = default);
/// <summary>A default file name such as <c>CaptureImage-diagnostics-20261019-071500.zip</c>.</summary>
string SuggestFileName();
}
/// <summary>Application shutdown, so view models can quit without referencing the UI framework.</summary>
public interface IAppLifetime
{
void Shutdown();
}
@@ -1,29 +0,0 @@
using System.Collections.ObjectModel;
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// In-app toast notifications. Anchors to a corner of the main window rather than the
/// OS Action Center — see plan §9.
/// </summary>
public interface IToastService
{
/// <summary>
/// Live collection the UI binds to. Always mutated on the UI thread (callers are
/// responsible for marshalling).
/// </summary>
ObservableCollection<ToastItem> Visible { get; }
/// <summary>Push a toast. Oldest toasts drop off when the visible cap is reached.</summary>
void Show(ToastItem item);
/// <summary>Dismiss a specific toast (user click, auto-timeout, or VM cleanup).</summary>
void Dismiss(Guid id);
/// <summary>Convenience helpers that build a <see cref="ToastItem"/> for you.</summary>
void ShowSuccess(string title, string message);
void ShowError(string title, string message);
void ShowInfo(string title, string message);
void ShowWarning(string title, string message);
}
@@ -1,18 +0,0 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Owns the system tray icon and its context menu. Lifecycle:
/// <list type="number">
/// <item>App startup calls <see cref="Initialize"/> once the main window exists.</item>
/// <item>Menu items post actions back to the main window (Show / Arm / Exit).</item>
/// <item>App shutdown disposes the host.</item>
/// </list>
/// </summary>
public interface ITrayIconHost : IDisposable
{
/// <summary>
/// Attach the tray icon to the application. The host takes a weak reference to the
/// main window so close-to-tray works.
/// </summary>
void Initialize(object mainWindow);
}
@@ -1,17 +0,0 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Abstraction over the UI thread so portable VM/service code can marshal work
/// without depending on Avalonia directly. The UI project provides the real impl.
/// </summary>
public interface IUIThreadDispatcher
{
/// <summary>True if the current thread is the UI thread.</summary>
bool IsOnUIThread { get; }
/// <summary>Fire-and-forget post to the UI thread.</summary>
void Post(Action action);
/// <summary>Await-able invoke on the UI thread.</summary>
Task InvokeAsync(Action action);
}
@@ -1,47 +1,28 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) CaptureImage Contributors
using CaptureImage.Core.Models;
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Self-update for CaptureImage. Backed by Velopack + GitHub Releases in production, or a
/// no-op stub in dev builds / when Velopack was never set up for the running installation.
/// </summary>
/// <summary>In-app updates from GitHub Releases (Velopack).</summary>
public interface IUpdateService
{
/// <summary>Currently-installed version string (e.g. <c>"0.1.0"</c>).</summary>
string CurrentVersion { get; }
/// <summary>
/// True when the service can actually perform updates (i.e. Velopack metadata is present
/// next to the executable). Dev / <c>dotnet run</c> sessions return false.
/// </summary>
/// <summary>False when running from source (not a Velopack install).</summary>
bool IsAvailable { get; }
/// <summary>
/// Raised whenever a log line should be appended to the Update tab's status log.
/// Fires on whatever thread the update workflow is running on — subscribers marshal
/// to the UI themselves.
/// </summary>
/// <summary>Human-readable progress lines for the Update page.</summary>
event EventHandler<string>? LogEmitted;
/// <summary>
/// Hit the update source and report whether a newer version is available.
/// </summary>
Task<UpdateCheckResult> CheckAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Download the update that was returned by the most recent <see cref="CheckAsync"/>.
/// Reports progress 0-100.
/// </summary>
/// <exception cref="InvalidOperationException">
/// No pending update to download (caller skipped <see cref="CheckAsync"/> or the previous
/// check returned <see cref="UpdateStatus.UpToDate"/>).
/// </exception>
Task DownloadAsync(IProgress<int>? progress = null, CancellationToken cancellationToken = default);
/// <summary>
/// Apply the downloaded update and restart the app. Does not return on success; throws
/// if no download has been performed yet.
/// Hand the downloaded update to the Velopack updater, which waits for this process to
/// exit, applies it and restarts the app. The caller must then shut down normally.
/// </summary>
void ApplyAndRestart();
void ApplyOnExit();
}
Loaded 100 of 412 files, more files were not shown because too many files have changed in this diff. Show more