diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0c16e06..c3b0a31 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -90,10 +90,33 @@ jobs: cargo clippy --manifest-path apps/desktop/src-tauri/Cargo.toml --all-targets -- -D warnings cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml + - name: Check updater signing setup + shell: powershell + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + run: | + if ([string]::IsNullOrWhiteSpace($env:TAURI_SIGNING_PRIVATE_KEY)) { + throw "TAURI_SIGNING_PRIVATE_KEY is not set. Add the updater private key as a repository secret (see docs/NOTES.md, Updater keys)." + } + $config = Get-Content -Raw -LiteralPath apps/desktop/src-tauri/tauri.conf.json | ConvertFrom-Json + if ($config.plugins.updater.pubkey -like "REPLACE_WITH_*") { + throw "plugins.updater.pubkey in tauri.conf.json is still the placeholder. Paste the public key (see docs/NOTES.md, Updater keys)." + } + - name: Build Windows installer + shell: powershell env: CAPKIT_COMMIT: ${{ github.sha }} - run: pnpm bundle:windows + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: | + # Updater artifacts (.sig) are enabled here only, so a local + # `pnpm bundle:windows` needs no signing key. A config file avoids + # JSON quoting problems across pnpm and PowerShell. + $overlay = Join-Path $env:RUNNER_TEMP "updater-artifacts.json" + [System.IO.File]::WriteAllText($overlay, '{"bundle":{"createUpdaterArtifacts":true}}', [System.Text.UTF8Encoding]::new($false)) + pnpm --filter @snaphub/desktop exec tauri build --bundles nsis --config $overlay + if ($LASTEXITCODE -ne 0) { throw "tauri build failed" } - name: Publish GitHub release shell: powershell @@ -115,7 +138,25 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "Could not generate release notes" } $notes = (@($generated) -join "`n") + "`n`nFull changelog: [CHANGELOG-PUBLIC.md](https://github.com/${{ github.repository }}/blob/v${{ env.VERSION }}/CHANGELOG-PUBLIC.md)`n" [System.IO.File]::WriteAllText("$PWD/notes.md", $notes, [System.Text.UTF8Encoding]::new($false)) - gh release create "v${{ env.VERSION }}" $installer $checksum --target "${{ github.sha }}" --title "CapKit ${{ env.VERSION }}" --notes-file notes.md + $signaturePath = "$installer.sig" + if (!(Test-Path -LiteralPath $signaturePath)) { + throw "Missing updater signature at $signaturePath" + } + $signature = (Get-Content -Raw -LiteralPath $signaturePath).Trim() + $manifest = [ordered]@{ + version = "${{ env.VERSION }}" + notes = "See CHANGELOG-PUBLIC.md" + pub_date = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") + platforms = [ordered]@{ + "windows-x86_64" = [ordered]@{ + signature = $signature + url = "https://github.com/${{ github.repository }}/releases/download/v${{ env.VERSION }}/CapKit_${{ env.VERSION }}_x64-setup.exe" + } + } + } + $latest = "latest.json" + [System.IO.File]::WriteAllText("$PWD/$latest", ($manifest | ConvertTo-Json -Depth 5), [System.Text.UTF8Encoding]::new($false)) + gh release create "v${{ env.VERSION }}" $installer $checksum $signaturePath $latest --target "${{ github.sha }}" --title "CapKit ${{ env.VERSION }}" --notes-file notes.md - name: Upload installer artifact uses: actions/upload-artifact@v4 diff --git a/.gitignore b/.gitignore index bfd5e8c..2068474 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ scripts .gitignore CHANGELOG.md AGENTS.md +marketing/launch-video/out/ diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index a5e5d48..b813b51 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -2,6 +2,39 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. +## Unreleased — 2026-11-19 + +### Added + +- CapKit can update itself. It checks GitHub once when it starts, tells you when a new version is ready, and installs only when you click Install and restart. You can turn the check off in Settings → General. +- Copy any capture from the Screenshots page, and drag it straight into another app. +- Choose how the capture overlay appears: Dim and rise, Fade in, or Fade in and out. +- Capture toolbar groups open when you click them and remember the last tool you used in each group. + +### Improved + +- The capture toolbar is a single card, with the colour and size row only for tools that use them. +- Only one CapKit runs at a time; opening it again brings the existing window forward. +- Folder paths in Settings no longer start with `\\?\`. + +## Earlier — 2026-10-29 + +### Added + +- Pick a colour while selecting: press I to copy the colour under the pointer as a hex code, or Shift+I for RGB. +- Copy text from a capture. It's read on your PC with Windows' built-in text recognition, so nothing is uploaded. +- Find sensitive text: CapKit spots things like API keys, card numbers, emails and phone numbers in a capture, and you choose which to black out. +- Save & Showcase sends a capture straight to Showcase. Star a style there to apply it to every capture you send. +- Recordings can show the shortcuts you press and your clicks as on-screen labels. It's off by default, and CapKit never records what you type. +- Zoom can follow your typing, so typed text stays readable in recordings. +- Export a recording to fit under 25 MB or 10 MB, for places with upload limits. + +### Improved + +- Open at startup works in the Microsoft Store version, using Windows' own startup list. +- If you turned CapKit off in Windows' startup settings, CapKit's Settings now tells you so and opens the right Windows page to turn it back on. +- The Store version asks for camera and microphone access through Windows' standard prompts. + ## 0.3.0 — 2026-09-28 ### Fixed diff --git a/apps/desktop/package.json b/apps/desktop/package.json index bb92a85..7c09392 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -22,7 +22,6 @@ "@hugeicons/core-free-icons": "4.2.3", "@hugeicons/react": "1.1.9", "@tauri-apps/api": "^2.11.1", - "@tauri-apps/plugin-autostart": "^2.5.1", "@tauri-apps/plugin-dialog": "^2.7.1", "@tauri-apps/plugin-global-shortcut": "^2.3.2", "konva": "^10.3.0", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index c8930cd..ff87fb4 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -111,6 +111,9 @@ name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] [[package]] name = "arboard" @@ -610,6 +613,8 @@ dependencies = [ "arboard", "chrono", "dirs 6.0.0", + "drag", + "dunce", "image", "imageproc", "serde", @@ -619,6 +624,8 @@ dependencies = [ "tauri-plugin-autostart", "tauri-plugin-dialog", "tauri-plugin-global-shortcut", + "tauri-plugin-single-instance", + "tauri-plugin-updater", "thiserror 2.0.18", "uuid", "webview2-com", @@ -841,6 +848,19 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags 2.13.1", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + [[package]] name = "core-graphics" version = "0.25.0" @@ -1035,6 +1055,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -1192,6 +1223,27 @@ dependencies = [ "serde", ] +[[package]] +name = "drag" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e90b4a25ace5ce0561534b073943594cbcd21af936e64d09aec444568411f8c" +dependencies = [ + "core-graphics 0.24.0", + "dunce", + "gdk", + "gdkx11", + "gtk", + "log", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "raw-window-handle", + "thiserror 2.0.18", + "windows 0.52.0", + "windows-core 0.58.0", +] + [[package]] name = "drm" version = "0.14.1" @@ -1449,6 +1501,16 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -2119,6 +2181,21 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.20" @@ -2454,6 +2531,36 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.18", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + [[package]] name = "jni-sys" version = "0.3.1" @@ -2806,6 +2913,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "minisign-verify" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -3337,6 +3450,18 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + [[package]] name = "objc2-quartz-core" version = "0.3.2" @@ -3400,6 +3525,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "option-ext" version = "0.2.0" @@ -3416,6 +3547,20 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "osakit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "owned_ttf_parser" version = "0.25.1" @@ -4104,15 +4249,20 @@ dependencies = [ "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", "serde", "serde_json", "sync_wrapper", "tokio", + "tokio-rustls", "tokio-util", "tower", "tower-http", @@ -4154,6 +4304,20 @@ version = "0.8.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -4195,6 +4359,79 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni 0.22.4", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -4219,6 +4456,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "0.8.22" @@ -4282,6 +4528,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.1", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "selectors" version = "0.36.1" @@ -4520,6 +4789,16 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simd_helpers" version = "0.1.0" @@ -4529,6 +4808,12 @@ dependencies = [ "quote", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "siphasher" version = "1.0.3" @@ -4641,6 +4926,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "swift-rs" version = "1.0.7" @@ -4728,7 +5019,7 @@ dependencies = [ "bitflags 2.13.1", "block2", "core-foundation", - "core-graphics", + "core-graphics 0.25.0", "crossbeam-channel", "dbus", "dispatch2", @@ -4737,7 +5028,7 @@ dependencies = [ "gdkwayland-sys", "gdkx11-sys", "gtk", - "jni", + "jni 0.21.1", "libc", "log", "ndk", @@ -4770,6 +5061,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "target-lexicon" version = "0.12.16" @@ -4800,7 +5102,7 @@ dependencies = [ "heck 0.5.0", "http", "http-range", - "jni", + "jni 0.21.1", "libc", "log", "mime", @@ -4983,6 +5285,55 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "tauri-plugin-single-instance" +version = "2.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db817fe9295e19b7d8357e900af31edb93703dd9fb6de524b007b47b6afc63b0" +dependencies = [ + "serde", + "serde_json", + "tauri", + "thiserror 2.0.18", + "tokio", + "tracing", + "windows-sys 0.60.2", + "zbus", +] + +[[package]] +name = "tauri-plugin-updater" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806d9dac662c2e4594ff03c647a552f2c9bd544e7d0f683ec58f872f952ce4af" +dependencies = [ + "base64 0.22.1", + "dirs 6.0.0", + "flate2", + "futures-util", + "http", + "infer", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest", + "rustls", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.18", + "time", + "tokio", + "url", + "windows-sys 0.60.2", + "zip", +] + [[package]] name = "tauri-runtime" version = "2.11.3" @@ -4993,7 +5344,7 @@ dependencies = [ "dpi", "gtk", "http", - "jni", + "jni 0.21.1", "objc2", "objc2-ui-kit", "objc2-web-kit", @@ -5016,7 +5367,7 @@ checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f" dependencies = [ "gtk", "http", - "jni", + "jni 0.21.1", "log", "objc2", "objc2-app-kit", @@ -5228,6 +5579,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.18" @@ -5553,6 +5914,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -5895,6 +6262,15 @@ dependencies = [ "system-deps 6.2.2", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webview2-com" version = "0.38.2" @@ -5905,8 +6281,8 @@ dependencies = [ "webview2-com-sys", "windows 0.61.3", "windows-core 0.61.2", - "windows-implement", - "windows-interface", + "windows-implement 0.60.2", + "windows-interface 0.59.3", ] [[package]] @@ -5999,6 +6375,18 @@ dependencies = [ "windows-version", ] +[[package]] +name = "windows" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +dependencies = [ + "windows-core 0.52.0", + "windows-implement 0.52.0", + "windows-interface 0.52.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows" version = "0.61.3" @@ -6042,14 +6430,36 @@ dependencies = [ "windows-core 0.62.2", ] +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement 0.58.0", + "windows-interface 0.58.0", + "windows-result 0.2.0", + "windows-strings 0.1.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows-core" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" dependencies = [ - "windows-implement", - "windows-interface", + "windows-implement 0.60.2", + "windows-interface 0.59.3", "windows-link 0.1.3", "windows-result 0.3.4", "windows-strings 0.4.2", @@ -6061,8 +6471,8 @@ version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-implement", - "windows-interface", + "windows-implement 0.60.2", + "windows-interface 0.59.3", "windows-link 0.2.1", "windows-result 0.4.1", "windows-strings 0.5.1", @@ -6090,6 +6500,28 @@ dependencies = [ "windows-threading 0.2.1", ] +[[package]] +name = "windows-implement" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12168c33176773b86799be25e2a2ba07c7aab9968b37541f1094dbd7a60c8946" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -6101,6 +6533,28 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-interface" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d8dc32e0095a7eeccebd0e3f09e9509365ecb3fc6ac4d6f5f14a3f6392942d1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-interface" version = "0.59.3" @@ -6144,6 +6598,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-result" version = "0.3.4" @@ -6162,6 +6625,16 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result 0.2.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows-strings" version = "0.4.2" @@ -6189,6 +6662,15 @@ dependencies = [ "windows-targets 0.42.2", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.59.0" @@ -6502,7 +6984,7 @@ dependencies = [ "gtk", "http", "javascriptcore-rs", - "jni", + "jni 0.21.1", "libc", "ndk", "objc2", @@ -6566,6 +7048,16 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.4", +] + [[package]] name = "xcap" version = "0.9.6" @@ -6751,6 +7243,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zerotrie" version = "0.2.4" @@ -6784,6 +7282,18 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "indexmap 2.14.0", + "memchr", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 2541e52..9d303d1 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -25,6 +25,9 @@ imageproc = { version = "0.27.0", default-features = false, features = ["text"] serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.150" tauri = { version = "2.11.5", features = ["tray-icon", "protocol-asset"] } +tauri-plugin-single-instance = "=2.4.5" +tauri-plugin-updater = "=2.10.1" +dunce = "=1.0.5" tauri-plugin-dialog = "2.7.1" tauri-plugin-autostart = "2" tauri-plugin-global-shortcut = "2.3.2" @@ -33,8 +36,13 @@ uuid = { version = "1.24.0", features = ["v4", "serde"] } xcap = { version = "0.9.6", features = ["image", "wgc"] } [target.'cfg(target_os = "windows")'.dependencies] +drag = "=2.1.1" windows = { version = "0.62.2", features = [ "Foundation", "Globalization", "Graphics_Imaging", "Storage", "Storage_Streams", + # Copy text and redaction suggestions: the OS OCR engine and its installed languages. + "Media_Ocr", + # Package identity and the MSIX startup task (Store build only). + "ApplicationModel", "ApplicationModel_Activation", "Win32_Foundation", "Win32_System_Com", "Win32_UI_Accessibility", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", # Recording: a Windows Graphics Capture frame pool onto our own D3D11 device. diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index d618432..63fd658 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -11,9 +11,6 @@ "core:window:allow-start-dragging", "core:window:allow-set-resizable", "dialog:default", - "autostart:allow-enable", - "autostart:allow-disable", - "autostart:allow-is-enabled", "global-shortcut:default" ] } diff --git a/apps/desktop/src-tauri/msix/AppxManifest.xml b/apps/desktop/src-tauri/msix/AppxManifest.xml index e08d2a7..b2d2d9e 100644 --- a/apps/desktop/src-tauri/msix/AppxManifest.xml +++ b/apps/desktop/src-tauri/msix/AppxManifest.xml @@ -4,7 +4,8 @@ xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:uap10="http://schemas.microsoft.com/appx/manifest/uap/windows10/10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" - IgnorableNamespaces="uap uap10 rescap"> + xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10" + IgnorableNamespaces="uap uap10 rescap desktop"> + + + + + + + + + diff --git a/apps/desktop/src-tauri/src/domain.rs b/apps/desktop/src-tauri/src/domain.rs index 612308a..be53781 100644 --- a/apps/desktop/src-tauri/src/domain.rs +++ b/apps/desktop/src-tauri/src/domain.rs @@ -205,6 +205,77 @@ pub struct CompletionResult { pub cleanup_warning: Option, } +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum ColorFormat { + Hex, + Rgb, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PickColorRequest { + pub session_id: String, + /// Display-local logical coordinates, the same space as the selection. + pub point: Point, + pub format: ColorFormat, +} + +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PickedColorDto { + pub hex: String, + pub copied: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextRecognitionRequest { + pub session_id: String, + pub selection: Rect, +} + +/// A recognised word. `bounds` are selection-local logical coordinates, the +/// same space as annotations, so the UI can place a redaction straight on it. +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct RecognizedWordDto { + pub text: String, + pub bounds: Rect, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct RecognizedLineDto { + pub text: String, + pub words: Vec, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct RecognizedTextDto { + /// Lines joined with `\n`, in reading order. + pub text: String, + pub lines: Vec, + /// BCP-47 tag of the recogniser the OS picked from the user's languages. + pub language: String, +} + +#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum TextCopyStatus { + Copied, + Empty, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextCopyResult { + pub status: TextCopyStatus, + pub text: String, + pub cleanup_warning: Option, +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScrollingCaptureRequest { @@ -300,6 +371,10 @@ pub struct RecordingRequestDto { pub microphone_device_id: Option, #[serde(default)] pub system_audio_device_id: Option, + /// Opt-in. Stores shortcut and named-key presses with the recording; plain + /// typed characters are stored only as "typing happened", never by identity. + #[serde(default)] + pub capture_keystrokes: bool, } /// Live counters for the recorder dock, emitted at most once per second. @@ -360,6 +435,22 @@ pub struct CursorEventDto { pub y: f32, } +/// A key press. `kind` is `"key"` for a named key or a shortcut, with `key` +/// naming it (`"C"`, `"Enter"`, `"Left"`), or `"text"` for a plain typed +/// character, whose identity is deliberately not recorded so passwords typed +/// while recording never reach the file. Modifiers are those held at the press. +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct KeyEventDto { + pub time: f64, + pub kind: &'static str, + pub key: &'static str, + pub ctrl: bool, + pub shift: bool, + pub alt: bool, + pub meta: bool, +} + /// Cursor positions and clicks sampled alongside the video. /// /// Positions are parallel arrays rather than an array of objects: a ten-minute @@ -377,6 +468,10 @@ pub struct CursorTrackDto { pub ys: Vec, pub events: Vec, pub shapes: Vec, + /// False when keystrokes were not recorded, so an empty `keys` list can + /// be told apart from "recorded, but nothing was pressed". + pub keys_recorded: bool, + pub keys: Vec, /// The recorded area in physical desktop px: the whole display, or the /// crop origin with the video's size for Window and Region recordings. pub display_bounds: Rect, @@ -422,3 +517,90 @@ mod request_tests { assert_eq!(request.system_audio_device_id, None); } } + +/// Whether CapKit opens when the user signs in, and who decides. +/// +/// The policy and user variants come from the MSIX startup task: once a user +/// turns CapKit off in Windows Settings or Task Manager, or a policy pins the +/// state, the app cannot change it and the UI must say so. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum StartupStatus { + Enabled, + Disabled, + DisabledByUser, + DisabledByPolicy, + EnabledByPolicy, +} + +impl StartupStatus { + /// Maps a `Windows.ApplicationModel.StartupTaskState` value. Unknown + /// future values read as disabled rather than failing the settings page. + pub fn from_task_state(state: i32) -> Self { + match state { + 1 => Self::DisabledByUser, + 2 => Self::Enabled, + 3 => Self::DisabledByPolicy, + 4 => Self::EnabledByPolicy, + _ => Self::Disabled, + } + } +} + +/// `package` is the MSIX startup task (Store build); `app` is the per-user +/// sign-in entry CapKit writes itself in the unpackaged installer and dev builds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum StartupManager { + Package, + App, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StartupStateDto { + pub status: StartupStatus, + pub managed_by: StartupManager, +} + +#[cfg(test)] +mod startup_tests { + use super::{StartupManager, StartupStateDto, StartupStatus}; + + #[test] + fn maps_every_documented_task_state() { + assert_eq!(StartupStatus::from_task_state(0), StartupStatus::Disabled); + assert_eq!( + StartupStatus::from_task_state(1), + StartupStatus::DisabledByUser + ); + assert_eq!(StartupStatus::from_task_state(2), StartupStatus::Enabled); + assert_eq!( + StartupStatus::from_task_state(3), + StartupStatus::DisabledByPolicy + ); + assert_eq!( + StartupStatus::from_task_state(4), + StartupStatus::EnabledByPolicy + ); + } + + #[test] + fn unknown_task_state_reads_as_disabled() { + assert_eq!(StartupStatus::from_task_state(99), StartupStatus::Disabled); + assert_eq!(StartupStatus::from_task_state(-1), StartupStatus::Disabled); + } + + #[test] + fn startup_state_serializes_for_the_settings_schema() { + let value = serde_json::to_value(StartupStateDto { + status: StartupStatus::DisabledByUser, + managed_by: StartupManager::Package, + }) + .expect("startup state serializes"); + assert_eq!( + value, + serde_json::json!({ "status": "disabled-by-user", "managedBy": "package" }) + ); + } +} diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index 224cee5..9d848a9 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -20,6 +20,12 @@ pub enum SnaphubError { Shortcut(String), #[error("SH-WINDOW-001: {0}")] Window(String), + #[error("SH-OCR-001: {0}")] + Ocr(String), + #[error("SH-STARTUP-001: {0}")] + Startup(String), + #[error("SH-UPDATE-001: {0}")] + Update(String), } impl SnaphubError { @@ -46,6 +52,10 @@ impl SnaphubError { pub fn audio(error: impl std::fmt::Display) -> Self { Self::Audio(error.to_string()) } + + pub fn startup(error: impl std::fmt::Display) -> Self { + Self::Startup(error.to_string()) + } } impl serde::Serialize for SnaphubError { diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 5dfb48e..76aea8d 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -7,30 +7,39 @@ use std::{ collections::HashMap, path::{Path, PathBuf}, str::FromStr, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, OnceLock}, time::Duration, }; use domain::{ AudioDeviceDto, CaptureSessionDto, CompletionAction, CompletionRequest, CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, MediaFileDto, MediaFolderDto, - OnScreenSessionDto, Point, RecordingArtifactsDto, RecordingRequestDto, RecordingSourceDto, - RecordingStatsDto, Rect, SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, + OnScreenSessionDto, PickColorRequest, PickedColorDto, Point, RecognizedTextDto, + RecordingArtifactsDto, RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, Rect, + SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, StartupStateDto, + TextCopyResult, TextCopyStatus, TextRecognitionRequest, }; use error::SnaphubError; +use platform::StartupBackend; +use platform::plugin_startup::PluginStartup; use platform::xcap_backend::{XcapPlatformBackend, display_bounds}; use services::capture::CaptureService; use services::recording::RecordingService; use services::scrolling::stitch_vertical; +use services::updates::{ + self, AvailableUpdate, UpdateRegistry, UpdateStatusDto, download_percent, install_failure, + install_guard, +}; #[cfg(debug_assertions)] use std::time::Instant; use tauri::{ AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindow, WebviewWindowBuilder, - menu::{Menu, MenuItem}, + menu::{IsMenuItem, Menu, MenuItem}, tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, }; use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState}; +use tauri_plugin_updater::UpdaterExt; #[cfg(target_os = "windows")] use windows::Win32::UI::WindowsAndMessaging::{ AW_BLEND, AnimateWindow, SW_HIDE, SetForegroundWindow, ShowWindow, @@ -39,6 +48,30 @@ use windows::Win32::UI::WindowsAndMessaging::{ // AnimateWindow's cross-fade masks the one or two frames before WebView2's swap chain // has composited fresh content, which otherwise reads as a black flash on reveal. const CAPTURE_REVEAL_MS: u32 = 90; +const CAPTURE_CONCEAL_MS: u32 = 120; + +/// How the capture overlay enters and leaves; chosen in Settings. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "kebab-case")] +enum OverlayMotion { + FadeIn, + DimRise, + FadeBoth, +} + +/// Fades the window out through Win32. It hides the window without telling +/// tao, so callers must still run `hide_capture_window` afterwards. +#[cfg(target_os = "windows")] +fn conceal_window_smoothly(window: &tauri::WebviewWindow) { + use windows::Win32::UI::WindowsAndMessaging::AW_HIDE; + if let Ok(hwnd) = window.hwnd() { + let hwnd = windows::Win32::Foundation::HWND(hwnd.0); + let _ = unsafe { AnimateWindow(hwnd, CAPTURE_CONCEAL_MS, AW_HIDE | AW_BLEND) }; + } +} + +#[cfg(not(target_os = "windows"))] +fn conceal_window_smoothly(_window: &tauri::WebviewWindow) {} #[cfg(target_os = "windows")] fn reveal_window_smoothly(window: &tauri::WebviewWindow) -> Result<(), SnaphubError> { @@ -115,6 +148,12 @@ struct OnScreenActiveState { struct OnScreenModeRegistry(Mutex); +/// A saved capture waiting for the dashboard to open it in Showcase. +/// +/// A slot rather than an event alone: when the dashboard has to be built, its +/// listeners do not exist yet, so it takes the capture once it has loaded. +struct PendingShowcase(Mutex>); + #[tauri::command] async fn begin_capture(app: AppHandle) -> Result { #[cfg(debug_assertions)] @@ -155,13 +194,26 @@ async fn begin_capture(app: AppHandle) -> Result Result<(), SnaphubError> { +fn show_capture_surface( + app: AppHandle, + motion: OverlayMotion, + reduced_motion: bool, +) -> Result<(), SnaphubError> { + // Every motion mode keeps the short blend-in: it masks WebView2's first-frame + // flash. `dim-rise` hides the blend by starting its scrim at opacity 0. + let _ = motion; let window = app .get_webview_window("capture") .ok_or_else(|| SnaphubError::Window("Capture window is unavailable".into()))?; #[cfg(debug_assertions)] let reveal_started = Instant::now(); - reveal_window_smoothly(&window)?; + if reduced_motion { + window + .show() + .map_err(|error| SnaphubError::Window(error.to_string()))?; + } else { + reveal_window_smoothly(&window)?; + } #[cfg(debug_assertions)] eprintln!( "[capture-timing] reveal={}ms", @@ -183,14 +235,79 @@ fn show_capture_surface(app: AppHandle) -> Result<(), SnaphubError> { Ok(()) } +/// True when this process started at sign-in: through the unpackaged sign-in +/// entry, which passes `--background`, or through the MSIX startup task, +/// which cannot pass arguments. Either way the dashboard stays hidden. +fn launched_in_background() -> bool { + static BACKGROUND: OnceLock = OnceLock::new(); + *BACKGROUND.get_or_init(|| { + if std::env::args().any(|argument| argument == "--background") { + return true; + } + #[cfg(target_os = "windows")] + { + platform::windows_startup::launched_by_startup_task() + } + #[cfg(not(target_os = "windows"))] + { + false + } + }) +} + #[tauri::command] -fn dashboard_ready(app: AppHandle) -> Result<(), SnaphubError> { - if std::env::args().any(|argument| argument == "--background") { +fn dashboard_ready( + app: AppHandle, + pending: tauri::State<'_, PendingShowcase>, +) -> Result<(), SnaphubError> { + // A capture sent to Showcase is an explicit request to see the dashboard, + // even in a session that started hidden at sign-in. + let showcase_requested = pending.0.lock().is_ok_and(|slot| slot.is_some()); + if launched_in_background() && !showcase_requested { return Ok(()); } show_dashboard(&app) } +/// Opens a saved capture in the dashboard's Showcase tab. +/// +/// Only files inside the save folder are accepted, the same rule the library +/// uses, so a capture window cannot point the dashboard at arbitrary files. +#[tauri::command] +async fn open_in_showcase(app: AppHandle, path: String) -> Result<(), SnaphubError> { + app.state::() + .validated_saved_capture(Path::new(&path))?; + *app.state::() + .0 + .lock() + .map_err(|_| SnaphubError::Window("Showcase request state is unavailable".into()))? = + Some(path); + let existing = app.get_webview_window("dashboard"); + show_dashboard(&app)?; + if let Some(window) = existing { + let _ = window.emit("capkit://showcase-requested", ()); + } + Ok(()) +} + +/// Hands the pending Showcase capture to the dashboard, at most once. +#[tauri::command] +fn take_pending_showcase( + window: WebviewWindow, + pending: tauri::State<'_, PendingShowcase>, +) -> Result, SnaphubError> { + if window.label() != "dashboard" { + return Err(SnaphubError::Session( + "Only the dashboard can open Showcase captures".into(), + )); + } + Ok(pending + .0 + .lock() + .map_err(|_| SnaphubError::Window("Showcase request state is unavailable".into()))? + .take()) +} + #[tauri::command] fn on_screen_session( registry: tauri::State<'_, OnScreenModeRegistry>, @@ -357,14 +474,79 @@ async fn retry_capture_save( Ok(result) } +#[tauri::command] +fn pick_capture_color( + window: WebviewWindow, + service: tauri::State<'_, CaptureService>, + request: PickColorRequest, +) -> Result { + ensure_capture_window(&window)?; + service.pick_color(&request) +} + +#[tauri::command] +fn text_recognition_supported(service: tauri::State<'_, CaptureService>) -> bool { + service.is_text_recognition_supported() +} + +/// Words with selection-local logical bounds, for redaction suggestions. The +/// capture stays open. +#[tauri::command] +async fn recognize_capture_text( + window: WebviewWindow, + app: AppHandle, + request: TextRecognitionRequest, +) -> Result { + ensure_capture_window(&window)?; + tauri::async_runtime::spawn_blocking(move || { + app.state::().recognize_text(&request) + }) + .await + .map_err(|error| SnaphubError::Ocr(format!("Text recognition worker failed: {error}")))? +} + +/// Copies the selection's text and closes the capture. When no text is found +/// the capture stays open so the user can adjust the selection. +#[tauri::command] +async fn copy_capture_text( + window: WebviewWindow, + app: AppHandle, + request: TextRecognitionRequest, +) -> Result { + ensure_capture_window(&window)?; + let session_id = request.session_id.clone(); + let worker_app = app.clone(); + let mut result = tauri::async_runtime::spawn_blocking(move || { + worker_app.state::().copy_text(&request) + }) + .await + .map_err(|error| SnaphubError::Ocr(format!("Text recognition worker failed: {error}")))??; + if matches!(result.status, TextCopyStatus::Empty) { + return Ok(result); + } + let hide_warning = hide_capture_window_with_recovery(&app); + let finalize_warning = app + .state::() + .finalize_committed(&session_id) + .err() + .map(|error| error.to_string()); + result.cleanup_warning = merge_cleanup_warning(hide_warning, finalize_warning); + Ok(result) +} + // Hide first so Escape feels instant, then wait for cancellation off the main thread. #[tauri::command] async fn cancel_capture( window: WebviewWindow, app: AppHandle, session_id: String, + motion: OverlayMotion, + reduced_motion: bool, ) -> Result<(), SnaphubError> { ensure_capture_window(&window)?; + if motion == OverlayMotion::FadeBoth && !reduced_motion { + conceal_window_smoothly(&window); + } let hide_result = hide_capture_window(&app); let worker_app = app.clone(); let worker_session_id = session_id.clone(); @@ -521,6 +703,57 @@ fn delete_saved_capture( service.delete_saved_capture(Path::new(&path)) } +#[tauri::command] +async fn copy_saved_capture(app: AppHandle, path: String) -> Result<(), SnaphubError> { + tauri::async_runtime::spawn_blocking(move || { + let service = app.state::(); + let validated = service.validated_saved_capture(Path::new(&path))?; + service.copy_image_path(&validated) + }) + .await + .map_err(|error| SnaphubError::Export(error.to_string()))? +} + +/// Starts a native OS file drag for a saved capture. The OLE drag loop is +/// modal on the main thread, so this only validates and schedules it. +#[tauri::command] +fn start_saved_capture_drag( + window: WebviewWindow, + service: tauri::State<'_, CaptureService>, + path: String, +) -> Result<(), SnaphubError> { + let validated = service.validated_saved_capture(Path::new(&path))?; + #[cfg(target_os = "windows")] + { + let preview = service.drag_preview_path(&validated); + let dragged = window.clone(); + window + .run_on_main_thread(move || { + let result = drag::start_drag( + &dragged, + drag::DragItem::Files(vec![validated]), + drag::Image::File(preview), + |_result, _position| {}, + drag::Options { + skip_animatation_on_cancel_or_failure: false, + mode: drag::DragMode::Copy, + }, + ); + if let Err(error) = result { + eprintln!("SH-DRAG-001: {error}"); + } + }) + .map_err(|error| SnaphubError::Window(error.to_string())) + } + #[cfg(not(target_os = "windows"))] + { + let _ = (window, validated); + Err(SnaphubError::Window( + "Dragging captures is not implemented on this platform".into(), + )) + } +} + /// Grants the webview read access to images the user explicitly picked from disk. /// /// The asset protocol scope is otherwise locked to the CapKit save and temp @@ -1681,6 +1914,204 @@ fn open_camera_privacy_settings() -> Result<(), SnaphubError> { } } +/// The package startup task in the Store build; the plugin's sign-in entry +/// otherwise. Never both: Store policy rejects a packaged app's Run entry. +fn startup_backend(app: &AppHandle) -> Box { + #[cfg(target_os = "windows")] + if platform::windows_startup::is_packaged() { + return Box::new(platform::windows_startup::PackagedStartupTask); + } + Box::new(PluginStartup::new(app.clone())) +} + +fn is_packaged_build() -> bool { + #[cfg(target_os = "windows")] + { + platform::windows_startup::is_packaged() + } + #[cfg(not(target_os = "windows"))] + { + false + } +} + +/// The tray's "Install update" entry, kept so its text follows the update state. +struct UpdateTrayItem(Mutex>>); + +/// Records the status where the tray and every window can see it. +fn publish_update_status(app: &AppHandle, status: &UpdateStatusDto) { + if let Some(item) = app + .state::() + .0 + .lock() + .ok() + .and_then(|item| item.clone()) + { + match status { + UpdateStatusDto::Available { version, .. } => { + let _ = item.set_text(format!("Install update v{version}")); + let _ = item.set_enabled(true); + } + _ => { + let _ = item.set_text("Install update"); + let _ = item.set_enabled(false); + } + } + } + let _ = app.emit(updates::STATUS_EVENT, status); +} + +async fn run_update_check(app: &AppHandle, manual: bool) -> UpdateStatusDto { + let registry = app.state::(); + if let Some(current) = registry.begin_check() { + return current; + } + publish_update_status(app, &UpdateStatusDto::Checking); + let current_version = app.package_info().version.to_string(); + let result = match app.updater() { + Ok(updater) => updater.check().await.map_err(|error| error.to_string()), + Err(error) => Err(error.to_string()), + } + .map(|found| { + found.map(|update| { + ( + AvailableUpdate { + version: update.version.clone(), + notes: update.body.clone(), + }, + update, + ) + }) + }); + if let Err(error) = &result { + eprintln!("SH-UPDATE-001: {error}"); + } + let status = registry.finish_check(¤t_version, result, manual); + publish_update_status(app, &status); + status +} + +async fn run_update_install(app: &AppHandle) -> Result { + let registry = app.state::(); + if is_packaged_build() { + return Ok(UpdateStatusDto::Unsupported); + } + if matches!(registry.status(), UpdateStatusDto::Installing { .. }) { + return Ok(registry.status()); + } + let capture_visible = app + .get_webview_window("capture") + .and_then(|window| window.is_visible().ok()) + .unwrap_or(false); + let recording_active = app + .state::() + .stats() + .map(|stats| stats.is_some()) + .unwrap_or(false); + install_guard(false, capture_visible, recording_active)?; + let update = match registry.begin_install() { + Ok(update) => update, + Err(status) => return Ok(status), + }; + let version = update.version.clone(); + publish_update_status( + app, + &UpdateStatusDto::Installing { + version: version.clone(), + percent: 0, + }, + ); + let current_version = app.package_info().version.to_string(); + let mut downloaded = 0_u64; + let mut published = 0_u8; + let result = update + .download_and_install( + |chunk, total| { + downloaded = downloaded.saturating_add(chunk as u64); + let Some(percent) = download_percent(downloaded, total) else { + return; + }; + let step = percent / 5 * 5; + if step > published { + published = step; + let status = UpdateStatusDto::Installing { + version: version.clone(), + percent: step, + }; + registry.set_status(status.clone()); + publish_update_status(app, &status); + } + }, + || {}, + ) + .await; + match result { + Ok(()) => Ok(registry.status()), + Err(error) => { + eprintln!("SH-UPDATE-001: {error}"); + let status = install_failure(¤t_version); + registry.set_status(status.clone()); + publish_update_status(app, &status); + Ok(status) + } + } +} + +#[tauri::command] +async fn auto_check_for_update(app: AppHandle) -> UpdateStatusDto { + let registry = app.state::(); + if is_packaged_build() || !registry.claim_auto_check() { + return registry.status(); + } + run_update_check(&app, false).await +} + +#[tauri::command] +async fn check_for_update(app: AppHandle) -> UpdateStatusDto { + run_update_check(&app, true).await +} + +#[tauri::command] +async fn install_update(app: AppHandle) -> Result { + run_update_install(&app).await +} + +#[tauri::command] +fn update_status(app: AppHandle) -> UpdateStatusDto { + app.state::().status() +} + +#[tauri::command] +async fn get_startup_state(app: AppHandle) -> Result { + tauri::async_runtime::spawn_blocking(move || startup_backend(&app).state()) + .await + .map_err(|error| SnaphubError::startup(format!("Startup worker failed: {error}")))? +} + +#[tauri::command] +async fn set_startup_enabled( + app: AppHandle, + enabled: bool, +) -> Result { + tauri::async_runtime::spawn_blocking(move || startup_backend(&app).set_enabled(enabled)) + .await + .map_err(|error| SnaphubError::startup(format!("Startup worker failed: {error}")))? +} + +#[tauri::command] +fn open_startup_settings() -> Result<(), SnaphubError> { + #[cfg(target_os = "windows")] + { + platform::windows_shell::open_startup_settings() + } + #[cfg(not(target_os = "windows"))] + { + Err(SnaphubError::Startup( + "Startup settings are only available on Windows".into(), + )) + } +} + #[tauri::command] fn close_camera(app: AppHandle) -> Result<(), SnaphubError> { if let Some(window) = app.get_webview_window("camera") { @@ -2167,7 +2598,25 @@ pub fn run() { let shortcuts = RegisteredShortcuts::parse(default_shortcuts()) .expect("CapKit default shortcuts must be valid"); - let app = tauri::Builder::default() + let builder = tauri::Builder::default(); + // Must be the first plugin registered. Release builds only, so a dev run + // can live beside an installed CapKit. + #[cfg(not(debug_assertions))] + let builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, _cwd| { + if args.iter().any(|argument| argument == "--background") { + return; + } + let app = app.clone(); + // Window building from an event handler deadlocks on Windows. + tauri::async_runtime::spawn_blocking(move || { + if let Err(error) = show_dashboard(&app) { + eprintln!("SH-DASHBOARD-002: {error}"); + } + }); + })); + + let app = builder + .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_autostart::init( tauri_plugin_autostart::MacosLauncher::LaunchAgent, @@ -2207,16 +2656,29 @@ pub fn run() { .manage(PinnedCaptureRegistry(Mutex::new(HashMap::new()))) .manage(RecordRegionRegistry(Mutex::new(None))) .manage(OnScreenModeRegistry(Mutex::new(OnScreenModeState::Idle))) + .manage(PendingShowcase(Mutex::new(None))) + .manage(UpdateRegistry::new(is_packaged_build())) + .manage(UpdateTrayItem(Mutex::new(None))) .invoke_handler(tauri::generate_handler![ + auto_check_for_update, + check_for_update, + install_update, + update_status, begin_capture, show_capture_surface, dashboard_ready, + open_in_showcase, + take_pending_showcase, on_screen_session, on_screen_snapshot, on_screen_ready, dismiss_on_screen, save_on_screen_capture, complete_capture, + pick_capture_color, + text_recognition_supported, + recognize_capture_text, + copy_capture_text, retry_capture_save, cancel_capture, dismiss_capture, @@ -2232,6 +2694,8 @@ pub fn run() { open_save_directory, open_saved_capture, delete_saved_capture, + copy_saved_capture, + start_saved_capture_drag, import_media_files, list_folder_images, scrolling_capture_supported, @@ -2272,10 +2736,13 @@ pub fn run() { camera_ready, close_camera, prepare_camera_permission, - open_camera_privacy_settings + open_camera_privacy_settings, + get_startup_state, + set_startup_enabled, + open_startup_settings ]) .setup(move |app| { - if std::env::args().any(|argument| argument == "--background") + if launched_in_background() && let Some(window) = app.get_webview_window("dashboard") { window.hide()?; @@ -2326,16 +2793,33 @@ pub fn run() { None::<&str>, )?; let quit_item = MenuItem::with_id(app, "quit", "Quit CapKit", true, None::<&str>)?; - let menu = Menu::with_items( - app, - &[ - &dashboard_item, - &capture_item, - &on_screen_item, - &restore_pins_item, - &quit_item, - ], - )?; + // No update entry in the Store build: the Store owns updates there. + let install_item = if is_packaged_build() { + None + } else { + let item = MenuItem::with_id( + app, + "install-update", + "Install update", + false, + None::<&str>, + )?; + if let Ok(mut slot) = app.state::().0.lock() { + *slot = Some(item.clone()); + } + Some(item) + }; + let mut entries: Vec<&dyn IsMenuItem> = vec![ + &dashboard_item, + &capture_item, + &on_screen_item, + &restore_pins_item, + ]; + if let Some(item) = &install_item { + entries.push(item); + } + entries.push(&quit_item); + let menu = Menu::with_items(app, &entries)?; let mut tray = TrayIconBuilder::new() .tooltip("CapKit - Capture, record, and showcase") @@ -2359,6 +2843,14 @@ pub fn run() { } } } + "install-update" => { + let app = app.clone(); + tauri::async_runtime::spawn(async move { + if let Err(error) = run_update_install(&app).await { + eprintln!("SH-UPDATE-002: {error}"); + } + }); + } "quit" => app.exit(0), _ => {} }) diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rs index 933db98..ce67d81 100644 --- a/apps/desktop/src-tauri/src/platform/mod.rs +++ b/apps/desktop/src-tauri/src/platform/mod.rs @@ -2,19 +2,25 @@ use image::RgbaImage; use crate::{ domain::{ - AudioDeviceDto, DetectedTargetDto, DisplayDto, Point, RecordingArtifactsDto, - RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, + AudioDeviceDto, DetectedTargetDto, DisplayDto, Point, RecognizedTextDto, + RecordingArtifactsDto, RecordingRequestDto, RecordingSourceDto, RecordingStatsDto, + StartupStateDto, }, error::SnaphubError, }; +pub(crate) mod plugin_startup; #[cfg(target_os = "windows")] pub(crate) mod windows_display; #[cfg(target_os = "windows")] +pub(crate) mod windows_ocr; +#[cfg(target_os = "windows")] pub(crate) mod windows_recorder; #[cfg(target_os = "windows")] pub mod windows_shell; #[cfg(target_os = "windows")] +pub(crate) mod windows_startup; +#[cfg(target_os = "windows")] pub(crate) mod windows_ui; #[cfg(target_os = "windows")] pub(crate) mod windows_webview; @@ -38,6 +44,14 @@ pub trait TargetDetectionBackend: Send + Sync { pub trait ClipboardBackend: Send + Sync { fn copy_image(&self, image: &RgbaImage) -> Result<(), SnaphubError>; + fn copy_text(&self, text: &str) -> Result<(), SnaphubError>; +} + +/// Optical character recognition of captured pixels. +pub trait TextRecognitionBackend: Send + Sync { + fn is_text_recognition_supported(&self) -> bool; + /// Word bounds in the returned value are in pixels of `image`. + fn recognize_text(&self, image: &RgbaImage) -> Result; } pub trait PermissionBackend: Send + Sync { @@ -89,3 +103,16 @@ pub trait AudioDeviceBackend: Send + Sync { pub trait WindowCaptureExclusionBackend: Send + Sync { fn set_excluded(&self, hwnd: isize, excluded: bool) -> Result<(), SnaphubError>; } + +/// Opening CapKit when the user signs in. +/// +/// The Store (MSIX) build must use the manifest startup task: Store policy +/// rejects packaged apps that write their own Run entry. The unpackaged +/// installer has no package identity, so it keeps the per-user Run entry. +pub trait StartupBackend { + fn state(&self) -> Result; + /// Returns the resulting state. It can differ from the request when the + /// user turned CapKit off in Windows or a policy controls it; the caller + /// shows that state instead of treating it as a failure. + fn set_enabled(&self, enabled: bool) -> Result; +} diff --git a/apps/desktop/src-tauri/src/platform/plugin_startup.rs b/apps/desktop/src-tauri/src/platform/plugin_startup.rs new file mode 100644 index 0000000..a993375 --- /dev/null +++ b/apps/desktop/src-tauri/src/platform/plugin_startup.rs @@ -0,0 +1,50 @@ +use tauri::AppHandle; +use tauri_plugin_autostart::ManagerExt; + +use crate::{ + domain::{StartupManager, StartupStateDto, StartupStatus}, + error::SnaphubError, + platform::StartupBackend, +}; + +/// The sign-in entry written by `tauri-plugin-autostart` (the per-user Run +/// key on Windows) for builds without package identity. The entry launches +/// CapKit with `--background`. Never use this in the Store build. +pub(crate) struct PluginStartup { + app: AppHandle, +} + +impl PluginStartup { + pub(crate) fn new(app: AppHandle) -> Self { + Self { app } + } +} + +impl StartupBackend for PluginStartup { + fn state(&self) -> Result { + let enabled = self + .app + .autolaunch() + .is_enabled() + .map_err(SnaphubError::startup)?; + Ok(StartupStateDto { + status: if enabled { + StartupStatus::Enabled + } else { + StartupStatus::Disabled + }, + managed_by: StartupManager::App, + }) + } + + fn set_enabled(&self, enabled: bool) -> Result { + let manager = self.app.autolaunch(); + if enabled { + manager.enable() + } else { + manager.disable() + } + .map_err(SnaphubError::startup)?; + self.state() + } +} diff --git a/apps/desktop/src-tauri/src/platform/windows_ocr.rs b/apps/desktop/src-tauri/src/platform/windows_ocr.rs new file mode 100644 index 0000000..c86f744 --- /dev/null +++ b/apps/desktop/src-tauri/src/platform/windows_ocr.rs @@ -0,0 +1,149 @@ +//! Offline text recognition through `Windows.Media.Ocr`. +//! +//! The engine ships with Windows and uses the OCR packs of the user's display +//! languages, so this adds no model to the app and nothing leaves the machine. + +use image::{RgbaImage, imageops}; +use windows::{ + Graphics::Imaging::{BitmapPixelFormat, SoftwareBitmap}, + Media::Ocr::OcrEngine, + Storage::Streams::DataWriter, + Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}, +}; + +use crate::{ + domain::{RecognizedLineDto, RecognizedTextDto, RecognizedWordDto, Rect}, + error::SnaphubError, +}; + +/// Text below roughly 20 px tall reads poorly; doubling small captures is the +/// accuracy fix Microsoft documents for this engine. +const UPSCALE_BELOW_PIXELS: u32 = 1_600 * 900; + +/// Recognises text in `image`. Word bounds are in `image` pixels. +/// +/// Blocks on the WinRT async call, so run it off the main thread. +pub(crate) fn recognize(image: &RgbaImage) -> Result { + // SAFETY: joins (or creates) this thread's MTA; a repeat call returns S_FALSE. + // RPC_E_CHANGED_MODE on an STA thread is fine too, because WinRT works there. + let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; + + let engine = OcrEngine::TryCreateFromUserProfileLanguages().map_err(|_| { + SnaphubError::Ocr( + "No text recognition language is installed. Add one in Settings > Time & language > Language & region.".into(), + ) + })?; + let language = engine + .RecognizerLanguage() + .and_then(|language| language.LanguageTag()) + .map(|tag| tag.to_string_lossy()) + .unwrap_or_default(); + + let max_dimension = OcrEngine::MaxImageDimension().unwrap_or(10_000).max(1); + let factor = recognition_factor(image.width(), image.height(), max_dimension); + let prepared = if (factor - 1.0).abs() < f64::EPSILON { + image.clone() + } else { + let width = ((f64::from(image.width()) * factor).round() as u32).max(1); + let height = ((f64::from(image.height()) * factor).round() as u32).max(1); + imageops::resize(image, width, height, imageops::FilterType::CatmullRom) + }; + + let bitmap = software_bitmap(&prepared)?; + let result = engine + .RecognizeAsync(&bitmap) + .and_then(|operation| operation.join()) + .map_err(|error| SnaphubError::Ocr(format!("Text recognition failed: {error}")))?; + + let mut lines = Vec::new(); + for line in result.Lines().map_err(ocr_error)? { + let mut words = Vec::new(); + for word in line.Words().map_err(ocr_error)? { + let rect = word.BoundingRect().map_err(ocr_error)?; + words.push(RecognizedWordDto { + text: word.Text().map_err(ocr_error)?.to_string_lossy(), + bounds: Rect { + x: f64::from(rect.X) / factor, + y: f64::from(rect.Y) / factor, + width: f64::from(rect.Width) / factor, + height: f64::from(rect.Height) / factor, + }, + }); + } + lines.push(RecognizedLineDto { + text: line.Text().map_err(ocr_error)?.to_string_lossy(), + words, + }); + } + let text = lines + .iter() + .map(|line| line.text.as_str()) + .collect::>() + .join("\n"); + Ok(RecognizedTextDto { + text, + lines, + language, + }) +} + +/// The scale applied before recognition: 2× for small captures, and down to +/// the engine's limit for oversized ones. Bounds are divided back by it. +fn recognition_factor(width: u32, height: u32, max_dimension: u32) -> f64 { + let longest = f64::from(width.max(height).max(1)); + let limit = f64::from(max_dimension); + if longest > limit { + return limit / longest; + } + if width.saturating_mul(height) < UPSCALE_BELOW_PIXELS && longest * 2.0 <= limit { + return 2.0; + } + 1.0 +} + +fn software_bitmap(image: &RgbaImage) -> Result { + let mut bgra = image.as_raw().clone(); + for pixel in bgra.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + let writer = DataWriter::new().map_err(ocr_error)?; + writer.WriteBytes(&bgra).map_err(ocr_error)?; + let buffer = writer.DetachBuffer().map_err(ocr_error)?; + let width = i32::try_from(image.width()) + .map_err(|_| SnaphubError::Ocr("Selection is too wide to read".into()))?; + let height = i32::try_from(image.height()) + .map_err(|_| SnaphubError::Ocr("Selection is too tall to read".into()))?; + SoftwareBitmap::CreateCopyFromBuffer(&buffer, BitmapPixelFormat::Bgra8, width, height) + .map_err(ocr_error) +} + +fn ocr_error(error: windows::core::Error) -> SnaphubError { + SnaphubError::Ocr(format!("Text recognition failed: {error}")) +} + +#[cfg(test)] +mod tests { + use super::recognition_factor; + + #[test] + fn small_captures_are_doubled_within_the_engine_limit() { + assert_eq!(recognition_factor(400, 120, 10_000), 2.0); + assert_eq!(recognition_factor(6_000, 100, 10_000), 1.0); + } + + #[test] + fn large_captures_are_left_alone_or_shrunk_to_the_limit() { + assert_eq!(recognition_factor(2_560, 1_440, 10_000), 1.0); + assert_eq!(recognition_factor(20_000, 1_000, 10_000), 0.5); + } + + /// Drives the real engine; needs an installed OCR language, so it is opt-in. + #[test] + #[ignore = "needs a Windows OCR language pack"] + fn blank_image_reads_as_empty_text() { + let image = image::RgbaImage::from_pixel(320, 120, image::Rgba([255, 255, 255, 255])); + let recognized = super::recognize(&image).expect("engine should run"); + assert!(recognized.text.trim().is_empty()); + assert!(!recognized.language.is_empty()); + } +} diff --git a/apps/desktop/src-tauri/src/platform/windows_recorder/mod.rs b/apps/desktop/src-tauri/src/platform/windows_recorder/mod.rs index 09e9fe1..788e100 100644 --- a/apps/desktop/src-tauri/src/platform/windows_recorder/mod.rs +++ b/apps/desktop/src-tauri/src/platform/windows_recorder/mod.rs @@ -471,8 +471,13 @@ impl WindowsRecordingSession { // The cursor track is recorded unconditionally: it cannot be // reconstructed later, and the smooth-cursor and zoom-on-click features // are worthless without it. The sampler works in the recorded area's - // coordinates, so crops line up with the video. - let pointer = Some(PointerSampler::start(area, scale)); + // coordinates, so crops line up with the video. Keys are read only when + // the user turned the keystroke overlay on. + let pointer = Some(PointerSampler::start( + area, + scale, + request.capture_keystrokes, + )); let mut audio_failures = Vec::new(); let system_audio = if request.system_audio { @@ -650,6 +655,7 @@ mod tests { microphone: false, microphone_device_id: None, system_audio_device_id: None, + capture_keystrokes: false, }; let (session, _) = backend.start(&request, &directory).expect("start"); @@ -713,6 +719,7 @@ mod tests { microphone: false, microphone_device_id: None, system_audio_device_id: None, + capture_keystrokes: false, }; let (session, _) = backend.start(&request, &directory).expect("start"); diff --git a/apps/desktop/src-tauri/src/platform/windows_recorder/pointer.rs b/apps/desktop/src-tauri/src/platform/windows_recorder/pointer.rs index 4713d1c..9e96de5 100644 --- a/apps/desktop/src-tauri/src/platform/windows_recorder/pointer.rs +++ b/apps/desktop/src-tauri/src/platform/windows_recorder/pointer.rs @@ -12,7 +12,7 @@ use windows::Win32::UI::WindowsAndMessaging::{ IDC_NO, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_WAIT, LoadCursorW, }; -use crate::domain::{CursorEventDto, CursorShapeSpanDto, CursorTrackDto, Rect}; +use crate::domain::{CursorEventDto, CursorShapeSpanDto, CursorTrackDto, KeyEventDto, Rect}; use crate::error::SnaphubError; /// Sampling rate. Fine enough to reconstruct motion and catch any real click, @@ -27,6 +27,153 @@ const BUTTONS: [(i32, &str); 3] = [ (VK_MBUTTON.0 as i32, "middle"), ]; +/// Keys are polled every fourth pointer tick (62.5 Hz). A deliberate key press +/// lasts 50 ms or more, so none is missed, and the ~90 reads per poll stay +/// a fraction of a percent of one core. +const KEY_POLL_EVERY: u64 = 4; + +const VK_SHIFT_CODE: i32 = 0x10; +const VK_CONTROL_CODE: i32 = 0x11; +const VK_MENU_CODE: i32 = 0x12; +const VK_LWIN_CODE: i32 = 0x5B; +const VK_RWIN_CODE: i32 = 0x5C; + +const LETTERS: [&str; 26] = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", + "T", "U", "V", "W", "X", "Y", "Z", +]; +const DIGITS: [&str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; +const FUNCTION_KEYS: [&str; 12] = [ + "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", +]; +const NAMED_KEYS: [(i32, &str); 14] = [ + (0x08, "Backspace"), + (0x09, "Tab"), + (0x0D, "Enter"), + (0x1B, "Esc"), + (0x21, "PageUp"), + (0x22, "PageDown"), + (0x23, "End"), + (0x24, "Home"), + (0x25, "Left"), + (0x26, "Up"), + (0x27, "Right"), + (0x28, "Down"), + (0x2D, "Insert"), + (0x2E, "Delete"), +]; +// TODO(nakul): punctuation names assume a US layout; ToUnicodeEx could name +// them per layout if non-US shortcut labels turn out to matter. +const PUNCTUATION_KEYS: [(i32, &str); 11] = [ + (0xBA, ";"), + (0xBB, "="), + (0xBC, ","), + (0xBD, "-"), + (0xBE, "."), + (0xBF, "/"), + (0xC0, "`"), + (0xDB, "["), + (0xDC, "\\"), + (0xDD, "]"), + (0xDE, "'"), +]; +const NUMPAD_KEYS: [(i32, &str); 15] = [ + (0x60, "0"), + (0x61, "1"), + (0x62, "2"), + (0x63, "3"), + (0x64, "4"), + (0x65, "5"), + (0x66, "6"), + (0x67, "7"), + (0x68, "8"), + (0x69, "9"), + (0x6A, "*"), + (0x6B, "+"), + (0x6D, "-"), + (0x6E, "."), + (0x6F, "/"), +]; + +/// One polled key: virtual-key code, display name, and whether pressing it +/// without a command modifier types a character. +type PolledKey = (i32, &'static str, bool); + +fn polled_keys() -> Vec { + let mut keys = Vec::with_capacity(90); + keys.extend( + LETTERS + .iter() + .zip(0x41..) + .map(|(name, code)| (code, *name, true)), + ); + keys.extend( + DIGITS + .iter() + .zip(0x30..) + .map(|(name, code)| (code, *name, true)), + ); + keys.extend( + FUNCTION_KEYS + .iter() + .zip(0x70..) + .map(|(name, code)| (code, *name, false)), + ); + keys.push((0x20, "Space", true)); + keys.extend(NAMED_KEYS.iter().map(|(code, name)| (*code, *name, false))); + keys.extend( + PUNCTUATION_KEYS + .iter() + .map(|(code, name)| (*code, *name, true)), + ); + keys.extend(NUMPAD_KEYS.iter().map(|(code, name)| (*code, *name, true))); + keys +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct Modifiers { + ctrl: bool, + shift: bool, + alt: bool, + meta: bool, +} + +fn modifiers() -> Modifiers { + Modifiers { + ctrl: button_down(VK_CONTROL_CODE), + shift: button_down(VK_SHIFT_CODE), + alt: button_down(VK_MENU_CODE), + meta: button_down(VK_LWIN_CODE) || button_down(VK_RWIN_CODE), + } +} + +/// Builds the stored event. Typed characters keep no identity and no +/// modifiers; Ctrl+Alt counts as typing because that is how AltGr reports. +fn key_event(time: f64, key: &'static str, types_character: bool, held: Modifiers) -> KeyEventDto { + let alt_gr = held.ctrl && held.alt && !held.meta; + let is_text = types_character && (alt_gr || !(held.ctrl || held.alt || held.meta)); + if is_text { + return KeyEventDto { + time, + kind: "text", + key: "", + ctrl: false, + shift: false, + alt: false, + meta: false, + }; + } + KeyEventDto { + time, + kind: "key", + key, + ctrl: held.ctrl, + shift: held.shift, + alt: held.alt, + meta: held.meta, + } +} + #[derive(Default)] struct Samples { times: Vec, @@ -34,6 +181,7 @@ struct Samples { ys: Vec, events: Vec, shapes: Vec, + keys: Vec, } /// Records where the cursor went and what it clicked, alongside the video. @@ -48,6 +196,7 @@ pub struct PointerSampler { handle: Option>, display_bounds: Rect, scale_factor: f64, + keys_recorded: bool, } /// Resolves the standard cursor handles once so each tick is a pointer compare. @@ -114,8 +263,26 @@ fn button_down(vk: i32) -> bool { (unsafe { GetAsyncKeyState(vk) } as u16 & 0x8000) != 0 } +/// Reads every polled key and returns the ones that went down since the last +/// poll. Modifiers are read only when something was pressed. +fn poll_key_presses(keys: &[PolledKey], held: &mut [bool], time: f64) -> Vec { + let mut pressed = Vec::new(); + let mut held_modifiers = None; + for ((vk, name, types_character), was_down) in keys.iter().zip(held.iter_mut()) { + let down = button_down(*vk); + if down && !*was_down { + let current = *held_modifiers.get_or_insert_with(modifiers); + pressed.push(key_event(time, name, *types_character, current)); + } + *was_down = down; + } + pressed +} + impl PointerSampler { - pub fn start(display_bounds: Rect, scale_factor: f64) -> Self { + /// `capture_keys` is the user's opt-in. When it is off no key state is ever + /// read, so a recording without the overlay carries no keyboard data at all. + pub fn start(display_bounds: Rect, scale_factor: f64, capture_keys: bool) -> Self { let running = Arc::new(AtomicBool::new(true)); let samples = Arc::new(Mutex::new(Samples::default())); @@ -130,9 +297,25 @@ impl PointerSampler { let started = std::time::Instant::now(); let mut pressed = [false; BUTTONS.len()]; let mut last_shape = ""; + let keys = if capture_keys { + polled_keys() + } else { + Vec::new() + }; + let mut keys_held = vec![false; keys.len()]; + let mut tick: u64 = 0; while thread_running.load(Ordering::Relaxed) { let elapsed = started.elapsed().as_secs_f64(); + if capture_keys && tick.is_multiple_of(KEY_POLL_EVERY) { + let pressed_now = poll_key_presses(&keys, &mut keys_held, elapsed); + if !pressed_now.is_empty() + && let Ok(mut buffer) = thread_samples.lock() + { + buffer.keys.extend(pressed_now); + } + } + tick = tick.wrapping_add(1); if let Some(point) = cursor_position() { let x = (f64::from(point.x) - origin_x) as f32; let y = (f64::from(point.y) - origin_y) as f32; @@ -174,6 +357,7 @@ impl PointerSampler { handle: Some(handle), display_bounds, scale_factor, + keys_recorded: capture_keys, } } @@ -195,6 +379,8 @@ impl PointerSampler { ys: samples.ys.clone(), events: samples.events.clone(), shapes: samples.shapes.clone(), + keys_recorded: self.keys_recorded, + keys: samples.keys.clone(), display_bounds: self.display_bounds, scale_factor: self.scale_factor, }) @@ -209,3 +395,96 @@ impl Drop for PointerSampler { } } } + +#[cfg(test)] +mod tests { + use super::*; + + const NONE: Modifiers = Modifiers { + ctrl: false, + shift: false, + alt: false, + meta: false, + }; + + #[test] + fn typed_characters_keep_no_identity() { + let event = key_event( + 1.5, + "Q", + true, + Modifiers { + shift: true, + ..NONE + }, + ); + assert_eq!(event.kind, "text"); + assert_eq!(event.key, ""); + assert!(!event.shift); + assert!((event.time - 1.5).abs() < f64::EPSILON); + } + + #[test] + fn shortcuts_keep_their_name_and_modifiers() { + let event = key_event( + 0.0, + "S", + true, + Modifiers { + ctrl: true, + shift: true, + ..NONE + }, + ); + assert_eq!(event.kind, "key"); + assert_eq!(event.key, "S"); + assert!(event.ctrl && event.shift && !event.alt && !event.meta); + + let windows_shortcut = key_event(0.0, "D", true, Modifiers { meta: true, ..NONE }); + assert_eq!(windows_shortcut.kind, "key"); + } + + #[test] + fn alt_gr_counts_as_typing() { + let event = key_event( + 0.0, + "Q", + true, + Modifiers { + ctrl: true, + alt: true, + ..NONE + }, + ); + assert_eq!(event.kind, "text"); + } + + #[test] + fn named_keys_are_always_shown() { + let enter = key_event(0.0, "Enter", false, NONE); + assert_eq!((enter.kind, enter.key), ("key", "Enter")); + } + + #[test] + fn polled_keys_have_unique_codes_and_names() { + let keys = polled_keys(); + let mut codes: Vec = keys.iter().map(|(code, _, _)| *code).collect(); + codes.sort_unstable(); + codes.dedup(); + assert_eq!(codes.len(), keys.len()); + assert!(keys.iter().all(|(_, name, _)| !name.is_empty())); + assert!(keys.contains(&(0x41, "A", true))); + assert!(keys.contains(&(0x39, "9", true))); + assert!(keys.contains(&(0x7B, "F12", false))); + assert!(!keys.iter().any(|(code, _, _)| { + [ + VK_SHIFT_CODE, + VK_CONTROL_CODE, + VK_MENU_CODE, + VK_LWIN_CODE, + VK_RWIN_CODE, + ] + .contains(code) + })); + } +} diff --git a/apps/desktop/src-tauri/src/platform/windows_shell.rs b/apps/desktop/src-tauri/src/platform/windows_shell.rs index 3ccafc4..40b0f57 100644 --- a/apps/desktop/src-tauri/src/platform/windows_shell.rs +++ b/apps/desktop/src-tauri/src/platform/windows_shell.rs @@ -16,6 +16,12 @@ pub fn open_camera_privacy_settings() -> Result<(), SnaphubError> { open_uri("ms-settings:privacy-webcam") } +/// Opens Settings > Apps > Startup, the only place a user can turn the +/// startup task back on after turning it off there or in Task Manager. +pub fn open_startup_settings() -> Result<(), SnaphubError> { + open_uri("ms-settings:startupapps") +} + fn open_uri(uri: &str) -> Result<(), SnaphubError> { let verb = wide(OsStr::new("open")); let target = wide(OsStr::new(uri)); diff --git a/apps/desktop/src-tauri/src/platform/windows_startup.rs b/apps/desktop/src-tauri/src/platform/windows_startup.rs new file mode 100644 index 0000000..cb3602f --- /dev/null +++ b/apps/desktop/src-tauri/src/platform/windows_startup.rs @@ -0,0 +1,92 @@ +use std::sync::OnceLock; + +use windows::{ + ApplicationModel::{ + Activation::ActivationKind, AppInstance, Package, StartupTask, StartupTaskState, + }, + core::HSTRING, +}; + +use crate::{ + domain::{StartupManager, StartupStateDto, StartupStatus}, + error::SnaphubError, + platform::StartupBackend, +}; + +/// Must match the `desktop:StartupTask` `TaskId` in `msix/AppxManifest.xml`. +const STARTUP_TASK_ID: &str = "CapKitStartup"; + +/// True when this process runs from an installed MSIX package. Package +/// identity cannot change during a process, so the lookup runs once. +pub(crate) fn is_packaged() -> bool { + static PACKAGED: OnceLock = OnceLock::new(); + *PACKAGED.get_or_init(|| Package::Current().is_ok()) +} + +/// True when Windows started this process through the startup task. That +/// activation cannot carry arguments, so this is the packaged equivalent of +/// the `--background` flag the unpackaged sign-in entry passes. +pub(crate) fn launched_by_startup_task() -> bool { + is_packaged() + && AppInstance::GetActivatedEventArgs() + .and_then(|arguments| arguments.Kind()) + .is_ok_and(|kind| kind == ActivationKind::StartupTask) +} + +/// The manifest startup task of the Store build. +/// +/// Calls block on WinRT async operations, so run them off the main thread. +pub(crate) struct PackagedStartupTask; + +impl PackagedStartupTask { + fn task() -> Result { + StartupTask::GetAsync(&HSTRING::from(STARTUP_TASK_ID)) + .and_then(|operation| operation.join()) + .map_err(|error| { + SnaphubError::startup(format!( + "Startup task {STARTUP_TASK_ID} is unavailable: {error}" + )) + }) + } +} + +fn package_state(state: StartupTaskState) -> StartupStateDto { + StartupStateDto { + status: StartupStatus::from_task_state(state.0), + managed_by: StartupManager::Package, + } +} + +impl StartupBackend for PackagedStartupTask { + fn state(&self) -> Result { + Self::task()? + .State() + .map(package_state) + .map_err(SnaphubError::startup) + } + + fn set_enabled(&self, enabled: bool) -> Result { + let task = Self::task()?; + let current = task.State().map_err(SnaphubError::startup)?; + // Windows ignores both calls once the user turned CapKit off in + // Settings or Task Manager, or a policy owns the state. + if !matches!( + StartupStatus::from_task_state(current.0), + StartupStatus::Enabled | StartupStatus::Disabled + ) { + return Ok(package_state(current)); + } + if enabled { + // Desktop apps get no consent dialog here; the result is final. + task.RequestEnableAsync() + .and_then(|operation| operation.join()) + .map(package_state) + .map_err(SnaphubError::startup) + } else { + task.Disable().map_err(SnaphubError::startup)?; + task.State() + .map(package_state) + .map_err(SnaphubError::startup) + } + } +} diff --git a/apps/desktop/src-tauri/src/platform/xcap_backend.rs b/apps/desktop/src-tauri/src/platform/xcap_backend.rs index 0237e70..701c787 100644 --- a/apps/desktop/src-tauri/src/platform/xcap_backend.rs +++ b/apps/desktop/src-tauri/src/platform/xcap_backend.rs @@ -4,11 +4,11 @@ use arboard::{Clipboard, ImageData}; use xcap::{Monitor, Window}; use crate::{ - domain::{DetectedTargetDto, DisplayDto, Point, Rect}, + domain::{DetectedTargetDto, DisplayDto, Point, RecognizedTextDto, Rect}, error::SnaphubError, platform::{ CaptureBackend, CapturedDisplay, ClipboardBackend, PermissionBackend, PinnedWindowBackend, - ScrollingCaptureBackend, TargetDetectionBackend, + ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, }, }; @@ -216,6 +216,33 @@ impl ClipboardBackend for XcapPlatformBackend { }) .map_err(SnaphubError::clipboard) } + + fn copy_text(&self, text: &str) -> Result<(), SnaphubError> { + let mut clipboard = Clipboard::new().map_err(SnaphubError::clipboard)?; + clipboard + .set_text(text.to_owned()) + .map_err(SnaphubError::clipboard) + } +} + +impl TextRecognitionBackend for XcapPlatformBackend { + fn is_text_recognition_supported(&self) -> bool { + cfg!(target_os = "windows") + } + + fn recognize_text(&self, image: &image::RgbaImage) -> Result { + #[cfg(target_os = "windows")] + { + crate::platform::windows_ocr::recognize(image) + } + #[cfg(not(target_os = "windows"))] + { + let _ = image; + Err(SnaphubError::Ocr( + "Text recognition is not available on this platform yet".into(), + )) + } + } } impl PermissionBackend for XcapPlatformBackend { diff --git a/apps/desktop/src-tauri/src/services/capture.rs b/apps/desktop/src-tauri/src/services/capture.rs index ced078f..924eaf7 100644 --- a/apps/desktop/src-tauri/src/services/capture.rs +++ b/apps/desktop/src-tauri/src/services/capture.rs @@ -29,17 +29,20 @@ use uuid::Uuid; use crate::{ domain::{ - Annotation, AnnotationScene, CaptureSessionDto, CompletionAction, CompletionRequest, - CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, Point, Rect, - SavedCaptureDto, ScrollingCaptureRequest, ScrollingCaptureResult, + Annotation, AnnotationScene, CaptureSessionDto, ColorFormat, CompletionAction, + CompletionRequest, CompletionResult, CompletionStatus, DetectedTargetDto, DisplayDto, + PickColorRequest, PickedColorDto, Point, RecognizedTextDto, Rect, SavedCaptureDto, + ScrollingCaptureRequest, ScrollingCaptureResult, TextCopyResult, TextCopyStatus, + TextRecognitionRequest, }, error::SnaphubError, platform::{ CaptureBackend, ClipboardBackend, PermissionBackend, PinnedWindowBackend, - ScrollingCaptureBackend, TargetDetectionBackend, + ScrollingCaptureBackend, TargetDetectionBackend, TextRecognitionBackend, }, }; +use super::paths::display_path; use super::scrolling::{frames_are_unchanged, stitch_vertical_with_metadata}; enum SessionOutputState { @@ -90,6 +93,7 @@ pub struct CaptureService { permissions: Arc, scrolling: Arc, pinning: Arc, + text_recognition: Arc, sessions: Mutex>, manual_scrolling: Mutex>, save_directory: Mutex, @@ -109,6 +113,7 @@ impl CaptureService { + PermissionBackend + ScrollingCaptureBackend + PinnedWindowBackend + + TextRecognitionBackend + 'static, { Self::with_save_directory(backend, load_save_directory()) @@ -122,6 +127,7 @@ impl CaptureService { + PermissionBackend + ScrollingCaptureBackend + PinnedWindowBackend + + TextRecognitionBackend + 'static, { let _ = fs::create_dir_all(&save_directory); @@ -131,6 +137,7 @@ impl CaptureService { targets: backend.clone(), permissions: backend.clone(), scrolling: backend.clone(), + text_recognition: backend.clone(), pinning: backend, sessions: Mutex::new(HashMap::new()), manual_scrolling: Mutex::new(HashMap::new()), @@ -635,6 +642,77 @@ impl CaptureService { self.clipboard.copy_image(&image) } + /// Copies the frozen snapshot's colour at a display-local logical point. + /// Reads the captured physical pixel, so the value matches the screen rather than the scaled preview. + pub fn pick_color(&self, request: &PickColorRequest) -> Result { + let id = parse_session_id(&request.session_id)?; + let pixel = { + let sessions = self + .sessions + .lock() + .map_err(|_| SnaphubError::Session("Capture state is unavailable".into()))?; + let asset = sessions + .get(&id) + .ok_or_else(|| SnaphubError::Session("Capture session has expired".into()))?; + pixel_at(&asset.image, request.point, asset.scale_factor)? + }; + let picked = format_color(pixel, request.format); + self.clipboard.copy_text(&picked.copied)?; + Ok(picked) + } + + pub fn is_text_recognition_supported(&self) -> bool { + self.text_recognition.is_text_recognition_supported() + } + + /// Reads text in the raw selection. Annotations are excluded so arrows and + /// labels drawn on top don't turn into stray characters. + pub fn recognize_text( + &self, + request: &TextRecognitionRequest, + ) -> Result { + let id = parse_session_id(&request.session_id)?; + validate_selection(request.selection)?; + let (crop, scale) = { + let sessions = self + .sessions + .lock() + .map_err(|_| SnaphubError::Session("Capture state is unavailable".into()))?; + let asset = sessions + .get(&id) + .ok_or_else(|| SnaphubError::Session("Capture session has expired".into()))?; + ( + crop_selection(&asset.image, request.selection, asset.scale_factor)?, + asset.scale_factor, + ) + }; + let recognized = self.text_recognition.recognize_text(&crop)?; + Ok(text_to_logical(recognized, scale)) + } + + /// Copies the selection's text. An empty result copies nothing, so the + /// caller can keep the capture open and say so. + pub fn copy_text( + &self, + request: &TextRecognitionRequest, + ) -> Result { + let recognized = self.recognize_text(request)?; + let text = recognized.text.trim(); + if text.is_empty() { + return Ok(TextCopyResult { + status: TextCopyStatus::Empty, + text: String::new(), + cleanup_warning: None, + }); + } + self.clipboard.copy_text(text)?; + Ok(TextCopyResult { + status: TextCopyStatus::Copied, + text: text.to_owned(), + cleanup_warning: None, + }) + } + pub fn save_image_path(&self, path: &Path) -> Result { let image = image::open(path) .map_err(SnaphubError::export)? @@ -656,7 +734,7 @@ impl CaptureService { )); } fs::create_dir_all(&directory).map_err(SnaphubError::export)?; - let directory = directory.canonicalize().map_err(SnaphubError::export)?; + let directory = display_path(&directory.canonicalize().map_err(SnaphubError::export)?); persist_save_directory(&directory)?; *self .save_directory @@ -696,10 +774,7 @@ impl CaptureService { .into_iter() .filter_map(|(path, size_bytes, modified)| { let (width, height) = image::image_dimensions(&path).ok()?; - let mut hasher = DefaultHasher::new(); - path.hash(&mut hasher); - modified.hash(&mut hasher); - let thumbnail_path = thumbnails.join(format!("{:016x}.png", hasher.finish())); + let thumbnail_path = thumbnail_path_for(&thumbnails, &path, modified); if !thumbnail_path.exists() { let image = image::open(&path).ok()?; image @@ -721,6 +796,17 @@ impl CaptureService { .collect::>()) } + /// The drag image for a saved capture: its library thumbnail, or the image itself when none exists yet. + pub fn drag_preview_path(&self, path: &Path) -> PathBuf { + let thumbnails = session_directory().join("library-thumbnails"); + fs::metadata(path) + .and_then(|metadata| metadata.modified()) + .map(|modified| thumbnail_path_for(&thumbnails, path, modified)) + .ok() + .filter(|thumbnail| thumbnail.exists()) + .unwrap_or_else(|| path.to_path_buf()) + } + pub fn validated_saved_capture(&self, path: &Path) -> Result { let directory = self .save_directory()? @@ -877,6 +963,31 @@ fn target_area(target: &DetectedTargetDto) -> f64 { target.bounds.width * target.bounds.height } +fn pixel_at(image: &RgbaImage, point: Point, scale: f64) -> Result, SnaphubError> { + if !point.x.is_finite() || !point.y.is_finite() || point.x < 0.0 || point.y < 0.0 { + return Err(SnaphubError::Session("Colour point is invalid".into())); + } + let x = (point.x * scale).floor(); + let y = (point.y * scale).floor(); + if x >= f64::from(image.width()) || y >= f64::from(image.height()) { + return Err(SnaphubError::Session( + "Colour point falls outside the captured display".into(), + )); + } + // Bounds-checked above, so the truncating casts stay inside the image. + Ok(*image.get_pixel(x as u32, y as u32)) +} + +fn format_color(pixel: Rgba, format: ColorFormat) -> PickedColorDto { + let [red, green, blue, _] = pixel.0; + let hex = format!("#{red:02X}{green:02X}{blue:02X}"); + let copied = match format { + ColorFormat::Hex => hex.clone(), + ColorFormat::Rgb => format!("rgb({red}, {green}, {blue})"), + }; + PickedColorDto { hex, copied } +} + fn parse_session_id(session_id: &str) -> Result { Uuid::parse_str(session_id).map_err(|_| SnaphubError::Session("Invalid capture session".into())) } @@ -888,7 +999,10 @@ fn validate_completion_request(request: &CompletionRequest) -> Result<(), Snaphu request.scene.version ))); } - let selection = request.selection; + validate_selection(request.selection) +} + +fn validate_selection(selection: Rect) -> Result<(), SnaphubError> { if !selection.x.is_finite() || !selection.y.is_finite() || !selection.width.is_finite() @@ -905,11 +1019,10 @@ fn validate_completion_request(request: &CompletionRequest) -> Result<(), Snaphu Ok(()) } -fn render_output( +fn crop_selection( source: &RgbaImage, selection: Rect, scale: f64, - scene: &AnnotationScene, ) -> Result { let x = non_negative_u32(selection.x * scale); let y = non_negative_u32(selection.y * scale); @@ -920,7 +1033,34 @@ fn render_output( "Selection falls outside the captured display".into(), )); } - let mut output = imageops::crop_imm(source, x, y, width, height).to_image(); + Ok(imageops::crop_imm(source, x, y, width, height).to_image()) +} + +/// Converts recogniser word bounds from captured pixels to selection-local logical coordinates. +fn text_to_logical(mut recognized: RecognizedTextDto, scale: f64) -> RecognizedTextDto { + let scale = if scale > 0.0 { scale } else { 1.0 }; + for word in recognized + .lines + .iter_mut() + .flat_map(|line| line.words.iter_mut()) + { + word.bounds = Rect { + x: word.bounds.x / scale, + y: word.bounds.y / scale, + width: word.bounds.width / scale, + height: word.bounds.height / scale, + }; + } + recognized +} + +fn render_output( + source: &RgbaImage, + selection: Rect, + scale: f64, + scene: &AnnotationScene, +) -> Result { + let mut output = crop_selection(source, selection, scale)?; for annotation in &scene.elements { render_annotation(&mut output, annotation, scale); } @@ -1259,7 +1399,11 @@ fn load_save_directory() -> PathBuf { } let _ = persist_save_directory(&directory); } - return directory; + let clean = display_path(&directory); + if clean != directory { + let _ = persist_save_directory(&clean); + } + return clean; } default_save_directory() } @@ -1318,10 +1462,17 @@ fn write_storage_preferences_to( /// The user's recordings folder, or the Videos default when none was chosen. pub(crate) fn load_recording_directory() -> PathBuf { - read_storage_preferences() + let Some(directory) = read_storage_preferences() .recording_directory .filter(|directory| directory.is_absolute()) - .unwrap_or_else(default_recording_directory) + else { + return default_recording_directory(); + }; + let clean = display_path(&directory); + if clean != directory { + let _ = persist_recording_directory(&clean); + } + clean } pub(crate) fn default_recording_directory() -> PathBuf { @@ -1336,6 +1487,14 @@ pub(crate) fn persist_recording_directory(directory: &Path) -> Result<(), Snaphu }) } +/// Where the library thumbnail for `path` lives; keyed by path and modified time. +fn thumbnail_path_for(thumbnails: &Path, path: &Path, modified: std::time::SystemTime) -> PathBuf { + let mut hasher = DefaultHasher::new(); + path.hash(&mut hasher); + modified.hash(&mut hasher); + thumbnails.join(format!("{:016x}.png", hasher.finish())) +} + #[cfg(test)] mod storage_preferences_tests { use super::*; @@ -1493,6 +1652,7 @@ mod tests { }; use super::*; + use crate::domain::{RecognizedLineDto, RecognizedWordDto}; use crate::platform::CapturedDisplay; struct TestDirectory(PathBuf); @@ -1514,6 +1674,9 @@ mod tests { struct FakeBackend { source: RgbaImage, copied: Mutex>, + copied_text: Mutex>, + recognized_text: Mutex, + recognized_size: Mutex>, clipboard_calls: AtomicUsize, fail_clipboard: AtomicBool, clipboard_entered: Mutex>>, @@ -1525,6 +1688,9 @@ mod tests { Self { source: RgbaImage::from_pixel(20, 20, Rgba([240, 241, 237, 255])), copied: Mutex::new(None), + copied_text: Mutex::new(None), + recognized_text: Mutex::new(String::new()), + recognized_size: Mutex::new(None), clipboard_calls: AtomicUsize::new(0), fail_clipboard: AtomicBool::new(false), clipboard_entered: Mutex::new(None), @@ -1574,6 +1740,14 @@ mod tests { *self.copied.lock().unwrap() = Some(image.clone()); Ok(()) } + + fn copy_text(&self, text: &str) -> Result<(), SnaphubError> { + if self.fail_clipboard.load(Ordering::SeqCst) { + return Err(SnaphubError::Clipboard("Fake clipboard failure".into())); + } + *self.copied_text.lock().unwrap() = Some(text.to_owned()); + Ok(()) + } } impl TargetDetectionBackend for FakeBackend { @@ -1590,6 +1764,38 @@ mod tests { } } + impl TextRecognitionBackend for FakeBackend { + fn is_text_recognition_supported(&self) -> bool { + true + } + + fn recognize_text(&self, image: &RgbaImage) -> Result { + *self.recognized_size.lock().unwrap() = Some((image.width(), image.height())); + let text = self.recognized_text.lock().unwrap().clone(); + let lines = if text.trim().is_empty() { + Vec::new() + } else { + vec![RecognizedLineDto { + text: text.clone(), + words: vec![RecognizedWordDto { + text: text.clone(), + bounds: Rect { + x: 2.0, + y: 4.0, + width: 6.0, + height: 8.0, + }, + }], + }] + }; + Ok(RecognizedTextDto { + text, + lines, + language: "en-US".into(), + }) + } + } + impl PermissionBackend for FakeBackend { fn can_capture(&self) -> Result { Ok(true) @@ -1738,6 +1944,180 @@ mod tests { assert!(result.is_err()); } + #[test] + fn pick_color_reads_the_physical_pixel_and_copies_text() { + let directory = TestDirectory::new("pick-color"); + let mut fake = FakeBackend::new(); + fake.source.put_pixel(7, 9, Rgba([18, 171, 255, 255])); + let backend = Arc::new(fake); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + let picked = service + .pick_color(&PickColorRequest { + session_id: session_id.clone(), + point: Point { x: 3.6, y: 4.9 }, + format: ColorFormat::Rgb, + }) + .expect("colour should be picked"); + assert_eq!(picked.hex, "#12ABFF"); + assert_eq!(picked.copied, "rgb(18, 171, 255)"); + assert_eq!( + backend.copied_text.lock().unwrap().as_deref(), + Some("rgb(18, 171, 255)") + ); + let hex = service + .pick_color(&PickColorRequest { + session_id, + point: Point { x: 0.0, y: 0.0 }, + format: ColorFormat::Hex, + }) + .expect("colour should be picked"); + assert_eq!(hex.copied, "#F0F1ED"); + } + + #[test] + fn pick_color_rejects_points_outside_the_snapshot() { + let directory = TestDirectory::new("pick-color-bounds"); + let backend = Arc::new(FakeBackend::new()); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + for point in [ + Point { x: 10.0, y: 2.0 }, + Point { x: -0.5, y: 2.0 }, + Point { + x: f64::NAN, + y: 2.0, + }, + ] { + assert!( + service + .pick_color(&PickColorRequest { + session_id: session_id.clone(), + point, + format: ColorFormat::Hex, + }) + .is_err() + ); + } + assert!(backend.copied_text.lock().unwrap().is_none()); + } + + fn text_request(session_id: &str) -> TextRecognitionRequest { + TextRecognitionRequest { + session_id: session_id.into(), + selection: Rect { + x: 1.0, + y: 2.0, + width: 6.0, + height: 4.0, + }, + } + } + + #[test] + fn saved_capture_actions_reject_files_outside_the_save_folder() { + let directory = TestDirectory::new("saved-validation"); + let outside = TestDirectory::new("saved-validation-outside"); + let backend = Arc::new(FakeBackend::new()); + let service = CaptureService::with_save_directory(backend, directory.0.clone()); + let inside_file = directory.0.join("inside.png"); + let outside_file = outside.0.join("outside.png"); + RgbaImage::new(2, 2).save(&inside_file).unwrap(); + RgbaImage::new(2, 2).save(&outside_file).unwrap(); + assert!(service.validated_saved_capture(&inside_file).is_ok()); + assert!(service.validated_saved_capture(&outside_file).is_err()); + } + + #[test] + fn thumbnail_path_depends_on_path_and_modified_time() { + let folder = Path::new("thumbs"); + let now = std::time::SystemTime::now(); + let later = now + std::time::Duration::from_secs(1); + let first = thumbnail_path_for(folder, Path::new("a.png"), now); + assert_eq!(first, thumbnail_path_for(folder, Path::new("a.png"), now)); + assert_ne!(first, thumbnail_path_for(folder, Path::new("a.png"), later)); + assert_ne!(first, thumbnail_path_for(folder, Path::new("b.png"), now)); + } + + #[test] + fn recognize_text_crops_physical_pixels_and_returns_logical_bounds() { + let directory = TestDirectory::new("ocr-bounds"); + let backend = Arc::new(FakeBackend::new()); + *backend.recognized_text.lock().unwrap() = "Invoice 42".into(); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + let recognized = service + .recognize_text(&text_request(&session_id)) + .expect("text should be recognised"); + assert_eq!(*backend.recognized_size.lock().unwrap(), Some((12, 8))); + let bounds = recognized.lines[0].words[0].bounds; + assert_eq!( + (bounds.x, bounds.y, bounds.width, bounds.height), + (1.0, 2.0, 3.0, 4.0) + ); + assert_eq!(recognized.language, "en-US"); + } + + #[test] + fn copy_text_copies_trimmed_text() { + let directory = TestDirectory::new("ocr-copy"); + let backend = Arc::new(FakeBackend::new()); + *backend.recognized_text.lock().unwrap() = " Invoice 42\n".into(); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + let result = service + .copy_text(&text_request(&session_id)) + .expect("text should be copied"); + assert!(matches!(result.status, TextCopyStatus::Copied)); + assert_eq!(result.text, "Invoice 42"); + assert_eq!( + backend.copied_text.lock().unwrap().as_deref(), + Some("Invoice 42") + ); + } + + #[test] + fn copy_text_reports_empty_without_touching_the_clipboard() { + let directory = TestDirectory::new("ocr-empty"); + let backend = Arc::new(FakeBackend::new()); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + let result = service + .copy_text(&text_request(&session_id)) + .expect("empty text is not an error"); + assert!(matches!(result.status, TextCopyStatus::Empty)); + assert!(backend.copied_text.lock().unwrap().is_none()); + } + + #[test] + fn recognize_text_rejects_invalid_or_outside_selections() { + let directory = TestDirectory::new("ocr-invalid"); + let backend = Arc::new(FakeBackend::new()); + let service = CaptureService::with_save_directory(backend.clone(), directory.0.clone()); + let session_id = begin_session(&service); + for selection in [ + Rect { + x: 8.0, + y: 0.0, + width: 5.0, + height: 5.0, + }, + Rect { + x: 0.0, + y: 0.0, + width: 0.0, + height: 5.0, + }, + ] { + let request = TextRecognitionRequest { + session_id: session_id.clone(), + selection, + }; + assert!(service.recognize_text(&request).is_err()); + } + assert!(backend.recognized_size.lock().unwrap().is_none()); + } + #[test] fn copy_and_save_renders_once_and_saves_clipboard_pixels() { let directory = TestDirectory::new("copy-save"); diff --git a/apps/desktop/src-tauri/src/services/mod.rs b/apps/desktop/src-tauri/src/services/mod.rs index 28e6a99..16ce1d9 100644 --- a/apps/desktop/src-tauri/src/services/mod.rs +++ b/apps/desktop/src-tauri/src/services/mod.rs @@ -1,4 +1,6 @@ pub mod capture; pub mod media; +pub mod paths; pub mod recording; pub mod scrolling; +pub mod updates; diff --git a/apps/desktop/src-tauri/src/services/paths.rs b/apps/desktop/src-tauri/src/services/paths.rs new file mode 100644 index 0000000..7308d2d --- /dev/null +++ b/apps/desktop/src-tauri/src/services/paths.rs @@ -0,0 +1,52 @@ +//! Path display helpers. + +use std::path::{Path, PathBuf}; + +/// Strips the Windows verbatim prefix (`\\?\C:\…`, `\\?\UNC\…`) that +/// `std::fs::canonicalize` adds, so stored and displayed folders read +/// normally. Paths that cannot be represented without the prefix (reserved +/// names, very long paths) are returned unchanged. +pub fn display_path(path: &Path) -> PathBuf { + // dunce leaves `\\?\UNC\server\share` alone; the `\\server\share` form is + // equivalent for any path that was canonicalized. + if let Some(rest) = path + .to_str() + .and_then(|text| text.strip_prefix(r"\\?\UNC\")) + { + return PathBuf::from(format!(r"\\{rest}")); + } + dunce::simplified(path).to_path_buf() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_paths_are_unchanged() { + let path = Path::new("relative").join("shots"); + assert_eq!(display_path(&path), path); + } + + #[cfg(windows)] + #[test] + fn strips_the_drive_prefix() { + assert_eq!(display_path(Path::new(r"\\?\C:\a")), PathBuf::from(r"C:\a")); + } + + #[cfg(windows)] + #[test] + fn strips_the_unc_prefix() { + assert_eq!( + display_path(Path::new(r"\\?\UNC\server\share\x")), + PathBuf::from(r"\\server\share\x") + ); + } + + #[cfg(windows)] + #[test] + fn keeps_the_prefix_when_the_path_cannot_be_simplified() { + let reserved = Path::new(r"\\?\C:\a\CON"); + assert_eq!(display_path(reserved), reserved); + } +} diff --git a/apps/desktop/src-tauri/src/services/recording.rs b/apps/desktop/src-tauri/src/services/recording.rs index 73832c1..42cef76 100644 --- a/apps/desktop/src-tauri/src/services/recording.rs +++ b/apps/desktop/src-tauri/src/services/recording.rs @@ -14,6 +14,7 @@ use crate::platform::{ use crate::services::capture::{ default_recording_directory, load_recording_directory, persist_recording_directory, }; +use crate::services::paths::display_path; /// Owns the one recording that can be in flight at a time. /// @@ -209,9 +210,11 @@ impl RecordingService { } std::fs::create_dir_all(&directory) .map_err(|error| SnaphubError::Record(error.to_string()))?; - let directory = directory - .canonicalize() - .map_err(|error| SnaphubError::Record(error.to_string()))?; + let directory = display_path( + &directory + .canonicalize() + .map_err(|error| SnaphubError::Record(error.to_string()))?, + ); persist_recording_directory(&directory)?; *self .root diff --git a/apps/desktop/src-tauri/src/services/updates.rs b/apps/desktop/src-tauri/src/services/updates.rs new file mode 100644 index 0000000..101bafc --- /dev/null +++ b/apps/desktop/src-tauri/src/services/updates.rs @@ -0,0 +1,325 @@ +//! In-app update state. Checks only run on request (dashboard start or a button +//! click); nothing here polls or sleeps. + +use std::sync::{ + Mutex, + atomic::{AtomicBool, Ordering}, +}; + +use serde::Serialize; +use tauri_plugin_updater::Update; + +use crate::error::SnaphubError; + +/// Event every window listens to for update state changes. +pub const STATUS_EVENT: &str = "capkit://update-status"; + +/// Shown when an install is requested while the user is mid-capture. +pub const GUARD_MESSAGE: &str = "Finish your capture or recording first."; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde( + tag = "state", + rename_all = "kebab-case", + rename_all_fields = "camelCase" +)] +pub enum UpdateStatusDto { + Unsupported, + Idle, + Checking, + UpToDate { + current_version: String, + }, + Available { + current_version: String, + version: String, + notes: Option, + }, + Installing { + version: String, + percent: u8, + }, + Error { + current_version: String, + message: String, + }, +} + +/// A newer release reported by the update endpoint. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AvailableUpdate { + pub version: String, + pub notes: Option, +} + +pub struct UpdateSlot { + pub status: UpdateStatusDto, + pub pending: Option, +} + +pub struct UpdateRegistry { + pub state: Mutex, + pub auto_checked: AtomicBool, +} + +impl UpdateRegistry { + pub fn new(packaged: bool) -> Self { + Self { + state: Mutex::new(UpdateSlot { + status: if packaged { + UpdateStatusDto::Unsupported + } else { + UpdateStatusDto::Idle + }, + pending: None, + }), + auto_checked: AtomicBool::new(false), + } + } + + pub fn status(&self) -> UpdateStatusDto { + self.state + .lock() + .map(|slot| slot.status.clone()) + .unwrap_or(UpdateStatusDto::Idle) + } + + /// True for the first caller in this process only. + pub fn claim_auto_check(&self) -> bool { + !self.auto_checked.swap(true, Ordering::SeqCst) + } + + /// Marks a check as running. Returns the current status instead when a + /// check or install is already running, or updates are unsupported. + pub fn begin_check(&self) -> Option { + let mut slot = self.state.lock().ok()?; + match slot.status { + UpdateStatusDto::Checking + | UpdateStatusDto::Installing { .. } + | UpdateStatusDto::Unsupported => Some(slot.status.clone()), + _ => { + slot.status = UpdateStatusDto::Checking; + None + } + } + } + + /// Stores the outcome of a check and returns the new status. + pub fn finish_check( + &self, + current_version: &str, + result: Result, String>, + manual: bool, + ) -> UpdateStatusDto { + let (summary, pending) = match result { + Ok(Some((summary, update))) => (Ok(Some(summary)), Some(update)), + Ok(None) => (Ok(None), None), + Err(error) => (Err(error), None), + }; + let status = status_after_check(current_version, summary, manual); + if let Ok(mut slot) = self.state.lock() { + slot.status = status.clone(); + slot.pending = pending; + } + status + } + + pub fn set_status(&self, status: UpdateStatusDto) { + if let Ok(mut slot) = self.state.lock() { + slot.status = status; + } + } + + /// Starts an install: returns the pending update, or the current status + /// when there is nothing to install or an install is already running. + pub fn begin_install(&self) -> Result { + let mut slot = self.state.lock().map_err(|_| UpdateStatusDto::Idle)?; + if matches!(slot.status, UpdateStatusDto::Installing { .. }) { + return Err(slot.status.clone()); + } + let Some(update) = slot.pending.clone() else { + return Err(slot.status.clone()); + }; + slot.status = UpdateStatusDto::Installing { + version: update.version.clone(), + percent: 0, + }; + Ok(update) + } +} + +/// Refuses an install when the build cannot update itself or the user is busy. +pub fn install_guard( + packaged: bool, + capture_visible: bool, + recording_active: bool, +) -> Result<(), SnaphubError> { + if packaged { + return Err(SnaphubError::Update( + "Updates come from the Microsoft Store.".into(), + )); + } + if capture_visible || recording_active { + return Err(SnaphubError::Update(GUARD_MESSAGE.into())); + } + Ok(()) +} + +/// Maps a check outcome to a status. A failed automatic check stays silent +/// (idle); a failed manual check reports an error. +pub fn status_after_check( + current_version: &str, + result: Result, String>, + manual: bool, +) -> UpdateStatusDto { + match result { + Ok(Some(update)) => UpdateStatusDto::Available { + current_version: current_version.to_owned(), + version: update.version, + notes: update.notes, + }, + Ok(None) => UpdateStatusDto::UpToDate { + current_version: current_version.to_owned(), + }, + Err(_) if !manual => UpdateStatusDto::Idle, + Err(_) => UpdateStatusDto::Error { + current_version: current_version.to_owned(), + message: "Couldn't check for updates. Try again later.".into(), + }, + } +} + +/// The status shown after a failed download or signature check. +pub fn install_failure(current_version: &str) -> UpdateStatusDto { + UpdateStatusDto::Error { + current_version: current_version.to_owned(), + message: format!("Update failed. CapKit is still on v{current_version}."), + } +} + +/// Whole percent downloaded, or `None` when the total size is unknown. +pub fn download_percent(downloaded: u64, total: Option) -> Option { + let total = total.filter(|total| *total > 0)?; + let percent = downloaded.saturating_mul(100) / total; + Some(u8::try_from(percent.min(100)).unwrap_or(100)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn available() -> AvailableUpdate { + AvailableUpdate { + version: "0.4.0".into(), + notes: None, + } + } + + #[test] + fn guard_blocks_packaged_capture_and_recording() { + assert!(install_guard(false, false, false).is_ok()); + assert!( + install_guard(true, false, false) + .unwrap_err() + .to_string() + .contains("Microsoft Store") + ); + for (capture, recording) in [(true, false), (false, true), (true, true)] { + assert!( + install_guard(false, capture, recording) + .unwrap_err() + .to_string() + .contains(GUARD_MESSAGE) + ); + } + } + + #[test] + fn check_results_map_to_statuses() { + assert_eq!( + status_after_check("0.3.0", Ok(Some(available())), true), + UpdateStatusDto::Available { + current_version: "0.3.0".into(), + version: "0.4.0".into(), + notes: None, + } + ); + assert_eq!( + status_after_check("0.3.0", Ok(None), false), + UpdateStatusDto::UpToDate { + current_version: "0.3.0".into() + } + ); + assert_eq!( + status_after_check("0.3.0", Err("offline".into()), false), + UpdateStatusDto::Idle + ); + assert!(matches!( + status_after_check("0.3.0", Err("offline".into()), true), + UpdateStatusDto::Error { .. } + )); + } + + #[test] + fn install_failure_names_the_current_version() { + assert_eq!( + install_failure("0.3.0"), + UpdateStatusDto::Error { + current_version: "0.3.0".into(), + message: "Update failed. CapKit is still on v0.3.0.".into(), + } + ); + } + + #[test] + fn overlapping_checks_do_not_start_twice() { + let registry = UpdateRegistry::new(false); + assert_eq!(registry.begin_check(), None); + assert_eq!(registry.begin_check(), Some(UpdateStatusDto::Checking)); + } + + #[test] + fn packaged_builds_never_start_a_check() { + let registry = UpdateRegistry::new(true); + assert_eq!(registry.begin_check(), Some(UpdateStatusDto::Unsupported)); + } + + #[test] + fn automatic_check_is_claimed_once_per_process() { + let registry = UpdateRegistry::new(false); + assert!(registry.claim_auto_check()); + assert!(!registry.claim_auto_check()); + } + + #[test] + fn install_without_a_pending_update_returns_the_status() { + let registry = UpdateRegistry::new(false); + assert_eq!(registry.begin_install().err(), Some(UpdateStatusDto::Idle)); + registry.set_status(UpdateStatusDto::Installing { + version: "0.4.0".into(), + percent: 10, + }); + assert!(matches!( + registry.begin_install().err(), + Some(UpdateStatusDto::Installing { .. }) + )); + } + + #[test] + fn percent_is_clamped_and_needs_a_known_size() { + assert_eq!(download_percent(50, Some(200)), Some(25)); + assert_eq!(download_percent(300, Some(200)), Some(100)); + assert_eq!(download_percent(10, None), None); + assert_eq!(download_percent(10, Some(0)), None); + } + + #[test] + fn status_serialises_with_a_kebab_tag_and_camel_fields() { + let json = serde_json::to_value(UpdateStatusDto::UpToDate { + current_version: "0.3.0".into(), + }) + .unwrap(); + assert_eq!(json["state"], "up-to-date"); + assert_eq!(json["currentVersion"], "0.3.0"); + } +} diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 89021b0..c402a5a 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -52,6 +52,13 @@ } } }, + "plugins": { + "updater": { + "pubkey": "REPLACE_WITH_UPDATER_PUBLIC_KEY", + "endpoints": ["https://github.com/imnakul/Capkit/releases/latest/download/latest.json"], + "windows": { "installMode": "passive" } + } + }, "bundle": { "active": true, "targets": "all", diff --git a/apps/desktop/src/App.test.tsx b/apps/desktop/src/App.test.tsx index 4754237..259d408 100644 --- a/apps/desktop/src/App.test.tsx +++ b/apps/desktop/src/App.test.tsx @@ -2,6 +2,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libra import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { App } from "./App"; import type { CaptureSession, CompletionAction } from "./domain/capture"; +import { defaultSnaphubSettings, saveSnaphubSettings, type OverlayMotion } from "./domain/settings"; import type { CompletionResult } from "./lib/tauri"; const captureMocks = vi.hoisted(() => ({ @@ -9,7 +10,12 @@ const captureMocks = vi.hoisted(() => ({ cancelManualScrolling: vi.fn(), captureScrolling: vi.fn(), completeCapture: vi.fn(), + copyCaptureText: vi.fn(), + recognizeCaptureText: vi.fn(), + isTextRecognitionSupported: vi.fn(), listeners: [] as (() => void)[], + openInShowcase: vi.fn(), + pickCaptureColor: vi.fn(), requestCapture: vi.fn(), retryCaptureSave: vi.fn(), showCaptureSurface: vi.fn(), @@ -23,6 +29,11 @@ vi.mock("./lib/tauri", async (importOriginal) => { cancelManualScrolling: captureMocks.cancelManualScrolling, captureScrolling: captureMocks.captureScrolling, completeCapture: captureMocks.completeCapture, + copyCaptureText: captureMocks.copyCaptureText, + recognizeCaptureText: captureMocks.recognizeCaptureText, + isTextRecognitionSupported: captureMocks.isTextRecognitionSupported, + openInShowcase: captureMocks.openInShowcase, + pickCaptureColor: captureMocks.pickCaptureColor, listenForCaptureRequest: vi.fn((callback: () => void) => { captureMocks.listeners.push(callback); return Promise.resolve((): void => { @@ -167,6 +178,7 @@ describe("App", () => { captureMocks.cancelManualScrolling.mockResolvedValue(undefined); captureMocks.requestCapture.mockImplementation(() => Promise.resolve(createCaptureSession())); captureMocks.showCaptureSurface.mockResolvedValue(undefined); + captureMocks.isTextRecognitionSupported.mockResolvedValue(false); captureMocks.completeCapture.mockImplementation((action: CompletionAction) => Promise.resolve(completedResult(action)), ); @@ -323,6 +335,119 @@ describe("App", () => { await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledTimes(1)); }); + it("copies the colour under the pointer with I and rgb with Shift+I", async () => { + captureMocks.pickCaptureColor.mockImplementation( + (_sessionId: string, _point: unknown, format: "hex" | "rgb") => + Promise.resolve({ hex: "#12ABFF", copied: format === "hex" ? "#12ABFF" : "rgb(18, 171, 255)" }), + ); + render(); + + expect(await screen.findAllByText(/Hover to preview targets/)).not.toHaveLength(0); + fireEvent.pointerMove(screen.getByRole("main"), { clientX: 40, clientY: 60, pointerId: 1 }); + fireEvent.keyDown(window, { key: "i" }); + expect(await screen.findAllByText(/Copied #12ABFF/)).not.toHaveLength(0); + fireEvent.keyDown(window, { key: "I", shiftKey: true }); + expect(await screen.findAllByText(/Copied rgb\(18, 171, 255\)/)).not.toHaveLength(0); + expect(captureMocks.pickCaptureColor).toHaveBeenNthCalledWith( + 1, + expect.any(String), + { x: 40, y: 60 }, + "hex", + ); + expect(captureMocks.pickCaptureColor).toHaveBeenLastCalledWith( + expect.any(String), + { x: 40, y: 60 }, + "rgb", + ); + expect(screen.getByRole("main")).toBeInTheDocument(); + }); + + it("copies selection text, or stays open when none is found", async () => { + captureMocks.isTextRecognitionSupported.mockResolvedValue(true); + captureMocks.copyCaptureText + .mockResolvedValueOnce({ status: "empty", text: "", cleanupWarning: null }) + .mockResolvedValueOnce({ status: "copied", text: "Invoice 42\nDue today", cleanupWarning: null }); + render(); + await selectRegion(); + + fireEvent.click(await screen.findByRole("button", { name: "Copy text" })); + expect(await screen.findAllByText(/No text found in this selection/)).not.toHaveLength(0); + expect(screen.getByRole("main")).toBeInTheDocument(); + expect(captureMocks.copyCaptureText).toHaveBeenLastCalledWith( + expect.any(String), + expect.objectContaining({ width: 440, height: 300 }), + ); + + fireEvent.click(screen.getByRole("button", { name: "Copy text" })); + await waitFor(() => { + expect(screen.queryByRole("main")).not.toBeInTheDocument(); + }); + expect(captureMocks.completeCapture).not.toHaveBeenCalled(); + }); + + it("blacks out only the confirmed sensitive text in one step", async () => { + captureMocks.isTextRecognitionSupported.mockResolvedValue(true); + captureMocks.recognizeCaptureText.mockResolvedValue({ + text: "Mail nakul@example.com or call +91 98765 43210", + language: "en-US", + lines: [{ + text: "Mail nakul@example.com or call +91 98765 43210", + words: [ + { text: "Mail", bounds: { x: 4, y: 10, width: 30, height: 14 } }, + { text: "nakul@example.com", bounds: { x: 40, y: 10, width: 120, height: 14 } }, + { text: "or", bounds: { x: 166, y: 10, width: 14, height: 14 } }, + { text: "call", bounds: { x: 186, y: 10, width: 26, height: 14 } }, + { text: "+91", bounds: { x: 218, y: 10, width: 24, height: 14 } }, + { text: "98765", bounds: { x: 248, y: 10, width: 40, height: 14 } }, + { text: "43210", bounds: { x: 294, y: 10, width: 40, height: 14 } }, + ], + }], + }); + render(); + await selectRegion(); + + fireEvent.click(await screen.findByRole("button", { name: "Find sensitive text" })); + const phone = await screen.findByRole("checkbox", { name: /Phone number/ }); + expect(screen.getByRole("checkbox", { name: /Email address/ })).toBeChecked(); + fireEvent.click(phone); + expect(phone).not.toBeChecked(); + fireEvent.click(screen.getByRole("button", { name: "Black out 1" })); + expect(await screen.findAllByText(/Blacked out 1 item/)).not.toHaveLength(0); + expect(screen.queryByRole("region", { name: "Sensitive text" })).toBeNull(); + + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + await waitFor(() => expect(captureMocks.completeCapture).toHaveBeenCalledTimes(1)); + expect(captureMocks.completeCapture).toHaveBeenCalledWith( + "copy", + expect.any(String), + expect.anything(), + { + version: 1, + elements: [expect.objectContaining({ + kind: "blackout", + bounds: { x: 37, y: 7, width: 126, height: 20 }, + })], + }, + ); + }); + + it("says so when nothing sensitive is found", async () => { + captureMocks.isTextRecognitionSupported.mockResolvedValue(true); + captureMocks.recognizeCaptureText.mockResolvedValue({ text: "", language: "en-US", lines: [] }); + render(); + await selectRegion(); + fireEvent.click(await screen.findByRole("button", { name: "Find sensitive text" })); + expect(await screen.findByText(/No emails, phone numbers/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Close" })); + expect(screen.queryByText(/No emails, phone numbers/)).toBeNull(); + }); + + it("hides Copy text when the OS cannot read text", async () => { + render(); + await selectRegion(); + expect(screen.queryByRole("button", { name: "Copy text" })).toBeNull(); + }); + it("dismisses capture with Escape before a region is selected", async () => { render(); @@ -378,6 +503,10 @@ describe("App", () => { ); expect(screen.getByText("440 × 300 px")).toBeInTheDocument(); + // The first Escape closes the open tool row; the next one cancels the capture. + fireEvent.keyDown(window, { key: "Escape" }); + expect(screen.queryByRole("group", { name: "Tool properties" })).toBeNull(); + expect(captureMocks.cancelCapture).not.toHaveBeenCalled(); fireEvent.keyDown(window, { key: "Escape" }); await waitFor(() => { expect(screen.queryByRole("main")).not.toBeInTheDocument(); @@ -394,7 +523,34 @@ describe("App", () => { expect(combined).toHaveTextContent("A"); expect( Array.from(toolbar.querySelectorAll("button")).map((button) => button.getAttribute("aria-label")), - ).toEqual(["Copy", "Copy & Save", "Save", "Pin"]); + ).toEqual(["Copy", "Copy & Save", "Save", "Pin", "Save & Showcase"]); + }); + + it("saves, then opens the saved file in Showcase", async () => { + captureMocks.openInShowcase.mockResolvedValue(undefined); + render(); + await selectRegion(); + fireEvent.click(screen.getByRole("button", { name: "Save & Showcase" })); + + await waitFor(() => expect(captureMocks.openInShowcase).toHaveBeenCalledWith("Demo/Capkit.png")); + expect(captureMocks.completeCapture).toHaveBeenCalledTimes(1); + expect(captureMocks.completeCapture.mock.calls[0]?.[0]).toBe("save"); + }); + + it("does not open Showcase when the save is still pending", async () => { + captureMocks.completeCapture.mockResolvedValueOnce({ + action: "save", + cleanupWarning: null, + diagnostic: "SH-EXPORT-001: disk full", + outputPath: null, + status: "save-pending", + }); + render(); + await selectRegion(); + fireEvent.click(screen.getByRole("button", { name: "Save & Showcase" })); + + expect(await screen.findByRole("button", { name: "Retry save" })).toBeVisible(); + expect(captureMocks.openInShowcase).not.toHaveBeenCalled(); }); it("ignores the completion key without a selection, with modifiers, or in an editable field", async () => { @@ -428,7 +584,7 @@ describe("App", () => { it("ignores the completion key during scrolling preview", async () => { render(); await selectRegion(); - fireEvent.pointerEnter(screen.getByRole("button", { name: "Counter group" })); + fireEvent.click(screen.getByRole("button", { name: "Counter group" })); fireEvent.click(screen.getByRole("button", { name: "Scrolling capture" })); expect(await screen.findByAltText("Stitched scrolling capture preview")).toBeVisible(); @@ -533,3 +689,111 @@ describe("App", () => { expect(screen.queryByRole("button", { name: "Copy & Save" })).not.toBeInTheDocument(); }); }); + +describe("App overlay motion", () => { + function useMotion(motion: OverlayMotion, reduced = false): void { + saveSnaphubSettings({ ...defaultSnaphubSettings, overlay: { ...defaultSnaphubSettings.overlay, motion } }); + vi.stubGlobal("matchMedia", (media: string) => ({ + matches: reduced, + media, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + })); + } + + beforeEach(() => { + vi.clearAllMocks(); + window.localStorage.clear(); + captureMocks.listeners.length = 0; + captureMocks.cancelCapture.mockResolvedValue(undefined); + captureMocks.cancelManualScrolling.mockResolvedValue(undefined); + captureMocks.requestCapture.mockImplementation(() => Promise.resolve(createCaptureSession())); + captureMocks.showCaptureSurface.mockResolvedValue(undefined); + captureMocks.isTextRecognitionSupported.mockResolvedValue(false); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.useRealTimers(); + window.localStorage.clear(); + }); + + it("dim-rise: scrim and hint start hidden, then transition in after two frames", async () => { + useMotion("dim-rise"); + const frames = createAnimationFrameQueue(); + render(); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith("dim-rise", false)); + const scrim = screen.getByTestId("capture-scrim"); + const hint = screen.getByTestId("capture-hint"); + expect(scrim).toHaveStyle({ opacity: "0" }); + expect(hint.style.transform).toBe("translateY(6px)"); + frames.flushNext(); + frames.flushNext(); + expect(scrim).toHaveStyle({ opacity: "1" }); + expect(scrim.style.transition).toBe("opacity 160ms cubic-bezier(0.22, 1, 0.36, 1)"); + expect(hint.style.transform).toBe("translateY(0px)"); + }); + + it("dim-rise: Escape fades out and cancels only after 120 ms, once for a double Escape", async () => { + useMotion("dim-rise"); + render(); + await screen.findByTestId("capture-scrim"); + await waitFor(() => expect(screen.getByTestId("capture-scrim")).toHaveStyle({ opacity: "1" })); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + fireEvent.keyDown(window, { key: "Escape" }); + fireEvent.keyDown(window, { key: "Escape" }); + const scrim = screen.getByTestId("capture-scrim"); + expect(scrim).toHaveStyle({ opacity: "0" }); + expect(scrim.style.transition).toBe("opacity 120ms cubic-bezier(0.4, 0, 1, 1)"); + expect(captureMocks.cancelCapture).not.toHaveBeenCalled(); + await act(async () => { + vi.advanceTimersByTime(120); + await Promise.resolve(); + }); + expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1); + }); + + it("fade-both: Escape cancels immediately with the fade-both motion", async () => { + useMotion("fade-both"); + render(); + await screen.findByRole("main"); + fireEvent.keyDown(window, { key: "Escape" }); + await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1)); + expect(captureMocks.cancelCapture).toHaveBeenCalledWith(expect.any(String), "fade-both", false); + }); + + it("fade-in: reveals without scrim animation and cancels immediately", async () => { + useMotion("fade-in"); + render(); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith("fade-in", false)); + expect(screen.getByTestId("capture-scrim").style.transition).toBe(""); + fireEvent.keyDown(window, { key: "Escape" }); + await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1)); + }); + + it("reduced motion: no scrim animation and Escape cancels immediately in every mode", async () => { + useMotion("dim-rise", true); + render(); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledWith("dim-rise", true)); + expect(screen.getByTestId("capture-scrim").style.transition).toBe(""); + fireEvent.keyDown(window, { key: "Escape" }); + await waitFor(() => expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1)); + expect(captureMocks.cancelCapture).toHaveBeenCalledWith(expect.any(String), "dim-rise", true); + }); + + it("a new capture during the exit fade cancels the old session once and reveals the new one", async () => { + useMotion("dim-rise"); + render(); + await waitFor(() => expect(screen.getByTestId("capture-scrim")).toHaveStyle({ opacity: "1" })); + fireEvent.keyDown(window, { key: "Escape" }); + act(() => { + captureMocks.listeners.forEach((listener) => listener()); + }); + await waitFor(() => expect(captureMocks.requestCapture).toHaveBeenCalledTimes(2)); + expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1); + await waitFor(() => expect(captureMocks.showCaptureSurface).toHaveBeenCalledTimes(2)); + await new Promise((resolve) => window.setTimeout(resolve, 200)); + expect(captureMocks.cancelCapture).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index e9f6915..fc2a9aa 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -4,6 +4,11 @@ import { AnnotationCanvas } from "./components/AnnotationCanvas"; import { AnnotationToolbar } from "./components/AnnotationToolbar"; import { CaptureBackdrop } from "./components/CaptureBackdrop"; import { CompletionToolbar } from "./components/CompletionToolbar"; +import { + RedactionPreview, + RedactionReviewPanel, + type RedactionReview, +} from "./components/RedactionReviewPanel"; import { SelectionFrame, type ResizeHandle } from "./components/SelectionFrame"; import { ScrollingCapturePanel, @@ -19,27 +24,43 @@ import { } from "./domain/annotations"; import type { CaptureSession, + ColorFormat, CompletionAction, DetectedTarget, Point, Rect, } from "./domain/capture"; -import { useSnaphubSettings } from "./domain/settings"; -import { chooseToolbarPlacement, clampRect, isUsableSelection, normalizeRect } from "./lib/geometry"; +import { useSnaphubSettings, type CaptureToolbarToolId } from "./domain/settings"; +import { + chooseToolbarPlacement, + clampRect, + isUsableSelection, + normalizeRect, + toolbarPosition, + type ToolbarSize, +} from "./lib/geometry"; import { captureCursor } from "./lib/cursor"; +import { prefersReducedMotion } from "./lib/motion"; +import { eyedropperFormat } from "./lib/eyedropper"; +import { suggestRedactions } from "./lib/redactionPatterns"; import { createVisualTargetDetector, type VisualTargetDetector } from "./lib/visualTargets"; import { cancelCapture, cancelManualScrolling, captureScrolling, completeCapture, + openInShowcase, completeScrollingCapture, + copyCaptureText, detectTargets, dismissCapture, discardScrollingOutput, describeInvokeError, + isTextRecognitionSupported, listTargets, listenForCaptureRequest, + pickCaptureColor, + recognizeCaptureText, requestCapture, retryCaptureSave, showCaptureSurface, @@ -81,6 +102,14 @@ export function App(): React.JSX.Element { const [style, setStyle] = useState(defaultAnnotationStyle); const [history, dispatchScene] = useReducer(sceneHistoryReducer, initialSceneHistory); const [busy, setBusy] = useState(false); + const [lastToolByGroup, setLastToolByGroup] = useState>>({}); + const [openGroupIndex, setOpenGroupIndex] = useState(null); + const [toolbarSize, setToolbarSize] = useState({ width: 430, height: 52 }); + const toolbarObserver = useRef(null); + const [revealed, setRevealed] = useState(false); + const [exiting, setExiting] = useState(false); + const exitTimer = useRef(null); + const revealFrames = useRef([]); const [completionState, setCompletionState] = useState({ phase: "idle", message: "", @@ -88,8 +117,14 @@ export function App(): React.JSX.Element { const [hoverTarget, setHoverTarget] = useState(null); const [targets, setTargets] = useState([]); const [isDraftingSelection, setIsDraftingSelection] = useState(false); - const [message, setMessage] = useState("Hover to preview targets / drag to draw a rectangle"); + const [message, setMessage] = useState("Hover to preview targets / drag to draw a rectangle / I copies a colour"); const [scrollingCapture, setScrollingCapture] = useState(null); + // The swatch shows only while its message is still the current one. + const [pickedSwatch, setPickedSwatch] = useState<{ hex: string; message: string } | null>(null); + const [canReadText, setCanReadText] = useState(false); + const [redactionReview, setRedactionReview] = useState(null); + const redactionSequence = useRef(0); + const lastPointer = useRef(null); const uiLookupSequence = useRef(0); const uiLookupInFlight = useRef(false); const pendingUiLookup = useRef(null); @@ -143,7 +178,38 @@ export function App(): React.JSX.Element { }); }, [session, settings.detection.uiRegions]); + const measureToolbar = useCallback((element: HTMLDivElement | null): void => { + toolbarObserver.current?.disconnect(); + toolbarObserver.current = null; + if (element === null || typeof ResizeObserver === "undefined") return; + const update = (): void => { + const { offsetWidth: width, offsetHeight: height } = element; + if (width === 0 || height === 0) return; + setToolbarSize((current) => current.width === width && current.height === height ? current : { width, height }); + }; + update(); + toolbarObserver.current = new ResizeObserver(update); + toolbarObserver.current.observe(element); + }, []); + + const rememberGroupTool = useCallback((groupIndex: number, toolId: CaptureToolbarToolId): void => { + setLastToolByGroup((current) => current[groupIndex] === toolId ? current : { ...current, [groupIndex]: toolId }); + }, []); + + function clearPendingMotion(): void { + if (exitTimer.current !== null) window.clearTimeout(exitTimer.current); + exitTimer.current = null; + for (const frame of revealFrames.current) window.cancelAnimationFrame(frame); + revealFrames.current = []; + } + + useEffect(() => clearPendingMotion, []); + function clearCaptureUi(): void { + clearPendingMotion(); + setOpenGroupIndex(null); + setExiting(false); + setRevealed(false); activationState.current = "idle"; activeSessionId.current = null; const pendingBackdrop = backdropReadyResolver.current; @@ -162,12 +228,24 @@ export function App(): React.JSX.Element { } const startSession = useCallback(async (): Promise => { + if (exitTimer.current !== null) { + // A new request during the exit fade: finish the old session once, then start fresh. + const oldSessionId = activeSessionId.current; + clearPendingMotion(); + setExiting(false); + activationState.current = "idle"; + sessionGeneration.current += 1; + if (oldSessionId !== null) await cancelCapture(oldSessionId, "fade-in", true).catch(() => undefined); + } if (activationState.current !== "idle") return; const timingStartedAt = import.meta.env.DEV ? performance.now() : null; let timingAfterRequest: number | null = null; let timingAfterReady: number | null = null; activationState.current = "preparing"; sessionGeneration.current += 1; + clearPendingMotion(); + setExiting(false); + setRevealed(false); completionInFlight.current = false; activeSessionId.current = null; let preparedSession: CaptureSession | null = null; @@ -196,7 +274,7 @@ export function App(): React.JSX.Element { }); dispatchScene({ type: "reset" }); }); - setMessage("Hover to preview targets / drag to draw a rectangle"); + setMessage("Hover to preview targets / drag to draw a rectangle / I copies a colour"); let readyTimeout: number | undefined; await Promise.race([ backdropReady, @@ -212,7 +290,19 @@ export function App(): React.JSX.Element { if (!isPreparingCaptureSession(activationState, activeSessionId, next.id)) { return; } - await showCaptureSurface(); + const motion = settingsRef.current.overlay.motion; + const reduced = prefersReducedMotion(); + await showCaptureSurface(motion, reduced); + if (motion === "dim-rise" && !reduced) { + // Two frames so the hidden styles paint before the transition target applies. + const first = window.requestAnimationFrame(() => { + const second = window.requestAnimationFrame(() => setRevealed(true)); + revealFrames.current.push(second); + }); + revealFrames.current.push(first); + } else { + setRevealed(true); + } if ( timingStartedAt !== null && timingAfterRequest !== null && @@ -276,8 +366,8 @@ export function App(): React.JSX.Element { () => selection === null ? null - : chooseToolbarPlacement(selection, viewportBounds(session?.display ?? null)), - [selection, session?.display], + : chooseToolbarPlacement(selection, viewportBounds(session?.display ?? null), toolbarSize.height), + [selection, session?.display, toolbarSize.height], ); function pointer(event: React.PointerEvent): Point { @@ -562,9 +652,10 @@ export function App(): React.JSX.Element { const handleCancel = useCallback(async (): Promise => { sessionGeneration.current += 1; + const exitMotion = settingsRef.current.overlay.motion; try { if (session !== null) { - await cancelCapture(session.id).catch(async () => dismissCapture()); + await cancelCapture(session.id, exitMotion, prefersReducedMotion()).catch(async () => dismissCapture()); await cancelManualScrolling(session.id).catch(() => undefined); } else { await dismissCapture(); @@ -577,8 +668,21 @@ export function App(): React.JSX.Element { } }, [session]); + const requestExit = useCallback((): void => { + if (exitTimer.current !== null) return; + if (settingsRef.current.overlay.motion !== "dim-rise" || prefersReducedMotion() || session === null) { + void handleCancel(); + return; + } + setExiting(true); + exitTimer.current = window.setTimeout(() => { + exitTimer.current = null; + void handleCancel(); + }, 120); + }, [handleCancel, session]); + const handleComplete = useCallback( - async (action: CompletionAction): Promise => { + async (action: CompletionAction, followUp: "none" | "showcase" = "none"): Promise => { if ( session === null || selection === null @@ -627,6 +731,13 @@ export function App(): React.JSX.Element { : `${successMessage} · ${result.cleanupWarning}`, ); clearCaptureUi(); + // The capture window is already hidden, so a failure here has no UI to + // land in; the image itself is saved either way. + if (followUp === "showcase" && result.outputPath !== null) { + void openInShowcase(result.outputPath).catch((error: unknown) => { + console.error("SH-SHOWCASE-OPEN-001", error); + }); + } } catch (error: unknown) { if ( activeSessionId.current === sessionId @@ -650,6 +761,131 @@ export function App(): React.JSX.Element { [busy, completionState.phase, history.present, scrollingCapture, selection, session], ); + const handleCopyText = useCallback(async (): Promise => { + if ( + session === null + || selection === null + || busy + || scrollingCapture !== null + || completionState.phase !== "idle" + || completionInFlight.current + ) return; + const sessionId = session.id; + const generation = sessionGeneration.current; + completionInFlight.current = true; + setCompletionState({ phase: "working", message: "Reading text…" }); + setMessage("Reading text…"); + try { + const result = await copyCaptureText(sessionId, selection); + if ( + activeSessionId.current !== sessionId + || sessionGeneration.current !== generation + ) return; + if (result.status === "empty") { + const emptyMessage = "No text found in this selection. Adjust it and try again."; + setCompletionState({ phase: "idle", message: emptyMessage }); + setMessage(emptyMessage); + return; + } + const lineCount = result.text.split("\n").length; + const copiedMessage = `Copied ${lineCount === 1 ? "1 line" : `${String(lineCount)} lines`} of text`; + setMessage( + result.cleanupWarning === null || result.cleanupWarning === undefined + ? copiedMessage + : `${copiedMessage} · ${result.cleanupWarning}`, + ); + clearCaptureUi(); + } catch (error: unknown) { + if ( + activeSessionId.current === sessionId + && sessionGeneration.current === generation + ) { + const errorMessage = `Could not read text. ${describeInvokeError(error, "The text recognition service did not return a diagnostic")}`; + setCompletionState({ phase: "idle", message: errorMessage }); + setMessage(errorMessage); + } + } finally { + if (sessionGeneration.current === generation) { + completionInFlight.current = false; + } + } + }, [busy, completionState.phase, scrollingCapture, selection, session]); + + const findSensitiveText = useCallback(async (): Promise => { + if ( + session === null + || selection === null + || busy + || scrollingCapture !== null + || completionState.phase !== "idle" + || completionInFlight.current + ) return; + const sequence = redactionSequence.current + 1; + redactionSequence.current = sequence; + const reviewedSelection = selection; + setCompletionState({ phase: "idle", message: "" }); + setRedactionReview({ phase: "reading" }); + try { + const recognized = await recognizeCaptureText(session.id, reviewedSelection); + if (redactionSequence.current !== sequence) return; + const suggestions = suggestRedactions(recognized, reviewedSelection); + setRedactionReview({ + phase: "ready", + suggestions, + selectedIds: new Set(suggestions.map((suggestion) => suggestion.id)), + }); + } catch (error: unknown) { + if (redactionSequence.current !== sequence) return; + setRedactionReview({ + phase: "error", + message: `Could not read text. ${describeInvokeError(error, "The text recognition service did not return a diagnostic")}`, + }); + } + }, [busy, completionState.phase, scrollingCapture, selection, session]); + + const closeRedactionReview = useCallback((): void => { + redactionSequence.current += 1; + setRedactionReview(null); + }, []); + + const toggleRedactionSuggestion = useCallback((suggestionId: string): void => { + setRedactionReview((current) => { + if (current?.phase !== "ready") return current; + const selectedIds = new Set(current.selectedIds); + if (selectedIds.has(suggestionId)) selectedIds.delete(suggestionId); + else selectedIds.add(suggestionId); + return { ...current, selectedIds }; + }); + }, []); + + const applyRedactions = useCallback((): void => { + if (redactionReview?.phase !== "ready") return; + // Blackout, not pixelate: large-block pixelation of text can be partly reversed. + const blackouts: Annotation[] = redactionReview.suggestions + .filter((suggestion) => redactionReview.selectedIds.has(suggestion.id)) + .map((suggestion) => ({ + id: crypto.randomUUID(), + kind: "blackout", + bounds: suggestion.bounds, + color: "#090a08", + intensity: 1, + opacity: 1, + })); + if (blackouts.length === 0) return; + // One replace, so a single undo removes the whole batch. + dispatchScene({ + type: "replace", + scene: { version: 1, elements: [...history.present.elements, ...blackouts] }, + }); + closeRedactionReview(); + setMessage(`Blacked out ${blackouts.length === 1 ? "1 item" : `${String(blackouts.length)} items`} · Ctrl+Z to undo`); + }, [closeRedactionReview, history.present.elements, redactionReview]); + + useEffect(() => { + // Suggestions are positioned for one selection; any change makes them stale. + closeRedactionReview(); + }, [closeRedactionReview, selection, session?.id]); + const handleRetrySave = useCallback(async (): Promise => { if ( session === null @@ -700,6 +936,45 @@ export function App(): React.JSX.Element { } }, [completionState.phase, session]); + useEffect(() => { + let isCurrent = true; + isTextRecognitionSupported() + .then((supported) => { + if (isCurrent) setCanReadText(supported); + }) + .catch(() => { + // An unsupported or unreachable engine just hides Copy text. + if (isCurrent) setCanReadText(false); + }); + return (): void => { + isCurrent = false; + }; + }, []); + + useEffect(() => { + // Window-level so the eyedropper knows the pointer even over the annotation canvas or toolbars. + function trackPointer(event: PointerEvent): void { + lastPointer.current = { x: event.clientX, y: event.clientY }; + } + window.addEventListener("pointermove", trackPointer, { capture: true, passive: true }); + return (): void => { + window.removeEventListener("pointermove", trackPointer, { capture: true }); + }; + }, []); + + const pickColor = useCallback(async (format: ColorFormat): Promise => { + const point = lastPointer.current; + if (session === null || point === null) return; + try { + const picked = await pickCaptureColor(session.id, point, format); + const pickedMessage = `Copied ${picked.copied}`; + setPickedSwatch({ hex: picked.hex, message: pickedMessage }); + setMessage(pickedMessage); + } catch (error) { + setMessage(`Could not copy colour · ${describeInvokeError(error, "The colour could not be read")}`); + } + }, [session]); + useEffect(() => { function handleKeyDown(event: KeyboardEvent): void { // Escape is the capture surface's unconditional exit hatch. Handle it in @@ -712,7 +987,11 @@ export function App(): React.JSX.Element { void closeScrollingCapture(); return; } - void handleCancel(); + if (openGroupIndex !== null) { + setOpenGroupIndex(null); + return; + } + requestExit(); return; } @@ -729,7 +1008,18 @@ export function App(): React.JSX.Element { && !busy && completionState.phase === "idle"; const key = event.key.toUpperCase(); - if ( + const { captureModeCopy, captureModeSave, captureModeCopyAndSave } = settingsRef.current.shortcuts; + const colorFormat = busy || scrollingCapture !== null || event.repeat + ? null + : eyedropperFormat( + event, + [captureModeCopy, captureModeSave, captureModeCopyAndSave], + selectedCompletionReady, + ); + if (colorFormat !== null) { + event.preventDefault(); + void pickColor(colorFormat); + } else if ( selectedCompletionReady && hasNoModifiers && key === settingsRef.current.shortcuts.captureModeCopy @@ -772,9 +1062,11 @@ export function App(): React.JSX.Element { }, [ busy, completionState.phase, - handleCancel, + requestExit, + openGroupIndex, handleComplete, isDraftingSelection, + pickColor, scrollingCapture, selection, ]); @@ -784,13 +1076,13 @@ export function App(): React.JSX.Element { } const viewport = viewportBounds(session.display); - const toolBarX = selection === null ? 16 : Math.max(16, Math.min(selection.x, viewport.width - 430)); - const toolBarY = - selection === null || toolbarPlacement === null - ? viewport.height - 68 - : toolbarPlacement.tools === "bottom" - ? Math.min(viewport.height - 64, selection.y + selection.height + 10) - : Math.max(10, selection.y - 62); + const swatchHex = pickedSwatch !== null && pickedSwatch.message === message ? pickedSwatch.hex : null; + const toolbarSide = toolbarPlacement?.tools ?? "bottom"; + const toolbarSpot = selection === null + ? { x: 16, y: viewport.height - toolbarSize.height - 16 } + : toolbarPosition(selection, viewport, toolbarSide, toolbarSize); + const toolBarX = toolbarSpot.x; + const toolBarY = toolbarSpot.y; const actionsOnLeft = selection !== null && selection.x + selection.width + 62 > viewport.width; const actionRailX = @@ -804,6 +1096,19 @@ export function App(): React.JSX.Element { ? 10 : Math.max(10, Math.min(selection.y, viewport.height - 190)); const activeCaptureCursor = captureCursor(settings.cursor, settings.accentColor); + const dimRise = settings.overlay.motion === "dim-rise" && !prefersReducedMotion(); + const shown = revealed && !exiting; + const fadeStyle: React.CSSProperties = dimRise + ? { + opacity: shown ? 1 : 0, + transition: exiting + ? "opacity 120ms cubic-bezier(0.4, 0, 1, 1)" + : "opacity 160ms cubic-bezier(0.22, 1, 0.36, 1)", + } + : {}; + const exitOnlyStyle: React.CSSProperties = dimRise + ? { opacity: exiting ? 0 : 1, transition: "opacity 120ms cubic-bezier(0.4, 0, 1, 1)" } + : {}; return (
) : null} - {selection === null ?
: null} + {selection === null ?
: null} {selection === null ? ( -
+
+ {swatchHex === null ? null : } {message}
) : isDraftingSelection ? ( @@ -858,6 +1176,7 @@ export function App(): React.JSX.Element {
) : ( dispatchScene({ type: "delete", annotationId })} onUpdate={(annotation) => dispatchScene({ type: "update", annotation })} /> + {redactionReview === null ? null : } {completionState.phase === "idle" ? null : (
); } +function ColorSwatch({ hex }: { hex: string }): React.JSX.Element { + return ( +