diff --git a/.github/workflows/desktop-platforms.yml b/.github/workflows/desktop-platforms.yml new file mode 100644 index 0000000..148652d --- /dev/null +++ b/.github/workflows/desktop-platforms.yml @@ -0,0 +1,189 @@ +name: Desktop platforms +on: + push: + branches: [main] + pull_request: + workflow_dispatch: +permissions: + contents: read +concurrency: + group: desktop-platforms-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: '0' +jobs: + desktop: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04 + platform: linux-x86_64 + - os: windows-2025 + platform: windows-x86_64 + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + with: + key: desktop-${{ matrix.platform }} + cache-on-failure: true + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Desktop observation dependency + run: python -m pip install Pillow + - name: Windows desktop observation dependencies + if: runner.os == 'Windows' + run: python -m pip install pywinauto psutil + - name: Linux dependencies + if: runner.os == 'Linux' + run: sudo bash scripts/build/linux-deps.sh + - name: Windows assembler + if: runner.os == 'Windows' + run: | + choco install nasm --no-progress -y + "C:\Program Files\NASM" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + - name: Windows concurrent storage regression + if: runner.os == 'Windows' + timeout-minutes: 10 + run: | + cargo test --locked -p removent-core --lib settings::tests -- --test-threads=1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + for ($attempt = 0; $attempt -lt 5; $attempt++) { + cargo test --locked -p removent-core --lib settings::tests::concurrent_writers_publish_complete_private_files -- --exact + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } + - name: Build desktop, host, tray and native probe + id: native_build + run: cargo build --locked --release -p removent-app -p removent-daemon -p removent-tray -p removent-host -p removent-client --bins --example desktop_smoke --example ipc_smoke --example desktop_session_smoke --example credential_smoke --example tray_probe --example tray_session + - name: Daemon IPC and lifecycle + shell: bash + run: target/release/examples/ipc_smoke + - name: Daemon IPC admission regression + run: cargo test --locked -p removent-daemon --test ipc -- --test-threads=1 + - name: Build desktop credential tests + run: cargo test --locked -p removent-app --bin removent --no-run + - name: Linux native desktop acceptance + timeout-minutes: 25 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Linux' }} + run: | + xvfb-run -a -s '-screen 0 1280x800x24' dbus-run-session -- bash -e -c ' + openbox > /tmp/openbox.log 2>&1 & + python3 scripts/qa/portable_desktop.py + python3 scripts/qa/portable_desktop.py --probe desktop_session_smoke + target/release/removent-tray --smoke + python3 scripts/qa/portable_app.py + python3 scripts/qa/portable_credentials.py --app-tests + ' + - name: Linux native tray interaction + timeout-minutes: 25 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Linux' }} + env: + GTK_MODULES: gail:atk-bridge + NO_AT_BRIDGE: '0' + run: | + xvfb-run -a -s '-screen 0 1280x800x24' dbus-run-session -- bash -e -c ' + openbox > /tmp/openbox-tray.log 2>&1 & + /usr/bin/python3 scripts/qa/linux_tray.py --soak-seconds 600 --evidence-dir target/qa-evidence/tray-en + ' + - name: Linux dark native tray presentation + timeout-minutes: 5 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Linux' }} + env: + GTK_MODULES: gail:atk-bridge + NO_AT_BRIDGE: '0' + run: | + xvfb-run -a -s '-screen 0 1280x800x24' dbus-run-session -- bash -e -c ' + openbox > /tmp/openbox-tray-dark.log 2>&1 & + /usr/bin/python3 scripts/qa/linux_tray.py --presentation-only --locale ZhCn --theme dark --evidence-dir target/qa-evidence/tray-zh-dark + ' + - name: Linux scaled native tray presentation + timeout-minutes: 5 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Linux' }} + env: + GTK_MODULES: gail:atk-bridge + NO_AT_BRIDGE: '0' + run: | + xvfb-run -a -s '-screen 0 2560x1600x24 -dpi 192' dbus-run-session -- bash -e -c ' + openbox > /tmp/openbox-scaled.log 2>&1 & + /usr/bin/python3 scripts/qa/linux_tray.py --presentation-only --locale ZhCn --theme light --scale 2 --evidence-dir target/qa-evidence/tray-zh-scale2 + ' + - name: Linux logical monitor reactivation + timeout-minutes: 5 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Linux' }} + env: + GTK_MODULES: gail:atk-bridge + NO_AT_BRIDGE: '0' + run: | + xvfb-run -a -s '-screen 0 2560x900x24 -noreset' dbus-run-session -- bash -e -c ' + xrandr --setmonitor LEFT 1280/338x900/238+0+0 screen + xrandr --setmonitor RIGHT 1280/338x900/238+1280+0 none + openbox > /tmp/openbox-monitors.log 2>&1 & + /usr/bin/python3 scripts/qa/linux_tray.py --presentation-only --second-monitor --evidence-dir target/qa-evidence/tray-monitors + ' + - name: Windows native capture and input + timeout-minutes: 5 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Windows' }} + run: python scripts/qa/portable_desktop.py + - name: Windows native QUIC desktop session + timeout-minutes: 5 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Windows' }} + run: python scripts/qa/portable_desktop.py --probe desktop_session_smoke + - name: Windows native tray interaction + timeout-minutes: 25 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Windows' }} + run: | + python scripts/qa/windows_tray.py --soak-seconds 600 --evidence-dir target/qa-evidence/tray-en + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/qa/windows_tray.py --presentation-only --locale ZhCn --theme dark --evidence-dir target/qa-evidence/tray-zh-dark + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Windows visible desktop application + timeout-minutes: 5 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Windows' }} + run: python scripts/qa/portable_app.py + - name: Windows credential storage + timeout-minutes: 5 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Windows' }} + run: python scripts/qa/portable_credentials.py --app-tests + - name: Protocol, codec and session regression tests + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' }} + timeout-minutes: 30 + run: cargo test --locked --no-fail-fast -p removent-proto -p removent-core -p removent-input -p removent-client -p removent-host -p removent-media-codec --lib -- --test-threads=1 + - name: Windows native account authentication + timeout-minutes: 10 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Windows' }} + run: ./scripts/qa/windows_account.ps1 + - name: Linux native account authentication + timeout-minutes: 10 + if: ${{ !cancelled() && steps.native_build.conclusion == 'success' && runner.os == 'Linux' }} + run: python3 scripts/qa/linux_account.py + - name: Package desktop artifacts + run: python scripts/build/package_portable.py --target ${{ matrix.platform }} + - name: Windows extracted package acceptance + if: runner.os == 'Windows' + timeout-minutes: 5 + run: | + Expand-Archive -Path dist/Removent-windows-x86_64.zip -DestinationPath target/package-check + python scripts/qa/portable_app.py --bin-dir target/package-check/Removent-windows-x86_64 --evidence-dir target/qa-evidence/package --require-local-runtime + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/qa/windows_tray.py --presentation-only --bin-dir target/package-check/Removent-windows-x86_64 --evidence-dir target/qa-evidence/package/tray + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - uses: actions/upload-artifact@v4 + if: always() + with: + name: desktop-evidence-${{ matrix.platform }} + path: target/qa-evidence + if-no-files-found: ignore + - uses: actions/upload-artifact@v4 + with: + name: Removent-${{ matrix.platform }} + path: | + dist/Removent-${{ matrix.platform }}.zip + dist/Removent-${{ matrix.platform }}.tar.gz + dist/Removent-${{ matrix.platform }}.*.sha256 + if-no-files-found: error + retention-days: 14 diff --git a/Cargo.lock b/Cargo.lock index 663385d..2dbf540 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,7 +23,7 @@ dependencies = [ "atspi-common", "phf 0.13.1", "serde", - "zvariant", + "zvariant 5.15.0", ] [[package]] @@ -65,7 +65,7 @@ dependencies = [ "futures-lite", "futures-util", "serde", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -242,6 +242,16 @@ dependencies = [ "libc", ] +[[package]] +name = "annotate-snippets" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" +dependencies = [ + "anstyle", + "unicode-width", +] + [[package]] name = "annotate-snippets" version = "0.12.16" @@ -332,6 +342,23 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "x11rb", +] + [[package]] name = "arc-swap" version = "1.9.2" @@ -391,7 +418,7 @@ version = "0.38.0+1.3.281" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" dependencies = [ - "libloading", + "libloading 0.8.9", ] [[package]] @@ -409,7 +436,23 @@ dependencies = [ "wayland-backend", "wayland-client", "wayland-protocols", - "zbus", + "zbus 5.19.0", +] + +[[package]] +name = "ashpd" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-util", + "getrandom 0.4.3", + "pipewire", + "serde", + "serde_repr", + "zbus 6.3.0", ] [[package]] @@ -550,7 +593,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix", + "rustix 1.1.5", "slab", "windows-sys 0.61.2", ] @@ -592,7 +635,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix", + "rustix 1.1.5", ] [[package]] @@ -618,7 +661,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix", + "rustix 1.1.5", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -641,6 +684,29 @@ dependencies = [ "syn 3.0.7", ] +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.2.2", +] + [[package]] name = "atomic" version = "0.5.3" @@ -701,11 +767,11 @@ dependencies = [ "enumflags2", "serde", "static_assertions", - "zbus", + "zbus 5.19.0", "zbus-lockstep", "zbus-lockstep-macros", - "zbus_names", - "zvariant", + "zbus_names 4.3.4", + "zvariant 5.15.0", ] [[package]] @@ -716,7 +782,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" dependencies = [ "atspi-common", "serde", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -855,12 +921,33 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bindgen" +version = "0.69.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.11.0", + "lazy_static", + "lazycell", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bindgen" version = "0.72.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" dependencies = [ + "annotate-snippets 0.11.5", "bitflags 2.13.2", "cexpr", "clang-sys", @@ -1045,7 +1132,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" dependencies = [ "once_cell", - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 3.0.7", @@ -1126,6 +1213,31 @@ dependencies = [ "libbz2-rs-sys", ] +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.2", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps 6.2.2", +] + [[package]] name = "calloop" version = "0.14.5" @@ -1134,7 +1246,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", - "rustix", + "rustix 1.1.5", "tracing", ] @@ -1145,7 +1257,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop", - "rustix", + "rustix 1.1.5", "wayland-backend", "wayland-client", ] @@ -1198,6 +1310,12 @@ dependencies = [ "shlex 2.0.1", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cexpr" version = "0.6.0" @@ -1207,6 +1325,26 @@ dependencies = [ "nom 7.1.3", ] +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon 0.12.16", +] + +[[package]] +name = "cfg-expr" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff" +dependencies = [ + "smallvec", + "target-lexicon 0.13.5", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -1283,7 +1421,7 @@ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" dependencies = [ "glob", "libc", - "libloading", + "libloading 0.8.9", ] [[package]] @@ -1326,6 +1464,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + [[package]] name = "cmake" version = "0.1.58" @@ -1547,6 +1694,12 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + [[package]] name = "core-audio-types-rs" version = "0.3.5" @@ -1794,7 +1947,7 @@ dependencies = [ "block2 0.6.2", "coreaudio-rs", "dasp_sample", - "jni", + "jni 0.22.4", "js-sys", "libc", "mach2 0.6.0", @@ -1853,6 +2006,15 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -1897,7 +2059,7 @@ dependencies = [ "document-features", "mio", "parking_lot", - "rustix", + "rustix 1.1.5", "signal-hook", "signal-hook-mio", ] @@ -1974,7 +2136,7 @@ checksum = "625cf4599c43d69a16996ce2573fc80745a0b0300c962f0bfa11d55b6cab2b2d" dependencies = [ "bitflags 2.13.2", "cryptoki-sys", - "libloading", + "libloading 0.8.9", "log", "secrecy", ] @@ -1985,7 +2147,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1fd850498411e4057f1cba79e6e2bc7cbe960544c1046ab46d4685c403a1121" dependencies = [ - "libloading", + "libloading 0.8.9", ] [[package]] @@ -2079,6 +2241,35 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "dbus-secret-service" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" +dependencies = [ + "aes 0.8.4", + "block-padding 0.3.3", + "cbc 0.1.2", + "dbus", + "fastrand", + "hkdf 0.12.4", + "num", + "once_cell", + "sha2 0.10.9", + "zeroize", +] + [[package]] name = "der" version = "0.7.10" @@ -2220,6 +2411,15 @@ dependencies = [ "dirs-sys 0.5.0", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -2279,7 +2479,30 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" dependencies = [ - "libloading", + "libloading 0.8.9", +] + +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -2307,6 +2530,67 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytemuck_derive", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 1.1.5", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.5", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + [[package]] name = "dunce" version = "1.0.5" @@ -2482,6 +2766,27 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enigo" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71c6c56e50f7acae2906a0dcbb34529ca647e40421119ad5d12e7f8ba6e50010" +dependencies = [ + "core-foundation 0.10.1", + "core-graphics 0.25.0", + "foreign-types-shared 0.3.1", + "libc", + "log", + "nom 8.0.0", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "windows 0.61.3", + "x11rb", + "xkbcommon 0.9.0", + "xkeysym", +] + [[package]] name = "enum-iterator" version = "2.3.0" @@ -2502,6 +2807,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "enum-repr" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad30c9c0fa1aaf1ae5010dab11f1117b15d35faf62cda4bbbc53b9987950f18" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -2581,6 +2897,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "etagere" version = "0.2.15" @@ -2695,6 +3017,16 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + [[package]] name = "filedescriptor" version = "0.8.3" @@ -3058,28 +3390,137 @@ dependencies = [ ] [[package]] -name = "generic-array" -version = "0.14.7" +name = "gbm" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" dependencies = [ - "typenum", - "version_check", + "bitflags 2.13.2", + "drm 0.14.1", + "drm-fourcc", + "gbm-sys", + "libc", + "wayland-backend", + "wayland-server", ] [[package]] -name = "gethostname" -version = "1.1.0" +name = "gbm-sys" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" dependencies = [ - "rustix", - "windows-link 0.2.1", + "libc", ] [[package]] -name = "getrandom" -version = "0.2.17" +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.2.2", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps 6.2.2", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps 6.2.2", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps 6.2.2", + "x11", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link 0.2.1", +] + +[[package]] +name = "getrandom" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ @@ -3153,6 +3594,47 @@ version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.2.2", + "winapi", +] + +[[package]] +name = "gl" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404" +dependencies = [ + "gl_generator", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -3164,6 +3646,53 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.0", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps 6.2.2", +] + [[package]] name = "glob" version = "0.3.4" @@ -3215,6 +3744,17 @@ dependencies = [ "gl_generator", ] +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps 6.2.2", +] + [[package]] name = "gpu-allocator" version = "0.28.0" @@ -3257,7 +3797,7 @@ checksum = "3cf698677b253118459f552fe15513858c669d79a25837a94e480db2ae330050" dependencies = [ "aho-corasick", "anyhow", - "ashpd", + "ashpd 0.13.13", "async-channel", "chrono", "data-url", @@ -3340,7 +3880,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2968cc7f4a2bd8f51b09cfe4f1e77409951b48a0e2d48f372b010e69c3d7fb49" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -3370,7 +3910,7 @@ dependencies = [ "async-channel", "async-task", "backtrace", - "bindgen", + "bindgen 0.72.1", "bitflags 2.13.2", "chrono", "core-video", @@ -3514,7 +4054,7 @@ dependencies = [ "accesskit_unix", "anyhow", "as-raw-xcb-connection", - "ashpd", + "ashpd 0.13.13", "bytemuck", "calloop", "calloop-wayland-source", @@ -3544,7 +4084,7 @@ dependencies = [ "wayland-protocols-plasma", "wayland-protocols-wlr", "x11rb", - "xkbcommon", + "xkbcommon 0.8.0", "zed-scap", "zed-xim", ] @@ -3602,7 +4142,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2ad26ca759364694cb55487bebff4c1b7dd6accab49990ff3cda6f7a818a9f4" dependencies = [ "heck 0.5.0", - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -3789,8 +4329,6 @@ dependencies = [ [[package]] name = "gpui-pre-wgpu" version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439c5421cafe1a7cf68d0c0ae5cc82b26fad6b0e6345ac98d20acaf1f2463914" dependencies = [ "anyhow", "bytemuck", @@ -3895,6 +4433,58 @@ dependencies = [ "subtle", ] +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps 6.2.2", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "h2" version = "0.4.20" @@ -4894,6 +5484,22 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + [[package]] name = "jni" version = "0.22.4" @@ -4983,6 +5589,30 @@ dependencies = [ "cpufeatures 0.3.1", ] +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "dbus-secret-service", + "log", + "secret-service", + "windows-sys 0.60.2", + "zeroize", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -4990,7 +5620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" dependencies = [ "libc", - "libloading", + "libloading 0.8.9", "pkg-config", ] @@ -5049,6 +5679,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + [[package]] name = "leak" version = "0.1.2" @@ -5070,6 +5706,30 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading 0.7.4", + "once_cell", +] + [[package]] name = "libbz2-rs-sys" version = "0.2.5" @@ -5082,6 +5742,15 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + [[package]] name = "libfuzzer-sys" version = "0.4.13" @@ -5092,6 +5761,16 @@ dependencies = [ "cc", ] +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + [[package]] name = "libloading" version = "0.8.9" @@ -5117,6 +5796,73 @@ dependencies = [ "libc", ] +[[package]] +name = "libspa" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40" +dependencies = [ + "bitflags 2.13.2", + "cc", + "cookie-factory", + "libc", + "libspa-sys", + "nom 8.0.0", + "rustix 1.1.5", + "system-deps 7.0.8", +] + +[[package]] +name = "libspa-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924" +dependencies = [ + "bindgen 0.72.1", + "cc", + "system-deps 7.0.8", +] + +[[package]] +name = "libwayshot-xcap" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5" +dependencies = [ + "drm 0.15.0", + "gbm", + "gl", + "image", + "khronos-egl", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "libxdo" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00333b8756a3d28e78def82067a377de7fa61b24909000aeaa2b446a948d14db" +dependencies = [ + "libxdo-sys", +] + +[[package]] +name = "libxdo-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db23b9e7e2b7831bbd8aac0bbeeeb7b68cbebc162b227e7052e8e55829a09212" +dependencies = [ + "libc", + "x11", +] + [[package]] name = "libz-sys" version = "1.1.29" @@ -5146,6 +5892,18 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e57c38c1e860fd37c604281cdfb1dd2216977fd76a50f85ba2f388ef3219616" +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -5507,6 +6265,27 @@ dependencies = [ "pxfm", ] +[[package]] +name = "muda" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "libxdo", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "png 0.18.1", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -5577,6 +6356,7 @@ dependencies = [ "log", "ndk-sys", "num_enum", + "raw-window-handle", "thiserror 1.0.69", ] @@ -5601,6 +6381,19 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + [[package]] name = "no_std_io2" version = "0.9.4" @@ -5679,7 +6472,7 @@ dependencies = [ "mac-notification-sys", "serde", "tauri-winrt-notification", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -5864,7 +6657,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -5968,6 +6761,18 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "objc2 0.6.5", + "objc2-core-graphics", + "objc2-core-media", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-avf-audio" version = "0.3.2" @@ -6057,6 +6862,7 @@ checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", "dispatch2", + "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", @@ -6317,7 +7123,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78f2bfed90f1618b4b48dcad9307f25e14ae894e2949642c87c351601d62cebd" dependencies = [ "aes 0.8.4", - "ashpd", + "ashpd 0.13.13", "async-fs", "async-io", "async-lock", @@ -6339,10 +7145,10 @@ dependencies = [ "serde_bytes", "sha2 0.10.9", "subtle", - "zbus", - "zbus_macros", + "zbus 5.19.0", + "zbus_macros 5.19.0", "zeroize", - "zvariant", + "zvariant 5.15.0", ] [[package]] @@ -6355,6 +7161,27 @@ dependencies = [ "libc", ] +[[package]] +name = "openh264" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a30840cd2b2cd6ae39af2544f66adf55357f68e0e4938a096fe0e9f8f412b59" +dependencies = [ + "openh264-sys2", + "wide", +] + +[[package]] +name = "openh264-sys2" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8de206369120cab1be98e587adad1389e2ec00b63c62cdb3c13238000c1290a" +dependencies = [ + "cc", + "nasm-rs", + "walkdir", +] + [[package]] name = "openssl" version = "0.10.81" @@ -6482,6 +7309,55 @@ dependencies = [ "sha2 0.11.0", ] +[[package]] +name = "pam-client" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51bd776116a7ada5ebbe31f54cdc5b1030ed7265686cf7c8a21c057a2f8dab9a" +dependencies = [ + "bitflags 1.3.2", + "enum-repr", + "libc", + "pam-sys", + "rpassword", + "rustversion", +] + +[[package]] +name = "pam-sys" +version = "1.0.0-alpha5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce9484729b3e52c0bacdc5191cb6a6a5f31ef4c09c5e4ab1209d3340ad9e997b" +dependencies = [ + "bindgen 0.69.5", + "libc", +] + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.2.2", +] + [[package]] name = "parking" version = "2.2.1" @@ -6850,6 +7726,31 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pipewire" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c" +dependencies = [ + "bitflags 2.13.2", + "libc", + "libspa", + "libspa-sys", + "pipewire-sys", + "rustix 1.1.5", +] + +[[package]] +name = "pipewire-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0" +dependencies = [ + "bindgen 0.72.1", + "libspa-sys", + "system-deps 7.0.8", +] + [[package]] name = "pkcs1" version = "0.7.5" @@ -6932,7 +7833,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix", + "rustix 1.1.5", "windows-sys 0.61.2", ] @@ -6948,6 +7849,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + [[package]] name = "polycool" version = "0.4.0" @@ -7085,6 +7992,25 @@ dependencies = [ "serdect", ] +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" +dependencies = [ + "toml_edit 0.20.7", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -7094,6 +8020,30 @@ dependencies = [ "toml_edit 0.25.17+spec-1.1.0", ] +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -7653,6 +8603,7 @@ dependencies = [ "ed25519-dalek 2.2.0", "futures", "gpui-component", + "gpui-kit-assets", "gpui-pre", "gpui-pre-platform", "hex", @@ -7738,6 +8689,7 @@ dependencies = [ "ironrdp-bulk", "ironrdp-server", "ironrdp-tokio", + "keyring", "libc", "md-5 0.11.0", "num-bigint 0.5.1", @@ -7765,7 +8717,9 @@ dependencies = [ "tracing", "tracing-subscriber", "url", + "windows-sys 0.61.2", "x509-cert 0.3.0", + "zeroize", ] [[package]] @@ -7794,6 +8748,7 @@ dependencies = [ "tracing", "tracing-subscriber", "url", + "windows-sys 0.61.2", ] [[package]] @@ -7822,11 +8777,13 @@ version = "0.1.12" dependencies = [ "anyhow", "apple-cf", + "bindgen 0.69.5", "core-foundation 0.10.1", "des", "futures", "hex", "libc", + "pam-client", "rand 0.10.3", "removent-automation", "removent-core", @@ -7842,13 +8799,17 @@ dependencies = [ "tokio", "tokio-util", "tracing", + "windows-sys 0.61.2", + "zeroize", ] [[package]] name = "removent-input" version = "0.1.12" dependencies = [ + "arboard", "core-graphics 0.25.0", + "enigo", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", @@ -7856,6 +8817,8 @@ dependencies = [ "removent-proto", "thiserror 2.0.21", "tracing", + "windows-sys 0.61.2", + "xcap", ] [[package]] @@ -7889,12 +8852,15 @@ dependencies = [ "core-foundation 0.10.1", "core-media-rs", "core-video-rs", + "image", "removent-core", + "removent-media-codec", "removent-proto", "screencapturekit 11.0.0", "thiserror 2.0.21", "tokio", "tracing", + "xcap", ] [[package]] @@ -7902,8 +8868,10 @@ name = "removent-media-codec" version = "0.1.12" dependencies = [ "apple-cf", + "image", "metal", "objc", + "openh264", "opus", "rav1e", "removent-proto", @@ -8049,6 +9017,22 @@ dependencies = [ "webpki-roots 1.0.9", ] +[[package]] +name = "removent-tray" +version = "0.1.12" +dependencies = [ + "anyhow", + "gtk", + "image", + "removent-core", + "rust-i18n", + "serde_json", + "tao", + "tokio", + "tray-icon", + "windows-sys 0.61.2", +] + [[package]] name = "removent-updater" version = "0.1.12" @@ -8262,6 +9246,18 @@ dependencies = [ "memchr", ] +[[package]] +name = "rpassword" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf099a1888612545b683d2661a1940089f6c2e5a8e38979b2159da876bfd956" +dependencies = [ + "libc", + "serde", + "serde_json", + "winapi", +] + [[package]] name = "rsa" version = "0.10.0-rc.18" @@ -8439,6 +9435,19 @@ dependencies = [ "nom 7.1.3", ] +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + [[package]] name = "rustix" version = "1.1.5" @@ -8448,7 +9457,7 @@ dependencies = [ "bitflags 2.13.2", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.12.1", "windows-sys 0.61.2", ] @@ -8507,7 +9516,7 @@ checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", - "jni", + "jni 0.22.4", "log", "once_cell", "rustls", @@ -8601,6 +9610,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "safe_arch" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f" +dependencies = [ + "bytemuck", +] + [[package]] name = "same-file" version = "1.0.6" @@ -8720,6 +9738,25 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secret-service" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +dependencies = [ + "aes 0.8.4", + "cbc 0.1.2", + "futures-util", + "generic-array", + "hkdf 0.12.4", + "num", + "once_cell", + "rand 0.8.8", + "serde", + "sha2 0.10.9", + "zbus 4.4.0", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -8775,7 +9812,7 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8050abb251097357e24aff63ba2c52a6309ecb7d23a5474023df960a02694d8" dependencies = [ - "annotate-snippets", + "annotate-snippets 0.12.16", "base64 0.23.1", "encoding_rs_io", "granit-parser", @@ -9639,6 +10676,32 @@ dependencies = [ "libc", ] +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr 0.15.8", + "heck 0.5.0", + "pkg-config", + "toml 0.8.23", + "version-compare", +] + +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr 0.20.11", + "heck 0.5.0", + "pkg-config", + "toml 1.1.8+spec-1.1.0", + "version-compare", +] + [[package]] name = "taffy" version = "0.13.0" @@ -9651,6 +10714,44 @@ dependencies = [ "smallvec", ] +[[package]] +name = "tao" +version = "0.34.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9103edf55f2da3c82aea4c7fab7c4241032bfeea0e71fa557d98e00e7ce7cc20" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "core-foundation 0.10.1", + "core-graphics 0.25.0", + "crossbeam-channel", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni 0.21.1", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "once_cell", + "parking_lot", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows 0.61.3", + "windows-core 0.61.2", + "windows-version", + "x11-dl", +] + [[package]] name = "tao-core-video-sys" version = "0.2.0" @@ -9663,6 +10764,17 @@ dependencies = [ "objc", ] +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tap" version = "1.0.1" @@ -9680,6 +10792,18 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tauri-winrt-notification" version = "0.8.1" @@ -9700,7 +10824,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix", + "rustix 1.1.5", "windows-sys 0.61.2", ] @@ -10031,6 +11155,28 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap", + "toml_datetime 0.6.11", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" +dependencies = [ + "indexmap", + "toml_datetime 0.6.11", + "winnow 0.5.40", +] + [[package]] name = "toml_edit" version = "0.22.27" @@ -10216,6 +11362,27 @@ dependencies = [ "tracing-serde", ] +[[package]] +name = "tray-icon" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" +dependencies = [ + "crossbeam-channel", + "dirs 7.0.0", + "libappindicator", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "once_cell", + "png 0.18.1", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "triomphe" version = "0.1.17" @@ -10539,6 +11706,12 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -10712,7 +11885,7 @@ dependencies = [ "cc", "downcast-rs", "log", - "rustix", + "rustix 1.1.5", "scoped-tls", "smallvec", "wayland-sys", @@ -10725,7 +11898,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix", + "rustix 1.1.5", "wayland-backend", "wayland-scanner", ] @@ -10736,7 +11909,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix", + "rustix 1.1.5", "wayland-client", "xcursor", ] @@ -10790,6 +11963,19 @@ dependencies = [ "quote", ] +[[package]] +name = "wayland-server" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" +dependencies = [ + "bitflags 2.13.2", + "downcast-rs", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + [[package]] name = "wayland-sys" version = "0.31.11" @@ -10797,7 +11983,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "dlib", + "libc", "log", + "memoffset", "once_cell", "pkg-config", ] @@ -10978,7 +12166,7 @@ dependencies = [ "js-sys", "khronos-egl", "libc", - "libloading", + "libloading 0.8.9", "log", "naga", "ndk-sys", @@ -11042,6 +12230,16 @@ dependencies = [ "libc", ] +[[package]] +name = "wide" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f" +dependencies = [ + "bytemuck", + "safe_arch", +] + [[package]] name = "widestring" version = "1.2.1" @@ -11421,6 +12619,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -11439,6 +12646,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.60.2" @@ -11457,6 +12673,21 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + [[package]] name = "windows-targets" version = "0.48.5" @@ -11532,6 +12763,12 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -11550,6 +12787,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -11568,6 +12811,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -11598,6 +12847,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -11616,6 +12871,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -11634,6 +12895,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -11652,6 +12919,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -11670,6 +12943,15 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "0.7.15" @@ -11761,6 +13043,17 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + [[package]] name = "x11rb" version = "0.13.2" @@ -11770,7 +13063,7 @@ dependencies = [ "as-raw-xcb-connection", "gethostname", "libc", - "rustix", + "rustix 1.1.5", "x11rb-protocol", "xcursor", ] @@ -11841,7 +13134,39 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix", + "rustix 1.1.5", +] + +[[package]] +name = "xcap" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e833d39f662982a09608f2550fd4036725f98d78738e40fa7206a26258b06384" +dependencies = [ + "ashpd 0.14.0", + "dispatch2", + "image", + "libwayshot-xcap", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "percent-encoding", + "pipewire", + "pollster 1.0.1", + "rand 0.10.3", + "scopeguard", + "serde", + "thiserror 2.0.21", + "url", + "widestring", + "windows 0.62.2", + "xcb", ] [[package]] @@ -11862,6 +13187,16 @@ version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" +[[package]] +name = "xdg-home" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "xim-ctext" version = "0.3.0" @@ -11892,6 +13227,17 @@ dependencies = [ "xkeysym", ] +[[package]] +name = "xkbcommon" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" +dependencies = [ + "libc", + "memmap2", + "xkeysym", +] + [[package]] name = "xkeysym" version = "0.2.1" @@ -11986,6 +13332,38 @@ dependencies = [ "num-traits", ] +[[package]] +name = "zbus" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +dependencies = [ + "async-broadcast", + "async-process", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix", + "ordered-stream", + "rand 0.8.8", + "serde", + "serde_repr", + "sha1 0.10.7", + "static_assertions", + "tracing", + "uds_windows", + "windows-sys 0.52.0", + "xdg-home", + "zbus_macros 4.4.0", + "zbus_names 3.0.0", + "zvariant 4.2.0", +] + [[package]] name = "zbus" version = "5.19.0" @@ -12008,7 +13386,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix", + "rustix 1.1.5", "serde", "serde_repr", "tracing", @@ -12016,9 +13394,36 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow 1.0.4", - "zbus_macros", - "zbus_names", - "zvariant", + "zbus_macros 5.19.0", + "zbus_names 4.3.4", + "zvariant 5.15.0", +] + +[[package]] +name = "zbus" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros 6.3.0", + "zbus_utils", + "zcheapstr", + "zruntime", ] [[package]] @@ -12028,7 +13433,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" dependencies = [ "zbus_xml", - "zvariant", + "zvariant 5.15.0", ] [[package]] @@ -12042,7 +13447,20 @@ dependencies = [ "syn 2.0.119", "zbus-lockstep", "zbus_xml", - "zvariant", + "zvariant 5.15.0", +] + +[[package]] +name = "zbus_macros" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils 2.1.0", ] [[package]] @@ -12051,13 +13469,36 @@ version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.7", + "zbus_names 4.3.4", + "zvariant 5.15.0", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zbus_macros" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529" +dependencies = [ "proc-macro2", "quote", "syn 3.0.7", - "zbus_names", - "zvariant", - "zvariant_utils", + "zbus_utils", +] + +[[package]] +name = "zbus_names" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +dependencies = [ + "serde", + "static_assertions", + "zvariant 4.2.0", ] [[package]] @@ -12068,7 +13509,20 @@ checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" dependencies = [ "serde", "winnow 1.0.4", - "zvariant", + "zvariant 5.15.0", +] + +[[package]] +name = "zbus_utils" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.7", + "winnow 1.0.4", ] [[package]] @@ -12079,8 +13533,8 @@ checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" dependencies = [ "serde", "winnow 1.0.4", - "zbus_names", - "zvariant", + "zbus_names 4.3.4", + "zvariant 5.15.0", ] [[package]] @@ -12286,6 +13740,19 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zruntime" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72" +dependencies = [ + "futures-core", + "futures-io", + "rustix 1.1.5", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "zune-core" version = "0.4.12" @@ -12325,6 +13792,19 @@ dependencies = [ "zune-core 0.5.3", ] +[[package]] +name = "zvariant" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +dependencies = [ + "endi", + "enumflags2", + "serde", + "static_assertions", + "zvariant_derive 4.2.0", +] + [[package]] name = "zvariant" version = "5.15.0" @@ -12337,8 +13817,21 @@ dependencies = [ "serde_bytes", "winnow 1.0.4", "zcheapstr", - "zvariant_derive", - "zvariant_utils", + "zvariant_derive 5.15.0", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_derive" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils 2.1.0", ] [[package]] @@ -12347,11 +13840,22 @@ version = "5.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 3.0.7", - "zvariant_utils", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_utils" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 0303d2d..940b9e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "apps/mcp", "apps/daemon", "apps/desktop", + "apps/tray-portable", "apps/relay", "packages/client", "packages/automation", @@ -84,6 +85,12 @@ opt-level = 1 [profile.dev.package."*"] opt-level = 3 +# NASM 3.02 crashes on OpenH264's win64 assembly with CodeView debug output +# (`nasm -fwin64 -g .../intra_pred.asm`). Keep optimized assembly enabled while +# omitting only this native dependency's debug information, including in tests. +[profile.dev.package.openh264-sys2] +debug = 0 + [profile.release] lto = "thin" codegen-units = 1 @@ -106,3 +113,6 @@ mdns-sd = { path = "vendor/mdns-sd" } # Chinese punctuation must stay attached when GPUI wraps text. gpui-pre = { path = "vendor/gpui" } gpui-pre-apple = { path = "vendor/gpui-apple" } + +# CPU-only Linux desktops need the validated OpenGL software presentation path. +gpui-pre-wgpu = { path = "vendor/gpui-wgpu" } diff --git a/apps/cli/src/interactive.rs b/apps/cli/src/interactive.rs index 2b48103..47013d2 100644 --- a/apps/cli/src/interactive.rs +++ b/apps/cli/src/interactive.rs @@ -79,7 +79,7 @@ pub(super) async fn run(paths: &DataPaths, verbose: bool) -> anyhow::Result<()> if output::interrupted(&error) { return Err(error); } - output::report(error, verbose); + let _ = output::report(error, verbose); } // Language edits take effect on the next prompt in this process too. if let Ok(current) = settings::load(paths) { diff --git a/apps/daemon/Cargo.toml b/apps/daemon/Cargo.toml index 174a6a3..6307c0a 100644 --- a/apps/daemon/Cargo.toml +++ b/apps/daemon/Cargo.toml @@ -23,9 +23,12 @@ anyhow = { workspace = true } tracing = { workspace = true } serde_json = { workspace = true } rust-i18n = { workspace = true } -core-foundation = { workspace = true } + libc = { workspace = true } [dev-dependencies] removent-proto = { workspace = true } tempfile = "3" + +[target.'cfg(target_os = "macos")'.dependencies] +core-foundation.workspace = true diff --git a/apps/daemon/examples/ipc_smoke.rs b/apps/daemon/examples/ipc_smoke.rs new file mode 100644 index 0000000..59e22f6 --- /dev/null +++ b/apps/daemon/examples/ipc_smoke.rs @@ -0,0 +1,101 @@ +//! Isolated daemon process lifecycle and real OS IPC test. +use removent_core::{ + DataPaths, Settings, + ipc::{self, IpcRequest, IpcResponse}, +}; +use std::time::Duration; +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let root = tempfile::tempdir()?; + let paths = DataPaths { + root: root.path().into(), + }; + paths.ensure_layout()?; + let settings = Settings { + authentication: removent_core::AuthenticationSettings { + mode: removent_core::AuthenticationMode::PairingCode, + ..Default::default() + }, + host_enabled: false, + host_port: 0, + prevent_idle_sleep: false, + ..Default::default() + }; + settings.save(&paths)?; + let binary = std::env::current_exe()? + .parent() + .unwrap() + .parent() + .unwrap() + .join(format!("removentd{}", std::env::consts::EXE_SUFFIX)); + let mut child = std::process::Command::new(binary) + .env("REMOVENT_DATA_DIR", &paths.root) + .spawn()?; + let result = tokio::time::timeout(Duration::from_secs(15), async { + let (mut r, mut w) = loop { + match ipc::connect(&paths).await { + Ok(pair) => break pair, + Err(_) => tokio::time::sleep(Duration::from_millis(100)).await, + } + }; + for request in [ + IpcRequest::Status, + IpcRequest::SetEnabled { on: true }, + IpcRequest::PairingGenerate, + IpcRequest::SetEnabled { on: false }, + IpcRequest::Shutdown, + ] { + ipc::write_msg(&mut w, &request).await?; + loop { + let value: serde_json::Value = ipc::read_msg(&mut r) + .await? + .ok_or_else(|| anyhow::anyhow!("Unexpected IPC EOF"))?; + if let Ok(response) = serde_json::from_value::(value) { + match (&request, response) { + (IpcRequest::Status, IpcResponse::Status(status)) => { + anyhow::ensure!(!status.running, "Unexpected initial sharing state") + } + (IpcRequest::PairingGenerate, IpcResponse::PairingCode { code, .. }) => { + anyhow::ensure!(code.len() == 12, "Invalid pairing invitation") + } + (IpcRequest::SetEnabled { .. } | IpcRequest::Shutdown, IpcResponse::Ok) => { + } + (_, other) => anyhow::bail!("Unexpected response {other:?}"), + } + break; + } + } + } + Ok::<(), anyhow::Error>(()) + }) + .await; + if !matches!(&result, Ok(Ok(()))) { + let _ = child.kill(); + let _ = child.wait(); + result??; + unreachable!(); + } + // Always reap the isolated subprocess, including failed IPC tests. + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while child.try_wait()?.is_none() && std::time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + if child.try_wait()?.is_none() { + let _ = child.kill(); + let _ = child.wait(); + anyhow::bail!("Daemon failed to stop"); + } + result??; + anyhow::ensure!( + child.wait()?.success(), + "Daemon exited with an error after acknowledged shutdown" + ); + anyhow::ensure!( + removent_core::service_intent::is_stopped(&paths)?, + "Stop intent was not persisted" + ); + println!( + "PASS: daemon status, pairing invitation, sharing toggle, shutdown and stop intent over OS IPC" + ); + Ok(()) +} diff --git a/apps/daemon/examples/tray_probe.rs b/apps/daemon/examples/tray_probe.rs new file mode 100644 index 0000000..91d9c6c --- /dev/null +++ b/apps/daemon/examples/tray_probe.rs @@ -0,0 +1,39 @@ +//! Isolated tray QA access to the real management protocol, never a fake daemon. +use removent_core::ipc::{self, IpcRequest, IpcResponse}; +use std::io::Write; +#[tokio::main] +async fn main() -> anyhow::Result<()> { + anyhow::ensure!( + std::env::var("REMOVENT_DESKTOP_TEST").as_deref() == Ok("1"), + "Requires isolated desktop" + ); + let args: Vec<_> = std::env::args().collect(); + let paths = removent_core::DataPaths::resolve(); + tokio::time::timeout(std::time::Duration::from_secs(1200), async { + let (mut r, mut w) = ipc::connect(&paths).await?; + let watch = args.get(1).is_some_and(|s| s == "watch"); + let request: IpcRequest = if watch { + IpcRequest::Status + } else { + serde_json::from_str( + args.get(1) + .ok_or_else(|| anyhow::anyhow!("Expected request JSON or watch"))?, + )? + }; + ipc::write_msg(&mut w, &request).await?; + while let Some(value) = ipc::read_msg::<_, serde_json::Value>(&mut r).await? { + let response = serde_json::from_value::(value.clone()).is_ok(); + if watch || response { + println!("{value}"); + std::io::stdout().flush()?; + if !watch { + return Ok::<_, anyhow::Error>(()); + } + } + } + anyhow::ensure!(watch, "IPC closed without a response"); + Ok(()) + }) + .await??; + Ok(()) +} diff --git a/apps/daemon/src/lib.rs b/apps/daemon/src/lib.rs index 73ad0b4..daf147e 100644 --- a/apps/daemon/src/lib.rs +++ b/apps/daemon/src/lib.rs @@ -9,7 +9,12 @@ rust_i18n::i18n!("locales"); pub mod hostmgr; +#[cfg(target_os = "macos")] pub mod login_window; +#[cfg(target_os = "macos")] +pub mod power; +#[cfg(not(target_os = "macos"))] +#[path = "power_portable.rs"] pub mod power; pub mod server; pub mod state; diff --git a/apps/daemon/src/main.rs b/apps/daemon/src/main.rs index a84c6f1..8ab49eb 100644 --- a/apps/daemon/src/main.rs +++ b/apps/daemon/src/main.rs @@ -1,4 +1,5 @@ //! removentd entry point: data-dir lock + tokio runtime + IPC server + host manager + signal shutdown. +#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] use anyhow::Context; use removent_core::{DataDirLock, DataPaths, Settings, identity, logging}; @@ -9,8 +10,13 @@ use std::sync::Arc; rust_i18n::i18n!("locales"); fn main() -> anyhow::Result<()> { + #[cfg(windows)] + removent_input::initialize_host_dpi(); let login_window = std::env::args().any(|arg| arg == "--login-window"); let paths = if login_window { + #[cfg(not(target_os = "macos"))] + anyhow::bail!("Pre-login hosting is only available on macOS"); + #[cfg(target_os = "macos")] removent_daemon::login_window::paths()? } else { DataPaths::resolve() @@ -26,9 +32,9 @@ fn main() -> anyhow::Result<()> { fn start(paths: DataPaths) -> anyhow::Result<()> { paths.ensure_layout().context(t!("error.init_data_dir"))?; - if std::env::args().any(|arg| matches!(arg.as_str(), "--background" | "--login-window")) - && removent_core::service_intent::is_stopped(&paths)? - { + let background = + std::env::args().any(|arg| matches!(arg.as_str(), "--background" | "--login-window")); + if background && removent_core::service_intent::is_stopped(&paths)? { return Ok(()); } let settings = Settings::load_strict(&paths)?; @@ -48,6 +54,11 @@ fn start(paths: DataPaths) -> anyhow::Result<()> { std::process::exit(1); } }; + // A previous host may have recorded an explicit stop and released its lock + // after our first check. A delayed watchdog child must not undo that stop. + if background && removent_core::service_intent::is_stopped(&paths)? { + return Ok(()); + } // Lifetime receipt that this daemon participates in update admission. The // updater can distinguish an unresponsive new host from a legacy process // whose live sessions do not yet hold the shared maintenance gate. @@ -61,10 +72,15 @@ fn start(paths: DataPaths) -> anyhow::Result<()> { } async fn run(paths: DataPaths) -> anyhow::Result<()> { - let mut settings = Settings::load_strict(&paths)?; - if std::env::args().any(|arg| arg == "--login-window") { - removent_daemon::login_window::restrict(&mut settings); - } + let settings = Settings::load_strict(&paths)?; + #[cfg(target_os = "macos")] + let settings = { + let mut settings = settings; + if std::env::args().any(|arg| arg == "--login-window") { + removent_daemon::login_window::restrict(&mut settings); + } + settings + }; let identity = identity::load_or_create(&paths, &settings.device_name) .context(t!("error.load_identity"))?; let mut state = DaemonState::new(paths, settings, identity.short_fingerprint_hex()); @@ -80,17 +96,29 @@ async fn run(paths: DataPaths) -> anyhow::Result<()> { removent_daemon::tcc::request_initial_permissions(&state); // SIGTERM / SIGINT / IPC Shutdown all trigger graceful shutdown. - let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) - .context(t!("error.register_sigterm"))?; + let terminate = async { + #[cfg(unix)] + { + if let Ok(mut signal) = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + { + signal.recv().await; + } + } + #[cfg(windows)] + std::future::pending::<()>().await; + }; tokio::select! { _ = tokio::signal::ctrl_c() => {}, - _ = sigterm.recv() => {}, + _ = terminate => {}, _ = state.shutdown.cancelled() => {}, result = &mut ipc => { + let expected = state.shutdown.is_cancelled(); state.power.lock().unwrap().set_enabled(false); state.shutdown.cancel(); let _ = mgr.await; result.context("IPC task failed")??; + if expected { return Ok(()); } anyhow::bail!("IPC server stopped unexpectedly"); }, } diff --git a/apps/daemon/src/power_portable.rs b/apps/daemon/src/power_portable.rs new file mode 100644 index 0000000..3b9f1b9 --- /dev/null +++ b/apps/daemon/src/power_portable.rs @@ -0,0 +1,17 @@ +//! Power inhibition is not silently reported as active on unsupported backends. +#[derive(Default)] +pub struct IdleSleepAssertion { + enabled: bool, +} +impl IdleSleepAssertion { + pub fn set_enabled(&mut self, enabled: bool) { + self.enabled = enabled; + } + pub fn is_active(&self) -> bool { + false + } + pub fn error(&self) -> Option<&str> { + self.enabled + .then_some("Idle sleep prevention is not available on this platform") + } +} diff --git a/apps/daemon/src/server.rs b/apps/daemon/src/server.rs index 51e7c30..4eb6781 100644 --- a/apps/daemon/src/server.rs +++ b/apps/daemon/src/server.rs @@ -7,13 +7,15 @@ use removent_core::ipc::{IpcRequest, IpcResponse, read_msg, write_msg}; use rust_i18n::t; use std::sync::Arc; use std::sync::atomic::Ordering; -use tokio::net::{UnixListener, UnixStream}; +#[cfg(unix)] +use tokio::net::UnixListener; use tokio::sync::broadcast; use crate::state::DaemonState; /// Listen on and serve IPC connections until the shutdown token is cancelled; /// removes the socket file on exit. +#[cfg(unix)] pub async fn serve(state: Arc) -> anyhow::Result<()> { let sock = state.paths.daemon_socket(); // A previous abnormal exit may have left a stale socket behind. @@ -52,9 +54,12 @@ pub async fn serve(state: Arc) -> anyhow::Result<()> { Ok(()) } -async fn handle_conn(state: Arc, stream: UnixStream) { +async fn handle_conn( + state: Arc, + stream: S, +) { state.tray_connections.fetch_add(1, Ordering::SeqCst); - let (r, w) = stream.into_split(); + let (r, w) = tokio::io::split(stream); let mut r = tokio::io::BufReader::new(r); let w = Arc::new(tokio::sync::Mutex::new(w)); @@ -405,3 +410,19 @@ mod invitation_tests { )); } } + +#[cfg(windows)] +pub async fn serve(state: Arc) -> anyhow::Result<()> { + let mut pending = removent_core::ipc::windows::server(&state.paths, true)?; + loop { + tokio::select! { + _ = state.shutdown.cancelled() => return Ok(()), + result = pending.connect() => { + result?; + let next = removent_core::ipc::windows::server(&state.paths, false)?; + let stream = std::mem::replace(&mut pending, next); + tokio::spawn(handle_conn(state.clone(), stream)); + } + } + } +} diff --git a/apps/daemon/src/state.rs b/apps/daemon/src/state.rs index 84964ed..3742e06 100644 --- a/apps/daemon/src/state.rs +++ b/apps/daemon/src/state.rs @@ -139,6 +139,7 @@ impl DaemonState { let mut settings = self.settings.lock().unwrap(); let mut next = Settings::update(&self.paths, |s| s.host_enabled = on)?; if self.login_window { + #[cfg(target_os = "macos")] crate::login_window::restrict(&mut next); } self.apply_settings(&mut settings, next); @@ -155,6 +156,7 @@ impl DaemonState { .validate() .map_err(removent_core::CoreError::Serialization)?; if self.login_window { + #[cfg(target_os = "macos")] crate::login_window::restrict(&mut next); } self.apply_settings(&mut current, next); diff --git a/apps/daemon/src/tcc.rs b/apps/daemon/src/tcc.rs index 22f57eb..bd41df6 100644 --- a/apps/daemon/src/tcc.rs +++ b/apps/daemon/src/tcc.rs @@ -245,23 +245,19 @@ unsafe extern "C" { static kAXTrustedCheckOptionPrompt: core_foundation::string::CFStringRef; } -// The daemon is macOS-only in practice; stubs keep the lib compiling elsewhere. #[cfg(not(target_os = "macos"))] pub fn screen_recording_granted() -> bool { - true + !removent_input::display_list().is_empty() } - #[cfg(not(target_os = "macos"))] pub fn accessibility_granted() -> bool { - true + removent_input::accessibility_trusted() } - #[cfg(not(target_os = "macos"))] pub fn request_screen_recording() -> bool { - true + screen_recording_granted() } - #[cfg(not(target_os = "macos"))] pub fn request_accessibility() -> bool { - true + accessibility_granted() } diff --git a/apps/daemon/tests/ipc.rs b/apps/daemon/tests/ipc.rs index 64c8c8f..fc271f6 100644 --- a/apps/daemon/tests/ipc.rs +++ b/apps/daemon/tests/ipc.rs @@ -1,11 +1,16 @@ -//! UDS IPC integration tests: status / set_enabled / admission reply and timeout. +//! Native IPC integration tests: status / set_enabled / admission reply and timeout. use removent_core::ipc::{IpcEvent, IpcRequest, IpcResponse, connect, read_msg, write_msg}; use removent_core::{DataPaths, Settings}; use removent_daemon::{server, state::DaemonState}; use std::sync::Arc; use std::time::Duration; +#[cfg(unix)] use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf}; +#[cfg(windows)] +type OwnedReadHalf = tokio::io::ReadHalf; +#[cfg(windows)] +type OwnedWriteHalf = tokio::io::WriteHalf; struct TestDaemon { state: Arc, @@ -48,13 +53,6 @@ async fn spawn_daemon_with(admission_timeout: Option) -> TestDaemon { server::serve(st).await.unwrap(); } }); - // Wait for the socket to appear before connecting, avoiding a startup race. - for _ in 0..100 { - if paths.daemon_socket().exists() { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } TestDaemon { state, paths, @@ -70,8 +68,13 @@ struct Client { impl Client { async fn connect(paths: &DataPaths) -> Self { - let (r, w) = connect(paths).await.unwrap(); - Self { r, w } + for _ in 0..100 { + if let Ok((r, w)) = connect(paths).await { + return Self { r, w }; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("Native IPC server did not become available"); } async fn request(&mut self, req: IpcRequest) -> IpcResponse { @@ -267,6 +270,7 @@ async fn admission_reply_resolves() { } #[tokio::test] +#[cfg(target_os = "macos")] async fn power_policy_applies_over_ipc_without_restarting_active_sharing() { let d = spawn_daemon_with(None).await; let mut host_changes = d.state.enabled_watch.subscribe(); diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index 2927f71..cf678f8 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -20,6 +20,7 @@ removent-client = { workspace = true } gpui = { package = "gpui-pre", version = "0.3" } gpui-platform = { package = "gpui-pre-platform", version = "0.3", features = ["font-kit", "wayland", "x11"] } gpui-component = "0.7" +gpui-kit-assets = "0.7" image = "0.25" chrono = { version = "0.4", default-features = false, features = ["clock"] } qrcode = { version = "0.14.1", default-features = false } @@ -36,12 +37,14 @@ tokio = { workspace = true } futures = { workspace = true } anyhow = { workspace = true } tracing = { workspace = true } -core-foundation = { workspace = true } cpal = { workspace = true } -core-video = { version = "0.5.2", features = ["metal"] } [dev-dependencies] tempfile = "3" gpui = { package = "gpui-pre", version = "0.3", features = ["test-support"] } gpui-platform = { package = "gpui-pre-platform", version = "0.3", features = ["test-support"] } removent-media-codec = { workspace = true } + +[target.'cfg(target_os = "macos")'.dependencies] +core-foundation = { workspace = true } +core-video = { version = "0.5.2", features = ["metal"] } diff --git a/apps/desktop/locales/en.yml b/apps/desktop/locales/en.yml index 4450169..68d0c50 100644 --- a/apps/desktop/locales/en.yml +++ b/apps/desktop/locales/en.yml @@ -92,7 +92,7 @@ device.address: Address device.fingerprint: Fingerprint device.trust: Trust -sharing.title: Share this Mac +sharing.title: Share this computer sharing.enabled: Sharing on sharing.disabled: Sharing off device.copy_fingerprint: Copy fingerprint @@ -129,7 +129,7 @@ settings.vnc_enabled: Enable VNC compatibility service settings.tcp_port: "TCP port" settings.vnc_password: VNC Password settings.vnc_password_placeholder: "Optional" -settings.vnc_hint: This password is for sharing this Mac over VNC (port 5900). Enter remote credentials in Add connection. +settings.vnc_hint: This password is for sharing this computer over VNC (port 5900). Enter remote credentials in Add connection. settings.data: Data settings.data_dir: Data Directory @@ -245,7 +245,7 @@ viewer.close_window: Close Window device.section: "Devices" device.nearby: "LAN discovery" -device.this_mac: "This Mac" +device.this_mac: "This computer" saved.section: "Saved" action.more: "More actions" saved.empty: "No saved connections" @@ -276,24 +276,24 @@ permissions.granted: "Allowed" settings.subtitle: "Make your connections and workspace feel at home." settings.sharing: "Sharing" settings.system: "System" -settings.general_description: "Make this Mac easy to find on your network." +settings.general_description: "Make this computer easy to find on your network." settings.device_name_hint: "The name other Removent devices see on your network." settings.language_hint: "Choose your interface language. Changes apply immediately." settings.appearance_description: "A comfortable view of your workspace." settings.color_mode: "Color mode" -settings.theme_hint: "Follow macOS or choose a light or dark appearance." +settings.theme_hint: "Follow the system or choose a light or dark appearance." settings.preview_hint: "Current appearance preview" -settings.security_description: "Decide which devices can access this Mac." +settings.security_description: "Decide which devices can access this computer." settings.admission_hint: "Applies to connections using the Removent protocol." -settings.admission.ask_hint: "Approve each connection on this Mac. Recommended for most setups." +settings.admission.ask_hint: "Approve each connection on this computer. Recommended for most setups." settings.admission.trusted_hint: "Paired devices connect automatically. New devices still need approval." settings.admission.deny_hint: "Reject all new Removent connection requests." -settings.sharing_description: "Share this Mac with compatible clients." -settings.sharing_scope_hint: "This switch controls the VNC server on this Mac. To connect to another Mac, choose VNC in Add Connection. Restart sharing after changing these settings." +settings.sharing_description: "Share this computer with compatible clients." +settings.sharing_scope_hint: "This switch controls the VNC server on this computer. To connect to another computer, choose VNC in Add Connection. Restart sharing after changing these settings." settings.system_description: "Local data, diagnostics, and application updates." -settings.data_hint: "Settings, device identity, and diagnostic logs stay on this Mac." +settings.data_hint: "Settings, device identity, and diagnostic logs stay on this computer." connection.subtitle: "Choose the connection available on your remote device." -connection.removent_hint: "Fast Mac-to-Mac connections · Secure pairing" +connection.removent_hint: "Fast desktop connections with secure pairing" connection.vnc_hint: "macOS Screen Sharing · Standard VNC servers" connection.rdp_hint: "Windows Remote Desktop · RDP servers" connection.credentials_hint: "For macOS Screen Sharing, enter the remote Mac’s short account name and login password. Leave the username empty only when using a dedicated VNC password." @@ -325,7 +325,7 @@ connection.vnc_auth_failed: "VNC authentication failed. Check the remote Mac acc connection.vnc_refused: "The remote device refused the VNC connection. Check that Screen Sharing is enabled and the port is correct." settings.logs: "Local diagnostics" -settings.logs_hint: "Connection stages, errors, and crash reports are saved on this Mac. Logs rotate automatically; passwords, pairing PINs, and clipboard contents are excluded." +settings.logs_hint: "Connection stages, errors, and crash reports are saved on this computer. Logs rotate automatically; passwords, pairing PINs, and clipboard contents are excluded." settings.open_logs: "Open Logs Folder" settings.open_logs_failed: "Could not open the logs folder: %{err}" @@ -347,7 +347,7 @@ connection.relay_quic: "VPS / QUIC" settings.discovery: LAN discovery settings.discovery_description: Choose which protocols appear in Nearby. Changes apply immediately. -settings.discovery_hint: Uses Bonjour/mDNS service broadcasts without scanning ports. Unadvertised devices can be added manually. Sharing this Mac is controlled separately. +settings.discovery_hint: Uses Bonjour/mDNS service broadcasts without scanning ports. Unadvertised devices can be added manually. Sharing this computer is controlled separately. device.protocol: Protocol device.discovery_off: LAN discovery is off @@ -404,9 +404,9 @@ auth.connect: "Connect" auth.saved_credentials_failed: "The saved credentials were rejected. Open this connection's edit form, update the username or password, and try again." auth.credentials_destination_changed: "The destination changed. Reopen the edit form before updating credentials." auth.saved_credentials_invalid: "Enter valid credentials, or turn off credential storage before saving." -auth.keychain_edit_failed: "Cannot read saved credentials. Check Keychain permissions and reopen the edit form." +auth.keychain_edit_failed: "Cannot read saved credentials. Check the system credential store permissions and reopen the edit form." auth.keychain_loading: "Loading saved credentials…" -auth.saved_credentials_hint: "Credentials are stored in Keychain and used automatically. Save to apply changes, or turn off the switch and save to remove them." +auth.saved_credentials_hint: "Credentials are stored in the system credential store and used automatically. Save to apply changes, or turn off the switch and save to remove them." auth.otp_setup: "Authenticator setup" auth.otp_setup_hint: "Six-digit codes refresh every 30 seconds and can be used only once." auth.copy_secret: "Copy setup secret" @@ -469,8 +469,8 @@ auth.otp_manual_label: "Enter a setup key" auth.otp_manual_hint: "If you cannot scan, copy the key into your authenticator." auth.system: "System account" -auth.system_desc: "Enter the username and login password of the account running Removent on the remote Mac." -auth.system_hint: "Verifies the account running the sharing service with macOS. Its login password is never stored in Removent." +auth.system_desc: "Enter the username and login password of the account running Removent on the remote computer." +auth.system_hint: "Use the username and login password of the account running the sharing service. The remote operating system verifies it; the sharing service does not store the login password." auth.system_username: "System username" auth.system_password: "Login password" @@ -480,9 +480,9 @@ connection.quality_standard: "Standard" connection.quality_high: "High (2K)" connection.quality_ultra: "Ultra (4K)" -auth.remember_credentials: "Remember credentials in Keychain" -auth.keychain_read_failed: "Cannot read Keychain. Enter your credentials again." -auth.keychain_save_failed: "Connected, but could not update Keychain credentials. Check Keychain access." +auth.remember_credentials: "Remember credentials in the system credential store" +auth.keychain_read_failed: "Cannot read the system credential store. Enter your credentials again." +auth.keychain_save_failed: "Connected, but could not update saved credentials. Check access to the system credential store." connection.native_unreachable: "Cannot reach Removent at %{address}. Enable Removent sharing on the host and check UDP port %{port}." update.err.installing: An update is being installed. Try connecting again shortly. @@ -491,3 +491,7 @@ update.auto_install: Install updates automatically update.auto_install_hint: When automatic checks are enabled, updates install after you close the main window and connections end. Updates requiring administrator approval or new permissions wait for you. update.background_attention: "Background update needs attention. Open Software Update or resolve the issue below:" +permissions.portable_capture: Screen capture +permissions.portable_input: Remote input +permissions.unavailable: Unavailable +permissions.desktop_session_hint: Run the background service in your signed-in desktop session. Linux hosting requires X11. diff --git a/apps/desktop/locales/zh-CN.yml b/apps/desktop/locales/zh-CN.yml index 5fa06e3..8f4c738 100644 --- a/apps/desktop/locales/zh-CN.yml +++ b/apps/desktop/locales/zh-CN.yml @@ -281,19 +281,19 @@ settings.device_name_hint: "其他 Removent 设备看到的本机名称。" settings.language_hint: "选择应用界面使用的语言,即时生效。" settings.appearance_description: "为你的工作空间选择舒适的外观。" settings.color_mode: "主题模式" -settings.theme_hint: "跟随 macOS,或固定使用深色、浅色主题。" +settings.theme_hint: "跟随系统,或固定使用深色、浅色主题。" settings.preview_hint: "当前主题预览" settings.security_description: "由你决定哪些设备可以接入本机。" settings.admission_hint: "应用于 Removent 原生协议的远程连接。" settings.admission.ask_hint: "每次连接都需要你在本机确认,适合大多数场景。" settings.admission.trusted_hint: "已配对的可信设备可直接接入;新设备仍需确认。" settings.admission.deny_hint: "拒绝所有新的 Removent 连接请求。" -settings.sharing_description: "通过兼容协议共享这台 Mac。" -settings.sharing_scope_hint: "此开关仅控制本机的 VNC 服务。连接其他 Mac 无需开启;请在「添加连接」中选择 VNC。修改后需重启被控服务。" +settings.sharing_description: "通过兼容协议共享本机。" +settings.sharing_scope_hint: "此开关仅控制本机的 VNC 服务。连接其他电脑无需开启;请在「添加连接」中选择 VNC。修改后需重启被控服务。" settings.system_description: "管理本地数据、诊断日志与应用更新。" settings.data_hint: "设置、设备身份与诊断日志保存在本机。" connection.subtitle: "选择远端设备使用的连接方式。" -connection.removent_hint: "Mac 之间的高速连接,支持安全配对" +connection.removent_hint: "电脑之间的高速连接,支持安全配对" connection.vnc_hint: "macOS 屏幕共享或标准 VNC 服务" connection.rdp_hint: "Windows 远程桌面(RDP)" connection.credentials_hint: "连接 macOS 屏幕共享时,请填写远端 Mac 的账户短名称与登录密码。仅使用 VNC 专用密码时,用户名留空。" @@ -404,9 +404,9 @@ auth.connect: "连接" auth.saved_credentials_failed: "已保存的凭据认证失败,请打开此连接的编辑表单更新用户名或密码后重试。" auth.credentials_destination_changed: "连接目标已变更,请重新打开编辑表单后修改凭据。" auth.saved_credentials_invalid: "请输入有效的用户名和密码,或关闭凭据存储后保存。" -auth.keychain_edit_failed: "无法读取已保存的凭据,请检查钥匙串权限后重新打开编辑表单。" +auth.keychain_edit_failed: "无法读取已保存的凭据,请检查系统凭据库权限后重新打开编辑表单。" auth.keychain_loading: "正在读取已保存的凭据…" -auth.saved_credentials_hint: "凭据存于 Keychain,连接时自动使用。修改后点击保存,关闭开关后保存可移除凭据。" +auth.saved_credentials_hint: "凭据存于系统凭据库,连接时自动使用。修改后点击保存,关闭开关后保存可移除凭据。" auth.otp_setup: "绑定验证器" auth.otp_setup_hint: "验证码为六位,每 30 秒更新,每个验证码仅可使用一次。" auth.copy_secret: "复制绑定密钥" @@ -469,8 +469,8 @@ auth.otp_manual_label: "手动绑定" auth.otp_manual_hint: "无法扫码时,可复制密钥到验证器中手动添加。" auth.system: "系统账户" -auth.system_desc: "输入远程 Mac 上运行 Removent 的系统用户名和登录密码。" -auth.system_hint: "由 macOS 验证运行共享服务的账户,系统登录密码不会保存在 Removent 中。" +auth.system_desc: "输入远程电脑上运行 Removent 的系统用户名和登录密码。" +auth.system_hint: "使用运行共享服务的系统账户及登录密码,由远端操作系统验证。共享服务不保存系统登录密码。" auth.system_username: "系统用户名" auth.system_password: "登录密码" @@ -480,9 +480,9 @@ connection.quality_standard: "标准" connection.quality_high: "高(2K)" connection.quality_ultra: "超高(4K)" -auth.remember_credentials: "记忆凭据并存入 Keychain" -auth.keychain_read_failed: "无法读取 Keychain,请重新输入凭据" -auth.keychain_save_failed: "连接已建立,但无法更新 Keychain 凭据,请检查钥匙串权限" +auth.remember_credentials: "记住凭据并存入系统凭据库" +auth.keychain_read_failed: "无法读取系统凭据库,请重新输入凭据" +auth.keychain_save_failed: "连接已建立,但无法更新系统凭据库中的凭据,请检查系统凭据库权限" connection.native_unreachable: "无法连接 Removent 服务(%{address})。请在远端开启 Removent 共享,并检查 UDP %{port} 是否可达" update.err.installing: 正在安装更新,请稍后重新连接。 @@ -491,3 +491,7 @@ update.auto_install: 自动安装更新 update.auto_install_hint: 开启自动检查后,关闭主窗口且连接结束时自动安装。需要管理员授权或新权限的更新会等待手动处理。 update.background_attention: "后台更新需要处理,请检查以下原因后重试:" +permissions.portable_capture: 屏幕采集 +permissions.portable_input: 远程输入 +permissions.unavailable: 不可用 +permissions.desktop_session_hint: 请在已登录的桌面会话中运行后台服务。Linux 被控端需要 X11 桌面。 diff --git a/apps/desktop/src/assets.rs b/apps/desktop/src/assets.rs index 1e3813c..91016ee 100644 --- a/apps/desktop/src/assets.rs +++ b/apps/desktop/src/assets.rs @@ -50,17 +50,48 @@ pub struct Assets; impl AssetSource for Assets { fn load(&self, path: &str) -> gpui::Result>> { - Ok(ICONS + let local = ICONS .iter() .find(|(p, _)| *p == path) - .map(|(_, svg)| Cow::Borrowed(svg.as_bytes()))) + .map(|(_, svg)| Cow::Borrowed(svg.as_bytes())); + if local.is_some() { + Ok(local) + } else { + // Components also request their own icons, including the Windows + // caption buttons, which are not used by the macOS title bar. + gpui_kit_assets::Assets.load(path) + } } fn list(&self, path: &str) -> gpui::Result> { - Ok(ICONS - .iter() - .filter(|(p, _)| p.starts_with(path)) - .map(|(p, _)| SharedString::from(*p)) - .collect()) + let mut paths = gpui_kit_assets::Assets.list(path)?; + paths.extend( + ICONS + .iter() + .filter(|(p, _)| p.starts_with(path)) + .map(|(p, _)| SharedString::from(*p)), + ); + paths.sort(); + paths.dedup(); + Ok(paths) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn component_window_controls_have_embedded_icons() { + use gpui_component::{IconName, IconNamed}; + for icon in [ + IconName::WindowMinimize, + IconName::WindowMaximize, + IconName::WindowRestore, + IconName::WindowClose, + ] { + let data = Assets.load(&icon.path()).unwrap().unwrap(); + assert!(std::str::from_utf8(&data).unwrap().contains(" bool { - cfg!(target_os = "macos") - && matches!( - mode, - AuthenticationMode::SystemAccount | AuthenticationMode::Password - ) + cfg!(any( + target_os = "macos", + target_os = "windows", + target_os = "linux" + )) && matches!( + mode, + AuthenticationMode::SystemAccount | AuthenticationMode::Password + ) } fn account(local: &str, host: [u8; 32], mode: AuthenticationMode) -> Option { @@ -98,9 +101,11 @@ fn prompt_with_loader( } Ok(Ok(_)) => None, _ => { - let _ = attempt - .events - .send(UiEvent::Notice(t!("auth.keychain_read_failed").to_string())); + if !pin_tx.is_closed() { + let _ = attempt.events.send(UiEvent::Notice( + t!("auth.keychain_read_failed").to_string(), + )); + } None } } @@ -110,7 +115,7 @@ fn prompt_with_loader( } else { None }; - // If the connection was cancelled during a Keychain read, do not open a dialog. + // If the connection was cancelled during a credential read, do not open a dialog. if pin_tx.is_closed() { return; } @@ -148,7 +153,7 @@ fn prompt_with_loader( answer.remember &= can_remember(mode); let value = answer.value.clone(); // Record before waking the handshake. Failed/cancelled handshakes - // drop this in-memory value without changing Keychain. + // drop this in-memory value without changing the credential store. if can_remember(mode) { *pending.lock().unwrap() = Some(PendingAuthentication { mode, answer, reused: false }); } diff --git a/apps/desktop/src/engine/credentials/saved.rs b/apps/desktop/src/engine/credentials/saved.rs index 844f8c3..145da22 100644 --- a/apps/desktop/src/engine/credentials/saved.rs +++ b/apps/desktop/src/engine/credentials/saved.rs @@ -1,6 +1,6 @@ use super::*; -/// A local Keychain snapshot. The scope cannot be changed by the form. +/// A local credential-store snapshot. The scope cannot be changed by the form. #[derive(Clone, Debug)] pub struct NativeCredential { local: String, @@ -16,7 +16,7 @@ pub struct NativeCredentialEdit { } impl Engine { - // Called on a background executor: DNS, file locks and Keychain can block. + // Called on a background executor: DNS, file locks and the credential store can block. fn native_credential_host(&self, request: &ConnectionRequest) -> Result> { if request.protocol != ConnectionProtocol::Removent || request.pairing_code.is_some() { return Ok(None); diff --git a/apps/desktop/src/engine/credentials/tests.rs b/apps/desktop/src/engine/credentials/tests.rs index 792c707..da2b546 100644 --- a/apps/desktop/src/engine/credentials/tests.rs +++ b/apps/desktop/src/engine/credentials/tests.rs @@ -1,8 +1,15 @@ use super::*; -#[cfg(target_os = "macos")] use std::time::Duration; -#[cfg(target_os = "macos")] +struct Cleanup(Vec); +impl Drop for Cleanup { + fn drop(&mut self) { + for key in &self.0 { + let _ = keychain::delete(key); + } + } +} + fn test_attempt() -> (ClientAttempt, std::sync::mpsc::Receiver) { let (events, rx) = std::sync::mpsc::channel(); ( @@ -18,7 +25,6 @@ fn test_attempt() -> (ClientAttempt, std::sync::mpsc::Receiver) { ) } -#[cfg(target_os = "macos")] #[tokio::test] async fn saved_credentials_connect_without_a_dialog_and_are_not_rewritten() { for mode in [ @@ -83,14 +89,13 @@ async fn saved_credentials_connect_without_a_dialog_and_are_not_rewritten() { .commit_with( "local", [1; 32], - |_, _| panic!("reuse must not overwrite Keychain"), - |_| panic!("reuse must not delete Keychain"), + |_, _| panic!("reuse must not overwrite credential store"), + |_| panic!("reuse must not delete credential store"), ) .unwrap(); } } -#[cfg(target_os = "macos")] #[tokio::test] async fn missing_invalid_untrusted_and_temporary_credentials_still_require_input() { for (mode, host, stored, should_load) in [ @@ -150,44 +155,93 @@ async fn missing_invalid_untrusted_and_temporary_credentials_still_require_input } } -#[cfg(target_os = "macos")] #[tokio::test] -async fn cancelling_a_keychain_read_never_opens_a_dialog_or_submits_a_credential() { +async fn cancelling_a_credential_read_never_opens_a_dialog_or_submits_a_credential() { + for fail in [false, true] { + let (attempt, events) = test_attempt(); + let pending: Pending = Default::default(); + let (tx, rx) = tokio::sync::oneshot::channel(); + let (reading, started) = tokio::sync::oneshot::channel(); + let (release, blocked) = std::sync::mpsc::channel(); + prompt_with_loader( + attempt, + "local".into(), + Some([1; 32]), + pending.clone(), + move |_| { + reading.send(()).unwrap(); + blocked.recv().unwrap(); + if fail { + Err(removent_core::CoreError::SecureStore("denied".into())) + } else { + Ok(Some("test-password".into())) + } + }, + )(AuthenticationMode::Password, tx); + started.await.unwrap(); + drop(rx); + release.send(()).unwrap(); + // The prompt task drops its event sender on completion. + tokio::time::timeout(Duration::from_secs(2), async { + loop { + match events.try_recv() { + Err(std::sync::mpsc::TryRecvError::Disconnected) => break, + Err(std::sync::mpsc::TryRecvError::Empty) => tokio::task::yield_now().await, + Ok(_) => panic!("cancelled read must not publish UI events"), + } + } + }) + .await + .unwrap(); + assert!(pending.lock().unwrap().is_none()); + } +} + +#[tokio::test] +async fn unavailable_store_prompts_without_leaking_backend_details() { let (attempt, events) = test_attempt(); let pending: Pending = Default::default(); - let (tx, rx) = tokio::sync::oneshot::channel(); - let (reading, started) = tokio::sync::oneshot::channel(); - let (release, blocked) = std::sync::mpsc::channel(); + let (tx, mut rx) = tokio::sync::oneshot::channel(); prompt_with_loader( attempt, "local".into(), Some([1; 32]), pending.clone(), - move |_| { - reading.send(()).unwrap(); - blocked.recv().unwrap(); - Ok(Some("test-password".into())) + |_| { + Err(removent_core::CoreError::SecureStore( + "private-backend-detail".into(), + )) }, - )(AuthenticationMode::Password, tx); - started.await.unwrap(); - drop(rx); - release.send(()).unwrap(); - // The prompt task drops its event sender on completion. - tokio::time::timeout(Duration::from_secs(2), async { + )(AuthenticationMode::SystemAccount, tx); + let mut notice = false; + let answer = tokio::time::timeout(Duration::from_secs(2), async { loop { match events.try_recv() { - Err(std::sync::mpsc::TryRecvError::Disconnected) => break, - Err(std::sync::mpsc::TryRecvError::Empty) => tokio::task::yield_now().await, - Ok(_) => panic!("cancelled read must not publish UI events"), + Ok(UiEvent::Notice(message)) => { + assert_eq!(message, t!("auth.keychain_read_failed")); + assert!(!message.contains("private-backend-detail")); + notice = true; + } + Ok(UiEvent::ClientNeedsPin { mode, tx, .. }) => { + assert_eq!(mode, AuthenticationMode::SystemAccount); + break tx; + } + _ => tokio::task::yield_now().await, } } }) .await .unwrap(); + assert!(notice); assert!(pending.lock().unwrap().is_none()); + assert_eq!( + rx.try_recv(), + Err(tokio::sync::oneshot::error::TryRecvError::Empty) + ); + drop(answer); + assert!(rx.await.is_err()); } -#[cfg(target_os = "macos")] #[tokio::test] async fn prompting_keeps_credentials_in_memory_until_success_and_cancellation_discards_them() { for cancel in [false, true] { @@ -248,17 +302,22 @@ async fn prompting_keeps_credentials_in_memory_until_success_and_cancellation_di } } -#[cfg(target_os = "macos")] #[tokio::test] -#[ignore = "uses an isolated synthetic item in the real login Keychain"] -async fn native_credentials_round_trip_in_keychain() { - let local = format!("qa-{}", std::process::id()); +#[ignore = "uses an isolated synthetic item in the real OS credential store"] +async fn native_credentials_round_trip_in_system_store() { + let directory = tempfile::tempdir().unwrap(); + let local = format!( + "qa-{}", + directory.path().file_name().unwrap().to_string_lossy() + ); + let mut cleanup = Cleanup(Vec::new()); let host = [71; 32]; for mode in [ AuthenticationMode::Password, AuthenticationMode::SystemAccount, ] { let key = account(&local, host, mode).unwrap(); + cleanup.0.push(key.clone()); let value = if mode == AuthenticationMode::SystemAccount { removent_proto::SystemCredentials { username: "qa-owner".into(), @@ -298,6 +357,8 @@ async fn native_credentials_round_trip_in_keychain() { #[test] fn credentials_are_isolated_by_local_host_and_method_and_debug_is_redacted() { + assert!(can_remember(AuthenticationMode::SystemAccount)); + assert!(can_remember(AuthenticationMode::Password)); let key = account("local", [1; 32], AuthenticationMode::Password).unwrap(); assert_ne!( Some(key.clone()), @@ -368,18 +429,9 @@ fn successful_authentication_stores_or_forgets_only_the_selected_method() { } } -#[cfg(target_os = "macos")] #[test] -#[ignore = "uses isolated synthetic items in the real login Keychain"] +#[ignore = "uses isolated synthetic items in the real OS credential store"] fn edited_credentials_are_used_on_the_next_connection_and_can_be_removed() { - struct Cleanup(Vec); - impl Drop for Cleanup { - fn drop(&mut self) { - for key in &self.0 { - let _ = keychain::delete(key); - } - } - } let dir = tempfile::tempdir().unwrap(); let paths = DataPaths { root: dir.path().into(), diff --git a/apps/desktop/src/engine/daemon.rs b/apps/desktop/src/engine/daemon.rs index 6ffc1a4..9530f0a 100644 --- a/apps/desktop/src/engine/daemon.rs +++ b/apps/desktop/src/engine/daemon.rs @@ -99,14 +99,22 @@ impl Engine { if let Ok(exe) = std::env::current_exe() && let Some(dir) = exe.parent() { - let candidate = dir.join("removentd"); + let candidate = dir.join(if cfg!(windows) { + "removentd.exe" + } else { + "removentd" + }); if candidate.is_file() { return Some(candidate); } } std::env::var_os("PATH").and_then(|paths| { std::env::split_paths(&paths).find_map(|dir| { - let candidate = dir.join("removentd"); + let candidate = dir.join(if cfg!(windows) { + "removentd.exe" + } else { + "removentd" + }); candidate.is_file().then_some(candidate) }) }) @@ -161,7 +169,12 @@ impl Engine { // Take a snapshot right after connecting. let _ = removent_core::ipc::write_msg(&mut w, &IpcRequest::Status).await; let mut reader = removent_core::ipc::MessageReader::default(); - let mut tick = tokio::time::interval(std::time::Duration::from_secs(3)); + // The snapshot above is already the first poll. An + // immediate interval tick sends a duplicate request and + // can race the final response of a departing daemon. + let period = std::time::Duration::from_secs(3); + let mut tick = + tokio::time::interval_at(tokio::time::Instant::now() + period, period); tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { tokio::select! { diff --git a/apps/desktop/src/engine/mod.rs b/apps/desktop/src/engine/mod.rs index 664cde7..9a8015e 100644 --- a/apps/desktop/src/engine/mod.rs +++ b/apps/desktop/src/engine/mod.rs @@ -120,6 +120,7 @@ pub enum UiEvent { }, /// Auto-update state machine snapshot (release.md §3; apps/desktop/src/updater.rs). UpdateStatus(UpdateStatus), + #[cfg(target_os = "macos")] BackgroundUpdateChanged, PairedConnections { generation: usize, @@ -360,7 +361,7 @@ pub struct Engine { startup: Arc>, /// Auto-update shared state (status + manifest + staged bundle). update: Arc>, - background_update: Arc>>, + background_update: Arc>>, /// Live controlled-side sessions (daemon IpcEvent SessionStarted/Ended, /// reconciled against StatusReport.sessions on every poll); /// an update install is deferred while any session runs. @@ -430,6 +431,7 @@ impl Engine { if !std::env::args().any(|arg| arg == "--update-smoke") { engine.spawn_daemon_link(); engine.spawn_update_scheduler(); + #[cfg(target_os = "macos")] engine.spawn_background_update_status(); crate::cloud_sync::start(&engine); } diff --git a/apps/desktop/src/engine/native.rs b/apps/desktop/src/engine/native.rs index f1c8b81..162c822 100644 --- a/apps/desktop/src/engine/native.rs +++ b/apps/desktop/src/engine/native.rs @@ -210,10 +210,10 @@ pub(super) async fn run_client( let submitted_auth = pending_auth.lock().unwrap().take(); if let Some(submitted) = submitted_auth { let events = attempt.events.clone(); - // A locked Keychain must not delay frame/audio forwarding. + // A locked credential store must not delay frame/audio forwarding. tokio::spawn(async move { if let Err(error) = submitted.commit(local_identity, peer_pin).await { - tracing::warn!(%error, "could not update native host credentials in Keychain"); + tracing::warn!(%error, "could not update native host credentials in the system store"); let _ = events.send(UiEvent::Notice(t!("auth.keychain_save_failed").to_string())); } }); diff --git a/apps/desktop/src/engine/preferences.rs b/apps/desktop/src/engine/preferences.rs index a0f3f77..702f99f 100644 --- a/apps/desktop/src/engine/preferences.rs +++ b/apps/desktop/src/engine/preferences.rs @@ -136,10 +136,11 @@ impl Engine { client_live || self.host_sessions.load(Ordering::SeqCst) > 0 } - pub fn background_update_status(&self) -> Option { + pub fn background_update_status(&self) -> Option { self.background_update.lock().unwrap().clone() } + #[cfg(target_os = "macos")] pub(super) fn spawn_background_update_status(&self) { let paths = self.paths.clone(); let shared = self.background_update.clone(); diff --git a/apps/desktop/src/engine/tests.rs b/apps/desktop/src/engine/tests.rs index 374259c..b5de9cd 100644 --- a/apps/desktop/src/engine/tests.rs +++ b/apps/desktop/src/engine/tests.rs @@ -1,5 +1,56 @@ use super::*; +#[cfg(unix)] +#[test] +fn daemon_link_waits_between_initial_snapshot_and_periodic_poll() { + let directory = tempfile::tempdir_in("/tmp").unwrap(); + let paths = DataPaths { + root: directory.path().to_owned(), + }; + paths.ensure_layout().unwrap(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let listener = runtime + .block_on(async { tokio::net::UnixListener::bind(paths.daemon_socket()) }) + .unwrap(); + let engine = Engine::with_state(runtime, paths, Settings::default()); + let server = engine.rt.spawn(async move { + let (socket, _) = listener.accept().await.unwrap(); + let (reader, _writer) = socket.into_split(); + let mut reader = tokio::io::BufReader::new(reader); + let request: IpcRequest = removent_core::ipc::read_msg(&mut reader) + .await + .unwrap() + .unwrap(); + assert!(matches!(request, IpcRequest::Status)); + let mut messages = removent_core::ipc::MessageReader::default(); + assert!( + tokio::time::timeout( + std::time::Duration::from_millis(250), + messages.read::<_, IpcRequest>(&mut reader), + ) + .await + .is_err(), + "the initial snapshot must not be followed by a duplicate immediate poll" + ); + let request = tokio::time::timeout( + std::time::Duration::from_secs(5), + messages.read::<_, IpcRequest>(&mut reader), + ) + .await + .expect("periodic status polling must continue") + .unwrap() + .unwrap(); + assert!(matches!(request, IpcRequest::Status)); + }); + engine.spawn_daemon_link(); + engine.rt.block_on(server).unwrap(); +} + +#[cfg(unix)] #[test] fn daemon_restart_republishes_unchanged_permissions_and_then_live_changes() { let directory = tempfile::tempdir_in("/tmp").unwrap(); @@ -62,10 +113,9 @@ fn daemon_restart_republishes_unchanged_permissions_and_then_live_changes() { let mut grants = Vec::new(); while grants.len() < 3 { let remaining = deadline.saturating_duration_since(std::time::Instant::now()); - match receiver - .recv_timeout(remaining) - .expect("daemon link must refresh grants after each restart") - { + match receiver.recv_timeout(remaining).unwrap_or_else(|err| { + panic!("daemon link must refresh grants after each restart: {err}; observed {grants:?}") + }) { UiEvent::DaemonPermissions { screen_recording, accessibility, diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 0c5e16e..8080740 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -1,4 +1,5 @@ //! Removent app entry: GPUI interface + tokio engine bridge. +#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] mod assets; mod audio; @@ -33,7 +34,17 @@ fn main() -> Result<()> { fn run(paths: DataPaths) -> Result<()> { let started = std::time::Instant::now(); - let smoke = std::env::args().any(|arg| arg == "--update-smoke"); + let visible_smoke = std::env::args().any(|arg| arg == "--desktop-smoke"); + let smoke = visible_smoke || std::env::args().any(|arg| arg == "--update-smoke"); + #[cfg(any(windows, target_os = "linux"))] + let instance = if smoke { + None + } else { + match removent_core::desktop_instance::DesktopInstance::claim(&paths)? { + Some(instance) => Some(instance), + None => return Ok(()), + } + }; // Main-window lifetime is an idle-update boundary. Closing it leaves the // host running and releases this lease for the independent installer. let _activity = removent_core::update_gate::ActivityLease::acquire(&paths)?; @@ -96,26 +107,88 @@ fn run(paths: DataPaths) -> Result<()> { cx.bind_keys([ KeyBinding::new("tab", ConnectionTab, Some("ConnectionDialog")), KeyBinding::new("shift-tab", ConnectionTabPrev, Some("ConnectionDialog")), - KeyBinding::new("ctrl-cmd-escape", ViewerEscape, Some("Viewer")), - KeyBinding::new("ctrl-cmd-f", ViewerToggleFullscreen, Some("Viewer")), - KeyBinding::new("ctrl-cmd-i", ViewerToggleInfo, Some("Viewer")), + KeyBinding::new( + if cfg!(target_os = "macos") { + "ctrl-cmd-escape" + } else { + "ctrl-alt-escape" + }, + ViewerEscape, + Some("Viewer"), + ), + KeyBinding::new( + if cfg!(target_os = "macos") { + "ctrl-cmd-f" + } else { + "ctrl-alt-f" + }, + ViewerToggleFullscreen, + Some("Viewer"), + ), + KeyBinding::new( + if cfg!(target_os = "macos") { + "ctrl-cmd-i" + } else { + "ctrl-alt-i" + }, + ViewerToggleInfo, + Some("Viewer"), + ), KeyBinding::new("escape", HomeEscape, Some("Home")), - KeyBinding::new("cmd-,", HomeSettings, Some("Home")), - KeyBinding::new("cmd-l", HomeConnect, Some("Home")), - KeyBinding::new("cmd-f", HomeSearch, Some("Home")), + KeyBinding::new( + if cfg!(target_os = "macos") { + "cmd-," + } else { + "ctrl-," + }, + HomeSettings, + Some("Home"), + ), + KeyBinding::new( + if cfg!(target_os = "macos") { + "cmd-l" + } else { + "ctrl-l" + }, + HomeConnect, + Some("Home"), + ), + KeyBinding::new( + if cfg!(target_os = "macos") { + "cmd-f" + } else { + "ctrl-f" + }, + HomeSearch, + Some("Home"), + ), ]); + // Keep caption controls and the footer on small desktop displays. + let window_size = cx.primary_display().map_or( + gpui::size(gpui::px(1040.), gpui::px(700.)), + |display| { + let screen = display.bounds().size; + gpui::size( + (screen.width - gpui::px(48.)).clamp(gpui::px(860.), gpui::px(1040.)), + (screen.height - gpui::px(112.)).clamp(gpui::px(600.), gpui::px(700.)), + ) + }, + ); let home_window = cx .open_window( gpui::WindowOptions { - focus: !smoke, - show: !smoke, + focus: !smoke || visible_smoke, + show: !smoke || visible_smoke, window_bounds: Some(gpui::WindowBounds::Windowed(gpui::Bounds::centered( None, - gpui::size(gpui::px(1040.), gpui::px(700.)), + window_size, cx, ))), - titlebar: Some(TitleBar::title_bar_options()), + titlebar: Some(gpui::TitlebarOptions { + title: Some("Removent".into()), + ..TitleBar::title_bar_options() + }), window_min_size: Some(gpui::size(gpui::px(860.), gpui::px(600.))), window_background: gpui::WindowBackgroundAppearance::Opaque, ..Default::default() @@ -157,6 +230,27 @@ fn run(paths: DataPaths) -> Result<()> { }, ) .expect("open home window"); + #[cfg(any(windows, target_os = "linux"))] + if let Some(instance) = instance { + cx.spawn(async move |cx| { + loop { + cx.background_executor() + .timer(std::time::Duration::from_millis(150)) + .await; + if instance.take_activation() + && home_window + .update(cx, |_, window, cx| { + window.activate_window(); + cx.activate(true); + }) + .is_err() + { + break; + } + } + }) + .detach(); + } // The menu bar app and hosting daemon are independent processes. // Leaving this process alive without its home window makes Dock/tray // activation a no-op, because the event receiver belongs to that view. @@ -185,6 +279,7 @@ fn run(paths: DataPaths) -> Result<()> { /// The tray is an independent process: the main app exiting does not take it down; only the /// user can quit it explicitly from the tray menu. Not launched again when already running. /// `REMOVENT_NO_TRAY=1` disables this (escape hatch for automated tests). +#[cfg(target_os = "macos")] fn autostart_tray(paths: DataPaths) { if std::env::var("REMOVENT_NO_TRAY").as_deref() == Ok("1") { return; @@ -282,3 +377,27 @@ fn autostart_tray(paths: DataPaths) { } tracing::warn!("RemoventTray not found; tray not started"); } + +#[cfg(not(target_os = "macos"))] +fn autostart_tray(paths: DataPaths) { + if std::env::var("REMOVENT_NO_TRAY").as_deref() == Ok("1") { + return; + } + let Ok(exe) = std::env::current_exe() else { + return; + }; + let Some(dir) = exe.parent() else { return }; + let result = std::process::Command::new( + dir.join(format!("removent-tray{}", std::env::consts::EXE_SUFFIX)), + ) + .env("REMOVENT_DATA_DIR", paths.root) + .spawn(); + match result { + Ok(mut child) => { + std::thread::spawn(move || { + let _ = child.wait(); + }); + } + Err(error) => tracing::warn!(%error,"Could not launch tray"), + } +} diff --git a/apps/desktop/src/permissions.rs b/apps/desktop/src/permissions.rs index fea2442..bff76b1 100644 --- a/apps/desktop/src/permissions.rs +++ b/apps/desktop/src/permissions.rs @@ -7,6 +7,9 @@ pub enum PermissionKind { } pub fn setup_hint(grants: Option<(bool, bool)>) -> String { + if !cfg!(target_os = "macos") { + return rust_i18n::t!("permissions.desktop_session_hint").to_string(); + } match grants { Some((true, false)) => rust_i18n::t!("permissions.accessibility_setup_hint").to_string(), Some((false, true)) => rust_i18n::t!("permissions.screen_capture_setup_hint").to_string(), @@ -31,6 +34,12 @@ impl PermissionKind { } pub fn title(&self) -> String { + if !cfg!(target_os = "macos") { + return match self { + Self::ScreenCapture => rust_i18n::t!("permissions.portable_capture").to_string(), + Self::Accessibility => rust_i18n::t!("permissions.portable_input").to_string(), + }; + } match self { Self::ScreenCapture => rust_i18n::t!("permissions.screen_capture").to_string(), Self::Accessibility => rust_i18n::t!("permissions.accessibility").to_string(), diff --git a/apps/desktop/src/ui/home/details.rs b/apps/desktop/src/ui/home/details.rs index 49c9020..e8b4420 100644 --- a/apps/desktop/src/ui/home/details.rs +++ b/apps/desktop/src/ui/home/details.rs @@ -36,7 +36,7 @@ impl HomeView { .child(icon_16("check").text_color(colors.muted_foreground)), ) }) - .when(granted == Some(false), |el| { + .when(granted == Some(false) && cfg!(target_os = "macos"), |el| { el.child( div() .debug_selector(move || format!("permission-settings-{}", kind.slug())) @@ -59,6 +59,14 @@ impl HomeView { ), ) }) + .when(granted == Some(false) && !cfg!(target_os = "macos"), |el| { + el.child( + div() + .text_size(px(12.)) + .text_color(colors.warning) + .child(t!("permissions.unavailable").to_string()), + ) + }) .when(granted.is_none(), |el| { el.child( div() diff --git a/apps/desktop/src/ui/home/events.rs b/apps/desktop/src/ui/home/events.rs index b76fb59..3697285 100644 --- a/apps/desktop/src/ui/home/events.rs +++ b/apps/desktop/src/ui/home/events.rs @@ -394,6 +394,7 @@ impl HomeView { } => { self.daemon_perms = Some((screen_recording, accessibility)); } + #[cfg(target_os = "macos")] UiEvent::BackgroundUpdateChanged => {} UiEvent::UpdateStatus(st) => { // Events are wakeups: a channel switch may already have diff --git a/apps/desktop/src/ui/home/settings.rs b/apps/desktop/src/ui/home/settings.rs index b040b66..66e2889 100644 --- a/apps/desktop/src/ui/home/settings.rs +++ b/apps/desktop/src/ui/home/settings.rs @@ -28,6 +28,9 @@ impl HomeView { (6, "cloud", "sync.title"), (4, "info", "settings.system"), ] { + if index == 6 && !cfg!(target_os = "macos") { + continue; + } let item = Button::new(("settings-tab", index)) .icon(icon_16(name)) .label(t!(key).to_string()) diff --git a/apps/desktop/src/ui/home/tests/authentication.rs b/apps/desktop/src/ui/home/tests/authentication.rs index 6131c67..d07f0e9 100644 --- a/apps/desktop/src/ui/home/tests/authentication.rs +++ b/apps/desktop/src/ui/home/tests/authentication.rs @@ -1,6 +1,5 @@ use super::*; -#[cfg(target_os = "macos")] #[gpui::test] fn manual_credentials_can_be_remembered_without_leaking_between_modes(cx: &mut TestAppContext) { cx.update(gpui_component::init); diff --git a/apps/desktop/src/ui/viewer/keys.rs b/apps/desktop/src/ui/viewer/keys.rs index 626fb3b..aa13b38 100644 --- a/apps/desktop/src/ui/viewer/keys.rs +++ b/apps/desktop/src/ui/viewer/keys.rs @@ -4,7 +4,11 @@ use super::*; /// the remote application. Suppress both key-down and key-up forwarding. pub(super) fn is_viewer_shortcut(key: &Keystroke) -> bool { key.modifiers.control - && key.modifiers.platform + && if cfg!(target_os = "macos") { + key.modifiers.platform + } else { + key.modifiers.alt + } && matches!(key.key.as_str(), "escape" | "f" | "i") } diff --git a/apps/desktop/src/ui/viewer/lifecycle.rs b/apps/desktop/src/ui/viewer/lifecycle.rs index 3fd2308..e3a9bff 100644 --- a/apps/desktop/src/ui/viewer/lifecycle.rs +++ b/apps/desktop/src/ui/viewer/lifecycle.rs @@ -175,10 +175,14 @@ impl ViewerView { if frame.width == 0 || frame.height == 0 { return; } + #[cfg(target_os = "macos")] use core_foundation::base::TCFType; + #[cfg(target_os = "macos")] let surface = frame.surface.map(|buffer| unsafe { core_video::pixel_buffer::CVPixelBuffer::wrap_under_get_rule(buffer.as_ptr().cast()) }); + #[cfg(not(target_os = "macos"))] + let surface: Option<()> = None; let next = if surface.is_none() { let Some(buf) = image::RgbaImage::from_raw(frame.width, frame.height, frame.data) else { @@ -188,7 +192,10 @@ impl ViewerView { } else { None }; - self.surface = surface; + #[cfg(target_os = "macos")] + { + self.surface = surface; + } self.surface_pts = frame.pts_us; { let epoch = self.recovery.connection_epoch(); diff --git a/apps/desktop/src/ui/viewer/mod.rs b/apps/desktop/src/ui/viewer/mod.rs index fa59412..90d025c 100644 --- a/apps/desktop/src/ui/viewer/mod.rs +++ b/apps/desktop/src/ui/viewer/mod.rs @@ -45,7 +45,10 @@ pub struct ViewerView { engine: Engine, session_generation: usize, current: Option>, + #[cfg(target_os = "macos")] surface: Option, + #[cfg(not(target_os = "macos"))] + surface: Option<()>, surface_pts: i64, presentation: Arc, width: u32, diff --git a/apps/desktop/src/ui/viewer/render.rs b/apps/desktop/src/ui/viewer/render.rs index 0cfe677..8e7a80a 100644 --- a/apps/desktop/src/ui/viewer/render.rs +++ b/apps/desktop/src/ui/viewer/render.rs @@ -200,6 +200,7 @@ impl Render for ViewerView { .min_w_0() .overflow_hidden() .child(match (self.surface.clone(), self.current.clone()) { + #[cfg(target_os = "macos")] (Some(surface), _) => { let telemetry = self.presentation.clone(); let pts = self.surface_pts; @@ -227,7 +228,7 @@ impl Render for ViewerView { .size_full() .into_any_element() } - (None, Some(image)) => gpui::canvas( + (_, Some(image)) => gpui::canvas( move |bounds, _, _| canvas_bounds.set(Some(bounds)), move |bounds, _, window, _| { // Img's intrinsic aspect ratio can expand its percentage @@ -249,7 +250,7 @@ impl Render for ViewerView { .absolute() .size_full() .into_any_element(), - (None, None) => div() + (_, None) => div() .size_full() .flex() .items_center() diff --git a/apps/desktop/src/updater/mod.rs b/apps/desktop/src/updater/mod.rs index 3e9ae2e..ff54322 100644 --- a/apps/desktop/src/updater/mod.rs +++ b/apps/desktop/src/updater/mod.rs @@ -1,7 +1,7 @@ //! Desktop event bridge. Download, validation and recovery live outside the UI. use crate::engine::UiEvent; use removent_core::DataPaths; -pub use removent_updater::{UpdatePolicy, UpdateShared, UpdateStatus, refresh_stale_tray}; +pub use removent_updater::{UpdatePolicy, UpdateShared, UpdateStatus}; use std::sync::{Arc, Mutex, mpsc::Sender}; fn forward(events: Sender, action: impl FnOnce(Sender)) { @@ -38,3 +38,6 @@ pub fn run_install( removent_updater::run_install(generation, shared, tx, paths) }); } + +#[cfg(target_os = "macos")] +pub use removent_updater::refresh_stale_tray; diff --git a/apps/tray-portable/Cargo.toml b/apps/tray-portable/Cargo.toml new file mode 100644 index 0000000..41b8d90 --- /dev/null +++ b/apps/tray-portable/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "removent-tray" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "removent-tray" +path = "src/main.rs" + +[target.'cfg(any(windows, target_os = "linux"))'.dependencies] +removent-core.workspace = true +serde_json.workspace = true +tokio.workspace = true +anyhow.workspace = true +rust-i18n.workspace = true +tray-icon = "0.25" +tao = "0.34" +image = { version = "0.25", default-features = false, features = ["png"] } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_System_Threading"] } +[target.'cfg(target_os = "linux")'.dependencies] +gtk = "0.18" diff --git a/apps/tray-portable/build.rs b/apps/tray-portable/build.rs new file mode 100644 index 0000000..62285c5 --- /dev/null +++ b/apps/tray-portable/build.rs @@ -0,0 +1,3 @@ +fn main() { + println!("cargo:rerun-if-changed=locales"); +} diff --git a/apps/tray-portable/locales/en.yml b/apps/tray-portable/locales/en.yml new file mode 100644 index 0000000..bc66a9f --- /dev/null +++ b/apps/tray-portable/locales/en.yml @@ -0,0 +1,14 @@ +_version: 1 +tray.connecting: Connecting to background service +tray.offline: Background service offline +tray.open: Open Removent +tray.share: Share this desktop +tray.start: Start background service +tray.pair: Show pairing code +tray.stop: Stop background service +tray.quit: Quit tray +tray.sharing: Sharing +tray.stopped: Sharing stopped +tray.status: "%{state} (%{count})" +dialog.pairing: Pairing code +dialog.admission: Remote access request diff --git a/apps/tray-portable/locales/zh-CN.yml b/apps/tray-portable/locales/zh-CN.yml new file mode 100644 index 0000000..b8c9845 --- /dev/null +++ b/apps/tray-portable/locales/zh-CN.yml @@ -0,0 +1,14 @@ +_version: 1 +tray.connecting: 正在连接后台服务 +tray.offline: 后台服务未连接 +tray.open: 打开 Removent +tray.share: 共享本机 +tray.start: 启动后台服务 +tray.pair: 显示配对码 +tray.stop: 停止后台服务 +tray.quit: 退出托盘 +tray.sharing: 正在共享 +tray.stopped: 共享已停止 +tray.status: "%{state} (%{count})" +dialog.pairing: 配对码 +dialog.admission: 远程访问请求 diff --git a/apps/tray-portable/src/dialogs.rs b/apps/tray-portable/src/dialogs.rs new file mode 100644 index 0000000..6e92118 --- /dev/null +++ b/apps/tray-portable/src/dialogs.rs @@ -0,0 +1,162 @@ +//! Nonblocking native dialogs. Polling the tray must continue while one is visible. +#[cfg(target_os = "linux")] +pub struct Dialog { + window: gtk::MessageDialog, + answer: std::rc::Rc>>, +} +#[cfg(target_os = "linux")] +impl Dialog { + pub fn new(title: &str, text: &str, question: bool) -> Self { + use gtk::prelude::*; + let window = gtk::MessageDialog::new( + None::<>k::Window>, + gtk::DialogFlags::empty(), + if question { + gtk::MessageType::Question + } else { + gtk::MessageType::Info + }, + if question { + gtk::ButtonsType::YesNo + } else { + gtk::ButtonsType::Ok + }, + text, + ); + window.set_title(title); + window.set_width_request(300); + window.set_default_response(if question { + gtk::ResponseType::No + } else { + gtk::ResponseType::Ok + }); + let answer = std::rc::Rc::new(std::cell::Cell::new(None)); + let result = answer.clone(); + window.connect_response(move |window, response| { + if result.get().is_none() { + result.set(Some(response == gtk::ResponseType::Yes)); + } + // close() emits another DeleteEvent response and would overwrite + // an affirmative answer. Hide now; release the window after poll. + window.hide(); + }); + window.show_all(); + window.present(); + Self { window, answer } + } + pub fn poll(&self) -> Option { + self.answer.get() + } + pub fn close(&self) { + use gtk::prelude::*; + self.window.response(gtk::ResponseType::No); + } +} +#[cfg(target_os = "linux")] +impl Drop for Dialog { + fn drop(&mut self) { + use gtk::prelude::*; + self.window.close(); + } +} + +#[cfg(windows)] +pub struct Dialog { + thread: std::sync::Arc, + answer: std::sync::mpsc::Receiver, + cancelled: std::cell::Cell, + question: bool, +} +#[cfg(windows)] +impl Dialog { + pub fn new(title: &str, text: &str, question: bool) -> Self { + use std::sync::{ + Arc, + atomic::{AtomicU32, Ordering}, + mpsc, + }; + use windows_sys::Win32::{ + System::Threading::GetCurrentThreadId, UI::WindowsAndMessaging::*, + }; + let thread = Arc::new(AtomicU32::new(0)); + let id = thread.clone(); + let (send, answer) = mpsc::channel(); + let wide = |text: &str| { + text.replace('\0', "") + .encode_utf16() + .chain(Some(0)) + .collect::>() + }; + let title = wide(title); + let text = wide(text); + std::thread::spawn(move || { + id.store(unsafe { GetCurrentThreadId() }, Ordering::Release); + let buttons = if question { + MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION + } else { + MB_OK | MB_ICONINFORMATION + }; + let answer = unsafe { + MessageBoxW( + std::ptr::null_mut(), + text.as_ptr(), + title.as_ptr(), + buttons | MB_SETFOREGROUND, + ) + }; + id.store(0, Ordering::Release); + let _ = send.send(answer == IDYES); + }); + Self { + thread, + answer, + cancelled: std::cell::Cell::new(false), + question, + } + } + pub fn poll(&self) -> Option { + if self.cancelled.get() { + self.close(); + } + match self.answer.try_recv() { + Ok(answer) => Some(answer), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(false), + Err(_) => None, + } + } + pub fn close(&self) { + use windows_sys::Win32::{ + Foundation::{HWND, LPARAM}, + UI::WindowsAndMessaging::*, + }; + unsafe extern "system" fn dismiss(window: HWND, button: LPARAM) -> windows_sys::core::BOOL { + unsafe { + let mut process = 0; + GetWindowThreadProcessId(window, &mut process); + if process == windows_sys::Win32::System::Threading::GetCurrentProcessId() { + PostMessageW(window, WM_COMMAND, button as usize, 0); + } + } + 1 + } + self.cancelled.set(true); + let thread = self.thread.load(std::sync::atomic::Ordering::Acquire); + if thread != 0 { + // Enumerate only this dialog's private worker thread. Repeating on + // each poll also closes a window created just after cancellation. + unsafe { + EnumThreadWindows( + thread, + Some(dismiss), + if self.question { IDNO } else { IDOK } as isize, + ); + } + } + } +} +#[cfg(windows)] +impl Drop for Dialog { + fn drop(&mut self) { + self.close(); + } +} diff --git a/apps/tray-portable/src/main.rs b/apps/tray-portable/src/main.rs new file mode 100644 index 0000000..ac9e23a --- /dev/null +++ b/apps/tray-portable/src/main.rs @@ -0,0 +1,17 @@ +#![cfg_attr(windows, windows_subsystem = "windows")] +#[cfg(any(windows, target_os = "linux"))] +rust_i18n::i18n!("locales"); +#[cfg(any(windows, target_os = "linux"))] +mod dialogs; +#[cfg(any(windows, target_os = "linux"))] +mod prompts; +#[cfg(any(windows, target_os = "linux"))] +mod tray; +#[cfg(any(windows, target_os = "linux"))] +fn main() -> anyhow::Result<()> { + tray::run() +} +#[cfg(not(any(windows, target_os = "linux")))] +fn main() { + eprintln!("macOS uses the Swift RemoventTray helper"); +} diff --git a/apps/tray-portable/src/prompts.rs b/apps/tray-portable/src/prompts.rs new file mode 100644 index 0000000..b96dc9e --- /dev/null +++ b/apps/tray-portable/src/prompts.rs @@ -0,0 +1,152 @@ +//! Keep native dialogs responsive to daemon resolution, cancellation and disconnects. +use crate::dialogs::Dialog; +use removent_core::ipc::IpcRequest; +use std::{ + collections::VecDeque, + time::{Duration, Instant}, +}; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Admission(u64), + Pairing, + Alert, +} +struct Pending { + kind: Kind, + title: String, + text: String, + ready: Instant, + expires: Instant, +} +struct Active { + pending: Pending, + dialog: Dialog, + cancelled: bool, +} +#[derive(Default)] +pub struct Prompts { + queue: VecDeque, + active: Option, + pairing: Option, +} +impl Prompts { + pub fn admission( + &mut self, + id: u64, + name: &str, + fingerprint: &str, + title: &str, + desktop_open: bool, + ) { + if self.queue.iter().any(|p| p.kind == Kind::Admission(id)) + || self + .active + .as_ref() + .is_some_and(|p| p.pending.kind == Kind::Admission(id)) + { + return; + } + let now = Instant::now(); + // Match the desktop-first policy of the macOS tray. The daemon remains + // the authority for the 30-second timeout and for competing answers. + self.enqueue(Pending { + kind: Kind::Admission(id), + title: title.into(), + text: format!("{name}\n{fingerprint}"), + ready: now + Duration::from_secs(if desktop_open { 8 } else { 0 }), + expires: now + Duration::from_secs(30), + }); + } + pub fn resolved(&mut self, id: u64) { + self.cancel(Kind::Admission(id)); + } + pub fn pairing(&mut self, code: String, title: &str) { + if self.pairing.as_ref() == Some(&code) { + return; + } + self.cancel(Kind::Pairing); + self.pairing = Some(code.clone()); + let now = Instant::now(); + self.enqueue(Pending { + kind: Kind::Pairing, + title: title.into(), + text: code, + ready: now, + expires: now + Duration::from_secs(300), + }); + } + pub fn reset_pairing(&mut self) { + self.pairing = None; + self.cancel(Kind::Pairing); + } + pub fn alert(&mut self, text: String) { + if self.queue.iter().any(|p| p.text == text) + || self.active.as_ref().is_some_and(|p| p.pending.text == text) + { + return; + } + let now = Instant::now(); + self.enqueue(Pending { + kind: Kind::Alert, + title: "Removent".into(), + text, + ready: now, + expires: now + Duration::from_secs(300), + }); + } + fn enqueue(&mut self, pending: Pending) { + // A remote peer cannot create an unbounded native-dialog backlog. + if self.queue.len() < 16 { + self.queue.push_back(pending); + } + } + fn cancel(&mut self, kind: Kind) { + self.queue.retain(|p| p.kind != kind); + if let Some(active) = self.active.as_mut().filter(|p| p.pending.kind == kind) { + active.cancelled = true; + active.dialog.close(); + } + } + pub fn disconnected(&mut self) { + self.queue.clear(); + self.pairing = None; + if let Some(active) = &mut self.active { + active.cancelled = true; + active.dialog.close(); + } + } + pub fn poll(&mut self, send: &tokio::sync::mpsc::UnboundedSender) { + let now = Instant::now(); + self.queue.retain(|p| p.expires > now); + if let Some(active) = &mut self.active { + if active.pending.expires <= now { + active.cancelled = true; + active.dialog.close(); + } + if let Some(allow) = active.dialog.poll() { + if !active.cancelled + && let Kind::Admission(request_id) = active.pending.kind + { + let _ = send.send(IpcRequest::AdmissionReply { request_id, allow }); + } + self.active = None; + } + } + if self.active.is_none() + && let Some(index) = self.queue.iter().position(|p| p.ready <= now) + { + let pending = self.queue.remove(index).unwrap(); + let dialog = Dialog::new( + &pending.title, + &pending.text, + matches!(pending.kind, Kind::Admission(_)), + ); + self.active = Some(Active { + pending, + dialog, + cancelled: false, + }); + } + } +} diff --git a/apps/tray-portable/src/tray.rs b/apps/tray-portable/src/tray.rs new file mode 100644 index 0000000..1ff9a75 --- /dev/null +++ b/apps/tray-portable/src/tray.rs @@ -0,0 +1,249 @@ +use removent_core::{ + DataDirLock, DataPaths, + ipc::{IpcEvent, IpcRequest, IpcResponse, write_msg}, +}; +use rust_i18n::t; +use std::{ + sync::mpsc, + time::{Duration, Instant}, +}; +use tao::{ + event::Event, + event_loop::{ControlFlow, EventLoopBuilder}, +}; +use tray_icon::{ + TrayIconBuilder, + menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem}, +}; + +fn sibling(name: &str) -> anyhow::Result { + let exe = std::env::current_exe()?; + Ok(exe + .parent() + .ok_or_else(|| anyhow::anyhow!("No executable directory"))? + .join(format!("{name}{}", std::env::consts::EXE_SUFFIX))) +} +fn launch(name: &str, paths: &DataPaths) -> anyhow::Result<()> { + let mut command = std::process::Command::new(sibling(name)?); + if name == "removentd" { + command.arg("--background"); + } + let mut child = command + .env("REMOVENT_DATA_DIR", &paths.root) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn()?; + std::thread::spawn(move || { + let _ = child.wait(); + }); + Ok(()) +} + +pub fn run() -> anyhow::Result<()> { + if std::env::args().any(|a| a == "--version") { + println!("RemoventTray {}", removent_core::APP_VERSION); + return Ok(()); + } + let paths = DataPaths::resolve(); + paths.ensure_layout()?; + let _lock = match DataDirLock::acquire_at(&paths.run_dir().join("tray.lock")) { + Ok(lock) => lock, + Err(removent_core::CoreError::AlreadyRunning) => return Ok(()), + Err(e) => return Err(e.into()), + }; + let settings = removent_core::Settings::load_strict(&paths)?; + rust_i18n::set_locale(removent_core::resolve_locale(settings.language)); + let event_loop = EventLoopBuilder::<()>::with_user_event().build(); + let wake = event_loop.create_proxy(); + // Tray-only processes have no windows; drive IPC/menu updates explicitly. + std::thread::spawn(move || { + loop { + std::thread::sleep(Duration::from_millis(150)); + if wake.send_event(()).is_err() { + break; + } + } + }); + let menu = Menu::new(); + let status = MenuItem::new(t!("tray.connecting"), false, None); + let open = MenuItem::new(t!("tray.open"), true, None); + let sharing = CheckMenuItem::new(t!("tray.share"), false, false, None); + let start = MenuItem::new(t!("tray.start"), true, None); + let pair = MenuItem::new(t!("tray.pair"), false, None); + let stop = MenuItem::new(t!("tray.stop"), false, None); + let quit = MenuItem::new(t!("tray.quit"), true, None); + menu.append_items(&[ + &status, + &open, + &sharing, + &start, + &pair, + &stop, + &PredefinedMenuItem::separator(), + &quit, + ])?; + let icon = image::load_from_memory(include_bytes!( + "../../tray/Sources/RemoventTray/Resources/AppIcon.png" + ))? + .resize(32, 32, image::imageops::FilterType::Lanczos3) + .to_rgba8(); + let _tray = TrayIconBuilder::new() + .with_menu(Box::new(menu)) + .with_tooltip("Removent") + .with_icon(tray_icon::Icon::from_rgba(icon.into_raw(), 32, 32)?) + .build()?; + let rt = tokio::runtime::Runtime::new()?; + let (requests, rx) = tokio::sync::mpsc::unbounded_channel(); + let (events, updates) = mpsc::channel(); + rt.spawn(link(paths.clone(), rx, events)); + let smoke = std::env::args().any(|a| a == "--smoke"); + let started = Instant::now(); + let mut prompts = crate::prompts::Prompts::default(); + event_loop.run(move |event, _, flow| { + *flow = ControlFlow::Wait; + if smoke && started.elapsed() > Duration::from_secs(2) { + *flow = ControlFlow::Exit; + return; + } + if !matches!(event, Event::UserEvent(())) { + return; + } + // Native check items toggle before queuing MenuEvent. Capture that + // click intent before a queued daemon status can repaint the checkmark. + let actions: Vec<_> = MenuEvent::receiver() + .try_iter() + .map(|event| { + let sharing_on = (event.id == sharing.id()).then(|| sharing.is_checked()); + (event, sharing_on) + }) + .collect(); + while let Ok(value) = updates.try_recv() { + if value.is_null() { + prompts.disconnected(); + status.set_text(t!("tray.offline")); + sharing.set_enabled(false); + pair.set_enabled(false); + stop.set_enabled(false); + start.set_enabled(true); + continue; + } + if let Ok(IpcResponse::Status(report)) = serde_json::from_value(value.clone()) { + status.set_text(if let Some(error) = report.host_error { + error + } else { + t!( + "tray.status", + state = if report.host_ready { + t!("tray.sharing") + } else { + t!("tray.stopped") + }, + count = report.sessions.len() + ) + .into_owned() + }); + sharing.set_enabled(true); + sharing.set_checked(report.running); + pair.set_enabled(true); + stop.set_enabled(true); + start.set_enabled(false); + } else if let Ok(IpcResponse::PairingCode { code, .. }) = + serde_json::from_value(value.clone()) + { + prompts.pairing(code, &t!("dialog.pairing")); + } else if let Ok(IpcResponse::Error { message }) = serde_json::from_value(value.clone()) + { + prompts.alert(message); + } else if let Ok(IpcEvent::PairingPin { pin }) = serde_json::from_value(value.clone()) { + prompts.pairing(pin, &t!("dialog.pairing")); + } else if let Ok(IpcEvent::PairingCleared) = serde_json::from_value(value.clone()) { + prompts.reset_pairing(); + } else if let Ok(IpcEvent::StateChanged { .. }) = serde_json::from_value(value.clone()) + { + let _ = requests.send(IpcRequest::Status); + } else if let Ok(IpcEvent::AdmissionResolved { request_id, .. }) = + serde_json::from_value(value.clone()) + { + prompts.resolved(request_id); + } else if let Ok(IpcEvent::AdmissionRequest { + request_id, + peer_name, + peer_fp16, + }) = serde_json::from_value(value) + { + prompts.admission( + request_id, + &peer_name, + &peer_fp16, + &t!("dialog.admission"), + removent_core::desktop_instance::DesktopInstance::is_running(&paths), + ); + } + } + for (event, sharing_on) in actions { + let result = if event.id == open.id() { + launch("removent", &paths) + } else if event.id == start.id() { + removent_core::service_intent::set_stopped(&paths, false) + .and_then(|_| launch("removentd", &paths)) + } else if let Some(on) = sharing_on { + let _ = requests.send(IpcRequest::SetEnabled { on }); + sharing.set_checked(on); + Ok(()) + } else if event.id == pair.id() { + prompts.reset_pairing(); + let _ = requests.send(IpcRequest::PairingGenerate); + Ok(()) + } else if event.id == stop.id() { + let _ = requests.send(IpcRequest::Shutdown); + Ok(()) + } else if event.id == quit.id() { + *flow = ControlFlow::Exit; + Ok(()) + } else { + Ok(()) + }; + if let Err(e) = result { + prompts.alert(e.to_string()); + } + } + prompts.poll(&requests); + // Keep runtime alive for the IPC worker throughout the event loop. + let _ = &rt; + }); +} +async fn link( + paths: DataPaths, + mut commands: tokio::sync::mpsc::UnboundedReceiver, + events: mpsc::Sender, +) { + let mut connected_once = false; + let mut restart_after = Instant::now(); + loop { + if let Ok((mut r, mut w)) = removent_core::ipc::connect(&paths).await { + connected_once = true; + let mut timer = tokio::time::interval(Duration::from_secs(2)); + let mut reader = removent_core::ipc::MessageReader::default(); + loop { + tokio::select! { + _=timer.tick()=>if write_msg(&mut w,&IpcRequest::Status).await.is_err(){break;}, + command=commands.recv()=>match command { Some(command)=>if write_msg(&mut w,&command).await.is_err(){break;},None=>return }, + event=reader.read::<_,serde_json::Value>(&mut r)=>match event {Ok(Some(value))=>{let _=events.send(value);},_=>break}, + } + } + } + let _ = events.send(serde_json::Value::Null); + while commands.try_recv().is_ok() {} + // Recover an unexpectedly lost service, while preserving an explicit + // stop. The child checks the intent again before acquiring its singleton. + if connected_once + && Instant::now() >= restart_after + && removent_core::service_intent::is_stopped(&paths).is_ok_and(|stopped| !stopped) + { + let _ = launch("removentd", &paths); + restart_after = Instant::now() + Duration::from_secs(5); + } + tokio::time::sleep(Duration::from_secs(1)).await; + } +} diff --git a/docs/design/protocol.md b/docs/design/protocol.md index f57ab7b..57c022d 100644 --- a/docs/design/protocol.md +++ b/docs/design/protocol.md @@ -186,7 +186,7 @@ WSS 容器冷启动时,仅允许凭据唯一定位一个离线房间的控制 Hello{ app_version, device_name, os_ver, caps[] } HelloAck{ proto_version, caps[], resume_token_opt } ``` -- `feature_bits`:按位声明扩展(bit0=file-transfer, bit1=two-way-audio, bit2=hdr, bit5=software AV1 temporal units, bit9=dynamic video profiles, bit10=automation RPC, …)。 +- `feature_bits`:按位声明扩展(bit0=file-transfer, bit1=two-way-audio, bit2=hdr, bit5=software AV1 temporal units, bit9=dynamic video profiles, bit10=automation RPC, bit11=automation handover, bit12=H264_ONLY(无 HEVC 解码器), …)。 - 版本不兼容且无公共特性集 → `Error{code=VersionMismatch}` 后关流。 ### 5.2 会话协商 @@ -224,7 +224,7 @@ offset size 字段 - 参数集变化必须随关键帧内联,客户端据此热重置解码器(支持运行中改分辨率)。 - host 对完整 BGRA 内容做逐字节去重:首帧、像素有变化的帧和强制关键帧必须编码发送;与最近一次**成功写入**完全相同的普通帧直接跳过。去重状态在编码失败、SendGate 丢帧或分辨率重建时不提交/重置,避免把接收端落后的画面误认为已同步。关键帧请求可复用最近缓存帧,因此静止画面也能立即恢复。 - H.264/HEVC 的帧间预测已经压缩了未变化区域;RVP/1 不额外传 raw pixel delta,避免破坏硬件编码器的全局预测和 QUIC 有序流语义。 -- `codec_id=0x03` 使用完整 rav1e temporal-unit OBU payload。关键 temporal unit 自带 sequence-header OBU,不发送单独 `av1C`;只有双方握手都声明 `feature_bits::SOFTWARE_AV1` 时才可选择。AV1 默认 opt-in(`REMOVENT_VIDEO_CODEC=av1`);协商前的软件 encoder 探测失败时回退 HEVC,已建立会话中的不可恢复编码错误按 `InternalError` 结束会话。 +- `codec_id=0x03` 使用完整 rav1e temporal-unit OBU payload。关键 temporal unit 自带 sequence-header OBU,不发送单独 `av1C`;只有双方握手都声明 `feature_bits::SOFTWARE_AV1` 时才可选择。AV1 默认 opt-in(`REMOVENT_VIDEO_CODEC=av1`);协商前的软件 encoder 探测失败时回退平台默认编码(Apple 默认为 HEVC,非 Apple 或对端声明 H264_ONLY 时为 H.264),已建立会话中的不可恢复编码错误按 `InternalError` 结束会话。 ### 6.2 音频包(uni-stream) diff --git a/docs/design/ui-design.md b/docs/design/ui-design.md index 3d1d918..40698d9 100644 --- a/docs/design/ui-design.md +++ b/docs/design/ui-design.md @@ -125,7 +125,7 @@ Removent 连接表单提供四个等宽画质上限选项:低、标准、高 iCloud 同步状态使用语义色胶囊标签,有待同步更改时才显示数量;「立即同步」使用紧凑的主按钮,靠右对齐。上次成功同步时间以本地时区的 24 小时制 HH:mm 显示,缺失或非法时间不展示,异常说明保留完整文案。 OTP 模式只显示验证器设置,不显示访问口令。绑定密钥与本地生成的标准 otpauth 二维码按需显示,离开页面后收起;二维码使用黑白整数模块和四模块留白,画布按模块实际大小收紧。绑定验证器使用独立表单卡片,扫码与手动添加使用分隔线分区;说明统一位于各自标题下方,二维码单独放在扫码说明下方。二维码显示操作位于自身区域右侧,采用固定宽度的展开/收起按钮;手动密钥采用只读行,右侧提供固定尺寸的眼睛显隐和复制图标按钮,并附操作提示。移动端验证码使用单个原生输入框,标记 oneTimeCode、自动聚焦,并提示键盘建议和系统自动填充菜单。 安全页默认认证方式为「系统账户」,使用下拉菜单选择认证方式,避免窄窗口中选项溢出。系统账户连接表单先聚焦用户名,密码使用隐藏输入,提交或取消后清空两项。 -macOS 控制端在系统账户和访问口令认证框提供「记忆凭据并存入 Keychain」开关,首次默认关闭;成功建立会话后保存相应凭据,取消及失败不覆盖原值。后续连接按本机身份、已核验的主机证书和认证方式读取凭据并自动认证,不再弹出凭据确认框。已保存凭据的修改和移除放在连接编辑表单,点击保存或连接后生效;关闭表单放弃未保存的修改。自动认证失败提示用户打开编辑表单更新凭据,不自动弹出输入框或覆盖原值。编辑连接目标或协议不携带旧凭据。用户名和密码均不写入连接配置或同步数据;OTP 与临时配对码不提供记忆开关。Keychain 访问在后台执行,失败时提示重新输入或检查钥匙串权限,不阻塞画面和音频。 +macOS、Windows 和 Linux 控制端在系统账户和访问口令认证框提供「记住凭据并存入系统凭据库」开关,首次默认关闭;成功建立会话后保存相应凭据,取消及失败不覆盖原值。后续连接按本机身份、已核验的主机证书和认证方式读取凭据并自动认证,不再弹出凭据确认框。已保存凭据的修改和移除放在连接编辑表单,点击保存或连接后生效;关闭表单放弃未保存的修改。自动认证失败提示用户打开编辑表单更新凭据,不自动弹出输入框或覆盖原值。编辑连接目标或协议不携带旧凭据。用户名和密码均不写入连接配置或同步数据;OTP 与临时配对码不提供记忆开关。凭据分别使用 macOS Keychain、Windows Credential Manager 和 Linux Secret Service 保存,不降级到明文文件。系统凭据库访问在后台执行,失败时提示重新输入或检查凭据库权限,不阻塞画面和音频。 安全页选择「访问口令」后展开并聚焦口令输入,显示占位提示、口令要求和当前仍生效的认证方式;有效口令保存成功后才启用,失败在输入旁提示。离开安全页丢弃未保存的口令草稿,再次进入恢复已保存的配置。 右侧只呈现当前分类标题和分组表单,底部有“返回设备”。分类切换不清除原有设备选择。 不再用会换行的横向分段按钮承担不同设置分类的导航。iCloud 的云图标与其他符号一起内嵌。 diff --git a/docs/guides/connection-reference.md b/docs/guides/connection-reference.md index 115f7f2..63afb1f 100644 --- a/docs/guides/connection-reference.md +++ b/docs/guides/connection-reference.md @@ -21,7 +21,7 @@ wait until all sessions end. Choose **Settings → Security → Connection authentication** on the desktop host. The iPhone/iPad app and desktop controller follow the host's choice automatically: -- **System account** (default): use the username and login password of the account running Removent on the Mac host. System passwords are not stored in Removent settings. +- **System account** (default): use the username and login password of the account running Removent on the macOS, Windows or Linux host. The host verifies the password through the operating system and does not store it in Removent settings. Windows requires the account password, not a Windows Hello PIN. This authenticates access to the existing desktop session; it does not switch users or sign in at the operating system's login screen. - **Pairing code**: enter the six-digit code displayed on the host. Choose **Remember paired devices** or **Pair every connection** in desktop Security settings. - **Access password**: set a non-empty host password; every new session requires it, including previously paired devices. - **OTP**: copy the setup secret into an authenticator as TOTP / SHA-1 / 6 digits / 30 seconds, then enter its current code. Each code can be used once; adjacent clock steps are tolerated. @@ -34,6 +34,17 @@ end active sessions and invalidate old resume tokens. Removent access passwords and the restricted LoginWindow service still requires previously approved device grants. System account, password and OTP require updated controllers; the pairing-code wire format remains compatible. +On desktop controllers, **Remember credentials in the system credential store** is +off initially. Enable it to save a successful system-account or access-password login +in macOS Keychain, Windows Credential Manager or Linux Secret Service. An unlocked +Secret Service provider is required on Linux. If storage fails, the connection can +continue with the entered credentials, but they are not saved to a plaintext fallback. +Saved credentials are used automatically only for the same local device identity, +verified host certificate and authentication method. Edit or remove them in the +saved connection's edit form. Cancelled or failed connections preserve existing +credentials; OTP and pairing codes are never remembered. Connection files and sync +data do not contain these remembered usernames or passwords. + ## Connection by code and CLI The host can generate a **12-digit connection code** from desktop Security settings or the CLI. diff --git a/docs/guides/windows-linux.md b/docs/guides/windows-linux.md new file mode 100644 index 0000000..4de45dc --- /dev/null +++ b/docs/guides/windows-linux.md @@ -0,0 +1,69 @@ +# Windows and Linux desktop builds + +Extract the complete archive to a writable installation directory. Run `removent` +(`removent.exe` on Windows). The desktop launches the sibling `removentd` and +`removent-tray` executables; keep all three together. Closing the main window +leaves sharing available through the tray. The tray can open the main window, +start or stop the service, toggle sharing, show a pairing invitation, and answer +access requests. Quitting only the tray does not stop the host. +Opening the desktop again restores its existing window for the same data directory. +Access prompts default to rejection and expire after 30 seconds. The main desktop +gets the first opportunity to answer; the tray presents an unanswered request after +eight seconds when that desktop is open. Cancellation, an answer in another window, +or losing the background service dismisses the tray prompt. +After connecting to the background service, the tray restarts it if it crashes. +An explicit service stop persists across tray restarts until you choose Start again. + +Windows archives include the Visual C++ runtime DLLs beside the executables; +keep these files together as well. A separate runtime installation is not needed. +Keep the data directory on local NTFS storage, which supports atomic replacement +while other processes read their existing file snapshots. +Windows requires an interactive signed-in desktop. The host cannot control the +UAC secure desktop or the sign-in screen. System-account authentication checks +that the authenticated token belongs to the user running the desktop host. +Use the account password, not a Windows Hello PIN. Allow UDP 48688 through the +firewall on networks where incoming native connections are needed. +Usernames may be local names, `DOMAIN\name`, or a domain UPN. An explicit domain +such as `MicrosoftAccount\email@example.com` is preserved during authentication. + +Linux hosting currently requires an X11 session. Wayland hosting fails with an +explicit error because portal-authorized capture/input sessions are not yet +implemented. The controller may run under X11 or Wayland. A desktop shell with +AppIndicator support is needed to display the tray (GNOME may require its +AppIndicator extension). Debian/Ubuntu runtime dependencies include GTK 3, +Ayatana AppIndicator, ALSA, PAM, PipeWire, X11, xkbcommon, and Vulkan/Mesa. +The CI Linux x86_64 archive is built on Ubuntu 24.04 and requires glibc 2.39 or +newer. Build from source for older distributions. Install a CJK font family +(for example, Noto CJK) to display Chinese text when the system has none. +Use the login password of the non-root user running the host for system authentication. +Linux verifies both the password and account validity through the system's `login` +PAM policy. An expired or locked account is not accepted. Authentication does not +switch users, and another user's valid password cannot authorize this desktop. +Remembered connection credentials use Windows Credential Manager with local-machine +persistence (not Windows profile roaming), or the Linux +Secret Service (for example, an unlocked GNOME Keyring). No plaintext fallback +is used when the credential store is unavailable. The remember switch is off initially; +credentials are saved only after a successful connection. Later connections reuse +them for the same verified host and authentication method. Use the connection's edit +form to update or remove them. See [authentication and storage](connection-reference.md#unattended-connection-authentication). +CPU-only Linux desktops prefer +the OpenGL software renderer to avoid black Vulkan frames on older Mesa. + +H.264 and AV1 use CPU codecs. New macOS hosts select H.264 when a Windows/Linux +controller advertises that HEVC is unavailable; older macOS releases that always +select HEVC need updating. System audio capture, pre-login access, native +Computer Use, idle-sleep prevention, and automatic package installation are not +implemented on these platforms. Text clipboard sharing is supported. Do not infer feature support +from a successful build; see [the validation report](../validation/windows-linux-2026-11-13.md) for tested scenarios. + +Data lives under `%LOCALAPPDATA%/Removent/userdata` on Windows and +`$XDG_DATA_HOME/removent/userdata` (default `~/.local/share/removent/userdata`) on +Linux. `REMOVENT_DATA_DIR` overrides either location. Development builds use the +workspace `userdata` only if that workspace exists on the running machine. +Windows management IPC uses a local owner-only named pipe; Linux uses a private +Unix socket. Pairing keys and settings remain local to that data directory. + +Build with `cargo build --locked --release -p removent-app -p removent-daemon +-p removent-tray`. Linux build dependencies are listed in +`scripts/build/linux-deps.sh`. CI archives are development packages, not signed +Windows installers or distribution-managed Linux packages. diff --git a/docs/validation/windows-linux-2026-11-13.md b/docs/validation/windows-linux-2026-11-13.md new file mode 100644 index 0000000..6ebe449 --- /dev/null +++ b/docs/validation/windows-linux-2026-11-13.md @@ -0,0 +1,80 @@ +# Windows and Linux desktop validation + +Work branch: `feat/windows-linux-desktop`, PR #2. These are development packages; +no release tag, merge, system-service installation, or public release was made. + +## Observed locally + +- Native Linux arm64 Debian 12 container, Xvfb 1280x800, Openbox and Mesa software rendering. +- Actual desktop pixels captured with xcap, H.264 encoded and decoded, matched against the independent red Tk window. +- Native click, Ctrl+A and exact mixed Chinese/English text received by that independent UI, including committed text and a physical-key Unicode payload. +- Authenticated pinned QUIC host/client session negotiated H.264, delivered real desktop pixels and input, synchronized text clipboard both directions, and shut down cleanly. +- Real Unix IPC: status, sharing enable/disable, pairing invitation, acknowledged shutdown, successful daemon exit, and persisted stop intent. +- Actual Xfce panel registration, tray start, sharing enable/disable, native GTK pairing dialog, service stop and tray quit. The test caught and fixed duplicate pairing dialogs and the former external `zenity` dependency. +- Visible GPUI main window content, first-frame receipt and clean exit. The test checks content pixels, not just window creation. Mesa CPU Vulkan black output was reproduced; the OpenGL preference fixed the default path. +- Native Secret Service credential create/read/update/delete, including Unicode and missing entries, with an isolated test collection. +- Linux: core 72, protocol 16, input 11, client 126, host 71 and codec 5 library tests passed. Native PAM authentication separately passed with a temporary non-root OS account (valid and invalid passwords). macOS workspace strict Clippy passed; Windows GNU cross-check passed including network and credential probes. + +## Native CI + +The [Desktop platforms workflow](https://github.com/backrunner/removent/actions/workflows/desktop-platforms.yml) +builds Windows x86_64 and Linux x86_64 desktop, daemon and tray. It runs native +desktop probes, IPC/admission tests and protocol/codec/session regressions before +packaging all three executables with checksums. Windows also checks password and +desktop-owner SID validation using a disposable local OS account. + +The [2026-11-13 native run](https://github.com/backrunner/removent/actions/runs/43462842578) +passed both platforms and produced both archives. Windows passed 298 library +tests plus eight IPC tests and native account validation. Its captured desktop +and Explorer tray were reviewed, including caption glyphs, actual minimize and +maximize clicks, pairing dialogs, exact `hello中文` input, and both clipboard +directions through a pinned QUIC session. Both archive checksums and executable +formats were checked after download. The Windows package check additionally +launches the extracted desktop, host and tray and verifies that the desktop loads +its bundled Visual C++ runtime instead of relying on the runner's installation. + +Each run attaches desktop/tray screenshots and logs to its exact commit. See +[PR #2 checks](https://github.com/backrunner/removent/pull/2/checks) for the run +results and downloadable packages. Earlier failures exposed a daemon fixture +error and Windows append-only log-lock access; both have regression coverage. + +## Expanded tray acceptance + +`scripts/qa/windows_tray.py` and `scripts/qa/linux_tray.py` now share a real-daemon +lifecycle harness. They click the shell's actual icon, select native menu items, +and click native dialog buttons. Xfce menu labels and enabled state are read from +D-Bus, but selection uses keyboard input in the visible popup rather than invoking +its exported callbacks. Windows uses Explorer icon bounds and actual pointer input. +Each Linux tray scenario uses an isolated X11/D-Bus session, with the accessibility +bridge enabled and its registry started before Xfce creates the embedded tray plugin. +This prevents earlier GTK probes from affecting native control discovery. + +The harness covers duplicate tray startup, opening/restoring one real main window, +reopening pairing dialogs, desktop-first approval, competing answers, default denial, +explicit denial/approval, controller cancellation, and the real 30-second timeout. +Opening, moving and restoring the main window also require visibly rendered content; +window bounds and focus alone are not sufficient, and screenshots wait for paint. +Repeated sharing changes must reach the real host while daemon status polls refresh +the menu, including immediately after closing the main window. +An accepted pinned QUIC session must keep delivering decoded desktop frames after +the tray quits and after Explorer/Xfce restarts. A ten-minute CI soak records tray +RSS, handles/file descriptors and threads. Killing the daemon must dismiss pending +prompts and recover sharing; a deliberate stop must survive watchdog polling and +tray restart. Chinese dark presentation, Linux 2x presentation, and restoring a +window on the second of two logical RandR monitors run separately. Logical monitors +do not validate physical monitor hotplug or mixed-DPI transitions. + +Screenshots, JSON results and daemon/desktop logs are retained in the workflow's +`desktop-evidence-*` artifacts, including on failure. Passing compilation or only +part of this harness does not establish that the whole lifecycle passed; use the +exact PR head's checks and `results.json` when evaluating a development package. + +## Boundaries + +The virtual desktop exercises the real capture/input APIs and real QUIC loopback +transport. It does not certify physical GPUs, WAN jitter, multi-monitor scaling, +locked/UAC secure desktops or tray behavior in every desktop shell. Linux needs +X11 for hosting and an AppIndicator-capable panel for a visible tray. Wayland +hosting, system-audio capture, pre-login access, native Computer Use and automatic +package installation remain unavailable. Unsupported capabilities are not +advertised as working. Use the account password rather than a Windows Hello PIN. diff --git a/packages/automation/src/lib.rs b/packages/automation/src/lib.rs index cb907d9..69a3e83 100644 --- a/packages/automation/src/lib.rs +++ b/packages/automation/src/lib.rs @@ -31,6 +31,13 @@ pub struct Executor { } impl Executor { + #[cfg(not(target_os = "macos"))] + pub fn native(_session: CancellationToken) -> Result { + Err(Failure::new( + "unsupported", + "Native Computer Use is not implemented on this platform", + )) + } /// At most one native worker per host process, including a stalled previous session. /// A cancelled native OS call cannot be killed safely; never accumulate threads. #[cfg(target_os = "macos")] diff --git a/packages/client/Cargo.toml b/packages/client/Cargo.toml index 6448a0a..1873c6f 100644 --- a/packages/client/Cargo.toml +++ b/packages/client/Cargo.toml @@ -50,3 +50,10 @@ tracing-subscriber = { workspace = true } [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] security-framework = "3" security-framework-sys = "2" + +[target.'cfg(windows)'.dependencies] +keyring = { version = "3.6", features = ["windows-native"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Credentials"] } +zeroize = "1.9" +[target.'cfg(target_os = "linux")'.dependencies] +keyring = { version = "3.6", features = ["sync-secret-service", "crypto-rust"] } diff --git a/packages/client/examples/credential_smoke.rs b/packages/client/examples/credential_smoke.rs new file mode 100644 index 0000000..5528b21 --- /dev/null +++ b/packages/client/examples/credential_smoke.rs @@ -0,0 +1,89 @@ +//! Exercise the actual credential store using only a unique test entry. +fn main() -> anyhow::Result<()> { + anyhow::ensure!( + std::env::var("REMOVENT_DESKTOP_TEST").as_deref() == Ok("1"), + "Requires an isolated test desktop" + ); + let account = format!("desktop-ci-{:032x}", rand::random::()); + if std::env::args().any(|arg| arg == "--expect-unavailable") { + anyhow::ensure!(removent_client::keychain::load(&account).is_err()); + anyhow::ensure!( + removent_client::keychain::store(&account, "must-not-reach-a-file").is_err() + ); + anyhow::ensure!(removent_client::keychain::delete(&account).is_err()); + println!("PASS: unavailable native credential store fails closed"); + return Ok(()); + } + let result = (|| -> anyhow::Result<()> { + anyhow::ensure!(removent_client::keychain::load(&account)?.is_none()); + #[cfg(windows)] + { + keyring::Entry::new("com.alkinum.removent", &account)? + .set_password("legacy test item")?; + anyhow::ensure!( + removent_client::keychain::load(&account)?.as_deref() == Some("legacy test item") + ); + } + removent_client::keychain::store(&account, "test password 一🔒")?; + #[cfg(windows)] + assert_local_persistence(&account)?; + anyhow::ensure!( + removent_client::keychain::load(&account)?.as_deref() == Some("test password 一🔒") + ); + removent_client::keychain::store(&account, "updated password 二")?; + #[cfg(windows)] + assert_local_persistence(&account)?; + anyhow::ensure!( + removent_client::keychain::load(&account)?.as_deref() == Some("updated password 二") + ); + #[cfg(windows)] + { + anyhow::ensure!(removent_client::keychain::store(&account, &"x".repeat(2561)).is_err()); + anyhow::ensure!( + removent_client::keychain::load(&account)?.as_deref() + == Some("updated password 二") + ); + } + Ok(()) + })(); + let cleanup = removent_client::keychain::delete(&account); + result?; + cleanup?; + anyhow::ensure!(removent_client::keychain::load(&account)?.is_none()); + println!("PASS: native credential store create, read, update, delete and missing entry"); + Ok(()) +} + +#[cfg(windows)] +fn assert_local_persistence(account: &str) -> anyhow::Result<()> { + use windows_sys::Win32::Security::Credentials::{ + CRED_PERSIST_LOCAL_MACHINE, CRED_TYPE_GENERIC, CredFree, CredReadW, + }; + use zeroize::Zeroize; + let target: Vec = format!("{account}.com.alkinum.removent") + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut credential = std::ptr::null_mut(); + anyhow::ensure!( + unsafe { CredReadW(target.as_ptr(), CRED_TYPE_GENERIC, 0, &mut credential) } != 0 + ); + let persistence = unsafe { + let persistence = (*credential).Persist; + if (*credential).CredentialBlobSize > 0 { + std::slice::from_raw_parts_mut( + (*credential).CredentialBlob, + (*credential).CredentialBlobSize as usize, + ) + .zeroize(); + } + CredFree(credential.cast()); + persistence + }; + anyhow::ensure!( + persistence == CRED_PERSIST_LOCAL_MACHINE, + "credentials must not roam" + ); + println!("PASS: Windows credentials persist on this computer only"); + Ok(()) +} diff --git a/packages/client/examples/desktop_session_smoke.rs b/packages/client/examples/desktop_session_smoke.rs new file mode 100644 index 0000000..6f9bf63 --- /dev/null +++ b/packages/client/examples/desktop_session_smoke.rs @@ -0,0 +1,192 @@ +//! Actual QUIC host/client session using the isolated desktop fixture. +use removent_core::{ + AuthenticationMode, AuthenticationSettings, DataPaths, MemoryClipboard, Settings, TextClipboard, +}; +use removent_proto::{Caps, CodecId, KeyKind, KeyModifiers, MouseKind}; +use std::{ + sync::{Arc, atomic::AtomicBool}, + time::Duration, +}; +#[tokio::main] +async fn main() -> anyhow::Result<()> { + #[cfg(windows)] + removent_input::initialize_host_dpi(); + anyhow::ensure!( + std::env::var("REMOVENT_DESKTOP_TEST").as_deref() == Ok("1"), + "Requires isolated desktop" + ); + tracing_subscriber::fmt().with_env_filter("info").init(); + tokio::time::timeout(Duration::from_secs(35), probe()).await??; + Ok(()) +} +async fn probe() -> anyhow::Result<()> { + let host_dir = tempfile::tempdir()?; + let client_dir = tempfile::tempdir()?; + let hp = DataPaths { + root: host_dir.path().into(), + }; + let cp = DataPaths { + root: client_dir.path().into(), + }; + let password = hex::encode(rand::random::<[u8; 32]>()); + let port = std::net::UdpSocket::bind("127.0.0.1:0")? + .local_addr()? + .port(); + let settings = Settings { + host_enabled: true, + host_port: port, + authentication: AuthenticationSettings { + mode: AuthenticationMode::Password, + password: password.clone(), + ..Default::default() + }, + ..Default::default() + }; + settings.save(&hp)?; + let host_id = removent_core::identity::load_or_create(&hp, "Isolated host")?; + let client_id = removent_core::identity::load_or_create(&cp, "Isolated controller")?; + let (ready, mut readiness) = tokio::sync::mpsc::channel(1); + let cancel = tokio_util::sync::CancellationToken::new(); + let _guard = cancel.clone().drop_guard(); + struct Clipboard; + impl TextClipboard for Clipboard { + fn change_count(&self) -> Result { + removent_input::change_count().map_err(|e| e.to_string()) + } + fn read(&self) -> Result { + removent_input::read_text().map_err(|e| e.to_string()) + } + fn write(&self, text: &str) -> Result<(), String> { + removent_input::write_text(text).map_err(|e| e.to_string()) + } + } + let host = tokio::spawn(removent_host::serve_forever( + removent_host::HostRunnerConfig { + paths: hp, + settings, + input_sink: Some(Arc::new(removent_host::RealInputSink::new())), + local_clip: Some(Arc::new(Clipboard)), + }, + removent_host::HostCallbacks { + show_pairing_pin: Box::new(|_| {}), + admission_prompt: Box::new(|_, _| Box::pin(async { true })), + on_event: Box::new(move |event| { + if matches!(event, removent_host::HostEvent::Listening) { + let _ = ready.try_send(()); + } + }), + }, + Arc::new(AtomicBool::new(true)), + cancel.clone(), + )); + tokio::time::timeout(Duration::from_secs(5), readiness.recv()) + .await? + .ok_or_else(|| anyhow::anyhow!("Host failed before listening"))?; + let (endpoint, _) = removent_net::make_client_endpoint( + "127.0.0.1:0".parse()?, + &client_id, + removent_net::PinState::new([host_id.fingerprint], false), + )?; + let clipboard = MemoryClipboard::new(); + clipboard + .write("Removent QUIC clipboard") + .map_err(anyhow::Error::msg)?; + let mut session = removent_client::connect_session( + endpoint, + std::net::SocketAddr::from(([127, 0, 0, 1], port)), + &client_id, + removent_client::ClientConfig { + native_video: false, + video_quality: Default::default(), + host_identity_verified: true, + pairing_code: None, + device_name: "Controller".into(), + caps: Caps::all(), + local_clip: Some(clipboard.clone()), + }, + None, + None, + Some(Box::new(move |_, send| { + let _ = send.send(password); + })), + ) + .await?; + anyhow::ensure!( + session.negotiated.video.codec == CodecId::H264, + "Portable session must negotiate H264" + ); + anyhow::ensure!( + !session.negotiated.audio.enabled, + "Portable host must not advertise system audio" + ); + let frame = tokio::time::timeout(Duration::from_secs(10), session.decoded_bgra_rx.recv()) + .await? + .ok_or_else(|| anyhow::anyhow!("No network video frame"))?; + anyhow::ensure!( + frame + .data + .as_chunks::<4>() + .0 + .iter() + .any(|p| p[2] > 160 && p[1] < 100 && p[0] < 100), + "Network frame lacks fixture pixels" + ); + let display = + removent_input::DisplayGeometry::main().ok_or_else(|| anyhow::anyhow!("No display"))?; + let target_x = std::env::var("REMOVENT_TEST_X")?.parse::()?; + let target_y = std::env::var("REMOVENT_TEST_Y")?.parse::()?; + let x = (target_x - display.origin_x as f32) * frame.width as f32 / display.width_px as f32; + let y = (target_y - display.origin_y as f32) * frame.height as f32 / display.height_px as f32; + session + .send_input_mouse(display.id as u64, x, y, 1, MouseKind::LeftDown) + .await?; + session + .send_input_mouse(display.id as u64, x, y, 0, MouseKind::LeftUp) + .await?; + for (vk, mods, kind) in [ + (0x3b, KeyModifiers::CONTROL, KeyKind::FlagsChanged), + (0x00, KeyModifiers::CONTROL, KeyKind::Down), + (0x00, KeyModifiers::CONTROL, KeyKind::Up), + (0x3b, KeyModifiers::empty(), KeyKind::FlagsChanged), + ] { + session.send_input_key(vk, mods, kind, None).await?; + } + for ch in "hello中文".chars() { + // Exercise both committed IME text and a non-ASCII physical-key payload. + let vk = if ch == '文' { + 0x00 + } else { + removent_input::UNICODE_ONLY_VK + }; + session + .send_input_key(vk, KeyModifiers::empty(), KeyKind::Down, Some(ch)) + .await?; + session + .send_input_key(vk, KeyModifiers::empty(), KeyKind::Up, Some(ch)) + .await?; + } + clipboard + .write("Controller to native host") + .map_err(anyhow::Error::msg)?; + tokio::time::timeout(Duration::from_secs(5), async { + while removent_input::read_text().ok().as_deref() != Some("Controller to native host") { + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await?; + removent_input::write_text("Native host to controller")?; + tokio::time::timeout(Duration::from_secs(5), async { + while clipboard.read().ok().as_deref() != Some("Native host to controller") { + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await?; + tokio::time::sleep(Duration::from_millis(250)).await; + session.close().await?; + cancel.cancel(); + tokio::time::timeout(Duration::from_secs(5), host).await???; + println!( + "PASS: authenticated QUIC session, negotiated H264, real desktop pixels, remote input, bidirectional native clipboard and clean teardown" + ); + Ok(()) +} diff --git a/packages/client/examples/tray_session.rs b/packages/client/examples/tray_session.rs new file mode 100644 index 0000000..cadf4a5 --- /dev/null +++ b/packages/client/examples/tray_session.rs @@ -0,0 +1,117 @@ +//! Real remote sessions used by native tray admission and lifetime acceptance. +use removent_core::{DataPaths, PeerRecord, PeersStore}; +use removent_proto::Caps; +use std::{ + io::{BufRead, Write}, + time::Duration, +}; + +fn emit(value: serde_json::Value) { + println!("{value}"); + std::io::stdout().flush().unwrap(); +} +fn commands() -> tokio::sync::mpsc::UnboundedReceiver { + let (send, receive) = tokio::sync::mpsc::unbounded_channel(); + std::thread::spawn(move || { + for line in std::io::stdin().lock().lines().map_while(Result::ok) { + if send.send(line).is_err() { + break; + } + } + }); + receive +} +#[tokio::main] +async fn main() -> anyhow::Result<()> { + anyhow::ensure!( + std::env::var("REMOVENT_DESKTOP_TEST").as_deref() == Ok("1"), + "Requires isolated desktop" + ); + let args: Vec<_> = std::env::args().collect(); + let hp = DataPaths::resolve(); + let cp = DataPaths { + root: std::env::var_os("REMOVENT_TEST_CLIENT_DIR") + .ok_or_else(|| anyhow::anyhow!("Missing isolated client directory"))? + .into(), + }; + let client = removent_core::identity::load_or_create(&cp, "Tray acceptance 中文")?; + let settings = removent_core::Settings::load_strict(&hp)?; + let host = removent_core::identity::load_or_create(&hp, &settings.device_name)?; + if args.get(1).is_some_and(|arg| arg == "prepare") { + PeersStore::load(&hp)?.upsert(PeerRecord { + fingerprint: client.fingerprint_hex(), + name: "Tray acceptance 中文".into(), + short_fp: client.short_fingerprint_hex(), + trusted: true, + granted_caps: Caps::none(), + added_at_unix: 0, + last_connected_unix: 0, + })?; + return Ok(()); + } + let port: u16 = args + .get(1) + .ok_or_else(|| anyhow::anyhow!("Missing host port"))? + .parse()?; + let (endpoint, _) = removent_net::make_client_endpoint( + "127.0.0.1:0".parse()?, + &client, + removent_net::PinState::new([host.fingerprint], false), + )?; + let mut commands = commands(); + let connect = removent_client::connect_session( + endpoint.clone(), + ([127, 0, 0, 1], port).into(), + &client, + removent_client::ClientConfig { + native_video: false, + video_quality: Default::default(), + host_identity_verified: true, + pairing_code: None, + device_name: "Tray acceptance 中文".into(), + caps: Caps { + video: true, + ..Caps::none() + }, + local_clip: None, + }, + None, + None, + None, + ); + let result = tokio::select! { + result = tokio::time::timeout(Duration::from_secs(45), connect) => result?, + _ = commands.recv() => { + endpoint.close(0u32.into(), b"tray QA cancellation"); + endpoint.wait_idle().await; + emit(serde_json::json!({"event":"cancelled"})); + return Ok(()); + } + }; + let mut session = match result { + Ok(session) => session, + Err(error) => { + emit(serde_json::json!({"event":"rejected","reason":error.to_string()})); + return Ok(()); + } + }; + emit(serde_json::json!({"event":"connected"})); + let mut frames = 0; + let mut report = tokio::time::interval(Duration::from_secs(1)); + let deadline = tokio::time::sleep(Duration::from_secs(1200)); + tokio::pin!(deadline); + loop { + tokio::select! { + frame = session.decoded_bgra_rx.recv() => { + anyhow::ensure!(frame.is_some(), "Remote video stopped"); + frames += 1; + }, + _ = report.tick() => emit(serde_json::json!({"event":"frames","count":frames})), + _ = commands.recv() => break, + _ = &mut deadline => anyhow::bail!("Tray session fixture timed out"), + } + } + session.close().await?; + emit(serde_json::json!({"event":"closed","frames":frames})); + Ok(()) +} diff --git a/packages/client/src/automation/broker_windows.rs b/packages/client/src/automation/broker_windows.rs new file mode 100644 index 0000000..b43798b --- /dev/null +++ b/packages/client/src/automation/broker_windows.rs @@ -0,0 +1,29 @@ +//! Local automation attachment is not advertised until a same-user pipe broker exists. +use super::*; +use removent_proto::automation::{Request, Response}; +#[derive(Clone)] +pub struct Info { + pub generation: String, + pub fingerprint: String, + pub features: u64, +} +pub struct Publisher; +impl Publisher { + pub fn start(_: &DataPaths, _: removent_net::RvpConnection, _: u64) -> anyhow::Result { + anyhow::bail!("Local automation attachment is unavailable on Windows") + } +} +pub struct Attachment { + pub info: Info, +} +impl Attachment { + pub async fn find(_: &DataPaths, _: [u8; 32]) -> anyhow::Result> { + Ok(None) + } + pub async fn alive(&self) -> bool { + false + } + pub async fn call(&self, _: &Request) -> anyhow::Result { + anyhow::bail!("Local automation attachment is unavailable on Windows") + } +} diff --git a/packages/client/src/automation/mod.rs b/packages/client/src/automation/mod.rs index 1b0a6c5..ba451e8 100644 --- a/packages/client/src/automation/mod.rs +++ b/packages/client/src/automation/mod.rs @@ -8,6 +8,10 @@ use removent_net::{PinState, make_client_endpoint}; use removent_proto::{AuthenticationMode, Caps}; use std::time::Duration; +#[cfg(unix)] +pub mod broker; +#[cfg(windows)] +#[path = "broker_windows.rs"] pub mod broker; pub struct Connection { session: Option, diff --git a/packages/client/src/cloud_sync/storage.rs b/packages/client/src/cloud_sync/storage.rs index a094d0c..34afbf9 100644 --- a/packages/client/src/cloud_sync/storage.rs +++ b/packages/client/src/cloud_sync/storage.rs @@ -33,19 +33,21 @@ pub(crate) fn recover(path: &Path) -> Result<()> { if journal.version != 1 || journal.sync.version != 1 { return Err(failure("Unsupported connection journal")); } - atomic_write( - &path.to_path_buf(), - &serde_json::to_vec_pretty(&journal.entries)?, - )?; + atomic_write(path, &serde_json::to_vec_pretty(&journal.entries)?)?; atomic_write(&state_path(path), &serde_json::to_vec(&journal.sync)?)?; sync_directory(path)?; std::fs::remove_file(journal_path(path))?; sync_directory(path) } -pub(super) fn sync_directory(path: &Path) -> Result<()> { +pub(super) fn sync_directory(_path: &Path) -> Result<()> { + #[cfg(unix)] + let path = _path; + #[cfg(unix)] if let Some(parent) = path.parent() { std::fs::File::open(parent)?.sync_all()?; } + // Windows atomic_write flushes each file and uses a write-through rename. + // Opening a directory with File::open is denied on that platform. Ok(()) } pub(crate) fn commit(path: &Path, entries: &[SavedConnection], sync: &SyncState) -> Result<()> { diff --git a/packages/client/src/keychain.rs b/packages/client/src/keychain.rs index 255887f..8ef1717 100644 --- a/packages/client/src/keychain.rs +++ b/packages/client/src/keychain.rs @@ -1,9 +1,9 @@ //! Password storage for saved connections. //! //! `connections.json` only records that a password exists (`password_hint`); -//! the secret itself lives in the macOS Keychain as a generic password keyed by +//! the secret lives in the platform credential store, keyed by //! the bookmark's versioned `password_key`. Items created by this app are readable by it -//! without an interactive prompt. +//! without an interactive prompt when the credential store is unlocked. use removent_core::{CoreError, Result}; @@ -65,26 +65,34 @@ fn delete_imp(account: &str) -> std::result::Result<(), StoreError> { } #[cfg(not(any(target_os = "macos", target_os = "ios")))] -type StoreError = String; +type StoreError = keyring::Error; #[cfg(not(any(target_os = "macos", target_os = "ios")))] -fn is_not_found(_: &StoreError) -> bool { - false +fn is_not_found(e: &StoreError) -> bool { + matches!(e, keyring::Error::NoEntry) } -#[cfg(not(any(target_os = "macos", target_os = "ios")))] -fn store_imp(_: &str, _: &str) -> std::result::Result<(), StoreError> { - Err("keychain is only supported on Apple platforms".into()) +#[cfg(windows)] +mod windows; + +#[cfg(windows)] +use windows::store as store_imp; + +#[cfg(target_os = "linux")] +fn store_imp(account: &str, password: &str) -> std::result::Result<(), StoreError> { + keyring::Entry::new(SERVICE, account)?.set_password(password) } #[cfg(not(any(target_os = "macos", target_os = "ios")))] -fn load_imp(_: &str) -> std::result::Result, StoreError> { - Err("keychain is only supported on Apple platforms".into()) +fn load_imp(account: &str) -> std::result::Result, StoreError> { + keyring::Entry::new(SERVICE, account)? + .get_password() + .map(String::into_bytes) } #[cfg(not(any(target_os = "macos", target_os = "ios")))] -fn delete_imp(_: &str) -> std::result::Result<(), StoreError> { - Ok(()) +fn delete_imp(account: &str) -> std::result::Result<(), StoreError> { + keyring::Entry::new(SERVICE, account)?.delete_credential() } #[cfg(all(test, target_os = "macos"))] diff --git a/packages/client/src/keychain/windows.rs b/packages/client/src/keychain/windows.rs new file mode 100644 index 0000000..0a11529 --- /dev/null +++ b/packages/client/src/keychain/windows.rs @@ -0,0 +1,45 @@ +//! Keep saved credentials on this computer. keyring's Windows writer defaults +//! to enterprise persistence, which allows Windows profile roaming. +use super::{SERVICE, StoreError}; +use windows_sys::Win32::Security::Credentials::{ + CRED_MAX_CREDENTIAL_BLOB_SIZE, CRED_PERSIST_LOCAL_MACHINE, CRED_TYPE_GENERIC, CREDENTIALW, + CredWriteW, +}; +use zeroize::Zeroizing; + +pub(super) fn store(account: &str, password: &str) -> Result<(), StoreError> { + if account.contains('\0') { + return Err(StoreError::Invalid( + "account".into(), + "contains a NUL".into(), + )); + } + // Retain keyring's target naming and UTF-16 blob encoding so existing items + // remain readable, editable and removable through its native backend. + let entry = keyring::windows::WinCredential::new_with_target(None, SERVICE, account)?; + let wide = |value: &str| value.encode_utf16().chain(Some(0)).collect::>(); + let mut target = wide(&entry.target_name); + let mut username = wide(&entry.username); + let mut secret = Zeroizing::new(password.encode_utf16().collect::>()); + let bytes = secret.len() * std::mem::size_of::(); + if bytes > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize { + return Err(StoreError::TooLong( + "password encoded as UTF-16".into(), + CRED_MAX_CREDENTIAL_BLOB_SIZE, + )); + } + // Zero initializes optional pointers, flags, attributes and the ignored + // timestamp. All referenced buffers remain live for this synchronous call. + let mut credential: CREDENTIALW = unsafe { std::mem::zeroed() }; + credential.Type = CRED_TYPE_GENERIC; + credential.TargetName = target.as_mut_ptr(); + credential.UserName = username.as_mut_ptr(); + credential.CredentialBlobSize = bytes as u32; + credential.CredentialBlob = secret.as_mut_ptr().cast(); + credential.Persist = CRED_PERSIST_LOCAL_MACHINE; + if unsafe { CredWriteW(&credential, 0) } == 0 { + Err(keyring::windows::decode_error()) + } else { + Ok(()) + } +} diff --git a/packages/client/src/session/handshake.rs b/packages/client/src/session/handshake.rs index 649a319..9840508 100644 --- a/packages/client/src/session/handshake.rs +++ b/packages/client/src/session/handshake.rs @@ -105,7 +105,11 @@ pub async fn connect_session_with_confirmation( magic: removent_proto::MAGIC, proto_version: removent_proto::PROTO_VERSION, // Honest declaration: file-transfer/two-way-audio are both unimplemented. - feature_bits: removent_proto::feature_bits::SOFTWARE_AV1 + feature_bits: (if cfg!(target_vendor = "apple") { + 0 + } else { + removent_proto::feature_bits::H264_ONLY + }) | removent_proto::feature_bits::SOFTWARE_AV1 | removent_proto::feature_bits::AUTH_METHODS | removent_proto::feature_bits::SYSTEM_ACCOUNT_AUTH | removent_proto::feature_bits::DYNAMIC_VIDEO diff --git a/packages/client/src/session/tests.rs b/packages/client/src/session/tests.rs index 9a8f745..13b9885 100644 --- a/packages/client/src/session/tests.rs +++ b/packages/client/src/session/tests.rs @@ -2,6 +2,11 @@ mod clipboard; use super::*; use removent_net::{ControlCodec, PinState, make_client_endpoint, make_server_endpoint}; use removent_proto::{AudioParams, CodecId, VideoParams}; +const TEST_CODEC: CodecId = if cfg!(target_os = "macos") { + CodecId::Hevc +} else { + CodecId::H264 +}; struct Peer { _endpoints: [removent_net::quinn::Endpoint; 2], @@ -53,7 +58,7 @@ async fn fixture( source.next().await.unwrap().unwrap(); let ack = NegotiateAck { video: VideoParams { - codec: CodecId::Hevc, + codec: TEST_CODEC, max_fps: 30, max_bitrate_kbps: 3000, initial_scale: 1., @@ -98,7 +103,7 @@ async fn missing_late_and_closed_audio_do_not_stop_video() { AudioPacketHeader, VideoFrameHeader, build_audio_packet, build_video_frame, video_flags, }; let (mut session, peer) = fixture(Caps::all(), None).await; - let mut encoder = VideoEncoder::new(CodecId::Hevc, 64, 64, 3000, 30).unwrap(); + let mut encoder = VideoEncoder::new(TEST_CODEC, 64, 64, 3000, 30).unwrap(); let encoded = encoder .encode_bgra(&[40, 80, 160, 255].repeat(64 * 64), 0) .unwrap() @@ -111,7 +116,7 @@ async fn missing_late_and_closed_audio_do_not_stop_video() { frame_id: n, pts_us: n as i64 * 100_000, flags: video_flags::KEYFRAME, - codec: CodecId::Hevc, + codec: TEST_CODEC, width: 64, height: 64, payload_len: encoded.data.len() as u32, @@ -191,7 +196,7 @@ async fn missing_video_still_closes_media_at_the_startup_deadline() { async fn receiver_stall_drives_host_adaptation_and_keeps_input_live() { use removent_core::{AdaptationController, QualityPreset}; use removent_media_codec::VideoEncoder; - use removent_proto::{CodecId, KeyKind, VideoFrameHeader, build_video_frame, video_flags}; + use removent_proto::{KeyKind, VideoFrameHeader, build_video_frame, video_flags}; let caps = Caps { audio: false, ..Caps::all() @@ -288,7 +293,7 @@ async fn receiver_stall_drives_host_adaptation_and_keeps_input_live() { .. } )); - let mut encoder = VideoEncoder::new(CodecId::Hevc, 320, 240, 3000, 30).unwrap(); + let mut encoder = VideoEncoder::new(TEST_CODEC, 320, 240, 3000, 30).unwrap(); let raw = [40, 80, 160, 255].repeat(320 * 240); let frame = encoder.encode_bgra(&raw, 0).unwrap().remove(0); let packet = build_video_frame( @@ -296,7 +301,7 @@ async fn receiver_stall_drives_host_adaptation_and_keeps_input_live() { frame_id: 0, pts_us: 0, flags: video_flags::KEYFRAME, - codec: CodecId::Hevc, + codec: TEST_CODEC, width: 320, height: 240, payload_len: frame.data.len() as u32, @@ -315,7 +320,7 @@ async fn receiver_stall_drives_host_adaptation_and_keeps_input_live() { frames_rx, keyframes_rx, quality_rx, - CodecId::Hevc, + TEST_CODEC, 320, 240, 3000, diff --git a/packages/client/tests/session_loopback.rs b/packages/client/tests/session_loopback.rs index 490084f..dbb865c 100644 --- a/packages/client/tests/session_loopback.rs +++ b/packages/client/tests/session_loopback.rs @@ -74,4 +74,5 @@ mod invitations; mod security; #[path = "session_loopback/automation.rs"] +#[cfg(unix)] mod automation; diff --git a/packages/core/Cargo.toml b/packages/core/Cargo.toml index 5babbdc..0e6e911 100644 --- a/packages/core/Cargo.toml +++ b/packages/core/Cargo.toml @@ -33,3 +33,6 @@ rustls = { workspace = true } [dev-dependencies] tempfile = "3" pkcs8 = { version = "0.11", features = ["pem", "std"] } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem"] } diff --git a/packages/core/src/desktop_instance.rs b/packages/core/src/desktop_instance.rs new file mode 100644 index 0000000..23581e2 --- /dev/null +++ b/packages/core/src/desktop_instance.rs @@ -0,0 +1,107 @@ +//! Per-data-directory desktop ownership and activation from a second launch. +//! Activation contains no command or address: it can only raise the existing window. +use crate::{CoreError, DataDirLock, DataPaths, Result}; +use std::{ + io::Read, + sync::{Arc, mpsc}, + time::Duration, +}; + +pub struct DesktopInstance { + _lock: DataDirLock, + _life: Arc<()>, + activations: mpsc::Receiver<()>, +} + +fn signal_path(paths: &DataPaths) -> std::path::PathBuf { + paths.run_dir().join("desktop-activate") +} + +fn read_signal(paths: &DataPaths) -> Option> { + let mut bytes = Vec::new(); + std::fs::File::open(signal_path(paths)) + .ok()? + .take(128) + .read_to_end(&mut bytes) + .ok()?; + Some(bytes) +} + +impl DesktopInstance { + /// The second launch asks the owner to activate, then exits without another engine. + pub fn claim(paths: &DataPaths) -> Result> { + paths.ensure_layout()?; + let lock = match DataDirLock::acquire_at(&paths.run_dir().join("desktop.lock")) { + Ok(lock) => lock, + Err(CoreError::AlreadyRunning) => { + crate::settings::atomic_write( + &signal_path(paths), + format!("{:032x}", rand::random::()).as_bytes(), + )?; + return Ok(None); + } + Err(error) => return Err(error), + }; + let life = Arc::new(()); + let alive = Arc::downgrade(&life); + let paths = paths.clone(); + let mut previous = read_signal(&paths); + let (send, activations) = mpsc::sync_channel(1); + std::thread::spawn(move || { + while alive.strong_count() > 0 { + std::thread::sleep(Duration::from_millis(150)); + let next = read_signal(&paths); + if next.is_some() && next != previous { + if matches!(send.try_send(()), Err(mpsc::TrySendError::Disconnected(_))) { + break; + } + previous = next; + } + } + }); + Ok(Some(Self { + _lock: lock, + _life: life, + activations, + })) + } + + pub fn take_activation(&self) -> bool { + self.activations.try_iter().count() > 0 + } + + pub fn is_running(paths: &DataPaths) -> bool { + matches!( + DataDirLock::acquire_at(&paths.run_dir().join("desktop.lock")), + Err(CoreError::AlreadyRunning) + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn second_launch_activates_only_its_data_directory_and_owner_can_restart() { + let a = tempfile::tempdir().unwrap(); + let b = tempfile::tempdir().unwrap(); + let paths = DataPaths { + root: a.path().into(), + }; + let other_paths = DataPaths { + root: b.path().into(), + }; + let first = DesktopInstance::claim(&paths).unwrap().unwrap(); + let other = DesktopInstance::claim(&other_paths).unwrap().unwrap(); + assert!(DesktopInstance::is_running(&paths)); + assert!(DesktopInstance::claim(&paths).unwrap().is_none()); + first + .activations + .recv_timeout(Duration::from_secs(2)) + .unwrap(); + assert!(!other.take_activation()); + drop(first); + assert!(!DesktopInstance::is_running(&paths)); + assert!(DesktopInstance::claim(&paths).unwrap().is_some()); + } +} diff --git a/packages/core/src/flock.rs b/packages/core/src/flock.rs index 39e31a8..2762c34 100644 --- a/packages/core/src/flock.rs +++ b/packages/core/src/flock.rs @@ -3,6 +3,7 @@ use crate::error::{CoreError, Result}; use crate::paths::DataPaths; use std::fs::File; +#[cfg(unix)] use std::os::unix::io::AsRawFd; pub struct DataDirLock { @@ -25,6 +26,7 @@ impl DataDirLock { Self::lock_at(lock_file, true) } + #[cfg(unix)] fn lock_at(lock_file: &std::path::Path, blocking: bool) -> Result { use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; if let Some(parent) = lock_file.parent() { @@ -66,6 +68,30 @@ impl DataDirLock { } Ok(Self { _file: file }) } + #[cfg(windows)] + fn lock_at(path: &std::path::Path, blocking: bool) -> Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(path)?; + if !file.metadata()?.is_file() { + return Err(std::io::Error::other("Invalid lock file").into()); + } + if blocking { + file.lock()?; + } else { + file.try_lock().map_err(|e| match e { + std::fs::TryLockError::WouldBlock => CoreError::AlreadyRunning, + std::fs::TryLockError::Error(e) => e.into(), + })?; + } + Ok(Self { _file: file }) + } } #[cfg(test)] @@ -88,6 +114,7 @@ mod tests { let _g2 = DataDirLock::acquire(&p).unwrap(); } + #[cfg(unix)] #[test] fn a_fifo_cannot_hang_service_or_recovery_startup() { let dir = tempdir().unwrap(); diff --git a/packages/core/src/identity.rs b/packages/core/src/identity.rs index 63f1a5c..e495997 100644 --- a/packages/core/src/identity.rs +++ b/packages/core/src/identity.rs @@ -82,12 +82,13 @@ fn create_and_store(paths: &DataPaths, _device_name: &str) -> Result { .map_err(|e| CoreError::Crypto(e.to_string()))?; let path = paths.device_key(); use std::io::Write; + #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(&path)?; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + options.mode(0o600); + let mut file = options.open(&path)?; file.write_all(pem.as_bytes())?; restrict_0600(&path)?; Ok(pem.to_string()) @@ -140,6 +141,7 @@ fn issue_self_signed(key: &SigningKey, device_name: &str) -> Result<(Vec, [u Ok((der, fp)) } +#[cfg(unix)] fn restrict_0600(path: &std::path::Path) -> Result<()> { use std::os::unix::fs::PermissionsExt; let mut perm = std::fs::metadata(path)?.permissions(); @@ -198,13 +200,16 @@ mod tests { &Signature::from_bytes(&bad) )); - use std::os::unix::fs::PermissionsExt; - let mode = std::fs::metadata(p.device_key()) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o600); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(p.device_key()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600); + } } #[test] @@ -228,3 +233,8 @@ mod tests { assert_ne!(a.fingerprint, b.fingerprint); } } + +#[cfg(windows)] +fn restrict_0600(_path: &std::path::Path) -> Result<()> { + Ok(()) +} diff --git a/packages/core/src/ipc.rs b/packages/core/src/ipc.rs index 86a87e8..058863f 100644 --- a/packages/core/src/ipc.rs +++ b/packages/core/src/ipc.rs @@ -6,7 +6,11 @@ use serde::{Deserialize, Serialize}; use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWriteExt}; +#[cfg(unix)] use tokio::net::UnixStream; +#[cfg(windows)] +#[path = "ipc_windows.rs"] +pub mod windows; /// Protocol version (bump on incompatible changes). pub const IPC_VERSION: u32 = 1; @@ -229,6 +233,7 @@ impl MessageReader { } /// Connect to the daemon's UDS (shared entry point for management clients). +#[cfg(unix)] pub async fn connect( paths: &crate::paths::DataPaths, ) -> std::io::Result<( @@ -281,9 +286,9 @@ mod tests { #[tokio::test] async fn json_lines_roundtrip() { - let (a, b) = UnixStream::pair().unwrap(); - let (ar, mut aw) = a.into_split(); - let (br, mut bw) = b.into_split(); + let (a, b) = tokio::io::duplex(4096); + let (ar, mut aw) = tokio::io::split(a); + let (br, mut bw) = tokio::io::split(b); let mut ar = tokio::io::BufReader::new(ar); let mut br = tokio::io::BufReader::new(br); @@ -336,10 +341,10 @@ mod tests { #[tokio::test] async fn blank_lines_are_skipped_not_eof() { - let (a, b) = UnixStream::pair().unwrap(); - let (ar, _aw) = a.into_split(); + let (a, b) = tokio::io::duplex(4096); + let (ar, _aw) = tokio::io::split(a); let mut ar = tokio::io::BufReader::new(ar); - let (_br, mut bw) = b.into_split(); + let (_br, mut bw) = tokio::io::split(b); bw.write_all(b"\n \n").await.unwrap(); write_msg(&mut bw, &IpcResponse::Ok).await.unwrap(); @@ -349,10 +354,10 @@ mod tests { #[tokio::test] async fn oversized_line_is_rejected() { - let (a, b) = UnixStream::pair().unwrap(); - let (ar, _aw) = a.into_split(); + let (a, b) = tokio::io::duplex(4096); + let (ar, _aw) = tokio::io::split(a); let mut ar = tokio::io::BufReader::new(ar); - let (_br, mut bw) = b.into_split(); + let (_br, mut bw) = tokio::io::split(b); // The payload far exceeds the socket buffer, so the write must be driven // concurrently with the read (writing first would deadlock). @@ -390,3 +395,26 @@ fn permission_requests_remain_compatible_and_can_target_one_grant() { .is_err() ); } + +#[cfg(windows)] +pub async fn connect( + paths: &crate::DataPaths, +) -> std::io::Result<( + tokio::io::BufReader>, + tokio::io::WriteHalf, +)> { + let name = windows::pipe_name(paths); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + match tokio::net::windows::named_pipe::ClientOptions::new().open(&name) { + Ok(stream) => { + let (r, w) = tokio::io::split(stream); + return Ok((tokio::io::BufReader::new(r), w)); + } + Err(e) if e.raw_os_error() == Some(231) && tokio::time::Instant::now() < deadline => { + tokio::time::sleep(std::time::Duration::from_millis(25)).await + } + Err(e) => return Err(e), + } + } +} diff --git a/packages/core/src/ipc_windows.rs b/packages/core/src/ipc_windows.rs new file mode 100644 index 0000000..24ab0cd --- /dev/null +++ b/packages/core/src/ipc_windows.rs @@ -0,0 +1,54 @@ +//! Per-data-directory named pipe with a protected owner-only DACL. +use std::{ffi::c_void, io}; +use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; +pub fn pipe_name(paths: &crate::DataPaths) -> String { + use sha2::{Digest, Sha256}; + let root = paths + .root + .canonicalize() + .unwrap_or_else(|_| paths.root.clone()); + format!( + r"\\.\pipe\removent-{}", + hex::encode(Sha256::digest( + root.to_string_lossy().to_lowercase().as_bytes() + )) + ) +} +pub fn server(paths: &crate::DataPaths, first: bool) -> io::Result { + use windows_sys::Win32::{ + Foundation::LocalFree, + Security::{ + Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, + SECURITY_ATTRIBUTES, + }, + }; + let sddl: Vec = "D:P(A;;GA;;;OW)\0".encode_utf16().collect(); + let mut descriptor = std::ptr::null_mut(); + // The owner-rights SID grants access only to the pipe's owner. Remote clients + // are rejected independently of the ACL. The descriptor is copied by CreateNamedPipe. + unsafe { + if ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl.as_ptr(), + 1, + &mut descriptor, + std::ptr::null_mut(), + ) == 0 + { + return Err(io::Error::last_os_error()); + } + let mut attrs = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: descriptor, + bInheritHandle: 0, + }; + let result = ServerOptions::new() + .first_pipe_instance(first) + .reject_remote_clients(true) + .create_with_security_attributes_raw( + pipe_name(paths), + (&mut attrs as *mut SECURITY_ATTRIBUTES).cast::(), + ); + LocalFree(descriptor); + result + } +} diff --git a/packages/core/src/lib.rs b/packages/core/src/lib.rs index fb66598..e1d5f2f 100644 --- a/packages/core/src/lib.rs +++ b/packages/core/src/lib.rs @@ -4,6 +4,7 @@ pub mod authentication; pub use authentication::{AuthenticationMode, AuthenticationSettings}; pub mod adapt; pub mod clip; +pub mod desktop_instance; pub mod error; pub mod flock; pub mod i18n; diff --git a/packages/core/src/logging.rs b/packages/core/src/logging.rs index edc8645..5f52599 100644 --- a/packages/core/src/logging.rs +++ b/packages/core/src/logging.rs @@ -3,7 +3,8 @@ use crate::paths::DataPaths; use std::fs::{self, File, OpenOptions}; use std::io::{self, Write}; -use std::os::unix::{fs::OpenOptionsExt, fs::PermissionsExt, io::AsRawFd}; +#[cfg(unix)] +use std::os::unix::{fs::OpenOptionsExt, fs::PermissionsExt}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use tracing::field::{Field, Visit}; @@ -139,16 +140,22 @@ impl<'writer> FormatFields<'writer> for SafeFields { fn private_dir(path: &Path) -> io::Result<()> { fs::create_dir_all(path)?; - fs::set_permissions(path, fs::Permissions::from_mode(0o700)) + #[cfg(unix)] + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + Ok(()) } fn private_file(path: &Path) -> io::Result { - let file = OpenOptions::new() - .append(true) - .create(true) - .mode(0o600) - .custom_flags(libc::O_NOFOLLOW) - .open(path)?; + let mut options = OpenOptions::new(); + options.append(true).create(true); + // Windows byte-range locks require read or write access, not append-only. + // The same helper opens the log's inter-process lock descriptor. + #[cfg(windows)] + options.read(true); + #[cfg(unix)] + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + let file = options.open(path)?; + #[cfg(unix)] file.set_permissions(fs::Permissions::from_mode(0o600))?; Ok(file) } @@ -156,16 +163,8 @@ fn private_file(path: &Path) -> io::Result { /// A fresh descriptor per acquisition also serializes independent threads in one process. fn lock_file(path: &Path) -> io::Result { let file = private_file(path)?; - loop { - // SAFETY: file owns a valid descriptor and remains alive for the lock's lifetime. - if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } == 0 { - return Ok(file); - } - let error = io::Error::last_os_error(); - if error.kind() != io::ErrorKind::Interrupted { - return Err(error); - } - } + file.lock()?; + Ok(file) } struct RollingLog { @@ -469,10 +468,12 @@ mod tests { .filter(|e| e.file_name().to_string_lossy().starts_with("panic-")) .collect::>(); assert_eq!(reports.len(), MAX_PANIC_REPORTS); + #[cfg(unix)] assert_eq!( fs::metadata(&panics).unwrap().permissions().mode() & 0o777, 0o700 ); + #[cfg(unix)] for report in reports { assert_eq!( report.metadata().unwrap().permissions().mode() & 0o777, diff --git a/packages/core/src/paths.rs b/packages/core/src/paths.rs index e0564e4..e4ce67b 100644 --- a/packages/core/src/paths.rs +++ b/packages/core/src/paths.rs @@ -105,7 +105,7 @@ fn resolve_root() -> PathBuf { Some(dir) if !dir.is_empty() => return PathBuf::from(dir), _ => {} } - if cfg!(debug_assertions) && workspace_root().is_some() { + if cfg!(debug_assertions) && workspace_root().is_some_and(|p| p.join("Cargo.toml").is_file()) { return workspace_root().unwrap().join("userdata"); } fallback_library_dir() @@ -117,6 +117,21 @@ fn workspace_root() -> Option { } fn fallback_library_dir() -> PathBuf { + #[cfg(windows)] + if let Some(dir) = std::env::var_os("LOCALAPPDATA") { + return PathBuf::from(dir).join("Removent/userdata"); + } + #[cfg(target_os = "linux")] + { + if let Some(dir) = std::env::var_os("XDG_DATA_HOME").filter(|p| Path::new(p).is_absolute()) + { + return PathBuf::from(dir).join("removent/userdata"); + } + if let Some(home) = std::env::var_os("HOME") { + return PathBuf::from(home).join(".local/share/removent/userdata"); + } + } + if let Some(home) = std::env::var_os("HOME") { return PathBuf::from(home).join("Library/Application Support/removent/userdata"); } diff --git a/packages/core/src/process.rs b/packages/core/src/process.rs index 808fe06..da6f081 100644 --- a/packages/core/src/process.rs +++ b/packages/core/src/process.rs @@ -1,5 +1,6 @@ //! Time-bounded system commands used by service management and recovery. use anyhow::{Result, bail}; +#[cfg(unix)] use std::os::unix::process::CommandExt; use std::{ io::Read, @@ -12,6 +13,7 @@ pub fn run_bounded(command: &mut Command, timeout: Duration) -> Result { .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); + #[cfg(unix)] unsafe { command.pre_exec(|| { if libc::setpgid(0, 0) == -1 { @@ -24,9 +26,12 @@ pub fn run_bounded(command: &mut Command, timeout: Duration) -> Result { impl Drop for Child { fn drop(&mut self) { if self.0.try_wait().ok().flatten().is_none() { + #[cfg(unix)] unsafe { libc::kill(-(self.0.id() as i32), libc::SIGKILL); } + #[cfg(windows)] + let _ = self.0.kill(); let _ = self.0.wait(); } } @@ -96,7 +101,7 @@ fn drain(mut stream: Box) -> std::io::Result> { } } -#[cfg(test)] +#[cfg(all(test, unix))] mod tests { use super::*; #[test] diff --git a/packages/core/src/settings.rs b/packages/core/src/settings.rs index 2cf6c1c..0542107 100644 --- a/packages/core/src/settings.rs +++ b/packages/core/src/settings.rs @@ -161,14 +161,21 @@ fn default_device_name() -> String { if let Ok(name) = std::env::var("REMOVENT_DEVICE_NAME") { return normalized_default_device_name(&name); } - // System hostname (macOS: same source as `scutil --get LocalHostName`). - let mut buf = [0u8; 256]; - let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) }; - if rc == 0 { - let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); - return normalized_default_device_name(&String::from_utf8_lossy(&buf[..end])); + #[cfg(windows)] + return normalized_default_device_name( + &std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()), + ); + #[cfg(unix)] + { + // System hostname (macOS: same source as `scutil --get LocalHostName`). + let mut buf = [0u8; 256]; + let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) }; + if rc == 0 { + let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); + return normalized_default_device_name(&String::from_utf8_lossy(&buf[..end])); + } + "Removent".to_string() } - "Mac".to_string() } impl Settings { @@ -240,21 +247,24 @@ impl Settings { } /// Atomic write via tmp + rename to avoid half-written files. -pub fn atomic_write(path: &PathBuf, bytes: &[u8]) -> Result<()> { +pub fn atomic_write(path: &std::path::Path, bytes: &[u8]) -> Result<()> { use std::io::Write; + #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; // Each writer owns a separate sibling file. A shared .tmp can be renamed // while another writer is still modifying it, corrupting the final file. let tmp = path.with_extension(format!("{:032x}.tmp", rand::random::())); - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(&tmp)?; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + options.mode(0o600); + let mut file = options.open(&tmp)?; let result = (|| -> std::io::Result<()> { file.write_all(bytes)?; file.sync_all()?; - std::fs::rename(&tmp, path) + // Finish and close the writer before the platform replacement step. + drop(file); + replace_written_file(&tmp, path) })(); if result.is_err() { let _ = std::fs::remove_file(&tmp); @@ -262,6 +272,83 @@ pub fn atomic_write(path: &PathBuf, bytes: &[u8]) -> Result<()> { result.map_err(Into::into) } +#[cfg(not(windows))] +fn replace_written_file(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { + std::fs::rename(from, to) +} + +#[cfg(windows)] +fn replace_written_file(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { + use std::os::windows::ffi::OsStrExt; + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::GENERIC_WRITE; + use windows_sys::Win32::Storage::FileSystem::{ + DELETE, FILE_FLAG_WRITE_THROUGH, FILE_RENAME_INFO, FileRenameInfoEx, + SetFileInformationByHandle, + }; + // Canonicalize the existing parent, not the possibly new destination, so + // Windows extended-length paths and non-ASCII data directories both work. + let parent = from.parent().filter(|p| !p.as_os_str().is_empty()); + let parent = std::fs::canonicalize(parent.unwrap_or(std::path::Path::new(".")))?; + let to: Vec = parent + .join(to.file_name().ok_or(std::io::ErrorKind::InvalidInput)?) + .as_os_str() + .encode_wide() + .collect(); + let file = std::fs::OpenOptions::new() + .access_mode(DELETE | GENERIC_WRITE) + .custom_flags(FILE_FLAG_WRITE_THROUGH) + .open(from)?; + // Unlike MoveFileExW, POSIX replacement keeps existing readers valid and + // makes every new open resolve to the new file, without a delete-pending + // interval that returns AccessDenied. Both flags are documented in + // FILE_RENAME_INFORMATION; they are not exported by windows-sys. + const REPLACE_IF_EXISTS: u32 = 1; + const POSIX_SEMANTICS: u32 = 2; + let size = std::mem::size_of::() + to.len() * 2; + let size_u32 = u32::try_from(size).map_err(|_| std::io::ErrorKind::InvalidInput)?; + // usize storage supplies the HANDLE alignment and room for the variable + // UTF-16 tail. Derive its pointer from the entire allocation, not the + // struct's one-element FileName array. + let mut storage = vec![0usize; size.div_ceil(std::mem::size_of::())]; + let information = storage.as_mut_ptr().cast::(); + unsafe { + (*information).Anonymous.Flags = REPLACE_IF_EXISTS | POSIX_SEMANTICS; + (*information).FileNameLength = (to.len() * 2) as u32; + let name = storage + .as_mut_ptr() + .cast::() + .add(std::mem::offset_of!(FILE_RENAME_INFO, FileName)) + .cast::(); + std::ptr::copy_nonoverlapping(to.as_ptr(), name, to.len()); + } + // External software may temporarily open a file without delete sharing. + // Retry the same atomic operation; never delete the destination first or + // fall back to MoveFileExW's weaker replacement semantics. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1); + loop { + if unsafe { + SetFileInformationByHandle( + file.as_raw_handle(), + FileRenameInfoEx, + information.cast(), + size_u32, + ) + } != 0 + { + return file.sync_all(); + } + let error = std::io::Error::last_os_error(); + if !matches!(error.raw_os_error(), Some(5 | 32 | 33)) + || std::time::Instant::now() >= deadline + { + return Err(error); + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } +} + #[cfg(test)] mod tests { use super::*; @@ -311,6 +398,7 @@ mod tests { #[test] fn concurrent_writers_publish_complete_private_files() { + #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use std::sync::{Arc, Barrier}; let dir = tempdir().unwrap(); @@ -323,7 +411,7 @@ mod tests { scope.spawn(move || { let payload = vec![byte; 64 * 1024]; barrier.wait(); - for _ in 0..10 { + for _ in 0..50 { atomic_write(path, &payload).unwrap(); let visible = std::fs::read(path).unwrap(); assert_eq!(visible.len(), payload.len()); @@ -332,6 +420,7 @@ mod tests { }); } }); + #[cfg(unix)] assert_eq!( std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600 @@ -339,6 +428,22 @@ mod tests { assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } + #[test] + fn held_reader_keeps_old_snapshot_during_atomic_replace() { + use std::io::Read; + let dir = tempdir().unwrap(); + let parent = dir.path().join("配置目录"); + std::fs::create_dir(&parent).unwrap(); + let path = parent.join("设置🪟.toml"); + atomic_write(&path, b"old snapshot").unwrap(); + let mut old_reader = std::fs::File::open(&path).unwrap(); + atomic_write(&path, b"new snapshot").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"new snapshot"); + let mut retained = Vec::new(); + old_reader.read_to_end(&mut retained).unwrap(); + assert_eq!(retained, b"old snapshot"); + } + #[test] fn failed_atomic_save_cleans_its_temporary_file() { let dir = tempdir().unwrap(); diff --git a/packages/core/src/settings/control/tests.rs b/packages/core/src/settings/control/tests.rs index 5fd46f2..aa64015 100644 --- a/packages/core/src/settings/control/tests.rs +++ b/packages/core/src/settings/control/tests.rs @@ -120,7 +120,9 @@ fn cli_edits_share_the_desktop_and_daemon_lock() { let settings = Settings::load_strict(&paths).unwrap(); assert!(!settings.host_enabled); assert_eq!(settings.device_name, "Office Mac"); + #[cfg(unix)] use std::os::unix::fs::PermissionsExt; + #[cfg(unix)] assert_eq!( std::fs::metadata(paths.settings_file()) .unwrap() diff --git a/packages/core/src/system_service/install.rs b/packages/core/src/system_service/install.rs index a04a7b1..0240527 100644 --- a/packages/core/src/system_service/install.rs +++ b/packages/core/src/system_service/install.rs @@ -157,7 +157,7 @@ pub(super) fn publish(staged: &Path, root: &Path, plist: &Path, enabled: bool) - } let result = (|| -> Result<()> { if enabled { - crate::settings::atomic_write(&plist.to_path_buf(), definition(root).as_bytes())?; + crate::settings::atomic_write(plist, definition(root).as_bytes())?; fs::set_permissions(plist, fs::Permissions::from_mode(0o644))?; crate::service_intent::set_stopped( &DataPaths { @@ -177,7 +177,7 @@ pub(super) fn publish(staged: &Path, root: &Path, plist: &Path, enabled: bool) - } match previous_plist { Some(bytes) => { - crate::settings::atomic_write(&plist.to_path_buf(), &bytes)?; + crate::settings::atomic_write(plist, &bytes)?; fs::set_permissions(plist, fs::Permissions::from_mode(0o644))?; } None if plist.is_file() => fs::remove_file(plist)?, diff --git a/packages/core/src/update_gate.rs b/packages/core/src/update_gate.rs index 70318d8..845a2f1 100644 --- a/packages/core/src/update_gate.rs +++ b/packages/core/src/update_gate.rs @@ -3,7 +3,7 @@ use crate::DataPaths; use std::fs::{File, OpenOptions}; use std::io; -use std::os::fd::AsRawFd; +#[cfg(unix)] use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; @@ -25,13 +25,16 @@ pub fn bundle_lock_file(bundle: &Path) -> io::Result { let home = std::env::var_os("HOME").ok_or_else(|| io::Error::other("HOME unavailable"))?; let root = PathBuf::from(home).join("Library/Application Support/removent/update-locks"); std::fs::create_dir_all(&root)?; + #[cfg(unix)] let meta = std::fs::symlink_metadata(&root)?; + #[cfg(unix)] if !meta.is_dir() || meta.uid() != unsafe { libc::geteuid() } || meta.mode() & 0o022 != 0 { return Err(io::Error::new( io::ErrorKind::PermissionDenied, "Unsafe installation lock directory", )); } + #[cfg(unix)] std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?; let parent = bundle .parent() @@ -74,15 +77,16 @@ fn acquire(paths: &DataPaths, exclusive: bool) -> io::Result { } fn acquire_file(path: &Path, exclusive: bool) -> io::Result { - let file = OpenOptions::new() - .create(true) - .truncate(false) - .read(true) - .write(true) + let mut options = OpenOptions::new(); + options.create(true).truncate(false).read(true).write(true); + #[cfg(unix)] + options .mode(0o600) - .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK) - .open(path)?; + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK); + let file = options.open(path)?; + #[cfg(unix)] let meta = file.metadata()?; + #[cfg(unix)] if !meta.is_file() || meta.uid() != unsafe { libc::geteuid() } || meta.nlink() != 1 @@ -93,20 +97,16 @@ fn acquire_file(path: &Path, exclusive: bool) -> io::Result { "unsafe update admission lock", )); } - loop { - let flags = if exclusive { - libc::LOCK_EX - } else { - libc::LOCK_SH - } | libc::LOCK_NB; - if unsafe { libc::flock(file.as_raw_fd(), flags) } == 0 { - return Ok(file); - } - let error = io::Error::last_os_error(); - if error.kind() != io::ErrorKind::Interrupted { - return Err(error); - } + if exclusive { + file.try_lock() + } else { + file.try_lock_shared() } + .map_err(|e| match e { + std::fs::TryLockError::WouldBlock => io::Error::from(io::ErrorKind::WouldBlock), + std::fs::TryLockError::Error(e) => e, + })?; + Ok(file) } impl ActivityLease { @@ -170,6 +170,7 @@ mod tests { drop(maintenance); assert!(ActivityLease::acquire(&paths).is_ok()); } + #[cfg(unix)] #[test] fn a_symlink_cannot_redirect_the_gate() { let temp = tempfile::tempdir().unwrap(); diff --git a/packages/host/Cargo.toml b/packages/host/Cargo.toml index 3983545..e9c24e0 100644 --- a/packages/host/Cargo.toml +++ b/packages/host/Cargo.toml @@ -26,8 +26,22 @@ des = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] core-foundation = { workspace = true } -libc = { workspace = true } +libc.workspace = true + [dev-dependencies] -apple-cf = "0.11" tempfile = "3" + +[target.'cfg(target_os = "macos")'.dev-dependencies] +apple-cf = "0.11" +[target.'cfg(target_os = "linux")'.dependencies] +libc.workspace = true +pam-client = "0.5" +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Threading"] } +zeroize = "1.9" + +# pam-sys disables bindgen defaults; explicitly load libclang when other build +# dependencies enable clang-sys runtime loading through feature unification. +[target.'cfg(target_os = "linux")'.build-dependencies] +bindgen = { version = "0.69", default-features = false, features = ["runtime"] } diff --git a/packages/host/examples/desktop_smoke.rs b/packages/host/examples/desktop_smoke.rs new file mode 100644 index 0000000..7ef83e9 --- /dev/null +++ b/packages/host/examples/desktop_smoke.rs @@ -0,0 +1,104 @@ +//! Run only in an isolated interactive desktop (CI Xvfb/Windows runner). +use removent_proto::{CodecId, KeyKind, KeyModifiers, MouseKind}; +use std::time::Duration; +#[tokio::main] +async fn main() -> anyhow::Result<()> { + #[cfg(windows)] + removent_input::initialize_host_dpi(); + anyhow::ensure!( + std::env::var("REMOVENT_DESKTOP_TEST").as_deref() == Ok("1"), + "Requires an isolated desktop and REMOVENT_DESKTOP_TEST=1" + ); + let display = removent_input::DisplayGeometry::main() + .ok_or_else(|| anyhow::anyhow!("No interactive display"))?; + let (tx, mut rx) = removent_core::latest::channel(); + let _capture = removent_media_capture::start_display_capture(display.id, 640, 480, tx, None)?; + let frame = tokio::time::timeout(Duration::from_secs(10), rx.recv()) + .await? + .ok_or_else(|| anyhow::anyhow!("No captured frame"))?; + let pixels = frame + .pixels + .bgra(frame.width, frame.height) + .map_err(anyhow::Error::msg)?; + anyhow::ensure!(pixels.len() == 640 * 480 * 4, "Capture size"); + // The UI fixture paints red; verify real capture contains the known color. + anyhow::ensure!( + pixels + .as_chunks::<4>() + .0 + .iter() + .any(|p| p[2] > 180 && p[1] < 80 && p[0] < 80), + "Fixture color absent from capture" + ); + let mut encoder = removent_media_codec::VideoEncoder::new(CodecId::H264, 640, 480, 6000, 30)?; + let packets = encoder.encode_bgra(&pixels, 0)?; + anyhow::ensure!( + !packets.is_empty() && packets[0].keyframe, + "No initial H264 keyframe" + ); + let decoder = removent_media_codec::VideoDecoder::new( + CodecId::H264, + 640, + 480, + encoder.parameter_sets().unwrap_or(&[]), + )?; + for packet in packets { + decoder.decode_annexb(&packet.data, packet.pts_us)?; + } + decoder.flush()?; + let decoded = decoder + .try_recv_decoded() + .ok_or_else(|| anyhow::anyhow!("No decoded H264 frame"))?; + anyhow::ensure!(decoded.data.len() == pixels.len(), "Decoded size"); + anyhow::ensure!( + decoded + .data + .as_chunks::<4>() + .0 + .iter() + .any(|p| p[2] > 160 && p[1] < 100 && p[0] < 100), + "Decoded color absent" + ); + removent_input::write_text("Removent clipboard smoke")?; + anyhow::ensure!( + removent_input::read_text()? == "Removent clipboard smoke", + "Clipboard roundtrip" + ); + let mut mouse = removent_input::mouse::MouseInjector::default(); + let mut keyboard = removent_input::keyboard::KeyboardInjector::default(); + // The fixture owns these coordinates and reports events independently. + let x = std::env::var("REMOVENT_TEST_X")?.parse::()?; + let y = std::env::var("REMOVENT_TEST_Y")?.parse::()?; + mouse + .inject(MouseKind::LeftDown, x, y, KeyModifiers::empty()) + .map_err(anyhow::Error::msg)?; + mouse + .inject(MouseKind::LeftUp, x, y, KeyModifiers::empty()) + .map_err(anyhow::Error::msg)?; + for (vk, mods, kind) in [ + (0x3b, KeyModifiers::CONTROL, KeyKind::FlagsChanged), + (0x00, KeyModifiers::CONTROL, KeyKind::Down), + (0x00, KeyModifiers::CONTROL, KeyKind::Up), + (0x3b, KeyModifiers::empty(), KeyKind::FlagsChanged), + ] { + keyboard + .inject(vk, mods, kind, None) + .map_err(anyhow::Error::msg)?; + } + for ch in "hello中文".chars() { + // Exercise both committed IME text and a non-ASCII physical-key payload. + let vk = if ch == '文' { + 0x00 + } else { + removent_input::UNICODE_ONLY_VK + }; + keyboard + .inject(vk, KeyModifiers::empty(), KeyKind::Down, Some(ch)) + .map_err(anyhow::Error::msg)?; + keyboard + .inject(vk, KeyModifiers::empty(), KeyKind::Up, Some(ch)) + .map_err(anyhow::Error::msg)?; + } + println!("capture, H264 encode/decode, clipboard and native input submitted"); + Ok(()) +} diff --git a/packages/host/src/input_sink.rs b/packages/host/src/input_sink.rs index 81bb9a1..f6a181a 100644 --- a/packages/host/src/input_sink.rs +++ b/packages/host/src/input_sink.rs @@ -83,6 +83,8 @@ pub struct RealInputSink { struct SessionInjection { mouse: removent_input::mouse::MouseInjector, keyboard: removent_input::keyboard::KeyboardInjector, + #[cfg(not(target_os = "macos"))] + scroll: removent_input::keyboard::ScrollInjector, } impl RealInputSink { @@ -165,11 +167,18 @@ impl InputSink for RealInputSink { .map(|g| g.dpi()) .unwrap_or(96.0); let px_per_mm = dpi / 25.4; - removent_input::keyboard::inject_scroll_with_modifiers( + #[cfg(target_os = "macos")] + return removent_input::keyboard::inject_scroll_with_modifiers( dx_mm as f64 * px_per_mm, dy_mm as f64 * px_per_mm, phase, self.injection.lock().unwrap().keyboard.modifiers, + ); + #[cfg(not(target_os = "macos"))] + self.injection.lock().unwrap().scroll.inject( + dx_mm as f64 * px_per_mm, + dy_mm as f64 * px_per_mm, + phase, ) } diff --git a/packages/host/src/runner/capture.rs b/packages/host/src/runner/capture.rs index 7aeefce..2d850bf 100644 --- a/packages/host/src/runner/capture.rs +++ b/packages/host/src/runner/capture.rs @@ -1,13 +1,14 @@ //! Rebuild capture without replacing the authenticated control/media session. use super::*; -use removent_media_capture::{ - AudioFrame, CaptureError, CapturedVideoFrame, SckCapture, quartz::QuartzCapture, -}; +#[cfg(target_os = "macos")] +use removent_media_capture::quartz::QuartzCapture; +use removent_media_capture::{AudioFrame, CaptureError, CapturedVideoFrame, SckCapture}; use removent_proto::DisplayInfo; use tokio::sync::mpsc; enum RunningCapture { Sck(SckCapture, mpsc::Receiver), + #[cfg(target_os = "macos")] Quartz(QuartzCapture, mpsc::Receiver), } @@ -18,6 +19,7 @@ impl RunningCapture { .recv() .await .unwrap_or_else(|| CaptureError::Sc("capture delegate closed".into())), + #[cfg(target_os = "macos")] Self::Quartz(_, rx) => CaptureError::Sc( rx.recv() .await @@ -28,6 +30,7 @@ impl RunningCapture { fn health_failure(&self) -> Option<&'static str> { match self { Self::Sck(capture, _) => capture.health_failure(), + #[cfg(target_os = "macos")] Self::Quartz(capture, _) => capture.health_failure(), } } @@ -72,12 +75,16 @@ pub(super) async fn run( let video = video.clone(); let audio = audio.clone(); let start = tokio::task::spawn_blocking(move || { - if legacy { - let mut stream = removent_media_capture::quartz::start(id as u32, w, h, video) - .map_err(CaptureError::Sc)?; - let stopped = stream.take_stopped_rx().expect("new stream"); - Ok(RunningCapture::Quartz(stream, stopped)) - } else { + if legacy && cfg!(target_os = "macos") { + #[cfg(target_os = "macos")] + { + let mut stream = removent_media_capture::quartz::start(id as u32, w, h, video) + .map_err(CaptureError::Sc)?; + let stopped = stream.take_stopped_rx().expect("new stream"); + return Ok(RunningCapture::Quartz(stream, stopped)); + } + } + { let mut stream = removent_media_capture::sck::start_remote_capture( id as u32, w, h, video, audio, fps, )?; diff --git a/packages/host/src/runner/connection.rs b/packages/host/src/runner/connection.rs index 5e77651..b73e829 100644 --- a/packages/host/src/runner/connection.rs +++ b/packages/host/src/runner/connection.rs @@ -100,7 +100,7 @@ pub(super) async fn run_connection( let host_cfg = HostConfig { authentication: ctx.settings.authentication.clone(), auth_paths: Some(ctx.paths.clone()), - audio_available: !ctx.settings.window_server_capture, + audio_available: cfg!(target_os = "macos") && !ctx.settings.window_server_capture, preapproved_only: ctx.settings.paired_only, device_name: ctx.settings.device_name.clone(), admission: ctx.settings.admission, diff --git a/packages/host/src/runner/display.rs b/packages/host/src/runner/display.rs index 1a1d54b..f79882f 100644 --- a/packages/host/src/runner/display.rs +++ b/packages/host/src/runner/display.rs @@ -1,6 +1,7 @@ //! Wake and retain the capture display for an admitted remote session. use crate::session::HostError; +#[cfg(target_os = "macos")] use core_foundation::{ base::TCFType, string::{CFString, CFStringRef}, @@ -8,6 +9,7 @@ use core_foundation::{ use removent_proto::DisplayInfo; use std::time::Duration; +#[cfg(target_os = "macos")] #[link(name = "IOKit", kind = "framework")] unsafe extern "C" { fn IOPMAssertionDeclareUserActivity(name: CFStringRef, user_type: u32, id: *mut u32) -> i32; @@ -22,8 +24,10 @@ unsafe extern "C" { /// Power assertions are scoped to the session, including failed negotiation, /// peer disconnect, and cancellation. This never changes Energy Saver settings. +#[cfg(target_os = "macos")] pub(super) struct DisplayAwake(Vec); +#[cfg(target_os = "macos")] impl DisplayAwake { pub(super) fn new() -> Self { let name = CFString::new("Removent remote desktop capture"); @@ -57,6 +61,7 @@ impl DisplayAwake { } } +#[cfg(target_os = "macos")] impl Drop for DisplayAwake { fn drop(&mut self) { for id in &self.0 { @@ -157,3 +162,12 @@ mod tests { assert!(matches!(result, Err(HostError::Timeout(_)))); } } + +#[cfg(not(target_os = "macos"))] +pub(super) struct DisplayAwake; +#[cfg(not(target_os = "macos"))] +impl DisplayAwake { + pub(super) fn new() -> Self { + Self + } +} diff --git a/packages/host/src/session/handshake.rs b/packages/host/src/session/handshake.rs index 8d90ba3..de2633c 100644 --- a/packages/host/src/session/handshake.rs +++ b/packages/host/src/session/handshake.rs @@ -124,8 +124,12 @@ where | removent_proto::feature_bits::AUTH_METHODS | removent_proto::feature_bits::SYSTEM_ACCOUNT_AUTH | removent_proto::feature_bits::DYNAMIC_VIDEO - | removent_proto::feature_bits::AUTOMATION_HANDOVER - | removent_proto::feature_bits::AUTOMATION, + | if cfg!(target_os = "macos") { + removent_proto::feature_bits::AUTOMATION_HANDOVER + | removent_proto::feature_bits::AUTOMATION + } else { + 0 + }, device_name: cfg.device_name.clone(), // Honest resume verdict (§7.4): Some(true) only when the presented token // validated; Some(false) tells the client to fall back to full @@ -351,9 +355,12 @@ where let short = peer_fp.chars().take(16).collect::(); // protocol.md §4.4: an admission prompt with no response within 30s is treated as a rejection. let prompt = (interactions.admission_prompt)(hello.hello.device_name.clone(), short); - let allowed = tokio::time::timeout(Duration::from_secs(30), prompt) - .await - .unwrap_or(false); + let allowed = tokio::select! { + // Drop the daemon's pending admission immediately, broadcasting + // resolution to every UI when the controller cancels. + _ = conn.inner().closed() => return Err(HostError::Rejected("controller disconnected during admission".into())), + result = tokio::time::timeout(Duration::from_secs(30), prompt) => result.unwrap_or(false), + }; if !allowed { sink.send(ControlMsg::SessionReject { reason: removent_proto::RejectReason::Denied, diff --git a/packages/host/src/session/handshake/system_account.rs b/packages/host/src/session/handshake/system_account.rs index 4418a7f..341def3 100644 --- a/packages/host/src/session/handshake/system_account.rs +++ b/packages/host/src/session/handshake/system_account.rs @@ -1,5 +1,5 @@ //! Verify the account owning this desktop service, never another user's desktop. -//! Passwords go directly to Open Directory, without shell arguments or persistence. +//! Passwords go directly to the OS authentication API, without shell arguments or persistence. use removent_proto::SystemCredentials; use super::*; @@ -61,9 +61,131 @@ pub(super) async fn exchange( } } -#[cfg(not(target_os = "macos"))] -pub(super) fn verify(_: &SystemCredentials) -> bool { - false +#[cfg(target_os = "linux")] +pub(super) fn verify(credentials: &SystemCredentials) -> bool { + if !credentials.valid() { + return false; + } + // Require the UID of the running desktop, not an arbitrary valid account. + let Ok(name) = std::ffi::CString::new(credentials.username.as_str()) else { + return false; + }; + let mut entry: libc::passwd = unsafe { std::mem::zeroed() }; + let mut result = std::ptr::null_mut(); + let mut storage = vec![0; 65536]; + if unsafe { + libc::getpwnam_r( + name.as_ptr(), + &mut entry, + storage.as_mut_ptr(), + storage.len(), + &mut result, + ) + } != 0 + || result.is_null() + || entry.pw_uid != unsafe { libc::geteuid() } + || entry.pw_uid == 0 + { + return false; + } + let conversation = pam_client::conv_mock::Conversation::with_credentials( + &credentials.username, + &credentials.password, + ); + let Ok(mut client) = + pam_client::Context::new("login", Some(&credentials.username), conversation) + else { + return false; + }; + client + .authenticate(pam_client::Flag::DISALLOW_NULL_AUTHTOK) + .is_ok() + && client.acct_mgmt(pam_client::Flag::NONE).is_ok() + && client.user().is_ok_and(|name| name == credentials.username) +} +#[cfg(any(windows, test))] +fn windows_logon_identity(username: &str) -> (Option<&str>, &str) { + if let Some((domain, name)) = username.split_once('\\') { + (Some(domain), name) + } else if username.contains('@') { + (None, username) + } else { + (Some("."), username) + } +} + +#[cfg(windows)] +pub(super) fn verify(credentials: &SystemCredentials) -> bool { + use windows_sys::Win32::{ + Foundation::{CloseHandle, HANDLE}, + Security::*, + System::Threading::{GetCurrentProcess, OpenProcessToken}, + }; + use zeroize::Zeroize; + if !credentials.valid() { + return false; + } + struct Token(HANDLE); + impl Drop for Token { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } + } + fn user(token: HANDLE) -> Option> { + let mut needed = 0; + unsafe { + GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &mut needed); + } + let mut buffer = vec![0usize; (needed as usize).div_ceil(std::mem::size_of::())]; + (unsafe { + GetTokenInformation( + token, + TokenUser, + buffer.as_mut_ptr().cast(), + needed, + &mut needed, + ) + } != 0) + .then_some(buffer) + } + let (domain, name) = windows_logon_identity(&credentials.username); + let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::>(); + let name = wide(name); + let domain = domain.map(wide); + let mut password = wide(&credentials.password); + let mut authenticated = std::ptr::null_mut(); + let ok = unsafe { + LogonUserW( + name.as_ptr(), + domain.as_ref().map_or(std::ptr::null(), |d| d.as_ptr()), + password.as_ptr(), + LOGON32_LOGON_NETWORK, + LOGON32_PROVIDER_DEFAULT, + &mut authenticated, + ) + }; + // Volatile writes prevent the optimizer from removing the password wipe. + password.zeroize(); + if ok == 0 { + return false; + } + let authenticated = Token(authenticated); + let mut current = std::ptr::null_mut(); + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut current) } == 0 { + return false; + } + let current = Token(current); + let (Some(a), Some(b)) = (user(authenticated.0), user(current.0)) else { + return false; + }; + unsafe { + EqualSid( + (*(a.as_ptr().cast::())).User.Sid, + (*(b.as_ptr().cast::())).User.Sid, + ) != 0 + } } #[cfg(target_os = "macos")] @@ -154,6 +276,93 @@ pub(super) fn verify(credentials: &SystemCredentials) -> bool { #[cfg(test)] mod tests { use super::*; + #[test] + fn windows_account_names_preserve_explicit_domains() { + for (input, domain, name) in [ + ("alice", Some("."), "alice"), + ("WORKGROUP\\alice", Some("WORKGROUP"), "alice"), + ("alice@example.com", None, "alice@example.com"), + ( + "MicrosoftAccount\\alice@example.com", + Some("MicrosoftAccount"), + "alice@example.com", + ), + ] { + assert_eq!(windows_logon_identity(input), (domain, name)); + } + } + #[tokio::test] + #[ignore = "requires an isolated OS account with REMOVENT_AUTH_TEST_USERNAME/PASSWORD"] + async fn native_desktop_account_authentication() { + let username = std::env::var("REMOVENT_AUTH_TEST_USERNAME").unwrap(); + let password = std::env::var("REMOVENT_AUTH_TEST_PASSWORD").unwrap(); + if std::env::var("REMOVENT_AUTH_EXPECT_REJECT").as_deref() == Ok("1") { + assert!(!authenticate_over_quic(SystemCredentials { username, password }).await); + return; + } + assert!( + authenticate_over_quic(SystemCredentials { + username: username.clone(), + password, + }) + .await + ); + assert!( + !authenticate_over_quic(SystemCredentials { + username, + password: "intentionally-wrong-native-test-password".into(), + }) + .await + ); + assert!( + !authenticate_over_quic(SystemCredentials { + username: "removent-nonexistent-test-account".into(), + password: "irrelevant".into(), + }) + .await + ); + } + async fn authenticate_over_quic(credentials: SystemCredentials) -> bool { + let (_endpoints, client, host) = crate::session::tests::quic_pair().await; + let peer = hex::encode(host.peer_fingerprint().unwrap()); + let client_fp = peer.clone(); + let server = host.clone(); + let task = tokio::spawn(async move { + let (mut sink, mut source) = server.accept_pairing().await.unwrap(); + let begin = source.next().await.unwrap().unwrap(); + exchange(begin, &peer, &mut sink, &mut source, verify).await + }); + let (mut sink, mut source) = client.open_pairing().await.unwrap(); + let nonce_c = [9; 16]; + sink.send(PairingMsg::Begin { + nonce_c, + fp_c: client_fp, + }) + .await + .unwrap(); + let PairingMsg::SystemChallenge { nonce_h } = source.next().await.unwrap().unwrap() else { + panic!("system challenge"); + }; + sink.send(PairingMsg::SystemVerify { + nonce_c, + nonce_h, + credentials, + }) + .await + .unwrap(); + let PairingMsg::SystemConfirm { + nonce_c: confirmed_c, + nonce_h: confirmed_h, + ok, + } = source.next().await.unwrap().unwrap() + else { + panic!("system confirmation"); + }; + assert_eq!(confirmed_c, nonce_c); + assert_eq!(confirmed_h, nonce_h); + assert_eq!(task.await.unwrap().is_ok(), ok); + ok + } #[tokio::test] async fn exchange_requires_matching_nonces_and_successful_verification() { for (password, replay, expected) in [ diff --git a/packages/host/src/session/negotiation.rs b/packages/host/src/session/negotiation.rs index 7008ab3..b1fd270 100644 --- a/packages/host/src/session/negotiation.rs +++ b/packages/host/src/session/negotiation.rs @@ -31,11 +31,18 @@ pub(super) fn preferred_video_codec( bitrate_kbps: u32, fps: u8, ) -> CodecId { + let fallback = if cfg!(not(target_vendor = "apple")) + || peer_features & removent_proto::feature_bits::H264_ONLY != 0 + { + CodecId::H264 + } else { + CodecId::Hevc + }; let requested = std::env::var("REMOVENT_VIDEO_CODEC") .ok() .is_some_and(|v| v.eq_ignore_ascii_case("av1") || v.eq_ignore_ascii_case("software-av1")); if !requested || peer_features & removent_proto::feature_bits::SOFTWARE_AV1 == 0 { - return CodecId::Hevc; + return fallback; } let (w, h) = fit_capture_dims(display_w, display_h); if removent_media_codec::VideoEncoder::new( @@ -50,6 +57,6 @@ pub(super) fn preferred_video_codec( CodecId::Av1 } else { tracing::warn!("software AV1 probe failed; falling back to HEVC"); - CodecId::Hevc + fallback } } diff --git a/packages/host/src/session/tests.rs b/packages/host/src/session/tests.rs index 57945a7..95dbf2c 100644 --- a/packages/host/src/session/tests.rs +++ b/packages/host/src/session/tests.rs @@ -232,7 +232,10 @@ async fn video_packet( #[tokio::test] async fn static_recovery_probe_uses_temporal_compression_and_explicit_refresh_is_keyframe() { - for codec in [CodecId::H264, CodecId::Hevc] { + for codec in [CodecId::H264, CodecId::Hevc] + .into_iter() + .filter(|codec| cfg!(target_os = "macos") || *codec != CodecId::Hevc) + { let (_endpoints, client, host) = quic_pair().await; let max = QualityState { bitrate_kbps: 3000, @@ -321,7 +324,10 @@ async fn static_recovery_probe_uses_temporal_compression_and_explicit_refresh_is #[tokio::test] async fn dynamic_quality_refreshes_static_frame_and_decodes_each_size() { - for codec in [CodecId::H264, CodecId::Hevc, CodecId::Av1] { + for codec in [CodecId::H264, CodecId::Hevc, CodecId::Av1] + .into_iter() + .filter(|codec| cfg!(target_os = "macos") || *codec != CodecId::Hevc) + { let (_endpoints, client, host) = quic_pair().await; let max = QualityState { bitrate_kbps: 3000, diff --git a/packages/host/src/session/tests/capture.rs b/packages/host/src/session/tests/capture.rs index a103e8f..86a0e3d 100644 --- a/packages/host/src/session/tests/capture.rs +++ b/packages/host/src/session/tests/capture.rs @@ -18,7 +18,11 @@ async fn capture_restart_refreshes_identical_pixels_and_new_dimensions_on_same_s rx, kf_rx, quality_rx, - CodecId::Hevc, + if cfg!(target_os = "macos") { + CodecId::Hevc + } else { + CodecId::H264 + }, 320, 240, 3000, @@ -67,6 +71,7 @@ async fn capture_restart_refreshes_identical_pixels_and_new_dimensions_on_same_s /// Manual release-mode throughput measurement, independent of CI load. Exercises /// production pacing, encode, encrypted QUIC, and decode; excludes SCK and GPUI. +#[cfg(target_os = "macos")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "manual 1080p60 throughput measurement; run with --release --ignored --nocapture"] async fn lan_video_throughput() { @@ -217,6 +222,7 @@ async fn lan_video_throughput() { } /// IOSurface-backed fixture, filled before it is shared with the encoder. +#[cfg(target_os = "macos")] pub(super) fn native_buffer(w: usize, h: usize, pixels: &[u8]) -> apple_cf::cv::CVPixelBuffer { let stride = (w * 4).next_multiple_of(64); let surface = apple_cf::iosurface::IOSurface::create_with_properties( diff --git a/packages/host/src/session/tests/resolution.rs b/packages/host/src/session/tests/resolution.rs index d7cf8ba..440a8f0 100644 --- a/packages/host/src/session/tests/resolution.rs +++ b/packages/host/src/session/tests/resolution.rs @@ -5,12 +5,18 @@ async fn uhd_to_540p_and_back_decodes_without_replacing_the_stream() { dynamic_resolution(false).await; } +#[cfg(target_os = "macos")] #[tokio::test] async fn native_uhd_to_540p_and_back_decodes_without_cpu_readback() { dynamic_resolution(true).await; } async fn dynamic_resolution(native: bool) { + let codec = if cfg!(target_os = "macos") { + CodecId::Hevc + } else { + CodecId::H264 + }; let (_endpoints, client, host) = quic_pair().await; let (tx, rx) = removent_core::latest::channel(); let (_kf, kf_rx) = mpsc::channel(1); @@ -27,7 +33,7 @@ async fn dynamic_resolution(native: bool) { rx, kf_rx, quality_rx, - CodecId::Hevc, + codec, 3840, 2160, 100_000, @@ -38,17 +44,24 @@ async fn dynamic_resolution(native: bool) { None, None, ); - let mut frame = removent_media_capture::CapturedVideoFrame::new( + let frame = removent_media_capture::CapturedVideoFrame::new( [40, 90, 160, 255].repeat(3840 * 2160), 3840, 2160, 1, ); - if native { - frame.pixels = removent_media_capture::CapturedPixels::Native( - super::capture::native_buffer(3840, 2160, &frame.pixels.bgra(3840, 2160).unwrap()), - ); - } + #[cfg(target_os = "macos")] + let frame = { + let mut frame = frame; + if native { + frame.pixels = removent_media_capture::CapturedPixels::Native( + super::capture::native_buffer(3840, 2160, &frame.pixels.bgra(3840, 2160).unwrap()), + ); + } + frame + }; + #[cfg(not(target_os = "macos"))] + assert!(!native); tx.send(frame).unwrap(); let mut stream = client.accept_media_stream().await.unwrap(); let mut previous_pts = 0; @@ -65,10 +78,10 @@ async fn dynamic_resolution(native: bool) { assert!(header.pts_us > previous_pts); previous_pts = header.pts_us; let decoder = removent_media_codec::VideoDecoder::new( - CodecId::Hevc, + codec, w as usize, h as usize, - &removent_media_codec::extract_param_sets(&payload, true), + &removent_media_codec::extract_param_sets(&payload, codec == CodecId::Hevc), ) .unwrap(); decoder.decode_annexb(&payload, header.pts_us).unwrap(); diff --git a/packages/input/Cargo.toml b/packages/input/Cargo.toml index 16bd37e..21d1360 100644 --- a/packages/input/Cargo.toml +++ b/packages/input/Cargo.toml @@ -7,9 +7,19 @@ license.workspace = true [dependencies] rand.workspace = true removent-proto = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } + +[target.'cfg(target_vendor = "apple")'.dependencies] core-graphics = { workspace = true, features = ["highsierra"] } objc2 = { workspace = true } objc2-foundation = { workspace = true } objc2-app-kit = { workspace = true } -thiserror = { workspace = true } -tracing = { workspace = true } + +[target.'cfg(not(target_vendor = "apple"))'.dependencies] +enigo = { version = "0.6", default-features = false, features = ["x11rb"] } +xcap = "0.9" +arboard = { version = "3", default-features = false } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging"] } diff --git a/packages/input/src/display.rs b/packages/input/src/display.rs index 254a632..4880fa3 100644 --- a/packages/input/src/display.rs +++ b/packages/input/src/display.rs @@ -1,9 +1,11 @@ //! Display information and coordinate conversion. +#[cfg(target_vendor = "apple")] use core_graphics::display::{CGDisplay, CGMainDisplayID}; /// Zero refresh rate denotes a variable/unknown mode. Leave room for ProMotion /// instead of imposing a 60 Hz ceiling; capture still emits only real updates. +#[cfg(target_vendor = "apple")] pub fn capture_frame_rate(display_id: u32) -> u8 { let rate = CGDisplay::new(display_id) .display_mode() @@ -33,6 +35,7 @@ pub struct DisplayGeometry { } impl DisplayGeometry { + #[cfg(target_vendor = "apple")] pub fn from_cg(id: u32) -> Self { let d = CGDisplay::new(id); let b = d.bounds(); @@ -59,6 +62,7 @@ impl DisplayGeometry { } } + #[cfg(target_vendor = "apple")] pub fn all() -> Vec { CGDisplay::active_displays() .unwrap_or_default() @@ -67,6 +71,7 @@ impl DisplayGeometry { .collect() } + #[cfg(target_vendor = "apple")] pub fn main() -> Option { let id = unsafe { CGMainDisplayID() }; (id != 0).then(|| Self::from_cg(id)) @@ -111,6 +116,7 @@ impl DisplayGeometry { } } +#[cfg(any(target_vendor = "apple", test))] fn pixel_geometry( mode_pixels: Option<(u64, u64)>, fallback: (u64, u64), @@ -232,3 +238,44 @@ mod tests { ); } } + +#[cfg(not(target_vendor = "apple"))] +pub fn capture_frame_rate(_id: u32) -> u8 { + 30 +} +#[cfg(not(target_vendor = "apple"))] +impl DisplayGeometry { + pub fn all() -> Vec { + #[cfg(target_os = "linux")] + if std::env::var_os("DISPLAY").is_none() || std::env::var_os("WAYLAND_DISPLAY").is_some() { + return vec![]; + } + + xcap::Monitor::all() + .unwrap_or_default() + .into_iter() + .filter_map(|m| { + let width = m.width().ok()?; + let height = m.height().ok()?; + Some(Self { + id: m.id().ok()?, + width_pt: width as f64, + height_pt: height as f64, + width_px: width as u64, + height_px: height as u64, + scale: 1., + origin_x: m.x().ok()? as f64, + origin_y: m.y().ok()? as f64, + is_main: m.is_primary().ok()?, + }) + }) + .collect() + } + pub fn main() -> Option { + let all = Self::all(); + all.iter() + .find(|g| g.is_main) + .copied() + .or_else(|| all.first().copied()) + } +} diff --git a/packages/input/src/lib.rs b/packages/input/src/lib.rs index a480680..ebefc6c 100644 --- a/packages/input/src/lib.rs +++ b/packages/input/src/lib.rs @@ -1,10 +1,25 @@ -//! removent-input: keyboard/mouse injection, clipboard, and display geometry (macOS). +//! Native keyboard/mouse injection, clipboard, and display geometry. +#[cfg(target_vendor = "apple")] +pub mod clipboard; +#[cfg(not(target_vendor = "apple"))] +#[path = "portable/clipboard.rs"] pub mod clipboard; pub mod display; +#[cfg(target_vendor = "apple")] +pub mod keyboard; +#[cfg(not(target_vendor = "apple"))] +#[path = "portable/keyboard.rs"] pub mod keyboard; +#[cfg(target_vendor = "apple")] +pub mod mouse; +#[cfg(not(target_vendor = "apple"))] +#[path = "portable/mouse.rs"] pub mod mouse; +#[cfg(target_vendor = "apple")] pub mod origin; +#[cfg(not(target_vendor = "apple"))] +mod portable; pub use clipboard::{ClipboardError, change_count, read, read_text, write_text}; pub use display::DisplayGeometry; @@ -26,10 +41,17 @@ unsafe extern "C" { fn AXIsProcessTrustedWithOptions(options: *const std::ffi::c_void) -> bool; } -// The crate is macOS-only in practice; the stub keeps it compiling elsewhere. #[cfg(not(target_os = "macos"))] pub fn accessibility_trusted() -> bool { - true + portable::available() +} + +/// Call at host process startup, before display APIs or windows are created. +/// Capture geometry must use physical pixels even on scaled Windows desktops. +#[cfg(windows)] +pub fn initialize_host_dpi() { + // An existing manifest/toolkit DPI policy cannot be changed and is retained. + let _ = enigo::set_dpi_awareness(); } use removent_proto::DisplayInfo as ProtoDisplay; diff --git a/packages/input/src/portable/clipboard.rs b/packages/input/src/portable/clipboard.rs new file mode 100644 index 0000000..cc4674b --- /dev/null +++ b/packages/input/src/portable/clipboard.rs @@ -0,0 +1,41 @@ +use std::sync::{Mutex, OnceLock}; +#[derive(Debug, thiserror::Error)] +pub enum ClipboardError { + #[error("clipboard unavailable")] + Unavailable, + #[error("unsupported clipboard format")] + UnsupportedFormat, + #[error("clipboard has no text")] + NoContent, +} +fn with( + f: impl FnOnce(&mut arboard::Clipboard) -> Result, +) -> Result { + static CLIP: OnceLock>> = OnceLock::new(); + let mut clip = CLIP + .get_or_init(|| Mutex::new(None)) + .lock() + .map_err(|_| ClipboardError::Unavailable)?; + if clip.is_none() { + *clip = Some(arboard::Clipboard::new().map_err(|_| ClipboardError::Unavailable)?); + } + f(clip.as_mut().unwrap()).map_err(|_| ClipboardError::NoContent) +} +pub fn change_count() -> Result { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + read_text()?.hash(&mut h); + Ok(h.finish()) +} +pub fn read(format: removent_proto::ClipFormat) -> Result, ClipboardError> { + if format != removent_proto::ClipFormat::TextUtf8 { + return Err(ClipboardError::UnsupportedFormat); + } + Ok(read_text()?.into_bytes()) +} +pub fn read_text() -> Result { + with(|c| c.get_text()) +} +pub fn write_text(text: &str) -> Result<(), ClipboardError> { + with(|c| c.set_text(text)) +} diff --git a/packages/input/src/portable/keyboard.rs b/packages/input/src/portable/keyboard.rs new file mode 100644 index 0000000..4ae6e6a --- /dev/null +++ b/packages/input/src/portable/keyboard.rs @@ -0,0 +1,253 @@ +use enigo::{Axis, Direction, Key, Keyboard, Mouse}; +use removent_proto::{KeyKind, KeyModifiers, ScrollPhase}; +pub const UNICODE_ONLY_VK: u16 = 0xffff; +pub fn modifier_of_vk(vk_code: u16) -> Option { + // macOS virtual key codes; mirrors modifier_flag_of_vk. + match vk_code { + 0x37 | 0x36 => Some(KeyModifiers::COMMAND), // L/R Command + 0x38 | 0x3C => Some(KeyModifiers::SHIFT), // L/R Shift + 0x3A | 0x3D => Some(KeyModifiers::OPTION), // L/R Option + 0x3B | 0x3E => Some(KeyModifiers::CONTROL), // L/R Control + 0x39 => Some(KeyModifiers::CAPS_LOCK), // Caps Lock + 0x3F => Some(KeyModifiers::FUNCTION), // Fn + _ => None, + } +} +fn key(vk: u16) -> Option { + Some(match vk { + 0x24 | 0x4c => Key::Return, + 0x30 => Key::Tab, + 0x31 => Key::Space, + 0x33 => Key::Backspace, + 0x35 => Key::Escape, + 0x37 | 0x36 => Key::Meta, + 0x38 | 0x3c => Key::Shift, + 0x3a | 0x3d => Key::Alt, + 0x3b | 0x3e => Key::Control, + 0x39 => Key::CapsLock, + 0x73 => Key::Home, + 0x77 => Key::End, + 0x74 => Key::PageUp, + 0x79 => Key::PageDown, + 0x75 => Key::Delete, + 0x7b => Key::LeftArrow, + 0x7c => Key::RightArrow, + 0x7d => Key::DownArrow, + 0x7e => Key::UpArrow, + 0x7a => Key::F1, + 0x78 => Key::F2, + 0x63 => Key::F3, + 0x76 => Key::F4, + 0x60 => Key::F5, + 0x61 => Key::F6, + 0x62 => Key::F7, + 0x64 => Key::F8, + 0x65 => Key::F9, + 0x6d => Key::F10, + 0x67 => Key::F11, + 0x6f => Key::F12, + 0x69 => Key::F13, + 0x6b => Key::F14, + 0x71 => Key::F15, + 0x6a => Key::F16, + 0x40 => Key::F17, + 0x4f => Key::F18, + 0x50 => Key::F19, + 0x5a => Key::F20, + 0x41 => Key::Unicode('.'), + 0x43 => Key::Unicode('*'), + 0x45 => Key::Unicode('+'), + 0x4b => Key::Unicode('/'), + 0x4e => Key::Unicode('-'), + 0x51 => Key::Unicode('='), + 0x52..=0x59 => Key::Unicode(char::from(b'0' + (vk - 0x52) as u8)), + 0x5b => Key::Unicode('8'), + 0x5c => Key::Unicode('9'), + _ => { + let keys = "asdfhgzxcv\0bqwerty123465=97-80]ou[ip\0lj'k;\\,/nm.\0 \x60"; + Key::Unicode(keys.chars().nth(vk as usize).filter(|c| *c != '\0')?) + } + }) +} +#[derive(Default)] +pub struct KeyboardInjector { + pub modifiers: KeyModifiers, + pressed: std::collections::HashMap, + #[cfg(windows)] + committed_text: std::collections::HashSet, +} +impl KeyboardInjector { + pub fn inject( + &mut self, + vk: u16, + mods: KeyModifiers, + kind: KeyKind, + text: Option, + ) -> Result<(), String> { + let previous = self.modifiers; + self.modifiers = mods; + // Committed IME text is an insertion, with no physical key to release. + // Enigo's Windows Unicode fallback inserts text even for Key::Release, + // which would duplicate characters if called for both wire transitions. + #[cfg(windows)] + if vk == UNICODE_ONLY_VK { + return if kind == KeyKind::Down { + match text.filter(|c| !c.is_control()) { + Some(ch) => crate::portable::with(|e| e.text(&ch.to_string())), + None => Ok(()), + } + } else { + Ok(()) + }; + } + #[cfg(windows)] + { + if kind == KeyKind::Up && self.committed_text.remove(&vk) { + return Ok(()); + } + if kind == KeyKind::Down + && !mods.intersects(KeyModifiers::CONTROL | KeyModifiers::COMMAND) + && let Some(ch) = text.filter(|c| !c.is_ascii() && !c.is_control()) + { + crate::portable::with(|e| e.text(&ch.to_string()))?; + self.committed_text.insert(vk); + return Ok(()); + } + } + if vk == 0x39 && kind == KeyKind::FlagsChanged { + if previous.contains(KeyModifiers::CAPS_LOCK) != mods.contains(KeyModifiers::CAPS_LOCK) + { + crate::portable::with(|e| e.key(Key::CapsLock, Direction::Click))?; + } + return Ok(()); + } + let down = match kind { + KeyKind::Down => true, + KeyKind::Up => false, + KeyKind::FlagsChanged => modifier_of_vk(vk).is_some_and(|m| mods.contains(m)), + }; + let mapped = if !down { + self.pressed.remove(&vk).or_else(|| key(vk)) + } else if !mods.intersects(KeyModifiers::CONTROL | KeyModifiers::COMMAND) + && text.is_some_and(|c| !c.is_control()) + { + text.map(Key::Unicode) + } else { + key(vk) + }; + let Some(mapped) = mapped else { + return Err(format!("Unsupported key code {vk:#x}")); + }; + crate::portable::with(|e| { + e.key( + mapped, + if down { + Direction::Press + } else { + Direction::Release + }, + ) + })?; + if down { + self.pressed.insert(vk, mapped); + } + Ok(()) + } +} +pub fn inject_key( + vk: u16, + mods: KeyModifiers, + kind: KeyKind, + text: Option, +) -> Result<(), String> { + KeyboardInjector::default().inject(vk, mods, kind, text) +} +pub fn build_key(vk: u16, mods: KeyModifiers, kind: KeyKind) -> Result<(), String> { + inject_key(vk, mods, kind, None) +} +pub fn inject_scroll_pixels(dx: f64, dy: f64, phase: ScrollPhase) -> Result<(), String> { + inject_scroll_with_modifiers(dx, dy, phase, KeyModifiers::empty()) +} +pub fn inject_scroll_with_modifiers( + dx: f64, + dy: f64, + phase: ScrollPhase, + _mods: KeyModifiers, +) -> Result<(), String> { + ScrollInjector::default().inject(dx, dy, phase) +} + +/// Preserve sub-wheel deltas for a session instead of dropping trackpad motion. +#[derive(Default)] +pub struct ScrollInjector { + residual: [f64; 2], +} +impl ScrollInjector { + fn steps(&mut self, dx: f64, dy: f64, phase: ScrollPhase) -> [i32; 2] { + if phase == ScrollPhase::Began { + self.residual = [0.; 2]; + } + let mut steps = [0; 2]; + for (i, delta) in [dx, dy].into_iter().enumerate() { + self.residual[i] -= delta / 16.; + steps[i] = self.residual[i].trunc() as i32; + self.residual[i] -= steps[i] as f64; + } + if phase == ScrollPhase::Ended { + self.residual = [0.; 2]; + } + steps + } + pub fn inject(&mut self, dx: f64, dy: f64, phase: ScrollPhase) -> Result<(), String> { + let [horizontal, vertical] = self.steps(dx, dy, phase); + if horizontal == 0 && vertical == 0 { + return Ok(()); + } + crate::portable::with(|e| { + if horizontal != 0 { + e.scroll(horizontal, Axis::Horizontal)?; + } + if vertical != 0 { + e.scroll(vertical, Axis::Vertical)?; + } + Ok(()) + }) + } +} + +pub fn key_text(vk: u16, mods: KeyModifiers, unicode: Option) -> Option { + if mods.intersects(KeyModifiers::COMMAND | KeyModifiers::CONTROL) + || matches!(vk, 0x24 | 0x30 | 0x33 | 0x35 | 0x4C | 0x72..=0x7E) + { + return None; + } + unicode.filter(|c| !c.is_control() && !('\u{f700}'..='\u{f8ff}').contains(c)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn trackpad_deltas_accumulate_and_reset_between_gestures() { + let mut scroll = ScrollInjector::default(); + assert_eq!(scroll.steps(0., 4., ScrollPhase::Began), [0, 0]); + for _ in 0..2 { + assert_eq!(scroll.steps(0., 4., ScrollPhase::Changed), [0, 0]); + } + assert_eq!(scroll.steps(0., 4., ScrollPhase::Changed), [0, -1]); + assert_eq!(scroll.steps(0., 12., ScrollPhase::Ended), [0, 0]); + assert_eq!(scroll.steps(0., 4., ScrollPhase::Began), [0, 0]); + assert_eq!(scroll.steps(-32., -20., ScrollPhase::Changed), [2, 1]); + } + #[test] + fn canonical_wire_keys_cover_shortcuts_and_keypad() { + assert_eq!(key(0), Some(Key::Unicode('a'))); + assert_eq!(key(8), Some(Key::Unicode('c'))); + assert_eq!(key(9), Some(Key::Unicode('v'))); + assert_eq!(key(0x3b), Some(Key::Control)); + assert_eq!(key(0x52), Some(Key::Unicode('0'))); + assert_eq!(key(0x59), Some(Key::Unicode('7'))); + assert_eq!(key(0x5c), Some(Key::Unicode('9'))); + assert_eq!(key(0xffff), None); + } +} diff --git a/packages/input/src/portable/mod.rs b/packages/input/src/portable/mod.rs new file mode 100644 index 0000000..4a2e1f8 --- /dev/null +++ b/packages/input/src/portable/mod.rs @@ -0,0 +1,28 @@ +use enigo::{Enigo, Settings}; +use std::sync::{Mutex, OnceLock}; +pub fn available() -> bool { + with(|_| Ok(())).is_ok() +} +pub fn with(f: impl FnOnce(&mut Enigo) -> Result) -> Result { + // XWayland input cannot control native Wayland windows. Fail explicitly. + #[cfg(target_os = "linux")] + if std::env::var_os("WAYLAND_DISPLAY").is_some() { + return Err( + "Remote input requires an X11 desktop session; Wayland portal input is not available" + .into(), + ); + } + #[cfg(target_os = "linux")] + if std::env::var_os("DISPLAY").is_none() { + return Err("No X11 desktop session is available".into()); + } + static INPUT: OnceLock>> = OnceLock::new(); + let mut input = INPUT + .get_or_init(|| Mutex::new(None)) + .lock() + .map_err(|e| e.to_string())?; + if input.is_none() { + *input = Some(Enigo::new(&Settings::default()).map_err(|e| e.to_string())?); + } + f(input.as_mut().unwrap()).map_err(|e| e.to_string()) +} diff --git a/packages/input/src/portable/mouse.rs b/packages/input/src/portable/mouse.rs new file mode 100644 index 0000000..696c90f --- /dev/null +++ b/packages/input/src/portable/mouse.rs @@ -0,0 +1,46 @@ +#[cfg(not(windows))] +use enigo::Coordinate; +use enigo::{Button, Direction, Mouse}; +use removent_proto::{KeyModifiers, MouseKind}; +#[derive(Default)] +pub struct MouseInjector; +impl MouseInjector { + pub fn inject( + &mut self, + kind: MouseKind, + x: f64, + y: f64, + _mods: KeyModifiers, + ) -> Result<(), String> { + // Enigo's Windows absolute motion normalizes against the primary + // monitor only. Physical coordinates also cover negative monitor + // origins and avoid DPI virtualization on secondary displays. + #[cfg(windows)] + if unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::SetPhysicalCursorPos( + x.round() as i32, + y.round() as i32, + ) + } == 0 + { + return Err(std::io::Error::last_os_error().to_string()); + } + crate::portable::with(|e| { + #[cfg(not(windows))] + e.move_mouse(x.round() as i32, y.round() as i32, Coordinate::Abs)?; + let (button, direction) = match kind { + MouseKind::LeftDown => (Button::Left, Direction::Press), + MouseKind::LeftUp => (Button::Left, Direction::Release), + MouseKind::RightDown => (Button::Right, Direction::Press), + MouseKind::RightUp => (Button::Right, Direction::Release), + MouseKind::MiddleDown => (Button::Middle, Direction::Press), + MouseKind::MiddleUp => (Button::Middle, Direction::Release), + _ => return Ok(()), + }; + e.button(button, direction) + }) + } +} +pub fn inject_mouse(kind: MouseKind, x: f64, y: f64) -> Result<(), String> { + MouseInjector.inject(kind, x, y, KeyModifiers::empty()) +} diff --git a/packages/media-capture/Cargo.toml b/packages/media-capture/Cargo.toml index 5f596c0..4a25eb0 100644 --- a/packages/media-capture/Cargo.toml +++ b/packages/media-capture/Cargo.toml @@ -7,12 +7,19 @@ license.workspace = true [dependencies] removent-core = { workspace = true } removent-proto = { workspace = true } +tokio = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } + +[target.'cfg(target_vendor = "apple")'.dependencies] screencapturekit = "11.0" core-media-rs = "0.3" core-foundation = "0.10" core-video-rs = "0.3" -tokio = { workspace = true } -thiserror = { workspace = true } -tracing = { workspace = true } block = "0.1" apple-cf = "0.11" + +[target.'cfg(not(target_vendor = "apple"))'.dependencies] +xcap = "0.9" +image = "0.25" +removent-media-codec.workspace = true diff --git a/packages/media-capture/src/lib.rs b/packages/media-capture/src/lib.rs index 8025139..38cf183 100644 --- a/packages/media-capture/src/lib.rs +++ b/packages/media-capture/src/lib.rs @@ -2,12 +2,30 @@ pub mod health; mod pixels; +#[cfg(target_vendor = "apple")] pub mod quartz; +#[cfg(target_vendor = "apple")] pub mod sck; +#[cfg(target_vendor = "apple")] pub mod sck_ffi; pub use pixels::CapturedPixels; +#[cfg(not(target_vendor = "apple"))] +#[path = "portable.rs"] +pub mod sck; +#[cfg(not(target_vendor = "apple"))] +pub mod quartz { + pub type QuartzCapture = super::sck::SckCapture; + pub fn start( + id: u32, + w: u32, + h: u32, + video: removent_core::latest::Sender, + ) -> Result { + super::sck::start_remote_capture(id, w, h, video, None, 30).map_err(|e| e.to_string()) + } +} pub use sck::{AudioFrame, CaptureError, SckCapture, start_display_capture}; /// Dimensions travel with pixels, including the first frame after display changes. diff --git a/packages/media-capture/src/pixels.rs b/packages/media-capture/src/pixels.rs index 3041f7d..c1395f8 100644 --- a/packages/media-capture/src/pixels.rs +++ b/packages/media-capture/src/pixels.rs @@ -1,4 +1,7 @@ +#[cfg(target_vendor = "apple")] use apple_cf::cv::CVPixelBuffer; +#[cfg(not(target_vendor = "apple"))] +pub use removent_media_codec::NativePixelBuffer as CVPixelBuffer; use std::borrow::Cow; /// Native buffers retain the capture pool's pixel buffer until encoding ends. @@ -15,6 +18,9 @@ impl CapturedPixels { Self::Bgra(bytes) => { width.checked_mul(height).and_then(|n| n.checked_mul(4)) == Some(bytes.len()) } + #[cfg(not(target_vendor = "apple"))] + Self::Native(buffer) => match *buffer {}, + #[cfg(target_vendor = "apple")] Self::Native(buffer) => { buffer.width() == width && buffer.height() == height @@ -34,36 +40,41 @@ impl CapturedPixels { }; return Ok(Cow::Borrowed(bytes)); }; - let guard = buffer - .lock_read_only() - .map_err(|e| format!("capture readback lock: {e}"))?; - let stride = guard.bytes_per_row(); - let row_bytes = width * 4; - let base = guard.base_address(); - if base.is_null() || stride < row_bytes { - return Err("invalid capture readback stride".into()); - } - let mut bytes = vec![0; row_bytes * height]; - // SAFETY: a retained, read-locked BGRA pixel buffer owns each source - // row; the destination is exclusively owned and sized above. - unsafe { - if stride == row_bytes { - std::ptr::copy_nonoverlapping(base, bytes.as_mut_ptr(), bytes.len()); - } else { - for row in 0..height { - std::ptr::copy_nonoverlapping( - base.add(row * stride), - bytes.as_mut_ptr().add(row * row_bytes), - row_bytes, - ); + #[cfg(not(target_vendor = "apple"))] + match *buffer {} + #[cfg(target_vendor = "apple")] + { + let guard = buffer + .lock_read_only() + .map_err(|e| format!("capture readback lock: {e}"))?; + let stride = guard.bytes_per_row(); + let row_bytes = width * 4; + let base = guard.base_address(); + if base.is_null() || stride < row_bytes { + return Err("invalid capture readback stride".into()); + } + let mut bytes = vec![0; row_bytes * height]; + // SAFETY: a retained, read-locked BGRA pixel buffer owns each source + // row; the destination is exclusively owned and sized above. + unsafe { + if stride == row_bytes { + std::ptr::copy_nonoverlapping(base, bytes.as_mut_ptr(), bytes.len()); + } else { + for row in 0..height { + std::ptr::copy_nonoverlapping( + base.add(row * stride), + bytes.as_mut_ptr().add(row * row_bytes), + row_bytes, + ); + } } } + Ok(Cow::Owned(bytes)) } - Ok(Cow::Owned(bytes)) } } -#[cfg(test)] +#[cfg(all(test, target_vendor = "apple"))] mod tests { use super::*; diff --git a/packages/media-capture/src/portable.rs b/packages/media-capture/src/portable.rs new file mode 100644 index 0000000..b38f58c --- /dev/null +++ b/packages/media-capture/src/portable.rs @@ -0,0 +1,139 @@ +//! Bounded, cancellable CPU capture for Windows and Linux X11 desktops. +use crate::{CapturedVideoFrame, health::CaptureHealth}; +use std::{ + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + time::{Duration, Instant}, +}; +use tokio::sync::mpsc; +#[derive(Debug, thiserror::Error)] +pub enum CaptureError { + #[error("screen capture: {0}")] + Sc(String), + #[error("display {0} not found")] + DisplayNotFound(u32), + #[error("screen capture permission: {0}")] + NotAuthorized(String), +} +pub struct AudioFrame { + pub samples: Vec, + pub pts_micros: i64, +} +pub struct SckCapture { + stop: Arc, + stopped: Option>, + health: Arc>, +} +impl Drop for SckCapture { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} +impl SckCapture { + pub fn take_stopped_rx(&mut self) -> Option> { + self.stopped.take() + } + pub fn health_failure(&self) -> Option<&'static str> { + self.health.lock().unwrap().failure(Instant::now()) + } +} +pub fn request_screen_capture_access() -> Result<(), CaptureError> { + xcap::Monitor::all() + .map(|_| ()) + .map_err(|e| CaptureError::Sc(e.to_string())) +} +pub fn start_display_capture( + id: u32, + w: u32, + h: u32, + video: removent_core::latest::Sender, + audio: Option>, +) -> Result { + start_remote_capture(id, w, h, video, audio, 30) +} +pub fn start_remote_capture( + id: u32, + w: u32, + h: u32, + video: removent_core::latest::Sender, + _audio: Option>, + fps: u8, +) -> Result { + #[cfg(target_os = "linux")] + if std::env::var_os("WAYLAND_DISPLAY").is_some() { + return Err(CaptureError::NotAuthorized("Choose an X11 desktop session for remote hosting; Wayland portal sessions are not implemented".into())); + } + if w == 0 || h == 0 || fps == 0 { + return Err(CaptureError::Sc( + "invalid capture dimensions or frame rate".into(), + )); + } + let stop = Arc::new(AtomicBool::new(false)); + let health = Arc::new(Mutex::new(CaptureHealth::default())); + let (tx, rx) = mpsc::channel(1); + let cancel = stop.clone(); + let worker_health = health.clone(); + let generation = crate::next_capture_generation(); + std::thread::Builder::new() + .name("desktop-capture".into()) + .spawn(move || { + let monitor = match xcap::Monitor::all() + .map_err(|e| CaptureError::Sc(e.to_string())) + .and_then(|monitors| { + monitors + .into_iter() + .find(|m| m.id().ok() == Some(id)) + .ok_or(CaptureError::DisplayNotFound(id)) + }) { + Ok(monitor) => monitor, + Err(error) => { + let _ = tx.blocking_send(error); + return; + } + }; + let start = Instant::now(); + let interval = Duration::from_secs_f64(1. / f64::from(fps.min(30))); + while !cancel.load(Ordering::Relaxed) { + let tick = Instant::now(); + let image = match monitor.capture_image() { + Ok(image) => image, + Err(e) => { + let _ = tx.blocking_send(CaptureError::Sc(e.to_string())); + break; + } + }; + let image = if image.width() != w || image.height() != h { + image::imageops::resize(&image, w, h, image::imageops::FilterType::Triangle) + } else { + image + }; + let mut bgra = image.into_raw(); + for pixel in bgra.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + let mut frame = CapturedVideoFrame::new( + bgra, + w as usize, + h as usize, + start.elapsed().as_micros() as i64, + ); + frame.generation = generation; + if cancel.load(Ordering::Relaxed) { + break; + } + if video.send(frame).is_err() { + break; + } + worker_health.lock().unwrap().frame(); + std::thread::sleep(interval.saturating_sub(tick.elapsed())); + } + }) + .map_err(|e| CaptureError::Sc(e.to_string()))?; + Ok(SckCapture { + stop, + stopped: Some(rx), + health, + }) +} diff --git a/packages/media-codec/Cargo.toml b/packages/media-codec/Cargo.toml index 4aeb084..1eb1ba6 100644 --- a/packages/media-codec/Cargo.toml +++ b/packages/media-codec/Cargo.toml @@ -6,12 +6,18 @@ license.workspace = true [dependencies] removent-proto = { workspace = true } -videotoolbox = "0.21" -apple-cf = "0.11" opus = { workspace = true } thiserror = { workspace = true } tracing = { workspace = true } -metal = "0.33" -objc = "0.2" rav1e = { version = "0.8.1", default-features = false, features = ["asm", "threading"] } rusty_av1d = { version = "1.2.0", default-features = false, features = ["bitdepth_8"] } + +[target.'cfg(target_vendor = "apple")'.dependencies] +videotoolbox = "0.21" +apple-cf = "0.11" +metal = "0.33" +objc = "0.2" + +[target.'cfg(not(target_vendor = "apple"))'.dependencies] +openh264 = "0.9" +image = { version = "0.25", default-features = false } diff --git a/packages/media-codec/src/lib.rs b/packages/media-codec/src/lib.rs index 7e2d3fc..1ebd707 100644 --- a/packages/media-codec/src/lib.rs +++ b/packages/media-codec/src/lib.rs @@ -2,9 +2,15 @@ pub mod audio; mod av1; +#[cfg(target_vendor = "apple")] pub mod cm_ffi; +#[cfg(target_vendor = "apple")] mod compat_decompression; pub mod scale; +#[cfg(target_vendor = "apple")] +pub mod video; +#[cfg(not(target_vendor = "apple"))] +#[path = "portable.rs"] pub mod video; pub use audio::{Application, AudioDecoder, AudioEncoder, AudioError, FRAME_SAMPLES_PER_CHANNEL}; @@ -14,4 +20,8 @@ pub use video::{ split_annexb_nals, }; +#[cfg(target_vendor = "apple")] pub use apple_cf::cv::CVPixelBuffer as NativePixelBuffer; +#[cfg(not(target_vendor = "apple"))] +#[derive(Debug, Clone)] +pub enum NativePixelBuffer {} diff --git a/packages/media-codec/src/portable.rs b/packages/media-codec/src/portable.rs new file mode 100644 index 0000000..f277a89 --- /dev/null +++ b/packages/media-codec/src/portable.rs @@ -0,0 +1,296 @@ +//! CPU H.264/AV1 implementation for Windows and Linux. +use crate::av1::{Av1Decoder, Av1Encoder}; +use removent_proto::CodecId; +use std::sync::{Arc, Mutex, mpsc}; +#[path = "video/annexb.rs"] +mod annexb; +pub use annexb::{annexb_has_idr, avcc_to_annexb, extract_param_sets, split_annexb_nals}; +pub const AV1_CODEC_TYPE: u32 = u32::from_be_bytes(*b"av01"); +#[derive(Debug, Clone, Copy)] +pub struct Av1HardwareSupport { + pub decoder: bool, + pub encoder: bool, +} +pub fn av1_hardware_support() -> Av1HardwareSupport { + Av1HardwareSupport { + decoder: false, + encoder: false, + } +} +#[derive(Debug, thiserror::Error)] +pub enum VideoError { + #[error("H264: {0}")] + H264(#[from] openh264::Error), + #[error("unsupported codec")] + Unsupported, + #[error("GPU processing: {0}")] + Gpu(String), + #[error("surface: {0}")] + Surface(String), + #[error("pixel data size mismatch: need {need}, got {got}")] + PixelSizeMismatch { need: usize, got: usize }, + #[error("video geometry mismatch: expected {expected:?}, got {actual:?}")] + GeometryMismatch { + expected: (usize, usize), + actual: (i32, i32), + }, + #[error("parameter sets unavailable before first encode")] + NoParameterSets, + #[error("core media status {0}")] + CoreMedia(i32), + #[error("decode failed with status {0}")] + DecodeStatus(i32), + #[error("core media returned null sample buffer")] + NullSampleBuffer, + #[error("avcc length prefix invalid")] + InvalidAvcc, + #[error("software AV1: {0}")] + Av1(String), +} + +/// One encoded frame (Annex-B for H264/HEVC, temporal-unit OBUs for AV1). +#[derive(Debug, Clone)] +pub struct EncodedVideoFrame { + pub data: Vec, + pub pts_us: i64, + pub keyframe: bool, +} + +pub struct DecodedBgra { + pub surface: Option, + pub data: Vec, + pub pts_us: i64, +} +pub struct VideoEncoder { + h264: Option, + av1: Option, + width: usize, + height: usize, + fps: u8, + bitrate: u32, + params: Option>>, +} +impl VideoEncoder { + pub fn new( + codec: CodecId, + width: usize, + height: usize, + bitrate: u32, + fps: u8, + ) -> Result { + if width == 0 || height == 0 || fps == 0 || width % 2 != 0 || height % 2 != 0 { + return Err(VideoError::Surface("invalid video geometry".into())); + } + let (h264, av1) = match codec { + CodecId::H264 => (Some(Self::h264(bitrate, fps)?), None), + CodecId::Av1 => (None, Some(Av1Encoder::new(width, height, bitrate, fps)?)), + _ => return Err(VideoError::Unsupported), + }; + Ok(Self { + h264, + av1, + width, + height, + fps, + bitrate, + params: None, + }) + } + fn h264(bitrate: u32, fps: u8) -> Result { + use openh264::encoder::*; + let config = EncoderConfig::new() + .bitrate(BitRate::from_bps(bitrate.saturating_mul(1000))) + .max_frame_rate(FrameRate::from_hz(fps as f32)); + Ok(Encoder::with_api_config( + openh264::OpenH264API::from_source(), + config, + )?) + } + pub fn hardware_accelerated(&self) -> bool { + false + } + pub fn quality_ceiling_supported(&self) -> bool { + self.av1.is_some() + } + pub fn width(&self) -> usize { + self.width + } + pub fn height(&self) -> usize { + self.height + } + pub fn parameter_sets(&self) -> Option<&[Vec]> { + self.params.as_deref() + } + pub fn request_keyframe(&mut self) { + if let Some(e) = &mut self.h264 { + e.force_intra_frame(); + } + if let Some(e) = &mut self.av1 { + e.request_keyframe(); + } + } + pub fn set_bitrate_kbps(&mut self, bitrate: u32) -> Result<(), VideoError> { + if let Some(e) = &mut self.av1 { + return e.set_bitrate_kbps(bitrate); + } + if bitrate != self.bitrate { + self.h264 = Some(Self::h264(bitrate, self.fps)?); + self.bitrate = bitrate; + } + Ok(()) + } + pub fn flush(&mut self) -> Result, VideoError> { + self.av1.as_mut().map_or(Ok(vec![]), |e| e.flush()) + } + pub fn encode_bgra( + &mut self, + bgra: &[u8], + pts_us: i64, + ) -> Result, VideoError> { + let need = self.width * self.height * 4; + if bgra.len() != need { + return Err(VideoError::PixelSizeMismatch { + need, + got: bgra.len(), + }); + } + if let Some(e) = &mut self.av1 { + return e.encode_bgra(bgra, pts_us); + } + let rgb: Vec = bgra + .chunks_exact(4) + .flat_map(|p| [p[2], p[1], p[0]]) + .collect(); + let yuv = openh264::formats::YUVBuffer::from_rgb_source( + openh264::formats::RgbSliceU8::new(&rgb, (self.width, self.height)), + ); + let data = self.h264.as_mut().unwrap().encode(&yuv)?.to_vec(); + if data.is_empty() { + return Ok(vec![]); + } + let keyframe = annexb_has_idr(&data, false); + if keyframe { + self.params = Some(extract_param_sets(&data, false)); + } + Ok(vec![EncodedVideoFrame { + data, + pts_us, + keyframe, + }]) + } + pub fn encode_native( + &mut self, + buffer: &crate::NativePixelBuffer, + _pts: i64, + ) -> Result, VideoError> { + match *buffer {} + } +} +enum Decoder { + H264(openh264::decoder::Decoder), + Av1(Av1Decoder), +} +pub struct VideoDecoder { + decoder: Mutex, + width: usize, + height: usize, + output: Arc, + rx: Mutex>, +} +impl VideoDecoder { + pub fn new( + codec: CodecId, + width: usize, + height: usize, + params: &[Vec], + ) -> Result { + let (tx, rx) = mpsc::channel(); + let mut d = Self::with_output(codec, width, height, params, move |f| { + let _ = tx.send(f); + })?; + d.rx = Mutex::new(rx); + Ok(d) + } + pub fn with_output( + codec: CodecId, + width: usize, + height: usize, + params: &[Vec], + output: impl Fn(DecodedBgra) + Send + Sync + 'static, + ) -> Result { + Self::with_surface_output(codec, width, height, params, false, output) + } + pub fn with_surface_output( + codec: CodecId, + width: usize, + height: usize, + params: &[Vec], + _native: bool, + output: impl Fn(DecodedBgra) + Send + Sync + 'static, + ) -> Result { + let decoder = match codec { + CodecId::H264 => { + let mut d = openh264::decoder::Decoder::new()?; + for p in params { + let mut bytes = vec![0, 0, 0, 1]; + bytes.extend(p); + d.decode(&bytes)?; + } + Decoder::H264(d) + } + CodecId::Av1 => Decoder::Av1(Av1Decoder::new(width, height)?), + _ => return Err(VideoError::Unsupported), + }; + Ok(Self { + decoder: Mutex::new(decoder), + width, + height, + output: Arc::new(output), + rx: Mutex::new(mpsc::channel().1), + }) + } + pub fn dimensions(&self) -> (usize, usize) { + (self.width, self.height) + } + pub fn try_recv_decoded(&self) -> Option { + self.rx.lock().unwrap().try_recv().ok() + } + pub fn decode_annexb(&self, bytes: &[u8], pts_us: i64) -> Result<(), VideoError> { + use openh264::formats::YUVSource; + match &mut *self.decoder.lock().unwrap() { + Decoder::Av1(d) => { + for frame in d.decode(bytes, pts_us)? { + (self.output)(frame); + } + } + Decoder::H264(d) => { + if let Some(yuv) = d.decode(bytes)? { + if yuv.dimensions() != (self.width, self.height) { + return Err(VideoError::Surface( + "decoded dimensions differ from negotiated frame".into(), + )); + } + let mut rgba = vec![0; self.width * self.height * 4]; + yuv.write_rgba8(&mut rgba); + for p in rgba.chunks_exact_mut(4) { + p.swap(0, 2); + } + (self.output)(DecodedBgra { + surface: None, + data: rgba, + pts_us, + }); + } + } + } + Ok(()) + } + pub fn flush(&self) -> Result<(), VideoError> { + if let Decoder::Av1(d) = &mut *self.decoder.lock().unwrap() { + for frame in d.flush()? { + (self.output)(frame); + } + } + Ok(()) + } +} diff --git a/packages/media-codec/src/scale.rs b/packages/media-codec/src/scale.rs index 714750a..6e137b1 100644 --- a/packages/media-codec/src/scale.rs +++ b/packages/media-codec/src/scale.rs @@ -1,6 +1,8 @@ //! Accelerate resampling of tightly packed BGRA frames. +#[cfg(target_vendor = "apple")] use std::ffi::c_void; +#[cfg(target_vendor = "apple")] #[repr(C)] struct Buffer { data: *mut c_void, @@ -9,6 +11,7 @@ struct Buffer { row_bytes: usize, } +#[cfg(target_vendor = "apple")] #[link(name = "Accelerate", kind = "framework")] unsafe extern "C" { fn vImageScale_ARGB8888( @@ -34,28 +37,43 @@ pub fn scale_bgra( { return Err("invalid BGRA dimensions".into()); } - let len = size(target).ok_or("BGRA target size overflow")?; - let mut output = vec![0; len]; - let src = Buffer { - data: input.as_ptr().cast_mut().cast(), - height: source.1, - width: source.0, - row_bytes: source.0 * 4, - }; - let dst = Buffer { - data: output.as_mut_ptr().cast(), - height: target.1, - width: target.0, - row_bytes: target.0 * 4, - }; - // SAFETY: dimensions/lengths were checked; input remains immutable and output - // exclusively borrowed until this synchronous operation returns. flags=0 is - // the low-latency resampling path; vImage allocates its own temporary storage. - let result = unsafe { vImageScale_ARGB8888(&src, &dst, std::ptr::null_mut(), 0) }; - if result != 0 { - return Err(format!("vImage scaling failed: {result}")); + #[cfg(target_vendor = "apple")] + { + let len = size(target).ok_or("BGRA target size overflow")?; + let mut output = vec![0; len]; + let src = Buffer { + data: input.as_ptr().cast_mut().cast(), + height: source.1, + width: source.0, + row_bytes: source.0 * 4, + }; + let dst = Buffer { + data: output.as_mut_ptr().cast(), + height: target.1, + width: target.0, + row_bytes: target.0 * 4, + }; + // SAFETY: dimensions/lengths were checked; input remains immutable and output + // exclusively borrowed until this synchronous operation returns. flags=0 is + // the low-latency resampling path; vImage allocates its own temporary storage. + let result = unsafe { vImageScale_ARGB8888(&src, &dst, std::ptr::null_mut(), 0) }; + if result != 0 { + return Err(format!("vImage scaling failed: {result}")); + } + Ok(output) + } + #[cfg(not(target_vendor = "apple"))] + { + let image = image::RgbaImage::from_raw(source.0 as u32, source.1 as u32, input.to_vec()) + .ok_or("Invalid image")?; + Ok(image::imageops::resize( + &image, + target.0 as u32, + target.1 as u32, + image::imageops::FilterType::Triangle, + ) + .into_raw()) } - Ok(output) } #[cfg(test)] diff --git a/packages/proto/src/constants.rs b/packages/proto/src/constants.rs index 03d765a..640c753 100644 --- a/packages/proto/src/constants.rs +++ b/packages/proto/src/constants.rs @@ -60,6 +60,8 @@ impl CodecId { } pub mod feature_bits { + /// Decoder accepts H264/AV1 but not HEVC; hosts must choose H264 by default. + pub const H264_ONLY: u64 = 1 << 12; /// Authenticated, separately authorized Computer Use RPC streams. pub const AUTOMATION: u64 = 1 << 10; pub const AUTOMATION_HANDOVER: u64 = 1 << 11; diff --git a/packages/updater/src/agent/mod.rs b/packages/updater/src/agent/mod.rs index 77ce0cb..96dfc0d 100644 --- a/packages/updater/src/agent/mod.rs +++ b/packages/updater/src/agent/mod.rs @@ -21,13 +21,7 @@ use std::{ time::{Duration, SystemTime, UNIX_EPOCH}, }; -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct AgentStatus { - pub state: String, - pub version: Option, - pub detail: String, - pub updated_at: u64, -} +pub use crate::AgentStatus; #[derive(Serialize, Deserialize)] struct Request { manifest: UpdateManifest, diff --git a/packages/updater/src/check.rs b/packages/updater/src/check.rs index 8583f38..fde2a47 100644 --- a/packages/updater/src/check.rs +++ b/packages/updater/src/check.rs @@ -8,6 +8,12 @@ pub fn run_check( shared: Arc>, events: std::sync::mpsc::Sender, ) { + if cfg!(not(target_os = "macos")) { + if manual { + set_status(&shared,&events,UpdateStatus::Failed("Automatic updates are not available for this platform; use the Windows or Linux package".into())); + } + return; + } run_check_with_fetch(manual, shared, events, fetch_and_validate); } diff --git a/packages/updater/src/download.rs b/packages/updater/src/download.rs index 782a859..d338df5 100644 --- a/packages/updater/src/download.rs +++ b/packages/updater/src/download.rs @@ -105,7 +105,7 @@ pub(super) fn download_and_stage( let _ = std::fs::remove_dir_all(&stage); std::fs::create_dir_all(&stage) .map_err(|e| t!("update.err.unpack", err = e.to_string()).to_string())?; - let unpacked = crate::agent::io::run( + let unpacked = removent_core::process::run_bounded( Command::new("/usr/bin/ditto") .arg("-x") .arg("-k") diff --git a/packages/updater/src/history.rs b/packages/updater/src/history.rs index 607bc89..dd9ad12 100644 --- a/packages/updater/src/history.rs +++ b/packages/updater/src/history.rs @@ -12,7 +12,7 @@ pub(super) fn load(path: &PathBuf) -> Option { .then_some(history.last_checked_at) } -pub(super) fn save(path: &PathBuf, last_checked_at: u64) -> removent_core::Result<()> { +pub(super) fn save(path: &std::path::Path, last_checked_at: u64) -> removent_core::Result<()> { removent_core::settings::atomic_write( path, &serde_json::to_vec(&CheckHistory { last_checked_at })?, diff --git a/packages/updater/src/install.rs b/packages/updater/src/install.rs index 8c895ba..60099f7 100644 --- a/packages/updater/src/install.rs +++ b/packages/updater/src/install.rs @@ -1,6 +1,7 @@ use super::*; /// Hand off a verified update to the independent agent. The UI can then quit. +#[cfg(target_os = "macos")] pub fn run_install( generation: u64, shared: Arc>, @@ -139,9 +140,24 @@ pub(super) fn restart_background( /// Locate the running .app bundle by walking up from the current executable /// (`.app/Contents/MacOS/removent`); None outside a bundle (dev runs). +#[cfg(target_os = "macos")] pub(super) fn current_bundle() -> Option { let exe = std::env::current_exe().ok()?; exe.ancestors() .find(|p| p.extension().is_some_and(|e| e == "app")) .map(|p| p.to_path_buf()) } + +#[cfg(not(target_os = "macos"))] +pub fn run_install( + _generation: u64, + shared: Arc>, + events: std::sync::mpsc::Sender, + _paths: DataPaths, +) { + set_status( + &shared, + &events, + UpdateStatus::Failed("Install the Windows or Linux package manually".into()), + ); +} diff --git a/packages/updater/src/lib.rs b/packages/updater/src/lib.rs index 2e7047c..767654f 100644 --- a/packages/updater/src/lib.rs +++ b/packages/updater/src/lib.rs @@ -207,6 +207,7 @@ mod verify; pub use check::run_check; #[cfg(test)] use check::{GithubRelease, fetch_update, release_candidate}; +#[cfg(any(target_os = "macos", test))] use download::bundle_version; pub use download::run_download; use fetch::curl_get; @@ -225,3 +226,11 @@ use verify::release_codesign_requirement; use verify::{codesign_verify, curl_download, find_app_bundle, sha256_file}; rust_i18n::i18n!("locales"); + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AgentStatus { + pub state: String, + pub version: Option, + pub detail: String, + pub updated_at: u64, +} diff --git a/packages/updater/src/verify.rs b/packages/updater/src/verify.rs index d2a5924..ee68251 100644 --- a/packages/updater/src/verify.rs +++ b/packages/updater/src/verify.rs @@ -69,7 +69,7 @@ pub(super) fn release_codesign_requirement() -> String { pub(super) fn codesign_verify(app: &Path) -> Result<(), String> { let requirement = release_codesign_requirement(); - let ok = crate::agent::io::run( + let ok = removent_core::process::run_bounded( Command::new("/usr/bin/codesign") .args(["--verify", "--deep", "--strict", "-R", &requirement]) .arg(app), diff --git a/scripts/build/linux-deps.sh b/scripts/build/linux-deps.sh new file mode 100644 index 0000000..23a4ec2 --- /dev/null +++ b/scripts/build/linux-deps.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +# Development and CI dependencies for the desktop, capture, input, and tray. +apt-get update +apt-get install -y --no-install-recommends build-essential cmake clang libclang-dev pkg-config nasm \ + libssl-dev libopus-dev libpam0g-dev libasound2-dev libudev-dev libfontconfig1-dev \ + libx11-dev libxi-dev libxrandr-dev libxinerama-dev libxcursor-dev libxkbcommon-dev \ + libxkbcommon-x11-dev libxcb1-dev libxcb-shape0-dev libxcb-xfixes0-dev libxfixes-dev \ + libxtst-dev libxdo-dev libwayland-dev libegl1-mesa-dev libgbm-dev libpipewire-0.3-dev \ + libgtk-3-dev libayatana-appindicator3-dev libdbus-1-dev \ + xvfb xauth x11-xserver-utils dbus-x11 openbox xdotool python3-tk python3-pil python3-dbus python3-gi \ + python3-pyatspi python3-psutil at-spi2-core fonts-noto-cjk \ + xfce4-panel libvulkan1 mesa-vulkan-drivers gnome-keyring diff --git a/scripts/build/package_portable.py b/scripts/build/package_portable.py new file mode 100644 index 0000000..c77ea21 --- /dev/null +++ b/scripts/build/package_portable.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Package built Windows/Linux binaries without modifying the installation.""" +import argparse, hashlib, json, os, shutil, subprocess, tarfile, tomllib, zipfile +from pathlib import Path + +def windows_crt_directory(): + """Use redistributable files from the installed build tools, never System32.""" + configured = os.environ.get("VCToolsRedistDir") + if configured: + redist = Path(configured) + candidates = list(redist.glob("x64/Microsoft.VC*.CRT")) + else: + vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe" + installation = subprocess.check_output([ + str(vswhere), "-latest", "-products", "*", "-requires", + "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath", + ], text=True).strip() + if not installation: + raise RuntimeError("Visual C++ build tools and their redistributable files are required") + candidates = list((Path(installation) / "VC/Redist/MSVC").glob("*/x64/Microsoft.VC*.CRT")) + candidates = [p for p in candidates if (p / "vcruntime140.dll").is_file()] + if not candidates: + raise RuntimeError("The x64 Visual C++ redistributable runtime was not found") + def version(path): + return tuple(int(part) for part in path.parent.parent.name.split(".") if part.isdigit()) + return max(candidates, key=version) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--target", required=True, choices=["windows-x86_64", "linux-x86_64", "linux-aarch64"]) + parser.add_argument("--bin-dir", type=Path, default=Path("target/release")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + out = root / "dist" / ("Removent-" + args.target) + if out.exists(): shutil.rmtree(out) + out.mkdir(parents=True) + suffix = ".exe" if args.target.startswith("windows") else "" + for name in ("removent", "removentd", "removent-tray"): + shutil.copy2(args.bin_dir / (name + suffix), out) + guide = (root / "docs/guides/windows-linux.md").read_text() + (out / "README.md").write_text(guide.replace("../validation/windows-linux-2026-11-13.md", "VALIDATION.md")) + shutil.copy2(root / "docs/validation/windows-linux-2026-11-13.md", out / "VALIDATION.md") + shutil.copy2(root / "LICENSE", out) + revision = subprocess.run(["git", "rev-parse", "HEAD"], cwd=root, capture_output=True, text=True) + manifest = tomllib.loads((root / "Cargo.toml").read_text()) + (out / "BUILD.json").write_text(json.dumps({ + "version": manifest["workspace"]["package"]["version"], + "platform": args.target, + "source_commit": revision.stdout.strip() if revision.returncode == 0 else None, + }, indent=2) + "\n") + # Carry explicitly built runtime DLLs if a Windows dependency provides them. + if suffix: + runtime = windows_crt_directory() + for dll in runtime.glob("*.dll"): shutil.copy2(dll, out) + (out / "WINDOWS-RUNTIME.txt").write_text( + "Microsoft Visual C++ Runtime\n" + "Copyright Microsoft Corporation. All rights reserved.\n\n" + "These redistributable DLLs are Microsoft components, separate from\n" + "Removent's Apache-2.0 license. They are supplied for application-local\n" + "deployment under the Visual Studio redistribution terms.\n" + "https://learn.microsoft.com/cpp/windows/redistributing-visual-cpp-files\n" + "https://visualstudio.microsoft.com/license-terms/\n" + ) + for dll in args.bin_dir.glob("*.dll"): shutil.copy2(dll, out) + archive = out.with_suffix(".zip") + with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as z: + for file in sorted(out.iterdir()): z.write(file, out.name + "/" + file.name) + else: + archive = out.with_suffix(".tar.gz") + with tarfile.open(archive,"w:gz") as t: t.add(out, arcname=out.name) + archive.with_name(archive.name + ".sha256").write_text(hashlib.sha256(archive.read_bytes()).hexdigest()+" "+archive.name+"\n") + print(archive) +if __name__ == "__main__": main() diff --git a/scripts/qa/linux_account.py b/scripts/qa/linux_account.py new file mode 100644 index 0000000..c0cabbb --- /dev/null +++ b/scripts/qa/linux_account.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Exercise PAM and the QUIC account handshake with a disposable Linux user.""" +import json +import os +from pathlib import Path +import secrets +import shutil +import subprocess +import tempfile + + +def main(): + if os.environ.get("GITHUB_ACTIONS") != "true": + raise RuntimeError("Requires an ephemeral GitHub Actions runner") + # Match the feature union of the preceding library regression step. + command = ["cargo", "test", "--locked"] + for package in ["proto", "core", "input", "client", "host", "media-codec"]: + command.extend(["-p", f"removent-{package}"]) + build = subprocess.run(command + ["--lib", "--no-run", "--message-format=json"], + stdout=subprocess.PIPE, text=True, check=True, timeout=300) + artifacts = [json.loads(line) for line in build.stdout.splitlines()] + binaries = [item["executable"] for item in artifacts + if item.get("reason") == "compiler-artifact" + and item.get("profile", {}).get("test") and item.get("executable") + and item.get("target", {}).get("name") == "removent_host"] + if len(binaries) != 1: + raise RuntimeError("Expected exactly one host test executable") + username = "rmv" + secrets.token_hex(6) + credentials = {"REMOVENT_AUTH_TEST_USERNAME": username, + "REMOVENT_AUTH_TEST_PASSWORD": secrets.token_hex(24) + "aA1!"} + # Supply secrets through stdin, never shell arguments or a temporary file. + child = """import json, os, sys +env = dict(os.environ, **json.load(sys.stdin)) +os.execve(sys.argv[1], [sys.argv[1], "native_desktop_account_authentication", "--ignored"], env) +""" + with tempfile.TemporaryDirectory(prefix="removent-account-") as directory: + root = Path(directory) + root.chmod(0o755) + binary = root / "host-test" + shutil.copyfile(binaries[0], binary) + binary.chmod(0o755) + created = False + try: + # Hosted runners put complete toolchains in /etc/skel. Copying that + # profile can take minutes; PAM needs only the account and password. + subprocess.run(["sudo", "-n", "useradd", "--no-log-init", "--no-create-home", + "--home-dir", directory, "--shell", "/bin/sh", username], + check=True, timeout=30) + created = True + subprocess.run(["sudo", "-n", "chpasswd"], + input=f"{username}:{credentials['REMOVENT_AUTH_TEST_PASSWORD']}\n", + text=True, check=True, timeout=30) + subprocess.run([str(binary), "native_desktop_account_authentication", "--ignored"], + env=dict(os.environ, **credentials, REMOVENT_AUTH_EXPECT_REJECT="1"), + cwd=directory, check=True, timeout=30) + run_as_owner = ["sudo", "-n", "-u", username, "python3", "-c", child, str(binary)] + subprocess.run(run_as_owner, input=json.dumps(credentials), text=True, + cwd=directory, check=True, timeout=30) + subprocess.run(["sudo", "-n", "chage", "--expiredate", "0", username], + check=True, timeout=30) + subprocess.run(run_as_owner, + input=json.dumps(dict(credentials, REMOVENT_AUTH_EXPECT_REJECT="1")), + text=True, cwd=directory, check=True, timeout=30) + print("PASS: Linux PAM/QUIC password, invalid password, owner UID and expired account checks") + finally: + if created: + subprocess.run(["sudo", "-n", "userdel", username], check=True, timeout=30) + + +if __name__ == "__main__": + main() diff --git a/scripts/qa/linux_tray.py b/scripts/qa/linux_tray.py new file mode 100644 index 0000000..8455789 --- /dev/null +++ b/scripts/qa/linux_tray.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Run the native linux tray lifecycle and remote-session acceptance.""" +from tray_lifecycle import run +from tray_ui_linux import LinuxDesktop + +if __name__ == "__main__": + run(LinuxDesktop) diff --git a/scripts/qa/portable_app.py b/scripts/qa/portable_app.py new file mode 100644 index 0000000..9ed9989 --- /dev/null +++ b/scripts/qa/portable_app.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Verify a visible GPUI window renders and completes its isolated startup probe.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time + +from PIL import ImageChops, ImageGrab + + +def windows_local_runtime(pid, directory, evidence): + """Prove the extracted application loads the runtime carried in its archive.""" + import ctypes as c + from ctypes import wintypes as w + kernel = c.WinDLL("kernel32", use_last_error=True) + kernel.OpenProcess.argtypes = [w.DWORD, w.BOOL, w.DWORD] + kernel.OpenProcess.restype = w.HANDLE + kernel.K32EnumProcessModules.argtypes = [w.HANDLE, c.POINTER(w.HMODULE), w.DWORD, c.POINTER(w.DWORD)] + kernel.K32GetModuleFileNameExW.argtypes = [w.HANDLE, w.HMODULE, w.LPWSTR, w.DWORD] + kernel.CloseHandle.argtypes = [w.HANDLE] + process = kernel.OpenProcess(0x410, False, pid) # QUERY_INFORMATION | VM_READ + assert process, f"Cannot inspect packaged desktop: {c.get_last_error()}" + try: + modules, needed = (w.HMODULE * 1024)(), w.DWORD() + assert kernel.K32EnumProcessModules(process, modules, c.sizeof(modules), c.byref(needed)) + assert needed.value <= c.sizeof(modules) + paths = [] + for module in modules[:needed.value // c.sizeof(w.HMODULE)]: + name = c.create_unicode_buffer(32768) + assert kernel.K32GetModuleFileNameExW(process, module, name, len(name)) + if Path(name.value).name.lower().startswith("vcruntime"): + paths.append(Path(name.value)) + assert paths and all(path.parent.samefile(directory) for path in paths), paths + (evidence / "runtime.json").write_text(json.dumps([str(path) for path in paths])) + finally: + kernel.CloseHandle(process) + print("PASS: extracted desktop loads its bundled Visual C++ runtime") + + +def windows_controls(pid, screenshot, evidence): + """Check visible GPUI caption glyphs and real native minimize/maximize clicks.""" + import ctypes as c + from ctypes import wintypes as w + user = c.WinDLL("user32", use_last_error=True) + callback = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM) + user.EnumWindows.argtypes = [callback, w.LPARAM] + user.GetWindowThreadProcessId.argtypes = [w.HWND, c.POINTER(w.DWORD)] + user.IsWindowVisible.argtypes = [w.HWND] + user.GetClientRect.argtypes = [w.HWND, c.POINTER(w.RECT)] + user.ClientToScreen.argtypes = [w.HWND, c.POINTER(w.POINT)] + user.GetDpiForWindow.argtypes = [w.HWND] + user.SendMessageW.argtypes = [w.HWND, w.UINT, w.WPARAM, w.LPARAM] + user.SendMessageW.restype = w.LPARAM + user.ShowWindow.argtypes = [w.HWND, c.c_int] + user.IsIconic.argtypes = [w.HWND] + user.IsZoomed.argtypes = [w.HWND] + windows = [] + @callback + def visit(hwnd, _): + owner = w.DWORD() + rect = w.RECT() + user.GetWindowThreadProcessId(hwnd, c.byref(owner)) + user.GetClientRect(hwnd, c.byref(rect)) + if owner.value == pid and user.IsWindowVisible(hwnd) and rect.right > 500: + windows.append(hwnd) + return True + user.EnumWindows(visit, 0) + assert windows, "Native desktop window missing" + hwnd = windows[0] + rect, origin = w.RECT(), w.POINT() + user.GetClientRect(hwnd, c.byref(rect)) + user.ClientToScreen(hwnd, c.byref(origin)) + # gpui-component 0.7 uses three 34-DIP caption buttons at the right edge. + scale = user.GetDpiForWindow(hwnd) / 96 + controls = {} + for index, (name, hit) in enumerate((("close", 20), ("maximize", 9), ("minimize", 8))): + x = round(origin.x + rect.right - (index + 0.5) * 34 * scale) + y = round(origin.y + 17 * scale) + assert 10 < x < screenshot.width - 10 and 10 < y < screenshot.height - 10, "Caption control is off-screen" + deadline = time.monotonic() + 2 + while True: + low, high = screenshot.crop((x - 10, y - 10, x + 10, y + 10)).convert("L").getextrema() + if high - low > 80: + break + assert time.monotonic() < deadline, f"Caption glyph is missing: {name}" + time.sleep(0.1) + screenshot = ImageGrab.grab().convert("RGB") + user.SetCursorPos(x, y) + time.sleep(0.12) # GPUI resolves the current pointer's control area. + observed = user.SendMessageW(hwnd, 0x84, 0, (y << 16) | (x & 0xffff)) + assert observed == hit, f"Native caption hit test for {name}: {observed}" + controls[name] = [x, y] + screenshot.save(evidence / "desktop.png") + def wait_for(check, message): + deadline = time.monotonic() + 2 + while not check(): + assert time.monotonic() < deadline, message + time.sleep(0.05) + for name, check in (("minimize", user.IsIconic), ("maximize", user.IsZoomed)): + user.SetCursorPos(*controls[name]) + time.sleep(0.12) + user.mouse_event(0x2, 0, 0, 0, 0) + user.mouse_event(0x4, 0, 0, 0, 0) + wait_for(lambda: check(hwnd), f"Native {name} click failed") + user.ShowWindow(hwnd, 9) # Restore without sending a synthetic caption action. + wait_for(lambda: not check(hwnd), f"Window did not restore after {name}") + time.sleep(0.2) + (evidence / "window-controls.json").write_text(json.dumps(controls)) + print("PASS: visible caption glyphs, native hit tests and minimize/maximize clicks") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--bin-dir", type=Path, default=Path("target/release")) + parser.add_argument("--evidence-dir", type=Path, default=Path("target/qa-evidence")) + parser.add_argument("--require-local-runtime", action="store_true") + args = parser.parse_args() + if os.name == "nt": + import ctypes + ctypes.windll.shcore.SetProcessDpiAwareness(2) + args.evidence_dir.mkdir(parents=True, exist_ok=True) + binary = args.bin_dir.resolve() / ("removent.exe" if os.name == "nt" else "removent") + before = ImageGrab.grab().convert("RGB") + with tempfile.TemporaryDirectory(prefix="removent-app-") as data: + env = dict(os.environ, REMOVENT_DATA_DIR=data, REMOVENT_NO_TRAY="1") + with (args.evidence_dir / "desktop.log").open("w") as log: + child = subprocess.Popen([str(binary), "--desktop-smoke"], env=env, + stdout=log, stderr=subprocess.STDOUT) + try: + # Software GPU discovery can take several seconds on a cold runner. + # Observe presented pixels, rather than assuming a fixed startup time. + deadline = time.monotonic() + 25 + while True: + assert child.poll() is None, "Desktop exited before the render observation" + after = ImageGrab.grab().convert("RGB") + after.save(args.evidence_dir / "desktop.png") + center = after.crop((after.width // 4, after.height // 4, + after.width * 3 // 4, after.height * 3 // 4)) + colors = center.getcolors(center.width * center.height) + difference = ImageChops.difference(before, after).convert("L") + changed = sum(difference.histogram()[24:]) + if colors and len(colors) > 30 and changed > 20000: + break + assert time.monotonic() < deadline, ( + f"Desktop did not visibly render ({len(colors or [])} colors, " + f"{changed} changed pixels)" + ) + time.sleep(0.25) + if os.name == "nt": + if args.require_local_runtime: + windows_local_runtime(child.pid, binary.parent, args.evidence_dir) + windows_controls(child.pid, after, args.evidence_dir) + assert child.wait(timeout=25) == 0, "Desktop process failed" + receipt = Path(data) / "run/update-smoke-ok" + assert receipt.is_file() and receipt.read_text().strip(), "No first-frame completion receipt" + finally: + if child.poll() is None: + child.kill() + child.wait() + print("PASS: visible GPUI window, rendered pixels, first-frame receipt and clean exit") + + +if __name__ == "__main__": + main() diff --git a/scripts/qa/portable_credentials.py b/scripts/qa/portable_credentials.py new file mode 100644 index 0000000..d8982e3 --- /dev/null +++ b/scripts/qa/portable_credentials.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Use a fresh Linux Secret Service collection or Windows Credential Manager.""" +import argparse +import json +import os +from pathlib import Path +import secrets +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--bin-dir", type=Path, default=Path("target/release")) + parser.add_argument("--app-tests", action="store_true", + help="also exercise the desktop remember, reuse and edit flows") + args = parser.parse_args() + binary = args.bin_dir.resolve() / "examples" / ("credential_smoke.exe" if os.name == "nt" else "credential_smoke") + with tempfile.TemporaryDirectory(prefix="removent-secrets-") as data: + env = dict(os.environ, REMOVENT_DESKTOP_TEST="1", XDG_DATA_HOME=data) + if os.name != "nt": + unavailable = dict(env, DBUS_SESSION_BUS_ADDRESS=f"unix:path={data}/absent-bus") + subprocess.run([str(binary), "--expect-unavailable"], env=unavailable, + check=True, timeout=20) + if any(Path(data).rglob("*")): + raise RuntimeError("An unavailable credential store wrote a fallback file") + control = str(Path(data) / "control") + env["GNOME_KEYRING_CONTROL"] = control + subprocess.run(["gnome-keyring-daemon", "--unlock", "--control-directory", control], + input=secrets.token_hex(32).encode(), env=env, check=True, timeout=15) + subprocess.run(["gnome-keyring-daemon", "--start", "--components=secrets", "--control-directory", control], + env=env, check=True, timeout=15) + subprocess.run([str(binary)], env=env, check=True, timeout=20) + if args.app_tests: + build = subprocess.run( + ["cargo", "test", "--locked", "-p", "removent-app", "--bin", "removent", + "--no-run", "--message-format=json"], + stdout=subprocess.PIPE, text=True, check=True, timeout=1200) + artifacts = [json.loads(line) for line in build.stdout.splitlines()] + binaries = [item["executable"] for item in artifacts + if item.get("reason") == "compiler-artifact" + and item.get("profile", {}).get("test") and item.get("executable") + and item.get("target", {}).get("name") == "removent"] + if len(binaries) != 1: + raise RuntimeError("Expected exactly one desktop test executable") + for test_filter, extra in [ + ("engine::credentials::tests::", []), + ("ui::home::tests::authentication::", []), + ("ui::connection::", []), + ("engine::credentials::tests::", ["--ignored"]), + ]: + subprocess.run([binaries[0], test_filter, "--test-threads=1", *extra], + env=env, check=True, timeout=120) + + +if __name__ == "__main__": + main() diff --git a/scripts/qa/portable_desktop.py b/scripts/qa/portable_desktop.py new file mode 100644 index 0000000..c1b51b8 --- /dev/null +++ b/scripts/qa/portable_desktop.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Independent GUI event oracle; run under an isolated Xvfb/Windows desktop.""" +import argparse, json, os, subprocess, tempfile, threading, tkinter as tk +from pathlib import Path +from PIL import ImageGrab + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument("--bin-dir",type=Path,default=Path("target/release")) + parser.add_argument("--probe",default="desktop_smoke") + parser.add_argument("--evidence-dir",type=Path,default=Path("target/qa-evidence")) + args=parser.parse_args() + args.evidence_dir.mkdir(parents=True, exist_ok=True) + if os.name == "nt": + import ctypes + ctypes.windll.shcore.SetProcessDpiAwareness(2) + binary=args.bin_dir.resolve()/"examples"/(args.probe + (".exe" if os.name=="nt" else "")) + root=tk.Tk(); root.geometry("640x480+0+0"); root.title("Removent isolated desktop test") + root.configure(background="#ff0000"); root.attributes("-topmost",True) + entry=tk.Entry(root,font=("Arial",20)); entry.place(x=50,y=170,width=500,height=60) + entry.insert(0,"replace me") + def select_all(event): + entry.selection_range(0,tk.END) + return "break" + entry.bind("", select_all) + clicks=[]; entry.bind("",lambda event:clicks.append((event.x,event.y))) + outcome=[] + def worker(): + with tempfile.TemporaryDirectory(prefix="removent-desktop-") as data: + env=dict(os.environ,REMOVENT_DESKTOP_TEST="1",REMOVENT_DATA_DIR=data, + REMOVENT_TEST_X=str(target[0]),REMOVENT_TEST_Y=str(target[1])) + try: + result=subprocess.run([str(binary)],env=env,capture_output=True,text=True,timeout=45) + outcome.append(result) + except Exception as e: outcome.append(e) + def begin(): + root.lift(); entry.focus_force() + target[:] = [entry.winfo_rootx()+entry.winfo_width()//2, entry.winfo_rooty()+entry.winfo_height()//2] + threading.Thread(target=worker,daemon=True).start(); root.after(100,poll) + def poll(): + if not outcome: root.after(100,poll); return + root.after(500,finish) + def finish(): + result=outcome[0] + try: + ImageGrab.grab().save(args.evidence_dir/(args.probe+".png")) + (args.evidence_dir/(args.probe+".json")).write_text(json.dumps({"target":target,"clicks":clicks,"text":entry.get()},ensure_ascii=True)) + if isinstance(result,Exception): raise result + print(result.stdout,flush=True); print(result.stderr,flush=True) + assert result.returncode==0, f"Native probe exited {result.returncode}" + assert clicks, "No native click reached the independent UI" + assert entry.get()=="hello中文", f"Native typing mismatch: {entry.get()!r}" + print("PASS: independent UI received native click, Ctrl+A and exact text",flush=True) + except BaseException as e: outcome.append(e) + finally: root.destroy() + target=[] + root.after(1500,begin); root.mainloop() + if len(outcome)>1: raise outcome[-1] +if __name__=="__main__": main() diff --git a/scripts/qa/tray_lifecycle.py b/scripts/qa/tray_lifecycle.py new file mode 100644 index 0000000..4746316 --- /dev/null +++ b/scripts/qa/tray_lifecycle.py @@ -0,0 +1,378 @@ +"""Shared native tray acceptance against real daemon IPC and QUIC video sessions.""" +import argparse +import json +import os +from pathlib import Path +import queue +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +import time +import traceback + +import psutil +from PIL import ImageGrab + + +def wait_for(check, message, seconds=15): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + value = check() + if value: + return value + time.sleep(0.1) + raise AssertionError(message) + + +def visible_app(ui, window, name): + """A mapped/focused window can still have an unpainted or lost surface.""" + def rendered(): + shot = ImageGrab.grab().convert("RGB") + left, top, right, bottom = ui.app_rect(window) + width, height = right - left, bottom - top + # Exclude the native frame and title bar, including resize artifacts. + content = shot.crop((left + width // 8, top + height // 4, + right - width // 8, bottom - height // 8)) + colors = content.getcolors(content.width * content.height) + low, high = content.convert("L").getextrema() + shot.save(ui.args.evidence_dir / f"{name}.png") + return colors and len(colors) > 30 and high - low > 50 + wait_for(rendered, f"Desktop content was not visibly rendered: {name}", 25) + + +class Stream: + def __init__(self, command, env, log): + self.events = queue.Queue() + self.process = subprocess.Popen(command, env=env, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=log, text=True, + encoding="utf-8", errors="replace", bufsize=1) + def read(): + for line in self.process.stdout: + log.write(f"probe {self.process.pid}: {line}") + log.flush() + try: + self.events.put(json.loads(line)) + except json.JSONDecodeError: + pass + threading.Thread(target=read, daemon=True).start() + + def event(self, predicate, seconds=15): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + event = self.events.get(timeout=0.2) + if predicate(event): + return event + except queue.Empty: + if self.process.poll() is not None: + raise AssertionError(f"Probe exited early: {self.process.returncode}") + raise AssertionError("Expected probe event was not received") + + def send(self, command): + self.process.stdin.write(command + "\n") + self.process.stdin.flush() + + def stop(self): + if self.process.poll() is None: + self.process.terminate() + self.process.wait(timeout=5) + + +def run(desktop_type): + parser = argparse.ArgumentParser() + parser.add_argument("--bin-dir", type=Path, default=Path("target/release")) + parser.add_argument("--probe-dir", type=Path, default=Path("target/release/examples")) + parser.add_argument("--evidence-dir", type=Path, default=Path("target/qa-evidence/tray")) + parser.add_argument("--soak-seconds", type=int, default=60) + parser.add_argument("--locale", choices=["En", "ZhCn"], default="En") + parser.add_argument("--theme", choices=["light", "dark"], default="light") + parser.add_argument("--scale", type=int, choices=[1, 2], default=1) + parser.add_argument("--presentation-only", action="store_true") + parser.add_argument("--second-monitor", action="store_true") + args = parser.parse_args() + if args.second_monitor and os.name == "nt": + parser.error("--second-monitor requires the isolated Linux RandR fixture") + args.evidence_dir.mkdir(parents=True, exist_ok=True) + suffix = ".exe" if os.name == "nt" else "" + binary = args.bin_dir.resolve() / ("removent-tray" + suffix) + probe = args.probe_dir.resolve() / ("tray_probe" + suffix) + session_binary = args.probe_dir.resolve() / ("tray_session" + suffix) + zh = args.locale == "ZhCn" + labels = { + "open": "打开 Removent" if zh else "Open Removent", + "start": "启动后台服务" if zh else "Start background service", + "stop": "停止后台服务" if zh else "Stop background service", + "share": "共享本机" if zh else "Share this desktop", + "pair": "显示配对码" if zh else "Show pairing code", + "quit": "退出托盘" if zh else "Quit tray", + "pair_title": "配对码" if zh else "Pairing code", + "admit": "远程访问请求" if zh else "Remote access request", + } + with tempfile.TemporaryDirectory(prefix="removent-tray-full-") as directory: + root = Path(directory) + data = root / "data" + data.mkdir() + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as reserve: + reserve.bind(("127.0.0.1", 0)) + port = reserve.getsockname()[1] + (data / "settings.toml").write_text( + f'language = "{args.locale}"\ntheme = "System"\nhost_enabled = false\n' + f'host_port = {port}\nprevent_idle_sleep = false\n' + '[authentication]\nmode = "pairing_code"\n', encoding="utf-8") + env = dict(os.environ, REMOVENT_DATA_DIR=str(data), REMOVENT_DESKTOP_TEST="1", + REMOVENT_TEST_CLIENT_DIR=str(root / "client"), REMOVENT_NO_TRAY="1") + results, resources, streams = [], [], [] + completed = False + tray = None + stimulus = None + daemon_pid = None + with (args.evidence_dir / "tray.log").open("w", encoding="utf-8") as log: + def passed(name): + results.append(name) + print("PASS: " + name, flush=True) + def ipc(request): + result = subprocess.run([str(probe), json.dumps(request)], env=env, + capture_output=True, text=True, encoding="utf-8", timeout=5) + if result.returncode: + return None + return json.loads(result.stdout.strip().splitlines()[-1]) + def health(): + value = ipc({"type": "update_health"}) + return value if value and value.get("type") == "update_health" else None + def sharing_state(on): + state = (health() or {}).get("status", {}) + return state.get("running") == on and state.get("host_ready") == on + def start_tray(ui): + process = subprocess.Popen([str(binary)], env=env, stdout=log, stderr=log) + ui.attach(process.pid) + wait_for(ui.registered, "Tray icon was not registered") + return process + def connect(watcher): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + stream = Stream([str(session_binary), str(port)], env, log) + streams.append(stream) + while time.monotonic() < deadline: + try: + event = watcher.events.get(timeout=0.1) + if event.get("type") == "admission_request": + return stream, event + except queue.Empty: + pass + try: + event = stream.events.get_nowait() + except queue.Empty: + continue + # A rejection reaches the client just before the host's + # connection teardown releases its single-session slot. + # Wait for that boundary, without retrying any denial or + # masking a host that never releases the slot. + assert event == {"event": "rejected", "reason": "rejected: Busy"}, event + assert stream.process.wait(timeout=5) == 0 + log.write("Waiting for the previous host admission to finish teardown\n") + log.flush() + time.sleep(0.1) + break + raise AssertionError("Host did not admit a new request within 10 seconds") + try: + subprocess.run([str(session_binary), "prepare"], env=env, check=True, + stdout=log, stderr=log, timeout=15) + with desktop_type(root, env, args, log) as ui: + tray = start_tray(ui) + duplicate = subprocess.run([str(binary)], env=env, stdout=log, stderr=log, timeout=5) + assert duplicate.returncode == 0 and tray.poll() is None + passed("tray singleton") + ui.click(labels["start"]) + state = wait_for(health, "Daemon did not start") + daemon_pid = state["pid"] + ui.click(labels["share"], checked=False) + wait_for(lambda: (health() or {}).get("status", {}).get("host_ready"), "Sharing listener did not become ready") + for index in range(2): + ui.click(labels["pair"]) + wait_for(lambda: ui.dialog(labels["pair_title"]), "Pairing dialog did not open") + ui.snapshot(f"pairing-{index}") + ui.answer(labels["pair_title"], None) + wait_for(lambda: not ui.dialog(labels["pair_title"]), "Pairing dialog did not close") + assert ipc({"type": "pairing_revoke"})["type"] == "ok" + passed("real icon clicks, sharing and repeatable native pairing dialogs") + ui.click(labels["open"]) + window = wait_for(ui.app_window, "Tray failed to open the real desktop", 30) + visible_app(ui, window, "desktop-open") + if args.second_monitor: + position = ui.move_to_secondary(window) + visible_app(ui, window, "desktop-secondary") + ui.minimize(window) + ui.click(labels["open"]) + wait_for(lambda: ui.app_active(window), "Existing desktop was not restored and activated") + assert ui.app_count() == 1, "Tray created duplicate desktop windows" + if args.second_monitor: + wait_for(lambda: ui.app_position(window) == position, + f"Reactivation did not restore the desktop position {position}", 5) + visible_app(ui, window, "desktop-secondary-restored") + passed("reactivation preserves the desktop position on a second logical monitor") + else: + visible_app(ui, window, "desktop-restored") + passed("open and reactivate a single real desktop window") + if args.presentation_only: + ui.close_app(window) + wait_for(lambda: not ui.app_window(), "Desktop did not close") + else: + watcher = Stream([str(probe), "watch"], env, log) + streams.append(watcher) + watcher.event(lambda e: e.get("type") == "status") + pending, request = connect(watcher) + time.sleep(1) + assert not ui.dialog(labels["admit"]), "Tray duplicated the desktop's prompt immediately" + assert ipc({"type": "admission_reply", "request_id": request["request_id"], "allow": False})["type"] == "ok" + pending.event(lambda e: e.get("event") == "rejected") + time.sleep(8) + assert not ui.dialog(labels["admit"]), "Resolved request produced a delayed duplicate prompt" + ui.close_app(window) + wait_for(lambda: not ui.app_window(), "Desktop did not close") + passed("desktop-first admission and resolution by another management client") + pending, _ = connect(watcher) + wait_for(lambda: ui.dialog(labels["admit"]), "Default-answer prompt missing") + ui.accept_default(labels["admit"]) + pending.event(lambda e: e.get("event") == "rejected") + wait_for(lambda: not ui.dialog(labels["admit"]), "Default-denied prompt remained visible") + passed("pressing Enter defaults to denying remote access") + pending, request = connect(watcher) + wait_for(lambda: ui.dialog(labels["admit"]), "Competing-answer prompt missing") + assert ipc({"type": "admission_reply", "request_id": request["request_id"], "allow": False})["type"] == "ok" + pending.event(lambda e: e.get("event") == "rejected") + wait_for(lambda: not ui.dialog(labels["admit"]), "Another client's answer did not dismiss the prompt") + passed("another management client's answer dismisses an already visible prompt") + for decision in (False, True): + pending, _ = connect(watcher) + wait_for(lambda: ui.dialog(labels["admit"]), "Admission dialog missing") + ui.snapshot("admission-allow" if decision else "admission-deny") + ui.answer(labels["admit"], decision) + pending.event(lambda e: e.get("event") == ("connected" if decision else "rejected")) + wait_for(lambda: not ui.dialog(labels["admit"]), "Answered prompt remained visible") + if decision: + pending.event(lambda e: e.get("event") == "frames" and e["count"] > 0) + # Capture intentionally suppresses unchanged frames. Animate + # an independent native window to prove continued delivery. + stimulus = subprocess.Popen([sys.executable, str(Path(__file__).with_name("tray_video_stimulus.py"))], + env=env, stdout=log, stderr=log) + ui.click(labels["quit"]) + assert tray.wait(timeout=5) == 0 + before = pending.event(lambda e: e.get("event") == "frames")["count"] + pending.event(lambda e: e.get("event") == "frames" and e["count"] > before + 2) + assert health()["pid"] == daemon_pid + passed("quitting the tray preserves the daemon and real QUIC video") + tray = start_tray(ui) + ui.restart_shell() + wait_for(ui.registered, "Tray icon did not recover after shell restart", 25) + ui.click(labels["pair"]) + # Pairing is refused during an active session; the native error + # dialog also proves menu dispatch survived shell replacement. + wait_for(lambda: ui.dialog("Removent"), "Expected busy-session feedback") + ui.answer("Removent", None) + passed("shell restart preserves tray registration and menu actions") + baseline = None + soak_started = time.monotonic() + deadline = soak_started + args.soak_seconds + last_frames = before + while time.monotonic() < deadline: + event = pending.event(lambda e: e.get("event") == "frames" and e["count"] > last_frames, seconds=10) + last_frames = event["count"] + process = psutil.Process(tray.pid) + sample = {"rss": process.memory_info().rss, "threads": process.num_threads(), + "handles": process.num_handles() if os.name == "nt" else process.num_fds(), + "elapsed_seconds": time.monotonic() - soak_started, + "decoded_frames": last_frames} + baseline = baseline or sample + assert sample["rss"] < baseline["rss"] + 64 * 1024 * 1024, sample + assert sample["handles"] < baseline["handles"] + 64, sample + assert sample["threads"] < baseline["threads"] + 8, sample + resources.append(sample) + assert tray.poll() is None and health()["pid"] == daemon_pid + pending.send("close") + pending.event(lambda e: e.get("event") == "closed") + assert pending.process.wait(timeout=5) == 0 + stimulus.terminate() + stimulus.wait(timeout=5) + passed(f"{args.soak_seconds}s live video soak with tray memory, handle and thread bounds") + else: + assert pending.process.wait(timeout=5) == 0 + passed("native denial and approval produce the corresponding real remote-session result") + pending, _ = connect(watcher) + wait_for(lambda: ui.dialog(labels["admit"]), "Cancellation prompt missing") + pending.send("cancel") + pending.event(lambda e: e.get("event") == "cancelled") + wait_for(lambda: not ui.dialog(labels["admit"]), "Remote cancellation did not close prompt", 5) + passed("controller cancellation dismisses the native approval dialog") + pending, _ = connect(watcher) + wait_for(lambda: ui.dialog(labels["admit"]), "Timeout prompt missing") + pending.event(lambda e: e.get("event") == "rejected", seconds=35) + wait_for(lambda: not ui.dialog(labels["admit"]), "Expired approval dialog remained visible") + passed("real 30-second admission timeout rejects and dismisses the prompt") + pending, _ = connect(watcher) + wait_for(lambda: ui.dialog(labels["admit"]), "Disconnect prompt missing") + psutil.Process(daemon_pid).kill() + wait_for(lambda: not ui.dialog(labels["admit"]), "Lost-daemon prompt remained visible") + state = wait_for(lambda: (h if (h := health()) and h["pid"] != daemon_pid else None), "Tray did not recover the crashed daemon", 20) + daemon_pid = state["pid"] + wait_for(lambda: health()["status"]["host_ready"], "Recovered host not ready") + passed("daemon crash clears stale prompts and restarts sharing") + pending.stop() + # Cross several 2-second daemon status polls. Each click + # must change the real host, including after closing the app. + for on in (False, True) * 4: + ui.click(labels["share"], checked=not on) + wait_for(lambda: sharing_state(on), + f"Native sharing click did not set running={on}") + passed("repeated sharing changes survive concurrent status refresh") + ui.click(labels["share"], checked=True) + wait_for(lambda: not health()["status"]["running"], "Sharing did not stop") + ui.click(labels["stop"]) + wait_for(lambda: not health(), "Daemon did not stop") + assert (data / "run/service-stopped").exists() + time.sleep(6) + assert not health(), "Watchdog overrode an explicit stop" + delayed = subprocess.run([str(args.bin_dir.resolve() / ("removentd" + suffix)), "--background"], + env=env, stdout=log, stderr=log, timeout=5) + assert delayed.returncode == 0 and not health(), "Delayed background launch overrode an explicit stop" + ui.click(labels["quit"]) + assert tray.wait(timeout=5) == 0 + tray = start_tray(ui) + time.sleep(2) + assert not health(), "Tray restart overrode an explicit stop" + ui.click(labels["start"]) + daemon_pid = wait_for(health, "Explicit restart did not work")["pid"] + ui.click(labels["stop"]) + wait_for(lambda: not health(), "Final service stop failed") + ui.click(labels["quit"]) + assert tray.wait(timeout=5) == 0 + passed("manual stop survives watchdog and tray restart; explicit start remains usable") + completed = True + finally: + if sys.exc_info()[0] is not None: + traceback.print_exc(file=log) + log.flush() + if stimulus and stimulus.poll() is None: + stimulus.terminate() + stimulus.wait(timeout=5) + if tray and tray.poll() is None: + tray.terminate() + tray.wait(timeout=5) + for stream in streams: + stream.stop() + try: + ipc({"type": "shutdown"}) + except (subprocess.TimeoutExpired, OSError): + pass + if daemon_pid and psutil.pid_exists(daemon_pid): + try: + psutil.Process(daemon_pid).wait(timeout=5) + except psutil.TimeoutExpired: + psutil.Process(daemon_pid).kill() + if (data / "logs").is_dir(): + shutil.copytree(data / "logs", args.evidence_dir / "logs", dirs_exist_ok=True) + (args.evidence_dir / "results.json").write_text(json.dumps({"completed": completed, "passed": results, "resources": resources, + "locale": args.locale, "theme": args.theme, "scale": args.scale, + "second_monitor": args.second_monitor}, indent=2), encoding="utf-8") diff --git a/scripts/qa/tray_ui_linux.py b/scripts/qa/tray_ui_linux.py new file mode 100644 index 0000000..af4f723 --- /dev/null +++ b/scripts/qa/tray_ui_linux.py @@ -0,0 +1,248 @@ +"""X11 pointer input with AT-SPI used only to locate native controls.""" +import os +import re +from pathlib import Path +import subprocess +import time + +import dbus +import pyatspi +from gi.repository import GLib +from PIL import ImageGrab +from tray_lifecycle import wait_for + + +def xdo(*args, check=True): + return subprocess.run(["xdotool", *map(str, args)], capture_output=True, text=True, check=check, timeout=10) + + +def descendants(root, depth=0): + if depth > 12: + return + try: + root.clearCache() + yield root + for child in root: + yield from descendants(child, depth + 1) + except (RuntimeError, LookupError): + return + + +def showing(node): + try: + return node.getState().contains(pyatspi.STATE_SHOWING) + except (RuntimeError, LookupError): + return False + + +def press(node, scale): + rect = node.queryComponent().getExtents(pyatspi.DESKTOP_COORDS) + assert rect.width > 0 and rect.height > 0, (node.name, rect) + xdo("mousemove", (rect.x + rect.width // 2) * scale, (rect.y + rect.height // 2) * scale, "click", 1) + + +class LinuxDesktop: + def __init__(self, root, env, args, log): + self.env, self.args, self.log = env, args, log + self.panel = None + self.pid = None + config = root / "config/xfce4/xfconf/xfce-perchannel-xml" + config.mkdir(parents=True) + (config / "xfce4-panel.xml").write_text(''' + + + + + + + + + + + + +''') + env.update(XDG_CONFIG_HOME=str(root / "config"), GTK_MODULES="gail:atk-bridge", + NO_AT_BRIDGE="0", GDK_SCALE=str(args.scale), + GTK_THEME="Adwaita:dark" if args.theme == "dark" else "Adwaita") + + def __enter__(self): + subprocess.run(["dbus-update-activation-environment", "XDG_CONFIG_HOME", "GTK_MODULES", "NO_AT_BRIDGE", "GDK_SCALE", "GTK_THEME"], env=self.env, check=True) + self.bus = dbus.SessionBus() + # Start the accessibility registry before Xfce creates its embedded + # systray plugin. Otherwise its visible icon can have no AT-SPI node. + list(self.nodes()) + self.start_panel() + return self + + def start_panel(self): + self.panel = subprocess.Popen(["xfce4-panel", "--disable-wm-check"], env=self.env, + stdout=self.log, stderr=self.log) + wait_for(lambda: self.bus.name_has_owner("org.kde.StatusNotifierWatcher"), "Desktop panel did not start") + + def __exit__(self, error_type, *_): + if error_type is not None: + self.snapshot("failure") + for node in self.nodes(): + self.log.write(f"AT-SPI {node.getRoleName()}: {node.name!r}, showing={showing(node)}\n") + self.log.flush() + for window in self.app_windows(): + self.close_app(window) + if self.panel and self.panel.poll() is None: + self.panel.terminate() + self.panel.wait(timeout=5) + + def attach(self, pid): + self.pid = pid + + def registered(self): + try: + watcher = self.bus.get_object("org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher") + entries = watcher.Get("org.kde.StatusNotifierWatcher", "RegisteredStatusNotifierItems", dbus_interface="org.freedesktop.DBus.Properties") + return bool(entries) + except dbus.DBusException: + return False + + def nodes(self): + context = GLib.MainContext.default() + while context.pending(): + context.iteration(False) + return descendants(pyatspi.Registry.getDesktop(0)) + + def click(self, label, checked=None): + # The fixture panel contains only this tray item. Query its actual AT-SPI + # bounds rather than invoking the exported D-Bus menu callbacks. + def icon(): + candidates = [] + for node in self.nodes(): + if showing(node) and node.getRole() == pyatspi.ROLE_PUSH_BUTTON: + if "removent" in (node.name or "").lower(): + return node + if node.getApplication().name == "xfce4-panel": + candidates.append(node) + # Xfce's StatusNotifier button has an empty accessible name. This + # isolated panel has only one plugin and one registered tray icon. + if len(candidates) == 1 and self.registered(): + return candidates[0] + return None + try: + node = wait_for(icon, "Accessible tray icon missing") + except AssertionError: + self.snapshot("missing-icon") + for node in self.nodes(): + self.log.write(f"AT-SPI {node.getRoleName()}: {node.name!r}, showing={showing(node)}\n") + self.log.flush() + raise + rect = node.queryComponent().getExtents(pyatspi.DESKTOP_COORDS) + # GTK's AT-SPI screen coordinates are logical pixels under GDK_SCALE. + xdo("mousemove", (rect.x + rect.width // 2) * self.args.scale, + (rect.y + rect.height // 2) * self.args.scale, "click", 3) + # Xfce's exported dbusmenu popup is not included in its AT-SPI tree. + # Read labels/state only, then navigate the visible GTK menu with actual + # keyboard input. Never invoke dbusmenu.Event or a widget callback. + def entries(): + watcher = self.bus.get_object("org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher") + registered = watcher.Get("org.kde.StatusNotifierWatcher", "RegisteredStatusNotifierItems", + dbus_interface="org.freedesktop.DBus.Properties") + assert len(registered) == 1 + service, path = str(registered[0]).split("/", 1) + item = self.bus.get_object(service, "/" + path) + menu_path = item.Get("org.kde.StatusNotifierItem", "Menu", dbus_interface="org.freedesktop.DBus.Properties") + menu = dbus.Interface(self.bus.get_object(service, menu_path), "com.canonical.dbusmenu") + children = menu.GetLayout(0, -1, [])[1][2] + labels = [str(child[1].get("label", "")).replace("_", "") + for child in children + if child[1].get("enabled", True) and child[1].get("visible", True) + and child[1].get("type") != "separator"] + target = next((child[1] for child in children + if str(child[1].get("label", "")).replace("_", "") == label), {}) + matches = checked is None or int(target.get("toggle-state", -1)) == int(checked) + return labels if label in labels and matches else None + labels = wait_for(entries, f"Enabled native menu item missing: {label}") + time.sleep(0.2) + self.snapshot("menu") + xdo("key", "--clearmodifiers", "Home", *(["Down"] * labels.index(label)), "Return") + time.sleep(0.3) + + def dialog(self, title): + # GtkMessageDialog exposes its message type (e.g. "Information") as + # the AT-SPI name; match the actual X11 title before inspecting controls. + window = xdo("search", "--onlyvisible", "--pid", self.pid, + "--name", "^" + re.escape(title) + "$", check=False) + if window.returncode: + return None + for node in self.nodes(): + if node.getRole() in (pyatspi.ROLE_DIALOG, pyatspi.ROLE_ALERT) and showing(node): + if node.get_process_id() == self.pid: + return node + return None + + def answer(self, title, allow): + dialog = wait_for(lambda: self.dialog(title), "Native dialog missing") + expected = ["OK", "确定"] if allow is None else ["Yes", "是", "允许"] if allow else ["No", "否", "拒绝"] + buttons = [node for node in descendants(dialog) if node.getRole() == pyatspi.ROLE_PUSH_BUTTON and showing(node)] + button = next((node for node in buttons if (node.name or "").replace("_", "") in expected), None) + assert button is not None, [node.name for node in buttons] + press(button, self.args.scale) + + def accept_default(self, title): + window = xdo("search", "--onlyvisible", "--pid", self.pid, + "--name", "^" + re.escape(title) + "$").stdout.strip().splitlines()[0] + xdo("windowactivate", "--sync", window, "key", "Return") + + def app_windows(self): + value = xdo("search", "--onlyvisible", "--name", "^Removent$", check=False) + found = [] + for window in value.stdout.strip().splitlines() if value.returncode == 0 else []: + result = xdo("getwindowgeometry", "--shell", window, check=False) + if result.returncode == 0: + geometry = dict(line.split("=", 1) for line in result.stdout.splitlines()) + if int(geometry["WIDTH"]) > 500 and int(geometry["HEIGHT"]) > 400: + found.append(window) + return found + + def app_window(self): + return next(iter(self.app_windows()), None) + + def app_count(self): + return len(self.app_windows()) + + def app_position(self, window): + geometry = dict(line.split("=", 1) for line in xdo("getwindowgeometry", "--shell", window).stdout.splitlines()) + return int(geometry["X"]), int(geometry["Y"]) + + def app_rect(self, window): + geometry = dict(line.split("=", 1) for line in xdo("getwindowgeometry", "--shell", window).stdout.splitlines()) + x, y, width, height = (int(geometry[key]) for key in ["X", "Y", "WIDTH", "HEIGHT"]) + return x, y, x + width, y + height + + def move_to_secondary(self, window): + result = subprocess.run(["xrandr", "--listmonitors"], capture_output=True, text=True, check=True) + (self.args.evidence_dir / "monitors.txt").write_text(result.stdout) + monitors = re.findall(r"(\d+)/\d+x(\d+)/\d+\+(\d+)\+(\d+)", result.stdout) + assert len(monitors) == 2, result.stdout + x, y = map(int, monitors[1][2:]) + xdo("windowsize", window, 1000, 680, "windowmove", window, x + 40, y + 40) + wait_for(lambda: self.app_position(window)[0] >= x, "Desktop did not move to the second monitor") + time.sleep(0.5) + return self.app_position(window) + + def minimize(self, window): + xdo("windowminimize", "--sync", window) + wait_for(lambda: window not in self.app_windows(), "Desktop did not minimize") + + def app_active(self, window): + return xdo("getactivewindow", check=False).stdout.strip() == window and window in self.app_windows() + + def close_app(self, window): + xdo("windowactivate", "--sync", window, "key", "alt+F4", check=False) + + def restart_shell(self): + self.panel.terminate() + self.panel.wait(timeout=5) + wait_for(lambda: not self.bus.name_has_owner("org.kde.StatusNotifierWatcher"), "Old panel watcher remained") + self.start_panel() + time.sleep(0.5) + + def snapshot(self, name): + ImageGrab.grab().save(self.args.evidence_dir / f"{name}.png") diff --git a/scripts/qa/tray_ui_windows.py b/scripts/qa/tray_ui_windows.py new file mode 100644 index 0000000..0b78d89 --- /dev/null +++ b/scripts/qa/tray_ui_windows.py @@ -0,0 +1,245 @@ +"""OS pointer input on Explorer icons, native menus and dialog buttons.""" +import ctypes as c +from ctypes import wintypes as w +import os +import subprocess +import time +import winreg + +from PIL import ImageGrab +from pywinauto import Desktop +from tray_lifecycle import wait_for + +user = c.WinDLL("user32", use_last_error=True) +shell = c.WinDLL("shell32", use_last_error=True) +callback = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM) +for name, args in { + "EnumWindows": [callback, w.LPARAM], + "GetWindowThreadProcessId": [w.HWND, c.POINTER(w.DWORD)], + "GetClassNameW": [w.HWND, w.LPWSTR, c.c_int], + "GetWindowTextW": [w.HWND, w.LPWSTR, c.c_int], + "GetWindowRect": [w.HWND, c.POINTER(w.RECT)], + "GetClientRect": [w.HWND, c.POINTER(w.RECT)], + "IsWindowVisible": [w.HWND], "IsIconic": [w.HWND], + "ShowWindow": [w.HWND, c.c_int], "SetForegroundWindow": [w.HWND], + "SendMessageW": [w.HWND, w.UINT, w.WPARAM, w.LPARAM], + "GetMenuItemCount": [w.HMENU], + "GetMenuStringW": [w.HMENU, w.UINT, w.LPWSTR, c.c_int, w.UINT], + "GetMenuState": [w.HMENU, w.UINT, w.UINT], + "GetMenuItemRect": [w.HWND, w.HMENU, w.UINT, c.POINTER(w.RECT)], +}.items(): + getattr(user, name).argtypes = args +user.SendMessageW.restype = w.LPARAM +user.GetForegroundWindow.restype = w.HWND + + +class IconIdentifier(c.Structure): + _fields_ = [("cbSize", w.DWORD), ("hWnd", w.HWND), ("uID", w.UINT), ("guidItem", c.c_ubyte * 16)] + + +shell.Shell_NotifyIconGetRect.argtypes = [c.POINTER(IconIdentifier), c.POINTER(w.RECT)] +shell.Shell_NotifyIconGetRect.restype = w.LONG + + +def windows(pid=None, class_name=None, title=None, visible=False, large=False): + found = [] + @callback + def visit(hwnd, _): + owner, rect = w.DWORD(), w.RECT() + user.GetWindowThreadProcessId(hwnd, c.byref(owner)) + name, text = c.create_unicode_buffer(256), c.create_unicode_buffer(256) + user.GetClassNameW(hwnd, name, 256) + user.GetWindowTextW(hwnd, text, 256) + user.GetClientRect(hwnd, c.byref(rect)) + if ((pid is None or owner.value == pid) and (class_name is None or name.value == class_name) + and (title is None or text.value == title) and (not visible or user.IsWindowVisible(hwnd)) + and (not large or rect.right > 500)): + found.append(hwnd) + return True + user.EnumWindows(visit, 0) + return found + + +def pointer(rect, button="left"): + user.SetCursorPos((rect.left + rect.right) // 2, (rect.top + rect.bottom) // 2) + time.sleep(0.15) + down, up = (0x2, 0x4) if button == "left" else (0x8, 0x10) + user.mouse_event(down, 0, 0, 0, 0) + user.mouse_event(up, 0, 0, 0, 0) + + +class WindowsDesktop: + def __init__(self, root, env, args, log): + assert os.environ.get("GITHUB_ACTIONS") == "true", "Explorer tests require an ephemeral CI desktop" + c.windll.shcore.SetProcessDpiAwareness(2) + self.args, self.log, self.pid = args, log, None + self.theme_key = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" + self.original = {} + + def __enter__(self): + with winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.theme_key) as key: + for name in ["AppsUseLightTheme", "SystemUsesLightTheme"]: + try: + self.original[name] = winreg.QueryValueEx(key, name)[0] + except FileNotFoundError: + self.original[name] = None + winreg.SetValueEx(key, name, 0, winreg.REG_DWORD, int(self.args.theme == "light")) + return self + + def __exit__(self, error_type, *_): + if error_type is not None: + self.snapshot("failure") + for hwnd in self.app_windows(): + self.close_app(hwnd) + with winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.theme_key) as key: + for name, value in self.original.items(): + if value is None: + try: winreg.DeleteValue(key, name) + except FileNotFoundError: pass + else: + winreg.SetValueEx(key, name, 0, winreg.REG_DWORD, value) + + def attach(self, pid): + self.pid = pid + self.owner = wait_for(lambda: next(iter(windows(pid, "tray_icon_app")), None), "Tray owner window missing") + + def icon_rect(self): + for identifier in range(32): + rect = w.RECT() + icon = IconIdentifier(c.sizeof(IconIdentifier), self.owner, identifier) + if shell.Shell_NotifyIconGetRect(c.byref(icon), c.byref(rect)) == 0: + return rect + return None + + def registered(self): + return self.icon_rect() is not None + + def popup(self): + return next(iter(windows(self.pid, "#32768", visible=True)), None) + + def click(self, label, checked=None): + # Start from the actual Explorer icon, including its overflow UI. No + # synthetic tray callback or menu command is used. + observed = [] + def open_menu(): + if self.popup(): + return self.popup() + rect = self.icon_rect() + if rect is None: + return None + pointer(rect, "right") + time.sleep(0.25) + if self.popup(): + return self.popup() + # Explorer may publish the icon rectangle while its notification + # area is still being constructed, or while the icon is hidden. + # Dismiss any taskbar menu before reading the actual chevron. + user.keybd_event(0x1B, 0, 0, 0) + user.keybd_event(0x1B, 0, 2, 0) + observed.clear() + for backend in ("uia", "win32"): + taskbar = Desktop(backend=backend).window(class_name="Shell_TrayWnd") + if not taskbar.exists(timeout=0.2): + continue + for control in taskbar.descendants(): + name = control.window_text().lower() + observed.append((backend, name, str(control.rectangle()))) + if ("hidden icons" in name or "notification chevron" in name) and control.is_visible(): + pointer(control.rectangle()) + time.sleep(0.25) + rect = self.icon_rect() + if rect is not None: + pointer(rect, "right") + time.sleep(0.25) + return self.popup() + return None + try: + popup = wait_for(open_menu, "Tray icon pointer click did not open menu after Explorer became ready", 25) + except AssertionError: + self.log.write(f"Taskbar controls: {observed!r}\n") + raise + menu = user.SendMessageW(popup, 0x1E1, 0, 0) + def item(): + for index in range(user.GetMenuItemCount(menu)): + text = c.create_unicode_buffer(256) + user.GetMenuStringW(menu, index, text, 256, 0x400) + state = user.GetMenuState(menu, index, 0x400) + if (text.value.replace("&", "") == label and not state & 3 + and (checked is None or bool(state & 8) == checked)): + self.log.write(f"Native menu click: {label!r}, checked={bool(state & 8)}\n") + rect = w.RECT() + assert user.GetMenuItemRect(None, menu, index, c.byref(rect)) + return rect + return None + rect = wait_for(item, f"Enabled menu item missing: {label}") + self.snapshot("menu") + pointer(rect) + wait_for(lambda: not self.popup(), "Menu remained open after pointer click") + + def dialog(self, title): + return next(iter(windows(self.pid, "#32770", title, True)), None) + + def answer(self, title, allow): + hwnd = wait_for(lambda: self.dialog(title), "Native dialog missing") + expected = {"ok", "确定"} if allow is None else {"yes", "是"} if allow else {"no", "否"} + observed = [] + def button(): + controls = Desktop(backend="uia").window(handle=hwnd).descendants(control_type="Button") + observed[:] = [(item.window_text(), item.element_info.automation_id) for item in controls] + for item in controls: + name = item.window_text().replace("&", "").split("(")[0].strip().lower() + if name in expected and item.is_visible() and item.is_enabled(): + return item + return None + try: + control = wait_for(button, "Native dialog button missing") + except AssertionError: + self.log.write(f"Dialog buttons: {observed!r}\n") + raise + # MessageBox return values are not a portable way to locate its child + # controls. Use UIA bounds, then exercise the actual pointer input path. + pointer(control.rectangle()) + + def accept_default(self, title): + hwnd = wait_for(lambda: self.dialog(title), "Native dialog missing") + user.SetForegroundWindow(hwnd) + user.keybd_event(0x0D, 0, 0, 0) + user.keybd_event(0x0D, 0, 2, 0) + + def app_windows(self): + return windows(title="Removent", visible=True, large=True) + + def app_window(self): + return next(iter(self.app_windows()), None) + + def app_count(self): + return len(self.app_windows()) + + def app_rect(self, hwnd): + rect = w.RECT() + assert user.GetWindowRect(hwnd, c.byref(rect)) + return rect.left, rect.top, rect.right, rect.bottom + + def minimize(self, hwnd): + user.ShowWindow(hwnd, 6) + wait_for(lambda: user.IsIconic(hwnd), "Desktop did not minimize") + + def app_active(self, hwnd): + return not user.IsIconic(hwnd) and user.GetForegroundWindow() == hwnd + + def close_app(self, hwnd): + user.ShowWindow(hwnd, 9) + user.SetForegroundWindow(hwnd) + user.keybd_event(0x12, 0, 0, 0) + user.keybd_event(0x73, 0, 0, 0) + user.keybd_event(0x73, 0, 2, 0) + user.keybd_event(0x12, 0, 2, 0) + + def restart_shell(self): + subprocess.run(["taskkill", "/IM", "explorer.exe", "/F"], check=True, stdout=self.log, stderr=self.log) + subprocess.Popen([os.path.join(os.environ["WINDIR"], "explorer.exe")], stdout=self.log, stderr=self.log) + wait_for(lambda: bool(windows(class_name="Shell_TrayWnd")), "Explorer did not restart", 25) + time.sleep(1) + + def snapshot(self, name): + ImageGrab.grab().save(self.args.evidence_dir / f"{name}.png") diff --git a/scripts/qa/tray_video_stimulus.py b/scripts/qa/tray_video_stimulus.py new file mode 100644 index 0000000..17e0bee --- /dev/null +++ b/scripts/qa/tray_video_stimulus.py @@ -0,0 +1,19 @@ +"""Independent native window that makes a live remote desktop visibly change.""" +import tkinter as tk + +root = tk.Tk() +root.title("Tray video acceptance stimulus") +root.overrideredirect(True) +root.attributes("-topmost", True) +root.geometry(f"200x80+20+{root.winfo_screenheight() - 100}") +label = tk.Label(root, text="", font=("Arial", 18)) +label.pack(fill="both", expand=True) + + +def animate(frame=0): + label.configure(text=f"Video {frame}", bg="#20a060" if frame % 2 else "#a04060", fg="white") + root.after(100, animate, frame + 1) + + +animate() +root.mainloop() diff --git a/scripts/qa/windows_account.ps1 b/scripts/qa/windows_account.ps1 new file mode 100644 index 0000000..de62894 --- /dev/null +++ b/scripts/qa/windows_account.ps1 @@ -0,0 +1,59 @@ +# Run only on an ephemeral Windows CI runner with local administrator rights. +$ErrorActionPreference = 'Stop' +if ($env:GITHUB_ACTIONS -ne 'true') { throw 'Requires an ephemeral GitHub Actions runner' } +$artifacts = cargo test --locked -p removent-proto -p removent-core -p removent-input -p removent-client -p removent-host -p removent-media-codec --lib --no-run --message-format=json +if ($LASTEXITCODE -ne 0) { throw 'Account test build failed' } +$binary = $artifacts | ForEach-Object { $_ | ConvertFrom-Json } | + Where-Object { $_.reason -eq 'compiler-artifact' -and $_.profile.test -and $_.executable -and $_.target.name -eq 'removent_host' } | + Select-Object -Last 1 -ExpandProperty executable +if (-not $binary) { throw 'Account test executable missing' } +$username = 'rmv' + [Guid]::NewGuid().ToString('N').Substring(0, 12) +$password = [Guid]::NewGuid().ToString('N') + 'aA1!' +$secure = ConvertTo-SecureString $password -AsPlainText -Force +$created = $false +$child = $null +$accountTemp = Join-Path $env:PUBLIC "removent-account-$username" +$tempCreated = $false +$previousTemp = $env:TEMP +$previousTmp = $env:TMP +$evidence = Join-Path (Get-Location) 'target/qa-evidence' +New-Item -ItemType Directory -Force $evidence | Out-Null +try { + Start-Service seclogon + New-LocalUser -Name $username -Password $secure -Description 'Ephemeral Removent authentication test' | Out-Null + $created = $true + $users = Get-LocalGroup -SID 'S-1-5-32-545' + Add-LocalGroupMember -Group $users -Member $username + # Start-Process inherits the runner's private TEMP, which the test user cannot + # access. Give the QUIC identity fixture its own directory and explicit ACL. + New-Item -ItemType Directory $accountTemp | Out-Null + $tempCreated = $true + $runnerSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $testSid = (Get-LocalUser -Name $username).SID.Value + icacls $accountTemp /inheritance:r /grant "*${runnerSid}:(OI)(CI)F" "*${testSid}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Cannot protect account test directory' } + $env:TEMP = $accountTemp + $env:TMP = $accountTemp + $env:REMOVENT_AUTH_TEST_USERNAME = $username + $env:REMOVENT_AUTH_TEST_PASSWORD = $password + $env:REMOVENT_AUTH_EXPECT_REJECT = '1' + & $binary native_desktop_account_authentication --ignored --nocapture + if ($LASTEXITCODE -ne 0) { throw 'A different account was accepted as the desktop owner' } + Remove-Item Env:REMOVENT_AUTH_EXPECT_REJECT + $credential = [PSCredential]::new("$env:COMPUTERNAME\$username", $secure) + $child = Start-Process -FilePath $binary -ArgumentList 'native_desktop_account_authentication --ignored --nocapture' -Credential $credential -PassThru -WorkingDirectory (Get-Location).Path -RedirectStandardOutput "$evidence/account.log" -RedirectStandardError "$evidence/account-errors.log" + if (-not $child.WaitForExit(30000)) { throw 'Native account test timed out' } + Get-Content "$evidence/account.log" + Get-Content "$evidence/account-errors.log" + if ($child.ExitCode -ne 0) { throw 'Native account authentication failed' } + Write-Output 'PASS: Windows account/QUIC password, invalid password and desktop-owner SID checks' +} finally { + $env:TEMP = $previousTemp + $env:TMP = $previousTmp + if ($child -and -not $child.HasExited) { Stop-Process -Id $child.Id -Force } + foreach ($name in @('REMOVENT_AUTH_TEST_USERNAME', 'REMOVENT_AUTH_TEST_PASSWORD', 'REMOVENT_AUTH_EXPECT_REJECT')) { + Remove-Item "Env:$name" -ErrorAction SilentlyContinue + } + if ($created) { Remove-LocalUser -Name $username } + if ($tempCreated) { Remove-Item -Recurse -Force $accountTemp } +} diff --git a/scripts/qa/windows_tray.py b/scripts/qa/windows_tray.py new file mode 100644 index 0000000..4458e7e --- /dev/null +++ b/scripts/qa/windows_tray.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Run the native windows tray lifecycle and remote-session acceptance.""" +from tray_lifecycle import run +from tray_ui_windows import WindowsDesktop + +if __name__ == "__main__": + run(WindowsDesktop) diff --git a/vendor/gpui-wgpu/Cargo.toml b/vendor/gpui-wgpu/Cargo.toml new file mode 100644 index 0000000..e83db3a --- /dev/null +++ b/vendor/gpui-wgpu/Cargo.toml @@ -0,0 +1,175 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +name = "gpui-pre-wgpu" +version = "0.3.8" +build = false +publish = true +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Zed's `gpui_wgpu` crate (gpui-pre snapshot of zed@279fe07)" +readme = false +license = "Apache-2.0" +repository = "https://github.com/zed-industries/zed" +resolver = "2" + +[package.metadata.gpui-pre] +zed-crate = "gpui_wgpu" +zed-version = "0.1.0" +zed-rev = "279fe070bb389b79652e52065b2f001edcc0b11b" + +[features] +bench-support = [ + "gpui/bench-support", + "dep:image", +] +default = [] +font-kit = ["dep:font-kit"] +test-support = [ + "gpui/test-support", + "dep:image", +] + +[lib] +name = "gpui_wgpu" +path = "src/gpui_wgpu.rs" +doctest = false + +[[bench]] +name = "layout_line" +path = "benches/layout_line.rs" +harness = false + +[dependencies.anyhow] +version = "1.0.86" + +[dependencies.bytemuck] +version = "1" + +[dependencies.collections] +version = "=0.3.8" +package = "gpui-pre-collections" + +[dependencies.cosmic-text] +version = "0.19.0" + +[dependencies.etagere] +version = "0.2" + +[dependencies.font-kit] +version = "0.14.1-zed" +optional = true +package = "zed-font-kit" + +[dependencies.gpui] +version = "=0.3.8" +default-features = false +package = "gpui-pre" + +[dependencies.gpui_util] +version = "=0.3.8" +package = "gpui-pre-util" + +[dependencies.image] +version = "0.25.1" +features = [ + "bmp", + "dds", + "exr", + "ff", + "gif", + "hdr", + "ico", + "jpeg", + "png", + "pnm", + "qoi", + "rayon", + "tga", + "tiff", + "webp", +] +optional = true +default-features = false + +[dependencies.itertools] +version = "0.14.0" + +[dependencies.log] +version = "0.4.16" +features = [ + "kv_unstable_serde", + "serde", +] + +[dependencies.parking_lot] +version = "0.12.1" + +[dependencies.profiling] +version = "1" + +[dependencies.raw-window-handle] +version = "0.6" + +[dependencies.smallvec] +version = "1.6" +features = [ + "union", + "const_new", +] + +[dependencies.swash] +version = "0.2.6" + +[dependencies.unicode-bidi] +version = "0.3.18" +features = ["hardcoded-data"] +default-features = false + +[dependencies.unicode-segmentation] +version = "1.10" + +[dependencies.wgpu] +version = "29.0.4" + +[target.'cfg(target_family = "wasm")'.dependencies.web-sys] +version = "0.3" +features = ["HtmlCanvasElement"] + +[target.'cfg(target_family = "wasm")'.dependencies.wgpu] +version = "29.0.4" +features = ["webgl"] + +[lints.clippy] +dbg_macro = "deny" +declare_interior_mutable_const = "deny" +disallowed_methods = "deny" +large_enum_variant = "allow" +let_underscore_future = "allow" +nonminimal_bool = "allow" +redundant_clone = "deny" +single_range_in_vec_init = "allow" +todo = "deny" +too_many_arguments = "allow" +type_complexity = "allow" + +[lints.clippy.style] +level = "allow" +priority = -1 + +[lints.rust.unexpected_cfgs] +level = "allow" +priority = 0 diff --git a/vendor/gpui-wgpu/LICENSE-APACHE b/vendor/gpui-wgpu/LICENSE-APACHE new file mode 100644 index 0000000..461a0fe --- /dev/null +++ b/vendor/gpui-wgpu/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + + http://www.apache.org/licenses/LICENSE-2.0 + + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + + 1. Definitions. + + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + + END OF TERMS AND CONDITIONS diff --git a/vendor/gpui-wgpu/REMOVENT-PATCH.md b/vendor/gpui-wgpu/REMOVENT-PATCH.md new file mode 100644 index 0000000..523896b --- /dev/null +++ b/vendor/gpui-wgpu/REMOVENT-PATCH.md @@ -0,0 +1,11 @@ +# Local presentation fix + +Based on crates.io gpui-pre-wgpu 0.3.8 (Apache-2.0). + +Only the adapter sort order is changed: CPU devices on Linux prefer OpenGL. +Discrete/integrated/virtual GPUs and explicit device priorities retain upstream +ordering. In the Debian 12 arm64 Xvfb fixture, Mesa 22/LLVM 15 Vulkan accepted +surface creation and frame submission but presented a black content area. +The same scene and renderer produced the complete interface through OpenGL. +`scripts/qa/portable_app.py` requires varied pixels inside the content area and +exports a screenshot so a native window frame cannot satisfy the check alone. diff --git a/vendor/gpui-wgpu/benches/layout_line.rs b/vendor/gpui-wgpu/benches/layout_line.rs new file mode 100644 index 0000000..6d66a7a --- /dev/null +++ b/vendor/gpui-wgpu/benches/layout_line.rs @@ -0,0 +1,104 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use gpui::{FontFallbacks, FontRun, PlatformTextSystem, font, px}; +use gpui_wgpu::CosmicTextSystem; +use std::borrow::Cow; + +const LILEX: &[u8] = include_bytes!("../../../assets/fonts/lilex/Lilex-Regular.ttf"); +const IBM_PLEX: &[u8] = + include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf"); + +// ~4 000 chars of typical ASCII code text, as a single display line. +// +// `layout_line` is handed one line at a time, already split on `\n` by its +// callers, so the newlines are replaced rather than kept: leaving them in would +// make this measure the multi-paragraph path instead of the common one, since +// `\n` is itself a bidi paragraph separator. +fn code_text() -> String { + concat!( + " fn compute_run_spans(\n", + " text: &str,\n", + " run_offset: usize,\n", + " run_len: usize,\n", + " primary: FontId,\n", + " fallback_chain: &[(FontId, SharedString)],\n", + " covers: &impl Fn(FontId, char) -> bool,\n", + " ) -> SmallVec<[RunSpan; 4]> {\n", + " let mut spans = SmallVec::new();\n", + " let run_end = run_offset + run_len;\n", + " if run_end <= run_offset { return spans; }\n", + " let run_text = &text[run_offset..run_end];\n", + " let mut span_start = run_offset;\n", + " let mut span_slot: Option = None;\n", + " for (ch_idx, ch) in run_text.char_indices() {\n", + " let abs = run_offset + ch_idx;\n", + " let next = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers);\n", + " if next == span_slot { continue; }\n", + " if abs > span_start {\n", + " spans.push(RunSpan { start: span_start, end: abs, slot: span_slot });\n", + " }\n", + " span_start = abs;\n", + " span_slot = next;\n", + " }\n", + " spans\n", + " }\n", + ) + .repeat(8) // ~3 800 chars + .replace('\n', " ") +} + +fn bench_layout_line(c: &mut Criterion) { + let system = CosmicTextSystem::new_without_system_fonts("Lilex"); + system + .add_fonts(vec![Cow::Borrowed(LILEX), Cow::Borrowed(IBM_PLEX)]) + .unwrap(); + + let font_id_no_fallback = system.font_id(&font("Lilex")).unwrap(); + + let font_id_with_fallback = { + let mut f = font("Lilex"); + f.fallbacks = Some(FontFallbacks::from_fonts(vec!["IBM Plex Sans".to_string()])); + system.font_id(&f).unwrap() + }; + + let text = code_text(); + + // Same text, but with a bidi paragraph separator (U+001C) and RTL content + // forcing the per-paragraph shaping path. + let text_mixed_direction = text.clone() + "\u{001c}\u{05d0}\u{05d1}"; + assert!( + !text.contains('\n'), + "fast-path corpus must contain no separator" + ); + + let runs_no_fallback = vec![FontRun { + len: text.len(), + font_id: font_id_no_fallback, + }]; + let runs_with_fallback = vec![FontRun { + len: text.len(), + font_id: font_id_with_fallback, + }]; + let runs_mixed_direction = vec![FontRun { + len: text_mixed_direction.len(), + font_id: font_id_no_fallback, + }]; + + let mut group = c.benchmark_group("layout_line"); + + group.bench_function("no_fallback", |b| { + b.iter(|| system.layout_line(&text, px(14.0), &runs_no_fallback)) + }); + + group.bench_function("with_fallback_ascii", |b| { + b.iter(|| system.layout_line(&text, px(14.0), &runs_with_fallback)) + }); + + group.bench_function("mixed_direction_paragraphs", |b| { + b.iter(|| system.layout_line(&text_mixed_direction, px(14.0), &runs_mixed_direction)) + }); + + group.finish(); +} + +criterion_group!(benches, bench_layout_line); +criterion_main!(benches); diff --git a/vendor/gpui-wgpu/src/cosmic_text_system.rs b/vendor/gpui-wgpu/src/cosmic_text_system.rs new file mode 100644 index 0000000..0e4e3b1 --- /dev/null +++ b/vendor/gpui-wgpu/src/cosmic_text_system.rs @@ -0,0 +1,1798 @@ +use anyhow::{Context as _, Ok, Result}; +use collections::HashMap; +use cosmic_text::{ + Attrs, AttrsList, Ellipsize, Family, Font as CosmicTextFont, + FontFeatures as CosmicFontFeatures, FontSystem, ShapeBuffer, ShapeLine, Stretch, Style, Weight, +}; +use gpui::{ + Bounds, DevicePixels, FallbackFontClass, Font, FontFallbacks, FontFeatures, FontId, + FontMetrics, FontRun, GlyphId, IsZero as _, LineLayout, MissingGlyph, MissingGlyphSink, Pixels, + PlatformTextSystem, RenderGlyphParams, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ShapedGlyph, + ShapedRun, SharedString, Size, TextRenderingMode, point, size, +}; + +use itertools::Itertools; +use parking_lot::RwLock; +use smallvec::SmallVec; +use std::{borrow::Cow, ops::Range, sync::Arc}; +use swash::{ + scale::{Render, ScaleContext, Source, StrikeWith}, + zeno::{Format, Vector}, +}; +use unicode_segmentation::UnicodeSegmentation; + +pub struct CosmicTextSystem(RwLock); + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct FontKey { + family: SharedString, + features: FontFeatures, + fallbacks: Option, +} + +impl FontKey { + fn new(family: SharedString, features: FontFeatures, fallbacks: Option) -> Self { + Self { + family, + features, + fallbacks, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct LoadedFontKey { + database_id: cosmic_text::fontdb::ID, + font: FontKey, +} + +struct CosmicTextSystemState { + font_system: FontSystem, + scratch: ShapeBuffer, + swash_scale_context: ScaleContext, + pending_glyph_images: HashMap, + /// Contains all already loaded fonts, including all faces. Indexed by `FontId`. + loaded_fonts: Vec, + loaded_font_ids_by_key: HashMap, + /// Caches the `FontId`s associated with a specific family to avoid iterating the font database + /// for every font face in a family. + font_ids_by_family_cache: HashMap>, + system_font_fallback: String, + missing_glyph_sink: Option>, +} + +struct LoadedFont { + font: Arc, + features: CosmicFontFeatures, + is_known_emoji_font: bool, + /// resolved at load time so `layout_line` shares one chain across faces. + /// `Arc` keeps clone cheap on the per-run hot path. + user_fallback_chain: Arc<[(FontId, SharedString)]>, +} + +struct FontMatchProperties { + primary_family_name: SharedString, + stretch: Stretch, + style: Style, + weight: Weight, + features: CosmicFontFeatures, + fallback_chain: Arc<[(FontId, SharedString)]>, +} + +impl FontMatchProperties { + fn attributes<'a>(&'a self, font_id: FontId, family_name: &'a str) -> Attrs<'a> { + Attrs::new() + .metadata(font_id.0) + .family(Family::Name(family_name)) + .stretch(self.stretch) + .style(self.style) + .weight(self.weight) + .font_features(self.features.clone()) + } +} + +impl CosmicTextSystem { + /// Returns the selected face's weight and style, which may differ from the request. + pub fn font_weight_and_style( + &self, + font_id: FontId, + ) -> Result<(gpui::FontWeight, gpui::FontStyle)> { + let state = self.0.read(); + let font = state + .loaded_fonts + .get(font_id.0) + .context("invalid font ID")?; + let face = state + .font_system + .db() + .face(font.font.id()) + .context("font face not found")?; + let style = match face.style { + cosmic_text::Style::Normal => gpui::FontStyle::Normal, + cosmic_text::Style::Italic => gpui::FontStyle::Italic, + cosmic_text::Style::Oblique => gpui::FontStyle::Oblique, + }; + Ok((gpui::FontWeight(face.weight.0 as f32), style)) + } + + /// Builds reports for unresolved source indices after an outer text system + /// has applied its own fallback. + pub fn missing_glyphs( + &self, + text: &str, + font_runs: &[FontRun], + missing_text_indices: impl IntoIterator, + ) -> Vec { + self.0 + .read() + .missing_glyphs(text, font_runs, missing_text_indices) + } + + pub fn new(system_font_fallback: &str) -> Self { + let font_system = FontSystem::new(); + + Self(RwLock::new(CosmicTextSystemState { + font_system, + scratch: ShapeBuffer::default(), + swash_scale_context: ScaleContext::new(), + pending_glyph_images: HashMap::default(), + loaded_fonts: Vec::new(), + loaded_font_ids_by_key: HashMap::default(), + font_ids_by_family_cache: HashMap::default(), + system_font_fallback: system_font_fallback.to_string(), + missing_glyph_sink: None, + })) + } + + pub fn new_without_system_fonts(system_font_fallback: &str) -> Self { + let font_system = FontSystem::new_with_locale_and_db( + "en-US".to_string(), + cosmic_text::fontdb::Database::new(), + ); + + Self(RwLock::new(CosmicTextSystemState { + font_system, + scratch: ShapeBuffer::default(), + swash_scale_context: ScaleContext::new(), + pending_glyph_images: HashMap::default(), + loaded_fonts: Vec::new(), + loaded_font_ids_by_key: HashMap::default(), + font_ids_by_family_cache: HashMap::default(), + system_font_fallback: system_font_fallback.to_string(), + missing_glyph_sink: None, + })) + } +} + +impl PlatformTextSystem for CosmicTextSystem { + fn add_fonts(&self, fonts: Vec>) -> Result<()> { + self.0.write().add_fonts(fonts) + } + + fn set_missing_glyph_sink(&self, sink: Option>) { + self.0.write().missing_glyph_sink = sink; + } + + fn all_font_names(&self) -> Vec { + let mut result = self + .0 + .read() + .font_system + .db() + .faces() + .filter_map(|face| face.families.first().map(|family| family.0.clone())) + .collect_vec(); + result.sort_unstable(); + result.dedup(); + result + } + + fn font_id(&self, font: &Font) -> Result { + let mut state = self.0.write(); + let key = FontKey::new( + font.family.clone(), + font.features.clone(), + font.fallbacks.clone(), + ); + let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&key) { + font_ids.as_slice() + } else { + let font_ids = + state.load_family(&font.family, &font.features, font.fallbacks.as_ref())?; + state.font_ids_by_family_cache.insert(key.clone(), font_ids); + state.font_ids_by_family_cache[&key].as_ref() + }; + + let ix = find_best_match(font, candidates, &state)?; + + Ok(candidates[ix]) + } + + fn prewarm_fonts(&self, font_ids: &[FontId]) { + self.0.write().prewarm_fonts(font_ids); + } + + fn font_metrics(&self, font_id: FontId) -> FontMetrics { + let metrics = self + .0 + .read() + .loaded_font(font_id) + .font + .as_swash() + .metrics(&[]); + + FontMetrics { + units_per_em: metrics.units_per_em as u32, + ascent: metrics.ascent, + descent: -metrics.descent, + line_gap: metrics.leading, + underline_position: metrics.underline_offset, + underline_thickness: metrics.stroke_size, + cap_height: metrics.cap_height, + x_height: metrics.x_height, + bounding_box: Bounds { + origin: point(0.0, 0.0), + size: size(metrics.max_width, metrics.ascent + metrics.descent), + }, + } + } + + fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result> { + let lock = self.0.read(); + let glyph_metrics = lock.loaded_font(font_id).font.as_swash().glyph_metrics(&[]); + let glyph_id = glyph_id.0 as u16; + Ok(Bounds { + origin: point(0.0, 0.0), + size: size( + glyph_metrics.advance_width(glyph_id), + glyph_metrics.advance_height(glyph_id), + ), + }) + } + + fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result> { + self.0.read().advance(font_id, glyph_id) + } + + fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option { + self.0.read().glyph_for_char(font_id, ch) + } + + fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result> { + self.0.write().raster_bounds(params) + } + + fn rasterize_glyph( + &self, + params: &RenderGlyphParams, + raster_bounds: Bounds, + ) -> Result<(Size, Vec)> { + self.0.write().rasterize_glyph(params, raster_bounds) + } + + fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { + self.0.write().layout_line(text, font_size, runs) + } + + fn recommended_rendering_mode( + &self, + _font_id: FontId, + _font_size: Pixels, + ) -> TextRenderingMode { + TextRenderingMode::Subpixel + } +} + +impl CosmicTextSystemState { + fn loaded_font(&self, font_id: FontId) -> &LoadedFont { + &self.loaded_fonts[font_id.0] + } + + fn font_match_properties(&self, font_id: FontId) -> Option { + let loaded_font = self.loaded_font(font_id); + let Some(face) = self.font_system.db().face(loaded_font.font.id()) else { + log::warn!("font face not found in database for font_id {:?}", font_id); + return None; + }; + let Some(first_family) = face.families.first() else { + log::warn!("font face has no family names for font_id {:?}", font_id); + return None; + }; + + Some(FontMatchProperties { + primary_family_name: first_family.0.clone().into(), + stretch: face.stretch, + style: face.style, + weight: face.weight, + features: loaded_font.features.clone(), + fallback_chain: Arc::clone(&loaded_font.user_fallback_chain), + }) + } + + fn prewarm_fonts(&mut self, font_ids: &[FontId]) { + for &font_id in font_ids { + let Some(properties) = self.font_match_properties(font_id) else { + continue; + }; + let primary_attributes = + properties.attributes(font_id, &properties.primary_family_name); + self.font_system.get_font_matches(&primary_attributes); + + for (fallback_id, fallback_name) in &*properties.fallback_chain { + let fallback_attributes = properties.attributes(*fallback_id, fallback_name); + self.font_system.get_font_matches(&fallback_attributes); + } + } + } + + #[profiling::function] + fn add_fonts(&mut self, fonts: Vec>) -> Result<()> { + self.font_ids_by_family_cache.clear(); + let db = self.font_system.db_mut(); + for bytes in fonts { + db.load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(bytes))); + } + Ok(()) + } + + #[profiling::function] + fn load_family( + &mut self, + name: &str, + features: &FontFeatures, + fallbacks: Option<&FontFallbacks>, + ) -> Result> { + let loaded_font_key = FontKey::new( + SharedString::from(name.to_owned()), + features.clone(), + fallbacks.cloned(), + ); + + // recurse with `fallbacks = None` so a fallback family cannot pull in + // another chain. missing fallback families are dropped so a typo in + // settings still lets the primary family load. + let user_fallback_chain: Arc<[(FontId, SharedString)]> = match fallbacks { + Some(fallbacks) if !fallbacks.fallback_list().is_empty() => { + let mut chain: Vec<(FontId, SharedString)> = Vec::new(); + for fallback_name in fallbacks.fallback_list() { + let fb_key = FontKey::new( + SharedString::from(fallback_name.clone()), + features.clone(), + None, + ); + let fb_ids = if let Some(cached) = self.font_ids_by_family_cache.get(&fb_key) { + cached.clone() + } else { + let loaded = self.load_family(fallback_name, features, None)?; + self.font_ids_by_family_cache + .insert(fb_key.clone(), loaded.clone()); + loaded + }; + let Some(&fb_id) = fb_ids.first() else { + continue; + }; + let db_id = self.loaded_fonts[fb_id.0].font.id(); + if let Some(face) = self.font_system.db().face(db_id) + && let Some(family) = face.families.first() + { + chain.push((fb_id, SharedString::from(family.0.clone()))); + } + } + Arc::from(chain) + } + _ => Arc::from(Vec::new()), + }; + + let name = gpui::font_name_with_fallbacks(name, &self.system_font_fallback); + + let families = self + .font_system + .db() + .faces() + .filter(|face| face.families.iter().any(|family| *name == family.0)) + .map(|face| (face.id, face.post_script_name.clone())) + .collect::>(); + + let cosmic_features = cosmic_font_features(features)?; + + let mut loaded_font_ids = SmallVec::new(); + for (database_id, postscript_name) in families { + let key = LoadedFontKey { + database_id, + font: loaded_font_key.clone(), + }; + if let Some(&font_id) = self.loaded_font_ids_by_key.get(&key) { + self.loaded_fonts[font_id.0].user_fallback_chain = Arc::clone(&user_fallback_chain); + loaded_font_ids.push(font_id); + continue; + } + + let font = self + .font_system + .get_font(database_id, cosmic_text::Weight::NORMAL) + .context("Could not load font")?; + + // HACK: To let the storybook run and render Windows caption icons. We should actually do better font fallback. + let allowed_bad_font_names = [ + "SegoeFluentIcons", // NOTE: Segoe fluent icons postscript name is inconsistent + "Segoe Fluent Icons", + ]; + + if font.as_swash().charmap().map('m') == 0 + && !allowed_bad_font_names.contains(&postscript_name.as_str()) + { + self.font_system.db_mut().remove_face(font.id()); + continue; + }; + + let font_id = FontId(self.loaded_fonts.len()); + loaded_font_ids.push(font_id); + self.loaded_fonts.push(LoadedFont { + font, + features: cosmic_features.clone(), + is_known_emoji_font: check_is_known_emoji_font(&postscript_name), + user_fallback_chain: Arc::clone(&user_fallback_chain), + }); + self.loaded_font_ids_by_key.insert(key, font_id); + } + + Ok(loaded_font_ids) + } + + fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result> { + let glyph_metrics = self.loaded_font(font_id).font.as_swash().glyph_metrics(&[]); + Ok(Size { + width: glyph_metrics.advance_width(glyph_id.0 as u16), + height: glyph_metrics.advance_height(glyph_id.0 as u16), + }) + } + + fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option { + let glyph_id = self.loaded_font(font_id).font.as_swash().charmap().map(ch); + if glyph_id == 0 { + None + } else { + Some(GlyphId(glyph_id.into())) + } + } + + fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result> { + let image = self.render_glyph_image(params)?; + let bounds = Bounds { + origin: point(image.placement.left.into(), (-image.placement.top).into()), + size: size(image.placement.width.into(), image.placement.height.into()), + }; + if !bounds.is_zero() { + self.pending_glyph_images.insert(params.clone(), image); + } + Ok(bounds) + } + + #[profiling::function] + fn rasterize_glyph( + &mut self, + params: &RenderGlyphParams, + glyph_bounds: Bounds, + ) -> Result<(Size, Vec)> { + if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 { + anyhow::bail!("glyph bounds are empty"); + } + + let mut image = match self.pending_glyph_images.remove(params) { + Some(image) => image, + None => self.render_glyph_image(params)?, + }; + let bitmap_size = glyph_bounds.size; + match image.content { + swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => { + // Convert from RGBA to BGRA. + for pixel in image.data.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + Ok((bitmap_size, image.data)) + } + swash::scale::image::Content::Mask => { + if params.subpixel_rendering { + // We must always return RGBA data when subpixel rendering is requested. + let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect(); + Ok((bitmap_size, expanded)) + } else { + Ok((bitmap_size, image.data)) + } + } + } + } + + fn render_glyph_image( + &mut self, + params: &RenderGlyphParams, + ) -> Result { + let loaded_font = &self.loaded_fonts[params.font_id.0]; + let font_ref = loaded_font.font.as_swash(); + let pixel_size = f32::from(params.font_size); + + let subpixel_offset = Vector::new( + params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor, + params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor, + ); + + let mut scaler = self + .swash_scale_context + .builder(font_ref) + .size(pixel_size * params.scale_factor) + .hint(true) + .build(); + + let sources: &[Source] = if params.is_emoji { + &[ + Source::ColorOutline(0), + Source::ColorBitmap(StrikeWith::BestFit), + Source::Outline, + ] + } else { + &[Source::Bitmap(StrikeWith::ExactSize), Source::Outline] + }; + + let mut renderer = Render::new(sources); + if params.subpixel_rendering { + // There seems to be a bug in Swash where the B and R values are swapped. + renderer + .format(Format::subpixel_bgra()) + .offset(subpixel_offset); + } else { + renderer.format(Format::Alpha).offset(subpixel_offset); + } + + let glyph_id: u16 = params.glyph_id.0.try_into()?; + renderer + .render(&mut scaler, glyph_id) + .with_context(|| format!("unable to render glyph via swash for {params:?}")) + } + + /// This is used when cosmic_text has chosen a fallback font instead of using the requested + /// font, typically to handle some unicode characters. When this happens, `loaded_fonts` may not + /// yet have an entry for this fallback font, and so one is added. + /// + /// Note that callers shouldn't use this `FontId` somewhere that will retrieve the corresponding + /// `LoadedFont.features`, as it will have an arbitrarily chosen or empty value. The only + /// current use of this field is for the *input* of `layout_line`, and so it's fine to use + /// `font_id_for_cosmic_id` when computing the *output* of `layout_line`. + fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> Result { + if let Some(ix) = self + .loaded_fonts + .iter() + .position(|loaded_font| loaded_font.font.id() == id) + { + Ok(FontId(ix)) + } else { + let font = self + .font_system + .get_font(id, cosmic_text::Weight::NORMAL) + .context("failed to get fallback font from cosmic-text font system")?; + let face = self + .font_system + .db() + .face(id) + .context("fallback font face not found in cosmic-text database")?; + + let font_id = FontId(self.loaded_fonts.len()); + self.loaded_fonts.push(LoadedFont { + font, + features: CosmicFontFeatures::new(), + is_known_emoji_font: check_is_known_emoji_font(&face.post_script_name), + user_fallback_chain: Arc::from(Vec::new()), + }); + + Ok(font_id) + } + } + + #[profiling::function] + fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout { + if contains_paragraph_separator(text) { + self.layout_line_with_separators(text, font_size, font_runs) + } else { + self.layout_line_no_separators(text, font_size, font_runs) + } + } + + fn layout_line_with_separators( + &mut self, + text: &str, + font_size: Pixels, + font_runs: &[FontRun], + ) -> LineLayout { + let mut layout = LineLayout { + font_size, + len: text.len(), + ..Default::default() + }; + let mut paragraph_start = 0; + + for (separator_start, separator) in text + .char_indices() + .filter(|(_, character)| is_paragraph_separator(*character)) + { + let separator_end = separator_start + separator.len_utf8(); + self.shape_segment( + text, + paragraph_start..separator_start, + font_size, + font_runs, + &mut layout, + ); + self.shape_segment( + text, + separator_start..separator_end, + font_size, + font_runs, + &mut layout, + ); + paragraph_start = separator_end; + } + + self.shape_segment( + text, + paragraph_start..text.len(), + font_size, + font_runs, + &mut layout, + ); + + layout + } + + fn shape_segment( + &mut self, + text: &str, + range: Range, + font_size: Pixels, + font_runs: &[FontRun], + layout: &mut LineLayout, + ) { + if range.is_empty() { + return; + } + + let segment_font_runs = clip_font_runs(font_runs, range.clone()); + let segment = + self.layout_line_no_separators(&text[range.clone()], font_size, &segment_font_runs); + + let mut segment_runs = segment.runs; + for run in &mut segment_runs { + for glyph in &mut run.glyphs { + glyph.index += range.start; + glyph.position.x += layout.width; + } + } + + for mut run in segment_runs { + if let Some(same_run) = layout + .runs + .last_mut() + .filter(|last| last.font_id == run.font_id) + { + same_run.glyphs.append(&mut run.glyphs); + } else { + layout.runs.push(run); + } + } + + layout.width += segment.width; + layout.ascent = layout.ascent.max(segment.ascent); + layout.descent = layout.descent.max(segment.descent); + } + + fn layout_line_no_separators( + &mut self, + text: &str, + font_size: Pixels, + font_runs: &[FontRun], + ) -> LineLayout { + let mut attrs_list = AttrsList::new(&Attrs::new()); + let mut offs = 0; + for run in font_runs { + let run_end = offs + run.len; + + let Some(properties) = self.font_match_properties(run.font_id) else { + offs = run_end; + continue; + }; + + let primary_attrs = properties.attributes(run.font_id, &properties.primary_family_name); + let fallback_attrs: SmallVec<[Attrs<'_>; 4]> = properties + .fallback_chain + .iter() + .map(|(font_id, family_name)| properties.attributes(*font_id, family_name)) + .collect(); + + let spans = if properties.fallback_chain.is_empty() { + let mut spans = SmallVec::<[RunSpan; 4]>::new(); + spans.push(RunSpan { + start: offs, + end: run_end, + slot: None, + font_id: run.font_id, + }); + spans + } else { + let loaded_fonts = &self.loaded_fonts; + let covers = |id: FontId, ch: char| charmap_covers(loaded_fonts, id, ch); + compute_run_spans( + text, + offs, + run.len, + run.font_id, + &properties.fallback_chain, + &covers, + ) + }; + + for span in spans { + let attrs = match span.slot { + None => &primary_attrs, + Some(ix) => &fallback_attrs[ix], + }; + attrs_list.add_span(span.start..span.end, attrs); + } + offs = run_end; + } + + let line = ShapeLine::new( + &mut self.font_system, + text, + &attrs_list, + cosmic_text::Shaping::Advanced, + 4, + ); + let mut layout_lines = Vec::with_capacity(1); + line.layout_to_buffer( + &mut self.scratch, + f32::from(font_size), + None, // We do our own wrapping + cosmic_text::Wrap::None, + Ellipsize::None, + None, + &mut layout_lines, + None, + cosmic_text::Hinting::Disabled, + ); + + let Some(layout) = layout_lines.first() else { + return LineLayout { + font_size, + width: Pixels::ZERO, + ascent: Pixels::ZERO, + descent: Pixels::ZERO, + runs: Vec::new(), + len: text.len(), + }; + }; + + let missing_glyphs = self.missing_glyph_sink.as_ref().map(|_| { + self.missing_glyphs( + text, + font_runs, + layout + .glyphs + .iter() + .filter(|glyph| glyph.glyph_id == 0) + .map(|glyph| glyph.start), + ) + }); + + let mut runs: Vec = Vec::new(); + for glyph in &layout.glyphs { + let mut font_id = FontId(glyph.metadata); + let mut loaded_font = self.loaded_font(font_id); + if loaded_font.font.id() != glyph.font_id { + match self.font_id_for_cosmic_id(glyph.font_id) { + std::result::Result::Ok(resolved_id) => { + font_id = resolved_id; + loaded_font = self.loaded_font(font_id); + } + Err(error) => { + log::warn!( + "failed to resolve cosmic font id {:?}: {error:#}", + glyph.font_id + ); + continue; + } + } + } + let is_emoji = loaded_font.is_known_emoji_font; + + // HACK: Prevent crash caused by variation selectors. + if glyph.glyph_id == 3 && is_emoji { + continue; + } + + let shaped_glyph = ShapedGlyph { + id: GlyphId(glyph.glyph_id as u32), + position: point(glyph.x.into(), glyph.y.into()), + index: glyph.start, + is_emoji, + }; + + if let Some(last_run) = runs + .last_mut() + .filter(|last_run| last_run.font_id == font_id) + { + last_run.glyphs.push(shaped_glyph); + } else { + runs.push(ShapedRun { + font_id, + glyphs: vec![shaped_glyph], + }); + } + } + + if let Some((sink, missing_glyphs)) = self.missing_glyph_sink.as_ref().zip(missing_glyphs) { + sink.report(missing_glyphs); + } + + LineLayout { + font_size, + width: layout.w.into(), + ascent: layout.max_ascent.into(), + descent: layout.max_descent.into(), + runs, + len: text.len(), + } + } + + fn missing_glyphs( + &self, + text: &str, + font_runs: &[FontRun], + missing_text_indices: impl IntoIterator, + ) -> Vec { + let mut missing_text_indices = missing_text_indices.into_iter().peekable(); + if missing_text_indices.peek().is_none() { + return Vec::new(); + } + let mut missing_text_indices = missing_text_indices.collect::>(); + missing_text_indices.sort_unstable(); + missing_text_indices.dedup(); + + let mut font_run_index = 0; + let mut font_run_end = font_runs.first().map_or(0, |font_run| font_run.len); + let mut missing_glyphs = Vec::new(); + let mut missing_index = 0; + for (grapheme_start, grapheme) in text.grapheme_indices(true) { + let grapheme_end = grapheme_start + grapheme.len(); + while missing_text_indices + .get(missing_index) + .is_some_and(|text_index| *text_index < grapheme_start) + { + missing_index += 1; + } + let Some(&text_index) = missing_text_indices.get(missing_index) else { + break; + }; + if text_index >= grapheme_end { + continue; + } + + while font_run_end <= text_index && font_run_index + 1 < font_runs.len() { + font_run_index += 1; + let Some(font_run) = font_runs.get(font_run_index) else { + break; + }; + font_run_end += font_run.len; + } + let font_class = self.fallback_font_class( + font_runs + .get(font_run_index) + .or_else(|| font_runs.last()) + .map(|font_run| font_run.font_id), + ); + missing_glyphs.push(MissingGlyph::new(grapheme.into(), font_class)); + while missing_text_indices + .get(missing_index) + .is_some_and(|text_index| *text_index < grapheme_end) + { + missing_index += 1; + } + } + missing_glyphs + } + + fn fallback_font_class(&self, font_id: Option) -> FallbackFontClass { + let Some(font_id) = font_id else { + return FallbackFontClass::Proportional; + }; + let loaded_font = self.loaded_font(font_id); + let is_monospace = self + .font_system + .db() + .face(loaded_font.font.id()) + .is_some_and(|face| face.monospaced); + if is_monospace { + FallbackFontClass::Monospace + } else { + FallbackFontClass::Proportional + } + } +} + +#[inline(always)] +fn is_paragraph_separator(character: char) -> bool { + unicode_bidi::bidi_class(character) == unicode_bidi::BidiClass::B +} + +fn contains_paragraph_separator(text: &str) -> bool { + if text + .bytes() + .any(|byte| matches!(byte, b'\n' | b'\r' | 0x1c | 0x1d | 0x1e)) + { + return true; + } + + !text.is_ascii() && text.chars().any(is_paragraph_separator) +} + +fn clip_font_runs(font_runs: &[FontRun], range: Range) -> SmallVec<[FontRun; 4]> { + let mut clipped = SmallVec::new(); + let mut offs = 0; + for run in font_runs { + let run_start = offs; + offs += run.len; + if offs <= range.start { + continue; + } + if run_start >= range.end { + break; + } + let start = run_start.max(range.start); + let end = offs.min(range.end); + if start < end { + clipped.push(FontRun { + len: end - start, + font_id: run.font_id, + }); + } + } + clipped +} + +#[cfg(feature = "font-kit")] +fn find_best_match( + font: &Font, + candidates: &[FontId], + state: &CosmicTextSystemState, +) -> Result { + let candidate_properties = candidates + .iter() + .map(|font_id| { + let database_id = state.loaded_font(*font_id).font.id(); + let face_info = state + .font_system + .db() + .face(database_id) + .context("font face not found in database")?; + Ok(face_info_into_properties(face_info)) + }) + .collect::>>()?; + + let ix = + font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font)) + .context("requested font family contains no font matching the other parameters")?; + + Ok(ix) +} + +#[cfg(not(feature = "font-kit"))] +fn find_best_match( + font: &Font, + candidates: &[FontId], + state: &CosmicTextSystemState, +) -> Result { + if candidates.is_empty() { + anyhow::bail!("requested font family contains no font matching the other parameters"); + } + if candidates.len() == 1 { + return Ok(0); + } + + let target_weight = font.weight.0; + let target_italic = matches!( + font.style, + gpui::FontStyle::Italic | gpui::FontStyle::Oblique + ); + + let mut best_index = 0; + let mut best_score = u32::MAX; + + for (index, font_id) in candidates.iter().enumerate() { + let database_id = state.loaded_font(*font_id).font.id(); + let face_info = state + .font_system + .db() + .face(database_id) + .context("font face not found in database")?; + + let is_italic = matches!( + face_info.style, + cosmic_text::Style::Italic | cosmic_text::Style::Oblique + ); + let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 }; + let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs(); + let score = style_penalty + weight_diff; + + if score < best_score { + best_score = score; + best_index = index; + } + } + + Ok(best_index) +} + +/// one contiguous slice of a `FontRun` that maps to a single slot. `slot` is +/// `None` for the primary font and `Some(ix)` for `fallback_chain[ix]`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct RunSpan { + start: usize, + end: usize, + slot: Option, + font_id: FontId, +} + +/// walks `text[run_offset..run_offset + run_len]` and groups codepoints into +/// spans. inheriting codepoints stay in the current span so shaping clusters +/// like emoji zwj sequences and combining marks are not torn apart. +fn compute_run_spans( + text: &str, + run_offset: usize, + run_len: usize, + primary: FontId, + fallback_chain: &[(FontId, SharedString)], + covers: &impl Fn(FontId, char) -> bool, +) -> SmallVec<[RunSpan; 4]> { + let mut spans = SmallVec::new(); + let run_end = run_offset + run_len; + if run_end <= run_offset { + return spans; + } + if fallback_chain.is_empty() { + spans.push(RunSpan { + start: run_offset, + end: run_end, + slot: None, + font_id: primary, + }); + return spans; + } + let run_text = &text[run_offset..run_end]; + let mut span_start = run_offset; + let mut span_slot: Option = None; + let mut span_font_id = primary; + for (grapheme_idx, grapheme) in run_text.grapheme_indices(true) { + let abs = run_offset + grapheme_idx; + let ch = grapheme.chars().next().unwrap_or('\0'); + let next_slot = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers); + if next_slot == span_slot { + continue; + } + if abs > span_start { + spans.push(RunSpan { + start: span_start, + end: abs, + slot: span_slot, + font_id: span_font_id, + }); + } + span_start = abs; + span_slot = next_slot; + span_font_id = slot_font_id(next_slot, primary, fallback_chain); + } + if span_start < run_end { + spans.push(RunSpan { + start: span_start, + end: run_end, + slot: span_slot, + font_id: span_font_id, + }); + } + spans +} + +fn slot_font_id( + slot: Option, + primary: FontId, + fallback_chain: &[(FontId, SharedString)], +) -> FontId { + match slot { + None => primary, + Some(ix) => fallback_chain[ix].0, + } +} + +fn pick_covering_slot( + ch: char, + current: Option, + primary: FontId, + fallback_chain: &[(FontId, SharedString)], + covers: &impl Fn(FontId, char) -> bool, +) -> Option { + if (ch as u32) <= 0x7F { + return None; + } + if covers(primary, ch) { + return None; + } + let current_id = slot_font_id(current, primary, fallback_chain); + if covers(current_id, ch) { + return current; + } + + fallback_chain + .iter() + .position(|(fb_id, _)| covers(*fb_id, ch)) +} + +fn charmap_covers(loaded_fonts: &[LoadedFont], id: FontId, ch: char) -> bool { + loaded_fonts + .get(id.0) + .is_some_and(|loaded| loaded.font.as_swash().charmap().map(ch) != 0) +} + +fn cosmic_font_features(features: &FontFeatures) -> Result { + let mut result = CosmicFontFeatures::new(); + for feature in features.0.iter() { + let name_bytes: [u8; 4] = feature + .0 + .as_bytes() + .try_into() + .context("Incorrect feature flag format")?; + + let tag = cosmic_text::FeatureTag::new(&name_bytes); + + result.set(tag, feature.1); + } + Ok(result) +} + +#[cfg(feature = "font-kit")] +fn font_into_properties(font: &gpui::Font) -> font_kit::properties::Properties { + font_kit::properties::Properties { + style: match font.style { + gpui::FontStyle::Normal => font_kit::properties::Style::Normal, + gpui::FontStyle::Italic => font_kit::properties::Style::Italic, + gpui::FontStyle::Oblique => font_kit::properties::Style::Oblique, + }, + weight: font_kit::properties::Weight(font.weight.0), + stretch: Default::default(), + } +} + +#[cfg(feature = "font-kit")] +fn face_info_into_properties( + face_info: &cosmic_text::fontdb::FaceInfo, +) -> font_kit::properties::Properties { + font_kit::properties::Properties { + style: match face_info.style { + cosmic_text::Style::Normal => font_kit::properties::Style::Normal, + cosmic_text::Style::Italic => font_kit::properties::Style::Italic, + cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique, + }, + weight: font_kit::properties::Weight(face_info.weight.0.into()), + stretch: match face_info.stretch { + cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED, + cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED, + cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED, + cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED, + cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL, + cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED, + cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED, + cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED, + cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED, + }, + } +} + +fn check_is_known_emoji_font(postscript_name: &str) -> bool { + // TODO: Include other common emoji fonts + postscript_name == "NotoColorEmoji" +} + +#[cfg(test)] +mod tests { + use super::*; + #[cfg(feature = "test-support")] + use std::{cell::RefCell, rc::Rc}; + + #[test] + fn all_font_names_tracks_available_families() -> Result<()> { + let text_system = gpui::TextSystem::new(Arc::new( + CosmicTextSystem::new_without_system_fonts("IBM Plex Sans"), + )); + assert!(text_system.all_font_names().is_empty()); + + text_system.add_fonts(vec![Cow::Borrowed(include_bytes!( + "../../../assets/fonts/lilex/Lilex-Regular.ttf" + ))])?; + assert_eq!(text_system.all_font_names(), ["Lilex"]); + + text_system.add_fonts(vec![ + Cow::Borrowed(IBM_PLEX), + Cow::Borrowed(include_bytes!("../../../assets/fonts/lilex/Lilex-Bold.ttf")), + ])?; + assert_eq!(text_system.all_font_names(), ["IBM Plex Sans", "Lilex"]); + Ok(()) + } + + fn fid(i: usize) -> FontId { + FontId(i) + } + + fn chain(ids: &[usize]) -> SmallVec<[(FontId, SharedString); 4]> { + ids.iter() + .map(|&i| (fid(i), SharedString::from(format!("fb{i}")))) + .collect() + } + + fn span(start: usize, end: usize, slot: Option, font_id: FontId) -> RunSpan { + RunSpan { + start, + end, + slot, + font_id, + } + } + + const IBM_PLEX: &[u8] = + include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf"); + const LILEX: &[u8] = include_bytes!("../../../assets/fonts/lilex/Lilex-Regular.ttf"); + + /// Every code point of `Bidi_Class=B`, each of which starts a new bidi + /// paragraph and so can split one line into mixed-direction paragraphs. + const SEPARATORS: &[char] = &[ + '\u{000a}', '\u{000d}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{0085}', '\u{2029}', + ]; + + fn text_system() -> Result { + let text_system = CosmicTextSystem::new_without_system_fonts("IBM Plex Sans"); + text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?; + Ok(text_system) + } + + #[test] + fn font_properties_describe_the_selected_face() -> Result<()> { + let text_system = text_system()?; + let regular = gpui::font("IBM Plex Sans"); + let regular_id = text_system.font_id(®ular)?; + for (weight, style) in [ + (gpui::FontWeight::MEDIUM, gpui::FontStyle::Normal), + (gpui::FontWeight::BOLD, gpui::FontStyle::Italic), + (gpui::FontWeight::NORMAL, gpui::FontStyle::Oblique), + ] { + let requested = Font { + weight, + style, + ..regular.clone() + }; + let font_id = text_system.font_id(&requested)?; + assert_eq!(font_id, regular_id); + assert_eq!( + text_system.font_weight_and_style(font_id)?, + (gpui::FontWeight::NORMAL, gpui::FontStyle::Normal) + ); + } + Ok(()) + } + + fn layout_text(text_system: &CosmicTextSystem, text: &str) -> Result { + let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?; + let runs = [FontRun { + len: text.len(), + font_id, + }]; + Ok(text_system.layout_line(text, gpui::px(14.0), &runs)) + } + + /// Mirrors the original crash: mixed-direction text reaching the shaper + /// through `shape_text`, which only splits lines on `\n`. + #[test] + fn shape_text_with_mixed_direction_paragraphs() -> Result<()> { + let platform_text_system = Arc::new(text_system()?); + let text_system = Arc::new(gpui::TextSystem::new(platform_text_system)); + let window_text_system = gpui::WindowTextSystem::new(text_system); + + let text: SharedString = "first line\n\u{05d0}\u{001c}A".into(); + let runs = [gpui::TextRun { + len: text.len(), + font: gpui::font("IBM Plex Sans"), + ..Default::default() + }]; + + let lines = window_text_system.shape_text(text, gpui::px(14.0), &runs, None, None)?; + + assert_eq!(lines.len(), 2); + assert_eq!(lines[1].len(), "\u{05d0}\u{001c}A".len()); + assert!(lines[1].width() > Pixels::ZERO); + Ok(()) + } + + #[cfg(feature = "test-support")] + #[test] + fn reports_graphemes_that_exhaust_font_fallback() -> Result<()> { + let platform_text_system = Arc::new(text_system()?); + let dispatcher = gpui::TestDispatcher::new(0); + let cx = + gpui::TestAppContext::build_with_text_system(dispatcher, None, platform_text_system); + let observed = Rc::new(RefCell::new(Vec::new())); + let _subscription = cx.update(|cx| { + let observed = observed.clone(); + cx.on_missing_glyphs(move |missing_glyphs, _| { + observed.borrow_mut().extend_from_slice(missing_glyphs); + }) + }); + let text: SharedString = "界".into(); + + cx.update(|cx| { + let text_system = gpui::WindowTextSystem::new(cx.text_system().clone()); + let runs = [gpui::TextRun { + len: text.len(), + font: gpui::font("IBM Plex Sans"), + ..Default::default() + }]; + text_system.shape_line(text, gpui::px(14.0), &runs, None); + }); + cx.run_until_parked(); + + let observed = observed.borrow(); + assert_eq!(observed.len(), 1); + assert_eq!(observed[0].grapheme(), "界"); + assert_eq!( + observed[0].font_class(), + gpui::FallbackFontClass::Proportional + ); + Ok(()) + } + + #[test] + fn combines_missing_glyphs_from_one_grapheme() -> Result<()> { + let text_system = text_system()?; + let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?; + let text = "x\u{0301}"; + let runs = [FontRun { + len: text.len(), + font_id, + }]; + + let missing_glyphs = text_system + .0 + .read() + .missing_glyphs(text, &runs, [0, "x".len()]); + + assert_eq!(missing_glyphs.len(), 1); + assert_eq!(missing_glyphs[0].grapheme(), text); + Ok(()) + } + + #[test] + fn adding_fonts_invalidates_cached_line_layouts() -> Result<()> { + let platform_text_system = Arc::new(text_system()?); + let text_system = Arc::new(gpui::TextSystem::new(platform_text_system.clone())); + let window_text_system = gpui::WindowTextSystem::new(text_system.clone()); + let text: SharedString = "cached text".into(); + let runs = [gpui::TextRun { + len: text.len(), + font: gpui::font("IBM Plex Sans"), + ..Default::default() + }]; + + let first_layout = window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None); + let cached_layout = + window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None); + assert!(std::ptr::eq::( + &**first_layout, + &**cached_layout + )); + let loaded_font_count = platform_text_system.0.read().loaded_fonts.len(); + + text_system.add_fonts(vec![Cow::Borrowed(LILEX)])?; + + let refreshed_layout = window_text_system.shape_line(text, gpui::px(14.0), &runs, None); + assert!(!std::ptr::eq::( + &**first_layout, + &**refreshed_layout + )); + assert_eq!( + platform_text_system.0.read().loaded_fonts.len(), + loaded_font_count + ); + Ok(()) + } + + #[test] + fn layout_line_with_mixed_direction_paragraphs() -> Result<()> { + let text_system = text_system()?; + + for separator in SEPARATORS { + for text in [ + format!("\u{05d0}{separator}A"), + format!("A{separator}\u{05d0}"), + ] { + let layout = layout_text(&text_system, &text)?; + + assert_eq!(layout.len, text.len(), "{text:?}"); + assert!(layout.width > Pixels::ZERO, "{text:?}"); + assert!( + layout.runs.iter().any(|run| !run.glyphs.is_empty()), + "{text:?}" + ); + } + } + + Ok(()) + } + + #[test] + fn layout_line_with_separators_at_line_edges() -> Result<()> { + let text_system = text_system()?; + + for text in [ + "\u{001c}", + "\u{001c}\u{001c}", + "\u{001c}\u{05d0}", + "\u{05d0}\u{001c}", + "\u{05d0}\u{001c}\u{001c}A", + "\u{001c}\u{05d0}\u{001c}A\u{001c}", + ] { + let layout = layout_text(&text_system, text)?; + assert_eq!(layout.len, text.len(), "{text:?}"); + } + + Ok(()) + } + + /// Glyph indices must stay absolute and positions ordered across segment + /// boundaries, otherwise cursor placement and hit testing desync. Uses + /// single-direction text so visual order matches logical order. + #[test] + fn layout_line_keeps_indices_and_positions_ordered_across_paragraphs() -> Result<()> { + let text_system = text_system()?; + let text = "ab\u{001c}cd\u{2029}ef"; + let layout = layout_text(&text_system, text)?; + + let glyphs: Vec<_> = layout.runs.iter().flat_map(|run| &run.glyphs).collect(); + assert!(!glyphs.is_empty()); + + for glyph in &glyphs { + assert!(glyph.index < text.len(), "{:?}", glyph.index); + assert!(text.is_char_boundary(glyph.index), "{:?}", glyph.index); + } + for pair in glyphs.windows(2) { + assert!(pair[0].index < pair[1].index); + assert!(pair[0].position.x <= pair[1].position.x); + } + + // Every segment contributes width, so the whole line is wider than its + // leading paragraph alone. + assert!(layout.width > layout_text(&text_system, "ab")?.width); + Ok(()) + } + + /// A font run boundary that does not line up with a paragraph boundary must + /// still be clipped to the right segments. + #[test] + fn layout_line_with_font_run_straddling_a_separator() -> Result<()> { + let text_system = text_system()?; + let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?; + let text = "ab\u{001c}\u{05d0}\u{05d1}"; + + // The run boundary falls inside the trailing RTL paragraph. + let runs = [ + FontRun { + len: "ab\u{001c}\u{05d0}".len(), + font_id, + }, + FontRun { + len: "\u{05d1}".len(), + font_id, + }, + ]; + let layout = text_system.layout_line(text, gpui::px(14.0), &runs); + + assert_eq!(layout.len, text.len()); + assert!(layout.width > Pixels::ZERO); + Ok(()) + } + + /// Lines with no separator take the fast path and must be shaped exactly as + /// they were before paragraph splitting existed. + #[test] + fn layout_line_without_separators_takes_fast_path() -> Result<()> { + let text_system = text_system()?; + + for text in [ + "hello world", + "\u{05d0}\u{05d1}\u{05d2}", + "mixed \u{05d0}\u{05d1}", + ] { + assert!(!contains_paragraph_separator(text), "{text:?}"); + let layout = layout_text(&text_system, text)?; + assert_eq!(layout.len, text.len(), "{text:?}"); + assert!(layout.width > Pixels::ZERO, "{text:?}"); + } + + Ok(()) + } + + /// cosmic-text sums word widths to get a line's width but accumulates glyph + /// advances to position glyphs, so a trailing zero-advance glyph (here a + /// zero-width space) can land a few ulps past the width. When that glyph is a + /// wrap boundary, the row before it extends past the line's width, and hit + /// testing in that sliver used to panic (ZED-BW8, ZED-75K, ZED-81Z). + #[test] + fn index_for_position_past_line_width() -> Result<()> { + let text_system = Arc::new(gpui::TextSystem::new(Arc::new(text_system()?))); + let window_text_system = gpui::WindowTextSystem::new(text_system); + let text: SharedString = "Warning: this will delete files\u{200b}".into(); + let runs = [gpui::TextRun { + len: text.len(), + font: gpui::font("IBM Plex Sans"), + ..Default::default() + }]; + let lines = + window_text_system.shape_text(text, gpui::px(14.), &runs, Some(gpui::px(4.)), None)?; + let line = &lines[0]; + let width = line.unwrapped_layout.width; + let boundary_glyph = |row: usize| { + let boundary = line.wrap_boundaries()[row]; + &line.runs()[boundary.run_ix].glyphs[boundary.glyph_ix] + }; + let row = (1..line.wrap_boundaries().len()) + .find(|row| boundary_glyph(*row).position.x > width) + .expect("trailing zero-width space should be a wrap boundary past the line width"); + let row_start_x = f32::from(boundary_glyph(row - 1).position.x); + let row_end = boundary_glyph(row); + + let mut x = f32::from(width) - row_start_x; + while x + row_start_x < f32::from(width) { + x = x.next_up(); + } + assert!(gpui::px(x + row_start_x) < row_end.position.x); + + let line_height = gpui::px(20.); + let position = gpui::point(gpui::px(x), line_height * row as f32 + gpui::px(1.)); + assert_eq!( + line.index_for_position(position, line_height), + Err(row_end.index) + ); + Ok(()) + } + + #[test] + fn paragraph_separator_detection() { + for separator in SEPARATORS { + assert!(is_paragraph_separator(*separator), "{separator:?}"); + assert!(contains_paragraph_separator(&format!("a{separator}b"))); + } + + for text in [ + "", + "plain ascii", + "\u{05d0}", + "tab\there", + "emoji \u{1f600}", + ] { + assert!(!contains_paragraph_separator(text), "{text:?}"); + } + } + + #[test] + fn font_runs_are_clipped_to_segment() { + let runs = [ + FontRun { + len: 3, + font_id: fid(1), + }, + FontRun { + len: 4, + font_id: fid(2), + }, + ]; + + assert_eq!(clip_font_runs(&runs, 0..7).as_slice(), &runs); + assert_eq!( + clip_font_runs(&runs, 2..5).as_slice(), + &[ + FontRun { + len: 1, + font_id: fid(1) + }, + FontRun { + len: 2, + font_id: fid(2) + }, + ] + ); + assert_eq!( + clip_font_runs(&runs, 3..7).as_slice(), + &[FontRun { + len: 4, + font_id: fid(2) + }] + ); + assert!(clip_font_runs(&runs, 5..5).is_empty()); + } + + #[test] + fn primary_wins_over_current_fallback_when_primary_covers() { + let primary = fid(0); + let fb = chain(&[1, 2]); + let covers = |id: FontId, _: char| id == fid(0) || id == fid(1); + assert_eq!( + pick_covering_slot('a', Some(0), primary, &fb, &covers), + None + ); + } + + #[test] + fn primary_preferred_over_fallback_when_both_cover() { + let primary = fid(0); + let fb = chain(&[1]); + let covers = |_: FontId, _: char| true; + assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None); + } + + #[test] + fn falls_through_chain_in_order() { + let primary = fid(0); + let fb = chain(&[1, 2, 3]); + // only fallback 2 at index 1 covers. + let covers = |id: FontId, _: char| id == fid(2); + assert_eq!( + pick_covering_slot('字', None, primary, &fb, &covers), + Some(1) + ); + } + + #[test] + fn no_coverage_returns_primary() { + let primary = fid(0); + let fb = chain(&[1, 2]); + let covers = |_: FontId, _: char| false; + // nothing covers. return `None` so the `cosmic-text` built in script + // fallback can take over during shaping. + assert_eq!( + pick_covering_slot('\u{1F600}', Some(1), primary, &fb, &covers), + None + ); + } + + #[test] + fn empty_chain_always_returns_primary() { + let primary = fid(0); + let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new(); + let covers = |_: FontId, _: char| false; + assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None); + } + + #[test] + fn slot_font_id_resolution() { + let primary = fid(7); + let fb = chain(&[10, 20]); + assert_eq!(slot_font_id(None, primary, &fb), fid(7)); + assert_eq!(slot_font_id(Some(0), primary, &fb), fid(10)); + assert_eq!(slot_font_id(Some(1), primary, &fb), fid(20)); + } + + #[test] + fn run_spans_with_no_chain_emit_one_primary_span() { + let primary = fid(0); + let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new(); + let covers = |_: FontId, _: char| false; + let text = "hello"; + let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); + assert_eq!(spans.as_slice(), &[span(0, text.len(), None, primary)]); + } + + #[test] + fn run_spans_use_byte_offsets_for_multibyte_chars() { + let primary = fid(0); + let fb = chain(&[1]); + // primary covers ascii. fallback covers cjk. + let covers = |id: FontId, ch: char| { + if id == primary { + ch.is_ascii() + } else { + !ch.is_ascii() + } + }; + let text = "a字b"; + let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); + // '字' is 3 bytes so split is at 1 then 4. + assert_eq!( + spans.as_slice(), + &[ + span(0, 1, None, primary), + span(1, 4, Some(0), fid(1)), + span(4, 5, None, primary), + ] + ); + } + + #[test] + fn run_spans_respect_run_offset() { + let primary = fid(0); + let fb = chain(&[1]); + let covers = |id: FontId, ch: char| { + if id == primary { + ch.is_ascii() + } else { + !ch.is_ascii() + } + }; + // outer text has a prefix that is not part of this run. + let text = "xx字y"; + let run_offset = 2; + let run_len = text.len() - run_offset; + let spans = compute_run_spans(text, run_offset, run_len, primary, &fb, &covers); + assert_eq!( + spans.as_slice(), + &[span(2, 5, Some(0), fid(1)), span(5, 6, None, primary)] + ); + } + + #[test] + fn run_spans_keep_combining_marks_with_base_in_fallback() { + let primary = fid(0); + let fb = chain(&[1]); + // primary covers ascii only. fallback covers the base char. + // combining mark must stay in the fallback span even when fallback + // does not advertise coverage of it. + let covers = |id: FontId, ch: char| { + if id == primary { + ch.is_ascii() + } else { + ch == '\u{0905}' + } + }; + // \u{0905} devanagari short a + \u{0902} candrabindu mark. + let text = "\u{0905}\u{0902}"; + let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); + assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]); + } + + #[test] + fn run_spans_keep_zwj_inside_emoji_cluster() { + let primary = fid(0); + let fb = chain(&[1]); + // only fallback covers the emoji codepoints. zwj must not split. + let covers = |id: FontId, ch: char| id == fid(1) && ch != '\u{200D}'; + // family zwj sequence woman zwj girl. + let text = "\u{1F469}\u{200D}\u{1F467}"; + let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); + assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]); + } + + #[test] + fn run_spans_collapse_adjacent_same_slot() { + let primary = fid(0); + let fb = chain(&[1]); + let covers = |id: FontId, ch: char| { + if id == primary { + ch.is_ascii() + } else { + !ch.is_ascii() + } + }; + let text = "字字字"; + let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); + assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]); + } + + #[test] + fn run_spans_empty_run_returns_no_spans() { + let primary = fid(0); + let fb = chain(&[1]); + let covers = |_: FontId, _: char| true; + let spans = compute_run_spans("anything", 3, 0, primary, &fb, &covers); + assert!(spans.is_empty()); + } +} diff --git a/vendor/gpui-wgpu/src/gpui_wgpu.rs b/vendor/gpui-wgpu/src/gpui_wgpu.rs new file mode 100644 index 0000000..29a79af --- /dev/null +++ b/vendor/gpui-wgpu/src/gpui_wgpu.rs @@ -0,0 +1,15 @@ +mod cosmic_text_system; +mod wgpu_atlas; +mod wgpu_context; +mod wgpu_renderer; + +pub use cosmic_text_system::*; +pub use wgpu; +pub use wgpu_atlas::*; +pub use wgpu_context::*; +#[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") +))] +pub use wgpu_renderer::WgpuHeadlessRenderer; +pub use wgpu_renderer::{GpuContext, WgpuRenderer, WgpuSurfaceConfig}; diff --git a/vendor/gpui-wgpu/src/shaders.wgsl b/vendor/gpui-wgpu/src/shaders.wgsl new file mode 100644 index 0000000..718cb75 --- /dev/null +++ b/vendor/gpui-wgpu/src/shaders.wgsl @@ -0,0 +1,1362 @@ +/* Functions useful for debugging: + +// A heat map color for debugging (blue -> cyan -> green -> yellow -> red). +fn heat_map_color(value: f32, minValue: f32, maxValue: f32, position: vec2) -> vec4 { + // Normalize value to 0-1 range + let t = clamp((value - minValue) / (maxValue - minValue), 0.0, 1.0); + + // Heat map color calculation + let r = t * t; + let g = 4.0 * t * (1.0 - t); + let b = (1.0 - t) * (1.0 - t); + let heat_color = vec3(r, g, b); + + // Create a checkerboard pattern (black and white) + let sum = floor(position.x / 3) + floor(position.y / 3); + let is_odd = fract(sum * 0.5); // 0.0 for even, 0.5 for odd + let checker_value = is_odd * 2.0; // 0.0 for even, 1.0 for odd + let checker_color = vec3(checker_value); + + // Determine if value is in range (1.0 if in range, 0.0 if out of range) + let in_range = step(minValue, value) * step(value, maxValue); + + // Mix checkerboard and heat map based on whether value is in range + let final_color = mix(checker_color, heat_color, in_range); + + return vec4(final_color, 1.0); +} + +*/ + +// Contrast and gamma correction adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.hlsl +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +fn color_brightness(color: vec3) -> f32 { + // REC. 601 luminance coefficients for perceived brightness + return dot(color, vec3(0.30, 0.59, 0.11)); +} + +fn light_on_dark_contrast(enhancedContrast: f32, color: vec3) -> f32 { + let brightness = color_brightness(color); + let multiplier = saturate(4.0 * (0.75 - brightness)); + return enhancedContrast * multiplier; +} + +fn enhance_contrast(alpha: f32, k: f32) -> f32 { + return alpha * (k + 1.0) / (alpha * k + 1.0); +} + +fn enhance_contrast3(alpha: vec3, k: f32) -> vec3 { + return alpha * (k + 1.0) / (alpha * k + 1.0); +} + +fn apply_alpha_correction(a: f32, b: f32, g: vec4) -> f32 { + let brightness_adjustment = g.x * b + g.y; + let correction = brightness_adjustment * a + (g.z * b + g.w); + return a + a * (1.0 - a) * correction; +} + +fn apply_alpha_correction3(a: vec3, b: vec3, g: vec4) -> vec3 { + let brightness_adjustment = g.x * b + g.y; + let correction = brightness_adjustment * a + (g.z * b + g.w); + return a + a * (1.0 - a) * correction; +} + +fn apply_contrast_and_gamma_correction(sample: f32, color: vec3, enhanced_contrast_factor: f32, gamma_ratios: vec4) -> f32 { + let enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color); + let brightness = color_brightness(color); + + let contrasted = enhance_contrast(sample, enhanced_contrast); + return apply_alpha_correction(contrasted, brightness, gamma_ratios); +} + +fn apply_contrast_and_gamma_correction3(sample: vec3, color: vec3, enhanced_contrast_factor: f32, gamma_ratios: vec4) -> vec3 { + let enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color); + + let contrasted = enhance_contrast3(sample, enhanced_contrast); + return apply_alpha_correction3(contrasted, color, gamma_ratios); +} + +struct GlobalParams { + viewport_size: vec2, + premultiplied_alpha: u32, + pad: u32, +} + +struct GammaParams { + gamma_ratios: vec4, + grayscale_enhanced_contrast: f32, + subpixel_enhanced_contrast: f32, + is_bgr: u32, + pad: u32, +} + +@group(0) @binding(0) var globals: GlobalParams; +@group(0) @binding(1) var gamma_params: GammaParams; +@group(2) @binding(0) var t_sprite: texture_2d; +@group(2) @binding(1) var s_sprite: sampler; + +const M_PI_F: f32 = 3.1415926; +const GRAYSCALE_FACTORS: vec3 = vec3(0.2126, 0.7152, 0.0722); + +struct Bounds { + origin: vec2, + size: vec2, +} + +struct Corners { + top_left: f32, + top_right: f32, + bottom_right: f32, + bottom_left: f32, +} + +struct Edges { + top: f32, + right: f32, + bottom: f32, + left: f32, +} + +struct Hsla { + h: f32, + s: f32, + l: f32, + a: f32, +} + +struct LinearColorStop { + color: Hsla, + percentage: f32, +} + +struct Background { + // 0u is Solid + // 1u is LinearGradient + // 2u is PatternSlash + // 3u is Checkerboard + tag: u32, + // 0u is sRGB linear color + // 1u is Oklab color + color_space: u32, + solid: Hsla, + gradient_angle_or_pattern_height: f32, + colors: array, + pad: u32, +} + +struct AtlasTextureId { + index: u32, + kind: u32, +} + +struct AtlasBounds { + origin: vec2, + size: vec2, +} + +struct AtlasTile { + texture_id: AtlasTextureId, + tile_id: u32, + padding: u32, + bounds: AtlasBounds, +} + +struct TransformationMatrix { + rotation_scale: mat2x2, + translation: vec2, +} + +fn to_device_position_impl(position: vec2) -> vec4 { + let device_position = position / globals.viewport_size * vec2(2.0, -2.0) + vec2(-1.0, 1.0); + return vec4(device_position, 0.0, 1.0); +} + +fn to_device_position(unit_vertex: vec2, bounds: Bounds) -> vec4 { + let position = unit_vertex * vec2(bounds.size) + bounds.origin; + return to_device_position_impl(position); +} + +fn to_device_position_transformed(unit_vertex: vec2, bounds: Bounds, transform: TransformationMatrix) -> vec4 { + let position = unit_vertex * vec2(bounds.size) + bounds.origin; + //Note: Rust side stores it as row-major, so transposing here + let transformed = transpose(transform.rotation_scale) * position + transform.translation; + return to_device_position_impl(transformed); +} + +fn to_tile_position(unit_vertex: vec2, tile: AtlasTile) -> vec2 { + let atlas_size = vec2(textureDimensions(t_sprite, 0)); + return (vec2(tile.bounds.origin) + unit_vertex * vec2(tile.bounds.size)) / atlas_size; +} + +fn distance_from_clip_rect_impl(position: vec2, clip_bounds: Bounds) -> vec4 { + let tl = position - clip_bounds.origin; + let br = clip_bounds.origin + clip_bounds.size - position; + return vec4(tl.x, br.x, tl.y, br.y); +} + +fn distance_from_clip_rect(unit_vertex: vec2, bounds: Bounds, clip_bounds: Bounds) -> vec4 { + let position = unit_vertex * vec2(bounds.size) + bounds.origin; + return distance_from_clip_rect_impl(position, clip_bounds); +} + +fn distance_from_clip_rect_transformed(unit_vertex: vec2, bounds: Bounds, clip_bounds: Bounds, transform: TransformationMatrix) -> vec4 { + let position = unit_vertex * vec2(bounds.size) + bounds.origin; + let transformed = transpose(transform.rotation_scale) * position + transform.translation; + return distance_from_clip_rect_impl(transformed, clip_bounds); +} + +// https://gamedev.stackexchange.com/questions/92015/optimized-linear-to-srgb-glsl +fn srgb_to_linear(srgb: vec3) -> vec3 { + let cutoff = srgb < vec3(0.04045); + let higher = pow((srgb + vec3(0.055)) / vec3(1.055), vec3(2.4)); + let lower = srgb / vec3(12.92); + return select(higher, lower, cutoff); +} + +fn srgb_to_linear_component(a: f32) -> f32 { + let cutoff = a < 0.04045; + let higher = pow((a + 0.055) / 1.055, 2.4); + let lower = a / 12.92; + return select(higher, lower, cutoff); +} + +fn linear_to_srgb(linear: vec3) -> vec3 { + let cutoff = linear < vec3(0.0031308); + let higher = vec3(1.055) * pow(linear, vec3(1.0 / 2.4)) - vec3(0.055); + let lower = linear * vec3(12.92); + return select(higher, lower, cutoff); +} + +/// Convert a linear color to sRGBA space. +fn linear_to_srgba(color: vec4) -> vec4 { + return vec4(linear_to_srgb(color.rgb), color.a); +} + +/// Convert a sRGBA color to linear space. +fn srgba_to_linear(color: vec4) -> vec4 { + return vec4(srgb_to_linear(color.rgb), color.a); +} + +/// Hsla to linear RGBA conversion. +fn hsla_to_rgba(hsla: Hsla) -> vec4 { + let h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range + let s = hsla.s; + let l = hsla.l; + let a = hsla.a; + + let c = (1.0 - abs(2.0 * l - 1.0)) * s; + let x = c * (1.0 - abs(h % 2.0 - 1.0)); + let m = l - c / 2.0; + var color = vec3(m); + + if (h >= 0.0 && h < 1.0) { + color.r += c; + color.g += x; + } else if (h >= 1.0 && h < 2.0) { + color.r += x; + color.g += c; + } else if (h >= 2.0 && h < 3.0) { + color.g += c; + color.b += x; + } else if (h >= 3.0 && h < 4.0) { + color.g += x; + color.b += c; + } else if (h >= 4.0 && h < 5.0) { + color.r += x; + color.b += c; + } else { + color.r += c; + color.b += x; + } + + return vec4(color, a); +} + +/// Convert a linear sRGB to Oklab space. +/// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab +fn linear_srgb_to_oklab(color: vec4) -> vec4 { + let l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b; + let m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b; + let s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b; + + let l_ = pow(l, 1.0 / 3.0); + let m_ = pow(m, 1.0 / 3.0); + let s_ = pow(s, 1.0 / 3.0); + + return vec4( + 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_, + 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_, + 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_, + color.a + ); +} + +/// Convert an Oklab color to linear sRGB space. +fn oklab_to_linear_srgb(color: vec4) -> vec4 { + let l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b; + let m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b; + let s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b; + + let l = l_ * l_ * l_; + let m = m_ * m_ * m_; + let s = s_ * s_ * s_; + + return vec4( + 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, + -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, + -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s, + color.a + ); +} + +fn over(below: vec4, above: vec4) -> vec4 { + let alpha = above.a + below.a * (1.0 - above.a); + let color = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha; + return vec4(color, alpha); +} + +// A standard gaussian function, used for weighting samples +fn gaussian(x: f32, sigma: f32) -> f32{ + return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma); +} + +// This approximates the error function, needed for the gaussian integral +fn erf(v: vec2) -> vec2 { + let s = sign(v); + let a = abs(v); + let r1 = 1.0 + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a; + let r2 = r1 * r1; + return s - s / (r2 * r2); +} + +fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2) -> f32 { + let delta = min(half_size.y - corner - abs(y), 0.0); + let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta)); + let integral = 0.5 + 0.5 * erf((x + vec2(-curved, curved)) * (sqrt(0.5) / sigma)); + return integral.y - integral.x; +} + +// Selects corner radius based on quadrant. +fn pick_corner_radius(center_to_point: vec2, radii: Corners) -> f32 { + if (center_to_point.x < 0.0) { + if (center_to_point.y < 0.0) { + return radii.top_left; + } else { + return radii.bottom_left; + } + } else { + if (center_to_point.y < 0.0) { + return radii.top_right; + } else { + return radii.bottom_right; + } + } +} + +// Signed distance of the point to the quad's border - positive outside the +// border, and negative inside. +// +// See comments on similar code using `quad_sdf_impl` in `fs_quad` for +// explanation. +fn quad_sdf(point: vec2, bounds: Bounds, corner_radii: Corners) -> f32 { + let half_size = bounds.size / 2.0; + let center = bounds.origin + half_size; + let center_to_point = point - center; + let corner_radius = pick_corner_radius(center_to_point, corner_radii); + let corner_to_point = abs(center_to_point) - half_size; + let corner_center_to_point = corner_to_point + corner_radius; + return quad_sdf_impl(corner_center_to_point, corner_radius); +} + +fn quad_sdf_impl(corner_center_to_point: vec2, corner_radius: f32) -> f32 { + if (corner_radius == 0.0) { + // Fast path for unrounded corners. + return max(corner_center_to_point.x, corner_center_to_point.y); + } else { + // Signed distance of the point from a quad that is inset by corner_radius. + // It is negative inside this quad, and positive outside. + let signed_distance_to_inset_quad = + // 0 inside the inset quad, and positive outside. + length(max(vec2(0.0), corner_center_to_point)) + + // 0 outside the inset quad, and negative inside. + min(0.0, max(corner_center_to_point.x, corner_center_to_point.y)); + + return signed_distance_to_inset_quad - corner_radius; + } +} + +// Abstract away the final color transformation based on the +// target alpha compositing mode. +fn blend_color(color: vec4, alpha_factor: f32) -> vec4 { + let alpha = color.a * alpha_factor; + let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u); + return vec4(color.rgb * multiplier, alpha); +} + + +struct GradientColor { + solid: vec4, + color0: vec4, + color1: vec4, +} + +fn prepare_gradient_color(tag: u32, color_space: u32, + solid: Hsla, colors: array) -> GradientColor { + var result = GradientColor(); + + if (tag == 0u || tag == 2u || tag == 3u) { + result.solid = hsla_to_rgba(solid); + } else if (tag == 1u) { + // The hsla_to_rgba is returns a linear sRGB color + result.color0 = hsla_to_rgba(colors[0].color); + result.color1 = hsla_to_rgba(colors[1].color); + + // Prepare color space in vertex for avoid conversion + // in fragment shader for performance reasons + if (color_space == 0u) { + // sRGB + result.color0 = linear_to_srgba(result.color0); + result.color1 = linear_to_srgba(result.color1); + } else if (color_space == 1u) { + // Oklab + result.color0 = linear_srgb_to_oklab(result.color0); + result.color1 = linear_srgb_to_oklab(result.color1); + } + } + + return result; +} + +fn gradient_color(background: Background, position: vec2, bounds: Bounds, + solid_color: vec4, color0: vec4, color1: vec4) -> vec4 { + var background_color = vec4(0.0); + + switch (background.tag) { + default: { + return solid_color; + } + case 1u: { + // Linear gradient background. + // -90 degrees to match the CSS gradient angle. + let angle = background.gradient_angle_or_pattern_height; + let radians = (angle % 360.0 - 90.0) * M_PI_F / 180.0; + var direction = vec2(cos(radians), sin(radians)); + let stop0_percentage = background.colors[0].percentage; + let stop1_percentage = background.colors[1].percentage; + + // Expand the short side to be the same as the long side + if (bounds.size.x > bounds.size.y) { + direction.y *= bounds.size.y / bounds.size.x; + } else { + direction.x *= bounds.size.x / bounds.size.y; + } + + // Get the t value for the linear gradient with the color stop percentages. + let half_size = bounds.size / 2.0; + let center = bounds.origin + half_size; + let center_to_point = position - center; + var t = dot(center_to_point, direction) / length(direction); + // Check the direct to determine the use x or y + if (abs(direction.x) > abs(direction.y)) { + t = (t + half_size.x) / bounds.size.x; + } else { + t = (t + half_size.y) / bounds.size.y; + } + + // Adjust t based on the stop percentages + t = (t - stop0_percentage) / (stop1_percentage - stop0_percentage); + t = clamp(t, 0.0, 1.0); + + switch (background.color_space) { + default: { + background_color = srgba_to_linear(mix(color0, color1, t)); + } + case 1u: { + let oklab_color = mix(color0, color1, t); + background_color = oklab_to_linear_srgb(oklab_color); + } + } + } + case 2u: { + // pattern slash + let gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height; + let pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f; + let pattern_interval = (gradient_angle_or_pattern_height % 65535.0f) / 255.0f; + let pattern_height = pattern_width + pattern_interval; + let stripe_angle = M_PI_F / 4.0; + let pattern_period = pattern_height * sin(stripe_angle); + let rotation = mat2x2( + cos(stripe_angle), -sin(stripe_angle), + sin(stripe_angle), cos(stripe_angle) + ); + let relative_position = position - bounds.origin; + let rotated_point = rotation * relative_position; + let pattern = rotated_point.x % pattern_period; + let distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) / 2.0f; + background_color = solid_color; + background_color.a *= saturate(0.5 - distance); + } + case 3u: { + // checkerboard + let size = background.gradient_angle_or_pattern_height; + let relative_position = position - bounds.origin; + + let x_index = floor(relative_position.x / size); + let y_index = floor(relative_position.y / size); + let should_be_colored = (x_index + y_index) % 2.0; + + background_color = solid_color; + background_color.a *= saturate(should_be_colored); + } + } + + return background_color; +} + +// --- quads --- // + +struct Quad { + order: u32, + border_style: u32, + bounds: Bounds, + content_mask: Bounds, + background: Background, + border_color: Hsla, + corner_radii: Corners, + border_widths: Edges, +} + +struct QuadVarying { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) border_color: vec4, + @location(1) @interpolate(flat) quad_id: u32, + // TODO: use `clip_distance` once Naga supports it + @location(2) clip_distances: vec4, + @location(3) @interpolate(flat) background_solid: vec4, + @location(4) @interpolate(flat) background_color0: vec4, + @location(5) @interpolate(flat) background_color1: vec4, +} + +@vertex +fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let quad = load_quad(instance_id); + + var out = QuadVarying(); + out.position = to_device_position(unit_vertex, quad.bounds); + + let gradient = prepare_gradient_color( + quad.background.tag, + quad.background.color_space, + quad.background.solid, + quad.background.colors + ); + out.background_solid = gradient.solid; + out.background_color0 = gradient.color0; + out.background_color1 = gradient.color1; + out.border_color = hsla_to_rgba(quad.border_color); + out.quad_id = instance_id; + out.clip_distances = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask); + return out; +} + +@fragment +fn fs_quad(input: QuadVarying) -> @location(0) vec4 { + // Alpha clip first, since we don't have `clip_distance`. + if (any(input.clip_distances < vec4(0.0))) { + return vec4(0.0); + } + + let quad = load_quad(input.quad_id); + + let background_color = gradient_color(quad.background, input.position.xy, quad.bounds, + input.background_solid, input.background_color0, input.background_color1); + + let unrounded = quad.corner_radii.top_left == 0.0 && + quad.corner_radii.bottom_left == 0.0 && + quad.corner_radii.top_right == 0.0 && + quad.corner_radii.bottom_right == 0.0; + + // Fast path when the quad is not rounded and doesn't have any border + if (quad.border_widths.top == 0.0 && + quad.border_widths.left == 0.0 && + quad.border_widths.right == 0.0 && + quad.border_widths.bottom == 0.0 && + unrounded) { + return blend_color(background_color, 1.0); + } + + let size = quad.bounds.size; + let half_size = size / 2.0; + let point = input.position.xy - quad.bounds.origin; + let center_to_point = point - half_size; + + // Signed distance field threshold for inclusion of pixels. 0.5 is the + // minimum distance between the center of the pixel and the edge. + let antialias_threshold = 0.5; + + // Radius of the nearest corner + let corner_radius = pick_corner_radius(center_to_point, quad.corner_radii); + + // Width of the nearest borders + let border = vec2( + select( + quad.border_widths.right, + quad.border_widths.left, + center_to_point.x < 0.0), + select( + quad.border_widths.bottom, + quad.border_widths.top, + center_to_point.y < 0.0)); + + // 0-width borders are reduced so that `inner_sdf >= antialias_threshold`. + // The purpose of this is to not draw antialiasing pixels in this case. + let reduced_border = + vec2(select(border.x, -antialias_threshold, border.x == 0.0), + select(border.y, -antialias_threshold, border.y == 0.0)); + + // Vector from the corner of the quad bounds to the point, after mirroring + // the point into the bottom right quadrant. Both components are <= 0. + let corner_to_point = abs(center_to_point) - half_size; + + // Vector from the point to the center of the rounded corner's circle, also + // mirrored into bottom right quadrant. + let corner_center_to_point = corner_to_point + corner_radius; + + // Whether the nearest point on the border is rounded + let is_near_rounded_corner = + corner_center_to_point.x >= 0 && + corner_center_to_point.y >= 0; + + // Vector from straight border inner corner to point. + let straight_border_inner_corner_to_point = corner_to_point + reduced_border; + + // Whether the point is beyond the inner edge of the straight border. + let is_beyond_inner_straight_border = + straight_border_inner_corner_to_point.x > 0 || + straight_border_inner_corner_to_point.y > 0; + + // Whether the point is far enough inside the quad, such that the pixels are + // not affected by the straight border. + let is_within_inner_straight_border = + straight_border_inner_corner_to_point.x < -antialias_threshold && + straight_border_inner_corner_to_point.y < -antialias_threshold; + + // Fast path for points that must be part of the background. + // + // This could be optimized further for large rounded corners by including + // points in an inscribed rectangle, or some other quick linear check. + // However, that might negatively impact performance in the case of + // reasonable sizes for rounded corners. + if (is_within_inner_straight_border && !is_near_rounded_corner) { + return blend_color(background_color, 1.0); + } + + // Signed distance of the point to the outside edge of the quad's border. It + // is positive outside this edge, and negative inside. + let outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius); + + // Approximate signed distance of the point to the inside edge of the quad's + // border. It is negative outside this edge (within the border), and + // positive inside. + // + // This is not always an accurate signed distance: + // * The rounded portions with varying border width use an approximation of + // nearest-point-on-ellipse. + // * When it is quickly known to be outside the edge, -1.0 is used. + var inner_sdf = 0.0; + if (corner_center_to_point.x <= 0 || corner_center_to_point.y <= 0) { + // Fast paths for straight borders. + inner_sdf = -max(straight_border_inner_corner_to_point.x, + straight_border_inner_corner_to_point.y); + } else if (is_beyond_inner_straight_border) { + // Fast path for points that must be outside the inner edge. + inner_sdf = -1.0; + } else if (reduced_border.x == reduced_border.y) { + // Fast path for circular inner edge. + inner_sdf = -(outer_sdf + reduced_border.x); + } else { + let ellipse_radii = max(vec2(0.0), corner_radius - reduced_border); + inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii); + } + + // Negative when inside the border + let border_sdf = max(inner_sdf, outer_sdf); + + var color = background_color; + if (border_sdf < antialias_threshold) { + var border_color = input.border_color; + + // Dashed border logic when border_style == 1 + if (quad.border_style == 1) { + // Position along the perimeter in "dash space", where each dash + // period has length 1 + var t = 0.0; + + // Total number of dash periods, so that the dash spacing can be + // adjusted to evenly divide it + var max_t = 0.0; + + // Border width is proportional to dash size. This is the behavior + // used by browsers, but also avoids dashes from different segments + // overlapping when dash size is smaller than the border width. + // + // Dash pattern: (2 * border width) dash, (1 * border width) gap + let dash_length_per_width = 2.0; + let dash_gap_per_width = 1.0; + let dash_period_per_width = dash_length_per_width + dash_gap_per_width; + + // Since the dash size is determined by border width, the density of + // dashes varies. Multiplying a pixel distance by this returns a + // position in dash space - it has units (dash period / pixels). So + // a dash velocity of (1 / 10) is 1 dash every 10 pixels. + var dash_velocity = 0.0; + + // Dividing this by the border width gives the dash velocity + let dv_numerator = 1.0 / dash_period_per_width; + + if (unrounded) { + // When corners aren't rounded, the dashes are separately laid + // out on each straight line, rather than around the whole + // perimeter. This way each line starts and ends with a dash. + let is_horizontal = + corner_center_to_point.x < + corner_center_to_point.y; + + // When applying dashed borders to just some, not all, the sides. + // The way we chose border widths above sometimes comes with a 0 width value. + // So we choose again to avoid division by zero. + // TODO: A better solution exists taking a look at the whole file. + // this does not fix single dashed borders at the corners + let dashed_border = vec2( + max( + quad.border_widths.bottom, + quad.border_widths.top, + ), + max( + quad.border_widths.right, + quad.border_widths.left, + ) + ); + + let border_width = select(dashed_border.y, dashed_border.x, is_horizontal); + dash_velocity = dv_numerator / border_width; + t = select(point.y, point.x, is_horizontal) * dash_velocity; + max_t = select(size.y, size.x, is_horizontal) * dash_velocity; + } else { + // When corners are rounded, the dashes are laid out clockwise + // around the whole perimeter. + + let r_tr = quad.corner_radii.top_right; + let r_br = quad.corner_radii.bottom_right; + let r_bl = quad.corner_radii.bottom_left; + let r_tl = quad.corner_radii.top_left; + + let w_t = quad.border_widths.top; + let w_r = quad.border_widths.right; + let w_b = quad.border_widths.bottom; + let w_l = quad.border_widths.left; + + // Straight side dash velocities + let dv_t = select(dv_numerator / w_t, 0.0, w_t <= 0.0); + let dv_r = select(dv_numerator / w_r, 0.0, w_r <= 0.0); + let dv_b = select(dv_numerator / w_b, 0.0, w_b <= 0.0); + let dv_l = select(dv_numerator / w_l, 0.0, w_l <= 0.0); + + // Straight side lengths in dash space + let s_t = (size.x - r_tl - r_tr) * dv_t; + let s_r = (size.y - r_tr - r_br) * dv_r; + let s_b = (size.x - r_br - r_bl) * dv_b; + let s_l = (size.y - r_bl - r_tl) * dv_l; + + let corner_dash_velocity_tr = corner_dash_velocity(dv_t, dv_r); + let corner_dash_velocity_br = corner_dash_velocity(dv_b, dv_r); + let corner_dash_velocity_bl = corner_dash_velocity(dv_b, dv_l); + let corner_dash_velocity_tl = corner_dash_velocity(dv_t, dv_l); + + // Corner lengths in dash space + let c_tr = r_tr * (M_PI_F / 2.0) * corner_dash_velocity_tr; + let c_br = r_br * (M_PI_F / 2.0) * corner_dash_velocity_br; + let c_bl = r_bl * (M_PI_F / 2.0) * corner_dash_velocity_bl; + let c_tl = r_tl * (M_PI_F / 2.0) * corner_dash_velocity_tl; + + // Cumulative dash space upto each segment + let upto_tr = s_t; + let upto_r = upto_tr + c_tr; + let upto_br = upto_r + s_r; + let upto_b = upto_br + c_br; + let upto_bl = upto_b + s_b; + let upto_l = upto_bl + c_bl; + let upto_tl = upto_l + s_l; + max_t = upto_tl + c_tl; + + if (is_near_rounded_corner) { + let radians = atan2(corner_center_to_point.y, + corner_center_to_point.x); + let corner_t = radians * corner_radius; + + if (center_to_point.x >= 0.0) { + if (center_to_point.y < 0.0) { + dash_velocity = corner_dash_velocity_tr; + // Subtracted because radians is pi/2 to 0 when + // going clockwise around the top right corner, + // since the y axis has been flipped + t = upto_r - corner_t * dash_velocity; + } else { + dash_velocity = corner_dash_velocity_br; + // Added because radians is 0 to pi/2 when going + // clockwise around the bottom-right corner + t = upto_br + corner_t * dash_velocity; + } + } else { + if (center_to_point.y >= 0.0) { + dash_velocity = corner_dash_velocity_bl; + // Subtracted because radians is pi/2 to 0 when + // going clockwise around the bottom-left corner, + // since the x axis has been flipped + t = upto_l - corner_t * dash_velocity; + } else { + dash_velocity = corner_dash_velocity_tl; + // Added because radians is 0 to pi/2 when going + // clockwise around the top-left corner, since both + // axis were flipped + t = upto_tl + corner_t * dash_velocity; + } + } + } else { + // Straight borders + let is_horizontal = + corner_center_to_point.x < + corner_center_to_point.y; + if (is_horizontal) { + if (center_to_point.y < 0.0) { + dash_velocity = dv_t; + t = (point.x - r_tl) * dash_velocity; + } else { + dash_velocity = dv_b; + t = upto_bl - (point.x - r_bl) * dash_velocity; + } + } else { + if (center_to_point.x < 0.0) { + dash_velocity = dv_l; + t = upto_tl - (point.y - r_tl) * dash_velocity; + } else { + dash_velocity = dv_r; + t = upto_r + (point.y - r_tr) * dash_velocity; + } + } + } + } + + let dash_length = dash_length_per_width / dash_period_per_width; + let desired_dash_gap = dash_gap_per_width / dash_period_per_width; + + // Straight borders should start and end with a dash, so max_t is + // reduced to cause this. + max_t -= select(0.0, dash_length, unrounded); + if (max_t >= 1.0) { + // Adjust dash gap to evenly divide max_t. + let dash_count = floor(max_t); + let dash_period = max_t / dash_count; + border_color.a *= dash_alpha( + t, + dash_period, + dash_length, + dash_velocity, + antialias_threshold); + } else if (unrounded) { + // When there isn't enough space for the full gap between the + // two start / end dashes of a straight border, reduce gap to + // make them fit. + let dash_gap = max_t - dash_length; + if (dash_gap > 0.0) { + let dash_period = dash_length + dash_gap; + border_color.a *= dash_alpha( + t, + dash_period, + dash_length, + dash_velocity, + antialias_threshold); + } + } + } + + // Blend the border on top of the background and then linearly interpolate + // between the two as we slide inside the background. + let blended_border = over(background_color, border_color); + color = mix(background_color, blended_border, + saturate(antialias_threshold - inner_sdf)); + } + + return blend_color(color, saturate(antialias_threshold - outer_sdf)); +} + +// Returns the dash velocity of a corner given the dash velocity of the two +// sides, by returning the slower velocity (larger dashes). +// +// Since 0 is used for dash velocity when the border width is 0 (instead of +// +inf), this returns the other dash velocity in that case. +// +// An alternative to this might be to appropriately interpolate the dash +// velocity around the corner, but that seems overcomplicated. +fn corner_dash_velocity(dv1: f32, dv2: f32) -> f32 { + if (dv1 == 0.0) { + return dv2; + } else if (dv2 == 0.0) { + return dv1; + } else { + return min(dv1, dv2); + } +} + +// Returns alpha used to render antialiased dashes. +// `t` is within the dash when `fmod(t, period) < length`. +fn dash_alpha(t: f32, period: f32, length: f32, dash_velocity: f32, antialias_threshold: f32) -> f32 { + let half_period = period / 2; + let half_length = length / 2; + // Value in [-half_period, half_period]. + // The dash is in [-half_length, half_length]. + let centered = fmod(t + half_period - half_length, period) - half_period; + // Signed distance for the dash, negative values are inside the dash. + let signed_distance = abs(centered) - half_length; + // Antialiased alpha based on the signed distance. + return saturate(antialias_threshold - signed_distance / dash_velocity); +} + +// This approximates distance to the nearest point to a quarter ellipse in a way +// that is sufficient for anti-aliasing when the ellipse is not very eccentric. +// The components of `point` are expected to be positive. +// +// Negative on the outside and positive on the inside. +fn quarter_ellipse_sdf(point: vec2, radii: vec2) -> f32 { + // Scale the space to treat the ellipse like a unit circle. + let circle_vec = point / radii; + let unit_circle_sdf = length(circle_vec) - 1.0; + // Approximate up-scaling of the length by using the average of the radii. + // + // TODO: A better solution would be to use the gradient of the implicit + // function for an ellipse to approximate a scaling factor. + return unit_circle_sdf * (radii.x + radii.y) * -0.5; +} + +// Modulus that has the same sign as `a`. +fn fmod(a: f32, b: f32) -> f32 { + return a - b * trunc(a / b); +} + +// --- shadows --- // + +struct Shadow { + order: u32, + blur_radius: f32, + // The shadow rect for drop shadows; the "hole" rect for inset shadows. + bounds: Bounds, + corner_radii: Corners, + content_mask: Bounds, + color: Hsla, + // Only consulted when `inset == 1u`: the element's own bounds, used as a rounded-rect + // clip so the shadow never escapes the element. + element_bounds: Bounds, + element_corner_radii: Corners, + // 0 = drop shadow, 1 = inset shadow. + inset: u32, + pad: u32, // align to 8 bytes +} + +struct ShadowVarying { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) color: vec4, + @location(1) @interpolate(flat) shadow_id: u32, + //TODO: use `clip_distance` once Naga supports it + @location(3) clip_distances: vec4, +} + +@vertex +fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> ShadowVarying { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + var shadow = load_shadow(instance_id); + + var geometry: Bounds; + if (shadow.inset != 0u) { + geometry = shadow.element_bounds; + } else { + // Leave room for the gaussian tail outside the shadow rect. + let margin = 3.0 * shadow.blur_radius; + geometry = shadow.bounds; + geometry.origin -= vec2(margin); + geometry.size += 2.0 * vec2(margin); + } + + var out = ShadowVarying(); + out.position = to_device_position(unit_vertex, geometry); + out.color = hsla_to_rgba(shadow.color); + out.shadow_id = instance_id; + out.clip_distances = distance_from_clip_rect(unit_vertex, geometry, shadow.content_mask); + return out; +} + +@fragment +fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { + // Alpha clip first, since we don't have `clip_distance`. + if (any(input.clip_distances < vec4(0.0))) { + return vec4(0.0); + } + + let shadow = load_shadow(input.shadow_id); + let half_size = shadow.bounds.size / 2.0; + let center = shadow.bounds.origin + half_size; + let center_to_point = input.position.xy - center; + + let corner_radius = pick_corner_radius(center_to_point, shadow.corner_radii); + + var alpha: f32; + if (shadow.blur_radius == 0.0) { + let distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); + alpha = saturate(0.5 - distance); + } else { + // The signal is only non-zero in a limited range, so don't waste samples + let low = center_to_point.y - half_size.y; + let high = center_to_point.y + half_size.y; + let start = clamp(-3.0 * shadow.blur_radius, low, high); + let end = clamp(3.0 * shadow.blur_radius, low, high); + + // Accumulate samples (we can get away with surprisingly few samples) + let step = (end - start) / 4.0; + var y = start + step * 0.5; + alpha = 0.0; + for (var i = 0; i < 4; i += 1) { + let blur = blur_along_x(center_to_point.x, center_to_point.y - y, + shadow.blur_radius, corner_radius, half_size); + alpha += blur * gaussian(y, shadow.blur_radius) * step; + y += step; + } + } + + if (shadow.inset != 0u) { + // The inset shadow is the complement of the (blurred) hole rect, clipped to the element. + // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0. + alpha = 1.0 - alpha; + let element_distance = quad_sdf(input.position.xy, shadow.element_bounds, + shadow.element_corner_radii); + alpha *= saturate(0.5 - element_distance); + } + + return blend_color(input.color, alpha); +} + +// --- path rasterization --- // + +struct PathRasterizationVertex { + xy_position: vec2, + st_position: vec2, + color: Background, + bounds: Bounds, +} + + + +struct PathRasterizationVarying { + @builtin(position) position: vec4, + @location(0) st_position: vec2, + @location(1) @interpolate(flat) vertex_id: u32, + //TODO: use `clip_distance` once Naga supports it + @location(3) clip_distances: vec4, +} + +@vertex +fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasterizationVarying { + let v = load_path_vertex(vertex_id); + + var out = PathRasterizationVarying(); + out.position = to_device_position_impl(v.xy_position); + out.st_position = v.st_position; + out.vertex_id = vertex_id; + out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.bounds); + return out; +} + +@fragment +fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) vec4 { + let dx = dpdx(input.st_position); + let dy = dpdy(input.st_position); + if (any(input.clip_distances < vec4(0.0))) { + return vec4(0.0); + } + + let v = load_path_vertex(input.vertex_id); + let background = v.color; + let bounds = v.bounds; + + var alpha: f32; + if (length(vec2(dx.x, dy.x)) < 0.001) { + // If the gradient is too small, return a solid color. + alpha = 1.0; + } else { + let gradient = 2.0 * input.st_position.xx * vec2(dx.x, dy.x) - vec2(dx.y, dy.y); + let f = input.st_position.x * input.st_position.x - input.st_position.y; + let distance = f / length(gradient); + alpha = saturate(0.5 - distance); + } + let prepared_gradient = prepare_gradient_color( + background.tag, + background.color_space, + background.solid, + background.colors, + ); + let color = gradient_color(background, input.position.xy, bounds, + prepared_gradient.solid, prepared_gradient.color0, prepared_gradient.color1); + return vec4(color.rgb * color.a * alpha, color.a * alpha); +} + +// --- paths --- // + +struct PathSprite { + bounds: Bounds, +} + + +struct PathVarying { + @builtin(position) position: vec4, + @location(0) texture_coords: vec2, +} + +@vertex +fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let sprite = load_path_sprite(instance_id); + // Don't apply content mask because it was already accounted for when rasterizing the path. + let device_position = to_device_position(unit_vertex, sprite.bounds); + // For screen-space intermediate texture, convert screen position to texture coordinates + let screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size; + let texture_coords = screen_position / globals.viewport_size; + + var out = PathVarying(); + out.position = device_position; + out.texture_coords = texture_coords; + + return out; +} + +@fragment +fn fs_path(input: PathVarying) -> @location(0) vec4 { + let sample = textureSample(t_sprite, s_sprite, input.texture_coords); + return sample; +} + +// --- underlines --- // + +struct Underline { + order: u32, + pad: u32, + bounds: Bounds, + content_mask: Bounds, + color: Hsla, + thickness: f32, + wavy: u32, +} + + +struct UnderlineVarying { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) color: vec4, + @location(1) @interpolate(flat) underline_id: u32, + //TODO: use `clip_distance` once Naga supports it + @location(3) clip_distances: vec4, +} + +@vertex +fn vs_underline(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> UnderlineVarying { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let underline = load_underline(instance_id); + + var out = UnderlineVarying(); + out.position = to_device_position(unit_vertex, underline.bounds); + out.color = hsla_to_rgba(underline.color); + out.underline_id = instance_id; + out.clip_distances = distance_from_clip_rect(unit_vertex, underline.bounds, underline.content_mask); + return out; +} + +@fragment +fn fs_underline(input: UnderlineVarying) -> @location(0) vec4 { + const WAVE_FREQUENCY: f32 = 2.0; + const WAVE_HEIGHT_RATIO: f32 = 0.8; + + // Alpha clip first, since we don't have `clip_distance`. + if (any(input.clip_distances < vec4(0.0))) { + return vec4(0.0); + } + + let underline = load_underline(input.underline_id); + if (underline.wavy == 0u) + { + return blend_color(input.color, input.color.a); + } + + let half_thickness = underline.thickness * 0.5; + + let st = (input.position.xy - underline.bounds.origin) / underline.bounds.size.y - vec2(0.0, 0.5); + let frequency = M_PI_F * WAVE_FREQUENCY * underline.thickness / underline.bounds.size.y; + let amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y; + + let sine = sin(st.x * frequency) * amplitude; + let dSine = cos(st.x * frequency) * amplitude * frequency; + let distance = (st.y - sine) / sqrt(1.0 + dSine * dSine); + let distance_in_pixels = distance * underline.bounds.size.y; + let distance_from_top_border = distance_in_pixels - half_thickness; + let distance_from_bottom_border = distance_in_pixels + half_thickness; + let alpha = saturate(0.5 - max(-distance_from_bottom_border, distance_from_top_border)); + return blend_color(input.color, alpha * input.color.a); +} + +// --- monochrome sprites --- // + +struct MonochromeSprite { + order: u32, + pad: u32, + bounds: Bounds, + content_mask: Bounds, + color: Hsla, + tile: AtlasTile, + transformation: TransformationMatrix, +} + + +struct MonoSpriteVarying { + @builtin(position) position: vec4, + @location(0) tile_position: vec2, + @location(1) @interpolate(flat) color: vec4, + @location(3) clip_distances: vec4, +} + +@vertex +fn vs_mono_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> MonoSpriteVarying { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let sprite = load_mono_sprite(instance_id); + + var out = MonoSpriteVarying(); + out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation); + + out.tile_position = to_tile_position(unit_vertex, sprite.tile); + out.color = hsla_to_rgba(sprite.color); + out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation); + return out; +} + +@fragment +fn fs_mono_sprite(input: MonoSpriteVarying) -> @location(0) vec4 { + let sample = textureSample(t_sprite, s_sprite, input.tile_position).r; + let alpha_corrected = apply_contrast_and_gamma_correction(sample, input.color.rgb, gamma_params.grayscale_enhanced_contrast, gamma_params.gamma_ratios); + + // Alpha clip after using the derivatives. + if (any(input.clip_distances < vec4(0.0))) { + return vec4(0.0); + } + + return blend_color(input.color, alpha_corrected); +} + +// --- polychrome sprites --- // + +struct PolychromeSprite { + order: u32, + pad: u32, + grayscale: u32, + opacity: f32, + bounds: Bounds, + content_mask: Bounds, + corner_radii: Corners, + tile: AtlasTile, +} + + +struct PolySpriteVarying { + @builtin(position) position: vec4, + @location(0) tile_position: vec2, + @location(1) @interpolate(flat) sprite_id: u32, + @location(3) clip_distances: vec4, +} + +@vertex +fn vs_poly_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PolySpriteVarying { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let sprite = load_poly_sprite(instance_id); + + var out = PolySpriteVarying(); + out.position = to_device_position(unit_vertex, sprite.bounds); + out.tile_position = to_tile_position(unit_vertex, sprite.tile); + out.sprite_id = instance_id; + out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask); + return out; +} + +@fragment +fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4 { + let sample = textureSample(t_sprite, s_sprite, input.tile_position); + // Alpha clip after using the derivatives. + if (any(input.clip_distances < vec4(0.0))) { + return vec4(0.0); + } + + let sprite = load_poly_sprite(input.sprite_id); + let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); + + var color = sample; + if (sprite.grayscale != 0u) { + let grayscale = dot(color.rgb, GRAYSCALE_FACTORS); + color = vec4(vec3(grayscale), sample.a); + } + return blend_color(color, sprite.opacity * saturate(0.5 - distance)); +} + +// --- surfaces --- // + +struct SurfaceParams { + bounds: Bounds, + content_mask: Bounds, +} + +@group(1) @binding(0) var surface_locals: SurfaceParams; +@group(1) @binding(1) var t_y: texture_2d; +@group(1) @binding(2) var t_cb_cr: texture_2d; +@group(1) @binding(3) var s_surface: sampler; + +const ycbcr_to_RGB = mat4x4( + vec4( 1.0000f, 1.0000f, 1.0000f, 0.0), + vec4( 0.0000f, -0.3441f, 1.7720f, 0.0), + vec4( 1.4020f, -0.7141f, 0.0000f, 0.0), + vec4(-0.7010f, 0.5291f, -0.8860f, 1.0), +); + +struct SurfaceVarying { + @builtin(position) position: vec4, + @location(0) texture_position: vec2, + @location(3) clip_distances: vec4, +} + +@vertex +fn vs_surface(@builtin(vertex_index) vertex_id: u32) -> SurfaceVarying { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + + var out = SurfaceVarying(); + out.position = to_device_position(unit_vertex, surface_locals.bounds); + out.texture_position = unit_vertex; + out.clip_distances = distance_from_clip_rect(unit_vertex, surface_locals.bounds, surface_locals.content_mask); + return out; +} + +@fragment +fn fs_surface(input: SurfaceVarying) -> @location(0) vec4 { + // Alpha clip after using the derivatives. + if (any(input.clip_distances < vec4(0.0))) { + return vec4(0.0); + } + + let y_cb_cr = vec4( + textureSampleLevel(t_y, s_surface, input.texture_position, 0.0).r, + textureSampleLevel(t_cb_cr, s_surface, input.texture_position, 0.0).rg, + 1.0); + + return ycbcr_to_RGB * y_cb_cr; +} diff --git a/vendor/gpui-wgpu/src/shaders_storage.wgsl b/vendor/gpui-wgpu/src/shaders_storage.wgsl new file mode 100644 index 0000000..55b8080 --- /dev/null +++ b/vendor/gpui-wgpu/src/shaders_storage.wgsl @@ -0,0 +1,42 @@ +// Storage-buffer instance transport. Concatenated after `shaders.wgsl` on backends +// with storage buffer support; `shaders_webgl.wgsl` is the WebGL2 counterpart that +// decodes the same records from a texture instead. +// +// All buffers share `@group(1) @binding(0)` because each pipeline binds only the +// buffer its own entry points read. + +@group(1) @binding(0) var b_quads: array; +@group(1) @binding(0) var b_shadows: array; +@group(1) @binding(0) var b_path_vertices: array; +@group(1) @binding(0) var b_path_sprites: array; +@group(1) @binding(0) var b_underlines: array; +@group(1) @binding(0) var b_mono_sprites: array; +@group(1) @binding(0) var b_poly_sprites: array; + +fn load_quad(instance_id: u32) -> Quad { + return b_quads[instance_id]; +} + +fn load_shadow(instance_id: u32) -> Shadow { + return b_shadows[instance_id]; +} + +fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex { + return b_path_vertices[vertex_id]; +} + +fn load_path_sprite(instance_id: u32) -> PathSprite { + return b_path_sprites[instance_id]; +} + +fn load_underline(instance_id: u32) -> Underline { + return b_underlines[instance_id]; +} + +fn load_mono_sprite(instance_id: u32) -> MonochromeSprite { + return b_mono_sprites[instance_id]; +} + +fn load_poly_sprite(instance_id: u32) -> PolychromeSprite { + return b_poly_sprites[instance_id]; +} diff --git a/vendor/gpui-wgpu/src/shaders_subpixel.wgsl b/vendor/gpui-wgpu/src/shaders_subpixel.wgsl new file mode 100644 index 0000000..8fd9364 --- /dev/null +++ b/vendor/gpui-wgpu/src/shaders_subpixel.wgsl @@ -0,0 +1,56 @@ +// --- subpixel sprites --- // + +struct SubpixelSprite { + order: u32, + pad: u32, + bounds: Bounds, + content_mask: Bounds, + color: Hsla, + tile: AtlasTile, + transformation: TransformationMatrix, +} +@group(1) @binding(0) var b_subpixel_sprites: array; + +struct SubpixelSpriteOutput { + @builtin(position) position: vec4, + @location(0) tile_position: vec2, + @location(1) @interpolate(flat) color: vec4, + @location(3) clip_distances: vec4, +} + +struct SubpixelSpriteFragmentOutput { + @location(0) @blend_src(0) foreground: vec4, + @location(0) @blend_src(1) alpha: vec4, +} + +@vertex +fn vs_subpixel_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> SubpixelSpriteOutput { + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let sprite = b_subpixel_sprites[instance_id]; + + var out = SubpixelSpriteOutput(); + out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation); + out.tile_position = to_tile_position(unit_vertex, sprite.tile); + out.color = hsla_to_rgba(sprite.color); + out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation); + return out; +} + +@fragment +fn fs_subpixel_sprite(input: SubpixelSpriteOutput) -> SubpixelSpriteFragmentOutput { + var sample = textureSample(t_sprite, s_sprite, input.tile_position).rgb; + if (gamma_params.is_bgr != 0u) { + sample = sample.bgr; + } + let alpha_corrected = apply_contrast_and_gamma_correction3(sample, input.color.rgb, gamma_params.subpixel_enhanced_contrast, gamma_params.gamma_ratios); + + // Alpha clip after using the derivatives. + if (any(input.clip_distances < vec4(0.0))) { + return SubpixelSpriteFragmentOutput(vec4(0.0), vec4(0.0)); + } + + var out = SubpixelSpriteFragmentOutput(); + out.foreground = vec4(input.color.rgb, 1.0); + out.alpha = vec4(input.color.a * alpha_corrected, 1.0); + return out; +} diff --git a/vendor/gpui-wgpu/src/shaders_webgl.wgsl b/vendor/gpui-wgpu/src/shaders_webgl.wgsl new file mode 100644 index 0000000..bf5f629 --- /dev/null +++ b/vendor/gpui-wgpu/src/shaders_webgl.wgsl @@ -0,0 +1,262 @@ +@group(1) @binding(0) var t_instances: texture_2d; + +// Each texel of `t_instances` packs four 32-bit words of instance data. Most +// records are read strictly front to back through a cursor that keeps the +// most recently fetched texel and only touches the texture again when the next +// word crosses a texel boundary. This fetches each texel exactly once per +// record load instead of once per word. The `read_*` functions must therefore +// consume their words in struct declaration order; skipping or re-reading words +// would still return correct data (the cursor re-fetches whenever the texel +// index changes) but would forfeit the single-fetch-per-texel guarantee. +struct InstanceCursor { + word_index: u32, + texel_index: u32, + texel: vec4, + width: u32, +} + +fn fetch_instance_texel(texel_index: u32, width: u32) -> vec4 { + let coordinate = vec2( + i32(texel_index % width), + i32(texel_index / width), + ); + return textureLoad(t_instances, coordinate, 0); +} + +fn instance_cursor(word_index: u32) -> InstanceCursor { + let width = textureDimensions(t_instances).x; + let texel_index = word_index / 4u; + return InstanceCursor( + word_index, + texel_index, + fetch_instance_texel(texel_index, width), + width, + ); +} + +fn read_word(cursor: ptr) -> u32 { + let word_index = (*cursor).word_index; + let texel_index = word_index / 4u; + if texel_index != (*cursor).texel_index { + (*cursor).texel = fetch_instance_texel(texel_index, (*cursor).width); + (*cursor).texel_index = texel_index; + } + (*cursor).word_index = word_index + 1u; + return (*cursor).texel[word_index % 4u]; +} + +fn read_f32(cursor: ptr) -> f32 { + return bitcast(read_word(cursor)); +} + +fn read_i32(cursor: ptr) -> i32 { + return bitcast(read_word(cursor)); +} + +fn read_vec2_f32(cursor: ptr) -> vec2 { + return vec2(read_f32(cursor), read_f32(cursor)); +} + +fn read_vec2_i32(cursor: ptr) -> vec2 { + return vec2(read_i32(cursor), read_i32(cursor)); +} + +fn read_hsla(cursor: ptr) -> Hsla { + return Hsla( + read_f32(cursor), + read_f32(cursor), + read_f32(cursor), + read_f32(cursor), + ); +} + +fn read_bounds(cursor: ptr) -> Bounds { + return Bounds(read_vec2_f32(cursor), read_vec2_f32(cursor)); +} + +fn read_corners(cursor: ptr) -> Corners { + return Corners( + read_f32(cursor), + read_f32(cursor), + read_f32(cursor), + read_f32(cursor), + ); +} + +fn read_edges(cursor: ptr) -> Edges { + return Edges( + read_f32(cursor), + read_f32(cursor), + read_f32(cursor), + read_f32(cursor), + ); +} + +fn read_color_stop(cursor: ptr) -> LinearColorStop { + return LinearColorStop(read_hsla(cursor), read_f32(cursor)); +} + +fn read_background(cursor: ptr) -> Background { + return Background( + read_word(cursor), + read_word(cursor), + read_hsla(cursor), + read_f32(cursor), + array( + read_color_stop(cursor), + read_color_stop(cursor), + ), + read_word(cursor), + ); +} + +fn read_atlas_tile(cursor: ptr) -> AtlasTile { + return AtlasTile( + AtlasTextureId( + read_word(cursor), + read_word(cursor), + ), + read_word(cursor), + read_word(cursor), + AtlasBounds( + read_vec2_i32(cursor), + read_vec2_i32(cursor), + ), + ); +} + +fn read_transformation(cursor: ptr) -> TransformationMatrix { + return TransformationMatrix( + mat2x2( + read_vec2_f32(cursor), + read_vec2_f32(cursor), + ), + read_vec2_f32(cursor), + ); +} + +fn load_quad(instance_id: u32) -> Quad { + // Keep this fixed-layout decoder explicit. Some WebGL shader compilers fail + // to optimize the cursor's branches and dynamic vector indexing for quads. + let first_texel_index = instance_id * 10u; + let width = textureDimensions(t_instances).x; + let texel0 = fetch_instance_texel(first_texel_index, width); + let texel1 = fetch_instance_texel(first_texel_index + 1u, width); + let texel2 = fetch_instance_texel(first_texel_index + 2u, width); + let texel3 = fetch_instance_texel(first_texel_index + 3u, width); + let texel4 = fetch_instance_texel(first_texel_index + 4u, width); + let texel5 = fetch_instance_texel(first_texel_index + 5u, width); + let texel6 = fetch_instance_texel(first_texel_index + 6u, width); + let texel7 = fetch_instance_texel(first_texel_index + 7u, width); + let texel8 = fetch_instance_texel(first_texel_index + 8u, width); + let texel9 = fetch_instance_texel(first_texel_index + 9u, width); + + let values0 = bitcast>(texel0); + let values1 = bitcast>(texel1); + let values2 = bitcast>(texel2); + let values3 = bitcast>(texel3); + let values4 = bitcast>(texel4); + let values5 = bitcast>(texel5); + let values6 = bitcast>(texel6); + let values7 = bitcast>(texel7); + let values8 = bitcast>(texel8); + let values9 = bitcast>(texel9); + + return Quad( + texel0.x, + texel0.y, + Bounds(values0.zw, values1.xy), + Bounds(values1.zw, values2.xy), + Background( + texel2.z, + texel2.w, + Hsla(values3.x, values3.y, values3.z, values3.w), + values4.x, + array( + LinearColorStop( + Hsla(values4.y, values4.z, values4.w, values5.x), + values5.y, + ), + LinearColorStop( + Hsla(values5.z, values5.w, values6.x, values6.y), + values6.z, + ), + ), + texel6.w, + ), + Hsla(values7.x, values7.y, values7.z, values7.w), + Corners(values8.x, values8.y, values8.z, values8.w), + Edges(values9.x, values9.y, values9.z, values9.w), + ); +} + +fn load_shadow(instance_id: u32) -> Shadow { + var cursor = instance_cursor(instance_id * 28u); + return Shadow( + read_word(&cursor), + read_f32(&cursor), + read_bounds(&cursor), + read_corners(&cursor), + read_bounds(&cursor), + read_hsla(&cursor), + read_bounds(&cursor), + read_corners(&cursor), + read_word(&cursor), + read_word(&cursor), + ); +} + +fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex { + var cursor = instance_cursor(vertex_id * 26u); + return PathRasterizationVertex( + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_background(&cursor), + read_bounds(&cursor), + ); +} + +fn load_path_sprite(instance_id: u32) -> PathSprite { + var cursor = instance_cursor(instance_id * 4u); + return PathSprite(read_bounds(&cursor)); +} + +fn load_underline(instance_id: u32) -> Underline { + var cursor = instance_cursor(instance_id * 16u); + return Underline( + read_word(&cursor), + read_word(&cursor), + read_bounds(&cursor), + read_bounds(&cursor), + read_hsla(&cursor), + read_f32(&cursor), + read_word(&cursor), + ); +} + +fn load_mono_sprite(instance_id: u32) -> MonochromeSprite { + var cursor = instance_cursor(instance_id * 28u); + return MonochromeSprite( + read_word(&cursor), + read_word(&cursor), + read_bounds(&cursor), + read_bounds(&cursor), + read_hsla(&cursor), + read_atlas_tile(&cursor), + read_transformation(&cursor), + ); +} + +fn load_poly_sprite(instance_id: u32) -> PolychromeSprite { + var cursor = instance_cursor(instance_id * 24u); + return PolychromeSprite( + read_word(&cursor), + read_word(&cursor), + read_word(&cursor), + read_f32(&cursor), + read_bounds(&cursor), + read_bounds(&cursor), + read_corners(&cursor), + read_atlas_tile(&cursor), + ); +} diff --git a/vendor/gpui-wgpu/src/wgpu_atlas.rs b/vendor/gpui-wgpu/src/wgpu_atlas.rs new file mode 100644 index 0000000..b541607 --- /dev/null +++ b/vendor/gpui-wgpu/src/wgpu_atlas.rs @@ -0,0 +1,566 @@ +use anyhow::{Context as _, Result}; +use etagere::{BucketedAtlasAllocator, size2}; +use gpui::{ + AtlasBackend, AtlasKey, AtlasState, AtlasTextureId, AtlasTextureKind, AtlasTextureList, + AtlasTile, Bounds, DevicePixels, PlatformAtlas, Point, Size, +}; +use parking_lot::Mutex; +use std::{borrow::Cow, ops, sync::Arc}; + +use crate::WgpuContext; + +fn device_size_to_etagere(size: Size) -> etagere::Size { + size2(size.width.0, size.height.0) +} + +fn etagere_point_to_device(point: etagere::Point) -> Point { + Point { + x: DevicePixels(point.x), + y: DevicePixels(point.y), + } +} + +pub struct WgpuAtlas(Mutex>); + +struct PendingUpload { + id: AtlasTextureId, + bounds: Bounds, + data: Vec, +} + +struct WgpuAtlasTextures { + device: Arc, + queue: Arc, + max_texture_size: u32, + color_texture_format: wgpu::TextureFormat, + storage: WgpuAtlasStorage, + pending_uploads: Vec, + next_texture_generation: u64, +} + +pub struct WgpuTextureInfo { + pub view: wgpu::TextureView, + /// Distinguishes new textures that reuse an [`AtlasTextureId`]. + pub generation: u64, +} + +impl WgpuAtlas { + pub fn new( + device: Arc, + queue: Arc, + color_texture_format: wgpu::TextureFormat, + ) -> Self { + let max_texture_size = device.limits().max_texture_dimension_2d; + WgpuAtlas(Mutex::new(AtlasState::new(WgpuAtlasTextures { + device, + queue, + max_texture_size, + color_texture_format, + storage: WgpuAtlasStorage::default(), + pending_uploads: Vec::new(), + next_texture_generation: 0, + }))) + } + + pub fn from_context(context: &WgpuContext) -> Self { + Self::new( + context.device.clone(), + context.queue.clone(), + context.color_texture_format(), + ) + } + + pub fn before_frame(&self) { + let mut lock = self.0.lock(); + lock.backend.flush_uploads(); + } + + /// Returns the view backing `id`, or `None` once every tile in it has been + /// removed. A scene can still reference such a texture when a cached view + /// replays a paint from before the image was dropped, so callers must skip + /// those sprites rather than assume the texture exists. + pub fn get_texture_info(&self, id: AtlasTextureId) -> Option { + let lock = self.0.lock(); + let texture = lock.backend.storage.get(id)?; + Some(WgpuTextureInfo { + view: texture.view.clone(), + generation: texture.generation, + }) + } + + /// Clears all cached textures and tiles, forcing them to be recreated. + /// Use this for incremental recovery when the device is still valid. + pub fn clear(&self) { + self.0.lock().clear(|textures| { + textures.storage = WgpuAtlasStorage::default(); + textures.pending_uploads.clear(); + }); + } + + /// Handles device lost by clearing all textures and cached tiles. + /// The atlas will lazily recreate textures as needed on subsequent frames. + pub fn handle_device_lost(&self, context: &WgpuContext) { + self.0.lock().clear(|textures| { + textures.device = context.device.clone(); + textures.queue = context.queue.clone(); + textures.color_texture_format = context.color_texture_format(); + textures.storage = WgpuAtlasStorage::default(); + textures.pending_uploads.clear(); + }); + } +} + +impl PlatformAtlas for WgpuAtlas { + fn get_or_insert_with<'a>( + &self, + key: AtlasKey, + build: &mut dyn FnMut() -> Result, Cow<'a, [u8]>)>>, + ) -> Result> { + self.0.lock().get_or_insert_with(key, build) + } + + fn remove(&self, key: &AtlasKey) { + self.0.lock().remove(key); + } +} + +impl AtlasBackend for WgpuAtlasTextures { + fn insert( + &mut self, + kind: AtlasTextureKind, + size: Size, + bytes: &[u8], + ) -> Result { + let tile = self.allocate(size, kind).context("failed to allocate")?; + self.upload_texture(tile.texture_id, tile.bounds, bytes); + Ok(tile) + } + + fn remove(&mut self, tile: AtlasTile) { + let id = tile.texture_id; + let Some(texture_slot) = self.storage[id.kind].textures.get_mut(id.index as usize) else { + return; + }; + + if let Some(mut texture) = texture_slot.take() { + texture.allocator.deallocate(tile.tile_id.into()); + texture.decrement_ref_count(); + if texture.is_unreferenced() { + self.pending_uploads + .retain(|upload| upload.id != texture.id); + self.storage[id.kind] + .free_list + .push(texture.id.index as usize); + } else { + *texture_slot = Some(texture); + } + } + } +} + +impl WgpuAtlasTextures { + fn allocate( + &mut self, + size: Size, + texture_kind: AtlasTextureKind, + ) -> Option { + { + let textures = &mut self.storage[texture_kind]; + + if let Some(tile) = textures + .iter_mut() + .rev() + .find_map(|texture| texture.allocate(size)) + { + return Some(tile); + } + } + + let texture = self.push_texture(size, texture_kind); + texture.allocate(size) + } + + fn push_texture( + &mut self, + min_size: Size, + kind: AtlasTextureKind, + ) -> &mut WgpuAtlasTexture { + const DEFAULT_ATLAS_SIZE: Size = Size { + width: DevicePixels(1024), + height: DevicePixels(1024), + }; + let max_texture_size = self.max_texture_size as i32; + let max_atlas_size = Size { + width: DevicePixels(max_texture_size), + height: DevicePixels(max_texture_size), + }; + + let size = min_size.min(&max_atlas_size).max(&DEFAULT_ATLAS_SIZE); + let format = match kind { + AtlasTextureKind::Monochrome => wgpu::TextureFormat::R8Unorm, + AtlasTextureKind::Subpixel | AtlasTextureKind::Polychrome => self.color_texture_format, + }; + + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("atlas"), + size: wgpu::Extent3d { + width: size.width.0 as u32, + height: size.height.0 as u32, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + + let texture_list = &mut self.storage[kind]; + let index = texture_list.free_list.pop(); + let generation = self.next_texture_generation; + self.next_texture_generation = self.next_texture_generation.wrapping_add(1); + + let atlas_texture = WgpuAtlasTexture { + id: AtlasTextureId { + index: index.unwrap_or(texture_list.textures.len()) as u32, + kind, + }, + generation, + allocator: BucketedAtlasAllocator::new(device_size_to_etagere(size)), + format, + texture, + view, + live_atlas_keys: 0, + }; + + if let Some(ix) = index { + texture_list.textures[ix] = Some(atlas_texture); + texture_list + .textures + .get_mut(ix) + .and_then(|t| t.as_mut()) + .expect("texture must exist") + } else { + texture_list.textures.push(Some(atlas_texture)); + texture_list + .textures + .last_mut() + .and_then(|t| t.as_mut()) + .expect("texture must exist") + } + } + + fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds, bytes: &[u8]) { + let data = self + .storage + .get(id) + .map(|texture| swizzle_upload_data(bytes, texture.format)) + .unwrap_or_else(|| bytes.to_vec()); + + self.pending_uploads + .push(PendingUpload { id, bounds, data }); + } + + fn flush_uploads(&mut self) { + for upload in self.pending_uploads.drain(..) { + let Some(texture) = self.storage.get(upload.id) else { + continue; + }; + let bytes_per_pixel = texture.bytes_per_pixel(); + + self.queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &texture.texture, + mip_level: 0, + origin: wgpu::Origin3d { + x: upload.bounds.origin.x.0 as u32, + y: upload.bounds.origin.y.0 as u32, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, + &upload.data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(upload.bounds.size.width.0 as u32 * bytes_per_pixel as u32), + rows_per_image: None, + }, + wgpu::Extent3d { + width: upload.bounds.size.width.0 as u32, + height: upload.bounds.size.height.0 as u32, + depth_or_array_layers: 1, + }, + ); + } + } +} + +#[derive(Default)] +struct WgpuAtlasStorage { + monochrome_textures: AtlasTextureList, + subpixel_textures: AtlasTextureList, + polychrome_textures: AtlasTextureList, +} + +impl ops::Index for WgpuAtlasStorage { + type Output = AtlasTextureList; + fn index(&self, kind: AtlasTextureKind) -> &Self::Output { + match kind { + AtlasTextureKind::Monochrome => &self.monochrome_textures, + AtlasTextureKind::Subpixel => &self.subpixel_textures, + AtlasTextureKind::Polychrome => &self.polychrome_textures, + } + } +} + +impl ops::IndexMut for WgpuAtlasStorage { + fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output { + match kind { + AtlasTextureKind::Monochrome => &mut self.monochrome_textures, + AtlasTextureKind::Subpixel => &mut self.subpixel_textures, + AtlasTextureKind::Polychrome => &mut self.polychrome_textures, + } + } +} + +impl WgpuAtlasStorage { + fn get(&self, id: AtlasTextureId) -> Option<&WgpuAtlasTexture> { + self[id.kind] + .textures + .get(id.index as usize) + .and_then(|t| t.as_ref()) + } +} + +struct WgpuAtlasTexture { + id: AtlasTextureId, + generation: u64, + allocator: BucketedAtlasAllocator, + texture: wgpu::Texture, + view: wgpu::TextureView, + format: wgpu::TextureFormat, + live_atlas_keys: u32, +} + +impl WgpuAtlasTexture { + fn allocate(&mut self, size: Size) -> Option { + let allocation = self.allocator.allocate(device_size_to_etagere(size))?; + let tile = AtlasTile { + texture_id: self.id, + tile_id: allocation.id.into(), + padding: 0, + bounds: Bounds { + origin: etagere_point_to_device(allocation.rectangle.min), + size, + }, + }; + self.live_atlas_keys += 1; + Some(tile) + } + + fn bytes_per_pixel(&self) -> u8 { + match self.format { + wgpu::TextureFormat::R8Unorm => 1, + wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm => 4, + _ => 4, + } + } + + fn decrement_ref_count(&mut self) { + self.live_atlas_keys -= 1; + } + + fn is_unreferenced(&self) -> bool { + self.live_atlas_keys == 0 + } +} + +fn swizzle_upload_data(bytes: &[u8], format: wgpu::TextureFormat) -> Vec { + match format { + wgpu::TextureFormat::Rgba8Unorm => { + let mut data = bytes.to_vec(); + for pixel in data.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + data + } + _ => bytes.to_vec(), + } +} + +#[cfg(all(test, not(target_family = "wasm")))] +mod tests { + use super::*; + use gpui::block_on; + use gpui::{ImageId, RenderImageParams}; + use std::sync::Arc; + + fn test_device_and_queue() -> anyhow::Result<(Arc, Arc)> { + block_on(async { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::all(), + flags: wgpu::InstanceFlags::default(), + backend_options: wgpu::BackendOptions::default(), + memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(), + display: None, + }); + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::LowPower, + compatible_surface: None, + force_fallback_adapter: false, + }) + .await + .map_err(|error| anyhow::anyhow!("failed to request adapter: {error}"))?; + let (device, queue) = adapter + .request_device(&wgpu::DeviceDescriptor { + label: Some("wgpu_atlas_test_device"), + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::downlevel_defaults() + .using_resolution(adapter.limits()) + .using_alignment(adapter.limits()), + memory_hints: wgpu::MemoryHints::MemoryUsage, + trace: wgpu::Trace::Off, + experimental_features: wgpu::ExperimentalFeatures::disabled(), + }) + .await + .map_err(|error| anyhow::anyhow!("failed to request device: {error}"))?; + Ok((Arc::new(device), Arc::new(queue))) + }) + } + + #[test] + fn before_frame_skips_uploads_for_removed_texture() -> anyhow::Result<()> { + let (device, queue) = test_device_and_queue()?; + + let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm); + let key = AtlasKey::Image(RenderImageParams { + image_id: ImageId(1), + frame_index: 0, + }); + let size = Size { + width: DevicePixels(1), + height: DevicePixels(1), + }; + let mut build = || Ok(Some((size, Cow::Owned(vec![0, 0, 0, 255])))); + + // Regression test: before the fix, this panicked in flush_uploads + atlas + .get_or_insert_with(key.clone(), &mut build)? + .expect("tile should be created"); + atlas.remove(&key); + atlas.before_frame(); + Ok(()) + } + + #[test] + fn remove_deallocates_tile_space_for_reuse() -> anyhow::Result<()> { + let (device, queue) = test_device_and_queue()?; + let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm); + + let small = Size { + width: DevicePixels(64), + height: DevicePixels(64), + }; + let big = Size { + width: DevicePixels(700), + height: DevicePixels(700), + }; + + let make_key = |image_id: usize| { + AtlasKey::Image(RenderImageParams { + image_id: ImageId(image_id), + frame_index: 0, + }) + }; + let insert = |key: AtlasKey, size: Size| { + let byte_count = (size.width.0 as usize) * (size.height.0 as usize) * 4; + atlas + .get_or_insert_with(key, &mut || { + Ok(Some((size, Cow::Owned(vec![0u8; byte_count])))) + }) + .expect("allocation should succeed") + .expect("callback returns Some") + }; + + let keeper_key = make_key(1); + let big_key_a = make_key(2); + let big_key_b = make_key(3); + + let keeper_tile = insert(keeper_key, small); + let tile_a = insert(big_key_a.clone(), big); + assert_eq!(keeper_tile.texture_id, tile_a.texture_id); + + atlas.remove(&big_key_a); + let tile_b = insert(big_key_b, big); + assert_eq!(tile_b.texture_id, keeper_tile.texture_id); + Ok(()) + } + + #[test] + fn reused_texture_id_has_new_generation() -> anyhow::Result<()> { + let (device, queue) = test_device_and_queue()?; + let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm); + let size = Size { + width: DevicePixels(700), + height: DevicePixels(700), + }; + let make_key = |image_id| { + AtlasKey::Image(RenderImageParams { + image_id: ImageId(image_id), + frame_index: 0, + }) + }; + let insert = |key: AtlasKey| { + atlas + .get_or_insert_with(key, &mut || { + Ok(Some(( + size, + Cow::Owned(vec![0; size.width.0 as usize * size.height.0 as usize * 4]), + ))) + }) + .expect("allocation should succeed") + .expect("callback returns Some") + }; + + let first_key = make_key(1); + let first_tile = insert(first_key.clone()); + let first_generation = atlas + .get_texture_info(first_tile.texture_id) + .context("first texture should exist")? + .generation; + atlas.remove(&first_key); + assert!(atlas.get_texture_info(first_tile.texture_id).is_none()); + + let second_tile = insert(make_key(2)); + let second_generation = atlas + .get_texture_info(second_tile.texture_id) + .context("second texture should exist")? + .generation; + + assert_eq!(second_tile.texture_id, first_tile.texture_id); + assert_ne!(second_generation, first_generation); + Ok(()) + } + + #[test] + fn swizzle_upload_data_preserves_bgra_uploads() { + let input = vec![0x10, 0x20, 0x30, 0x40]; + assert_eq!( + swizzle_upload_data(&input, wgpu::TextureFormat::Bgra8Unorm), + input + ); + } + + #[test] + fn swizzle_upload_data_converts_bgra_to_rgba() { + let input = vec![0x10, 0x20, 0x30, 0x40, 0xAA, 0xBB, 0xCC, 0xDD]; + assert_eq!( + swizzle_upload_data(&input, wgpu::TextureFormat::Rgba8Unorm), + vec![0x30, 0x20, 0x10, 0x40, 0xCC, 0xBB, 0xAA, 0xDD] + ); + } +} diff --git a/vendor/gpui-wgpu/src/wgpu_context.rs b/vendor/gpui-wgpu/src/wgpu_context.rs new file mode 100644 index 0000000..7a060c7 --- /dev/null +++ b/vendor/gpui-wgpu/src/wgpu_context.rs @@ -0,0 +1,841 @@ +#[cfg(not(target_family = "wasm"))] +use anyhow::Context as _; +#[cfg(not(target_family = "wasm"))] +use gpui_util::ResultExt; +use parking_lot::Mutex; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use wgpu::TextureFormat; + +#[derive(Clone)] +pub struct WgpuContext { + pub instance: wgpu::Instance, + pub adapter: wgpu::Adapter, + pub device: Arc, + pub queue: Arc, + backend: WgpuBackend, + dual_source_blending: bool, + color_texture_format: wgpu::TextureFormat, + errors: Arc, +} + +/// Errors reported by wgpu's device-wide callbacks. +/// +/// A device has exactly one lost callback and one uncaptured-error callback, so this +/// state is installed once per device and shared by every renderer using it. Renderers +/// keep their own handle so they can keep observing a loss after the context that +/// produced it has been dropped for recovery. +#[derive(Default)] +pub struct DeviceErrorState { + lost: AtomicBool, + last_error: Mutex<(u64, Option)>, +} + +impl DeviceErrorState { + fn install(device: &wgpu::Device) -> Arc { + let errors = Arc::new(Self::default()); + device.set_device_lost_callback({ + let errors = Arc::clone(&errors); + move |reason, message| { + log::error!("wgpu device lost: reason={reason:?}, message={message}"); + if reason != wgpu::DeviceLostReason::Destroyed { + errors.lost.store(true, Ordering::Relaxed); + } + } + }); + device.on_uncaptured_error(Arc::new({ + let errors = Arc::clone(&errors); + move |error| errors.record(error.to_string()) + })); + errors + } + + /// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume). + pub fn device_lost(&self) -> bool { + self.lost.load(Ordering::Relaxed) + } + + fn record(&self, error: String) { + let mut last_error = self.last_error.lock(); + last_error.0 = last_error.0.wrapping_add(1); + last_error.1 = Some(error); + } + + /// Returns the latest error once per observer, without consuming shared state. + /// Start each observer at zero, including after switching devices, so errors + /// raised during construction are observed. Multiple errors between observations + /// coalesce into the latest error; this is not an error queue. + pub fn observe_error(&self, generation: &mut u64) -> Option { + let last_error = self.last_error.lock(); + if *generation == last_error.0 { + return None; + } + *generation = last_error.0; + last_error.1.clone() + } + + /// The generation an observer should start from to see only errors raised after + /// this call, for a renderer joining a device other renderers already used. + pub fn current_generation(&self) -> u64 { + self.last_error.lock().0 + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum WgpuBackend { + BrowserWebGpu, + Gl, + Native(wgpu::Backend), +} + +#[cfg(target_family = "wasm")] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum WebBackendPreference { + #[default] + Auto, + WebGpu, + WebGl, +} + +#[cfg(target_family = "wasm")] +pub struct PreparedWebGraphics { + pub context: WgpuContext, + pub surface: wgpu::Surface<'static>, +} + +/// wgpu-core refuses to create a surface when neither the instance nor the surface +/// target carries a display handle, and `SurfaceTarget::Canvas` always passes `None`. +/// The WebGL2 backend never reads the handle (WebGPU bypasses wgpu-core entirely), so +/// a unit web display handle on the instance satisfies the check. +#[cfg(target_family = "wasm")] +#[derive(Debug)] +struct WebDisplaySource; + +#[cfg(target_family = "wasm")] +impl raw_window_handle::HasDisplayHandle for WebDisplaySource { + fn display_handle( + &self, + ) -> Result, raw_window_handle::HandleError> { + Ok(raw_window_handle::DisplayHandle::web()) + } +} + +#[derive(Clone, Copy)] +pub struct CompositorGpuHint { + pub vendor_id: u32, + pub device_id: u32, +} + +impl WgpuContext { + #[cfg(not(target_family = "wasm"))] + pub fn new( + instance: wgpu::Instance, + surface: &wgpu::Surface<'_>, + compositor_gpu: Option, + ) -> anyhow::Result { + Self::new_with_options(instance, surface, compositor_gpu, false) + } + + #[cfg(not(target_family = "wasm"))] + pub fn new_rejecting_software( + instance: wgpu::Instance, + surface: &wgpu::Surface<'_>, + compositor_gpu: Option, + ) -> anyhow::Result { + Self::new_with_options(instance, surface, compositor_gpu, true) + } + + #[cfg(not(target_family = "wasm"))] + fn new_with_options( + instance: wgpu::Instance, + surface: &wgpu::Surface<'_>, + compositor_gpu: Option, + reject_software: bool, + ) -> anyhow::Result { + let device_id_filter = Self::device_id_filter(); + + // Select an adapter by actually testing surface configuration with the real device. + // This is the only reliable way to determine compatibility on hybrid GPU systems. + let (adapter, device, queue, dual_source_blending, color_texture_format) = + gpui::block_on(Self::select_adapter_and_device( + &instance, + device_id_filter, + surface, + compositor_gpu.as_ref(), + reject_software, + ))?; + + Ok(Self::from_native_adapter_and_device( + instance, + adapter, + device, + queue, + dual_source_blending, + color_texture_format, + )) + } + + #[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") + ))] + pub(crate) fn new_headless() -> anyhow::Result<(Self, wgpu::TextureFormat)> { + // Creating a device takes tens of milliseconds, and benchmarks create a headless + // renderer for every window they open, so the process shares one device until it + // is lost. A static rather than a thread-local: the cached device is never dropped, + // because wgpu's queue reads its own thread-locals on drop and would panic if + // dropped while a thread's thread-locals are being destroyed. + static HEADLESS: Mutex> = Mutex::new(None); + let mut headless = HEADLESS.lock(); + if let Some((context, format)) = headless.as_ref() + && !context.device_lost() + { + return Ok((context.clone(), *format)); + } + let created = Self::create_headless()?; + *headless = Some(created.clone()); + Ok(created) + } + + #[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") + ))] + fn create_headless() -> anyhow::Result<(Self, wgpu::TextureFormat)> { + let instance = Self::instance(None); + let device_id_filter = Self::device_id_filter(); + let (adapter, device, queue, dual_source_blending, color_texture_format, target_format) = + gpui::block_on(async { + let mut adapters = instance.enumerate_adapters(wgpu::Backends::all()).await; + Self::sort_adapters(&mut adapters, device_id_filter, None); + + for adapter in adapters { + let adapter_info = adapter.get_info(); + let Some(target_format) = Self::headless_target_format(&adapter) else { + log::warn!( + "Adapter {:?} has no supported headless render target format", + adapter_info.name + ); + continue; + }; + + match Self::create_device(&adapter).await { + Ok((device, queue, dual_source_blending, color_texture_format)) => { + #[cfg(feature = "bench-support")] + if adapter_info.device_type == wgpu::DeviceType::Cpu { + log::error!( + "Headless renderer selected software adapter {:?}; \ + benchmark results measure CPU software rendering, not hardware GPU rendering", + adapter_info.name + ); + } + return Ok(( + adapter, + device, + queue, + dual_source_blending, + color_texture_format, + target_format, + )); + } + Err(error) => { + log::warn!( + "Failed to create a headless device for adapter {:?}: {error:#}", + adapter_info.name + ); + } + } + } + + anyhow::bail!("No usable headless GPU adapter found") + })?; + + Ok(( + Self::from_native_adapter_and_device( + instance, + adapter, + device, + queue, + dual_source_blending, + color_texture_format, + ), + target_format, + )) + } + + #[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") + ))] + /// Both candidates are 8-bit RGBA-ordered or BGRA-ordered formats: headless readback + /// copies rows as 4 bytes per pixel and only swizzles, so no other formats may be added + /// here without updating it. + fn headless_target_format(adapter: &wgpu::Adapter) -> Option { + let required_usages = + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC; + [ + wgpu::TextureFormat::Rgba8Unorm, + wgpu::TextureFormat::Bgra8Unorm, + ] + .into_iter() + .find(|format| { + adapter + .get_texture_format_features(*format) + .allowed_usages + .contains(required_usages) + }) + } + + #[cfg(not(target_family = "wasm"))] + fn from_native_adapter_and_device( + instance: wgpu::Instance, + adapter: wgpu::Adapter, + device: wgpu::Device, + queue: wgpu::Queue, + dual_source_blending: bool, + color_texture_format: TextureFormat, + ) -> Self { + let errors = DeviceErrorState::install(&device); + + log::info!( + "Selected GPU adapter: {:?} ({:?})", + adapter.get_info().name, + adapter.get_info().backend + ); + let backend = WgpuBackend::Native(adapter.get_info().backend); + + Self { + instance, + adapter, + device: Arc::new(device), + queue: Arc::new(queue), + backend, + dual_source_blending, + color_texture_format, + errors, + } + } + + #[cfg(not(target_family = "wasm"))] + fn device_id_filter() -> Option { + match std::env::var("ZED_DEVICE_ID") { + Ok(value) => parse_pci_id(&value) + .context("Failed to parse device ID from `ZED_DEVICE_ID` environment variable") + .log_err(), + Err(std::env::VarError::NotPresent) => None, + error => { + error + .context("Failed to read value of `ZED_DEVICE_ID` environment variable") + .log_err(); + None + } + } + } + + #[cfg(target_family = "wasm")] + pub async fn new_web( + canvas: &web_sys::HtmlCanvasElement, + preference: WebBackendPreference, + ) -> anyhow::Result { + Self::new_web_with_backend(canvas, preference).await + } + + #[cfg(target_family = "wasm")] + #[allow(clippy::arc_with_non_send_sync)] + async fn new_web_with_backend( + canvas: &web_sys::HtmlCanvasElement, + preference: WebBackendPreference, + ) -> anyhow::Result { + let backends = match preference { + WebBackendPreference::Auto => wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL, + WebBackendPreference::WebGpu => wgpu::Backends::BROWSER_WEBGPU, + WebBackendPreference::WebGl => wgpu::Backends::GL, + }; + let descriptor = wgpu::InstanceDescriptor { + backends, + flags: wgpu::InstanceFlags::default(), + backend_options: wgpu::BackendOptions::default(), + memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(), + display: Some(Box::new(WebDisplaySource)), + }; + let instance = if preference == WebBackendPreference::Auto { + wgpu::util::new_instance_with_webgpu_detection(descriptor).await + } else { + wgpu::Instance::new(descriptor) + }; + let surface = instance + .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone())) + .map_err(|error| { + anyhow::anyhow!("Failed to create browser graphics surface: {error}") + })?; + + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + compatible_surface: Some(&surface), + force_fallback_adapter: false, + }) + .await + .map_err(|error| { + anyhow::anyhow!( + "Failed to request a {preference:?} adapter compatible with the canvas: {error}" + ) + })?; + let adapter_info = adapter.get_info(); + let backend = match adapter_info.backend { + wgpu::Backend::BrowserWebGpu => WgpuBackend::BrowserWebGpu, + wgpu::Backend::Gl => WgpuBackend::Gl, + backend => { + anyhow::bail!( + "Browser graphics initialization selected unexpected backend {backend:?}" + ) + } + }; + + let (device, queue, dual_source_blending, color_texture_format) = + Self::create_device(&adapter).await?; + let errors = DeviceErrorState::install(&device); + log::info!( + "Browser graphics initialized: requested={preference:?}, selected={backend:?}, \ + adapter={:?}, limits={:?}, dual_source_blending={dual_source_blending}", + adapter_info.name, + device.limits(), + ); + + let context = Self { + instance, + adapter, + device: Arc::new(device), + queue: Arc::new(queue), + backend, + dual_source_blending, + color_texture_format, + errors, + }; + Ok(PreparedWebGraphics { context, surface }) + } + + async fn create_device( + adapter: &wgpu::Adapter, + ) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> { + let dual_source_blending = adapter + .features() + .contains(wgpu::Features::DUAL_SOURCE_BLENDING); + + let mut required_features = wgpu::Features::empty(); + if dual_source_blending { + required_features |= wgpu::Features::DUAL_SOURCE_BLENDING; + } else { + log::warn!( + "Dual-source blending not available on this GPU. \ + Subpixel text antialiasing will be disabled." + ); + } + + let color_atlas_texture_format = Self::select_color_texture_format(adapter)?; + #[cfg(target_family = "wasm")] + let required_limits = if adapter.get_info().backend == wgpu::Backend::Gl { + wgpu::Limits::downlevel_webgl2_defaults() + .using_resolution(adapter.limits()) + .using_alignment(adapter.limits()) + } else { + wgpu::Limits::downlevel_defaults() + .using_resolution(adapter.limits()) + .using_alignment(adapter.limits()) + }; + #[cfg(not(target_family = "wasm"))] + let required_limits = wgpu::Limits::downlevel_defaults() + .using_resolution(adapter.limits()) + .using_alignment(adapter.limits()); + + let (device, queue) = adapter + .request_device(&wgpu::DeviceDescriptor { + label: Some("gpui_device"), + required_features, + required_limits, + memory_hints: wgpu::MemoryHints::MemoryUsage, + trace: wgpu::Trace::Off, + experimental_features: wgpu::ExperimentalFeatures::disabled(), + }) + .await + .map_err(|e| anyhow::anyhow!("Failed to create wgpu device: {e}"))?; + + Ok(( + device, + queue, + dual_source_blending, + color_atlas_texture_format, + )) + } + + #[cfg(not(target_family = "wasm"))] + pub fn instance(display: Option>) -> wgpu::Instance { + wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::VULKAN | wgpu::Backends::GL, + flags: wgpu::InstanceFlags::default(), + backend_options: wgpu::BackendOptions::default(), + memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(), + display, + }) + } + + pub fn check_compatible_with_surface(&self, surface: &wgpu::Surface<'_>) -> anyhow::Result<()> { + let caps = surface.get_capabilities(&self.adapter); + if caps.formats.is_empty() { + let info = self.adapter.get_info(); + anyhow::bail!( + "Adapter {:?} (backend={:?}, device={:#06x}) is not compatible with the \ + display surface for this window.", + info.name, + info.backend, + info.device, + ); + } + Ok(()) + } + + /// Select an adapter and create a device, testing that the surface can actually be configured. + /// This is the only reliable way to determine compatibility on hybrid GPU systems, where + /// adapters may report surface compatibility via get_capabilities() but fail when actually + /// configuring (e.g., NVIDIA reporting Vulkan Wayland support but failing because the + /// Wayland compositor runs on the Intel GPU). + #[cfg(not(target_family = "wasm"))] + async fn select_adapter_and_device( + instance: &wgpu::Instance, + device_id_filter: Option, + surface: &wgpu::Surface<'_>, + compositor_gpu: Option<&CompositorGpuHint>, + reject_software: bool, + ) -> anyhow::Result<( + wgpu::Adapter, + wgpu::Device, + wgpu::Queue, + bool, + TextureFormat, + )> { + let mut adapters: Vec<_> = instance.enumerate_adapters(wgpu::Backends::all()).await; + + if adapters.is_empty() { + anyhow::bail!("No GPU adapters found"); + } + + if let Some(device_id) = device_id_filter { + log::info!("ZED_DEVICE_ID filter: {:#06x}", device_id); + } + + Self::sort_adapters(&mut adapters, device_id_filter, compositor_gpu); + + // Log all available adapters (in sorted order) + log::info!("Found {} GPU adapter(s):", adapters.len()); + for adapter in &adapters { + let info = adapter.get_info(); + log::info!( + " - {} (vendor={:#06x}, device={:#06x}, backend={:?}, type={:?})", + info.name, + info.vendor, + info.device, + info.backend, + info.device_type, + ); + } + + // Test each adapter by creating a device and configuring the surface + for adapter in adapters { + let info = adapter.get_info(); + + if reject_software && info.device_type == wgpu::DeviceType::Cpu { + log::info!( + "Skipping software renderer: {} ({:?})", + info.name, + info.backend + ); + continue; + } + + log::info!("Testing adapter: {} ({:?})...", info.name, info.backend); + + match Self::try_adapter_with_surface(&adapter, surface).await { + Ok((device, queue, dual_source_blending, color_atlas_texture_format)) => { + log::info!( + "Selected GPU (passed configuration test): {} ({:?})", + info.name, + info.backend + ); + return Ok(( + adapter, + device, + queue, + dual_source_blending, + color_atlas_texture_format, + )); + } + Err(e) => { + log::info!( + " Adapter {} ({:?}) failed: {}, trying next...", + info.name, + info.backend, + e + ); + } + } + } + + anyhow::bail!("No GPU adapter found that can configure the display surface") + } + + /// Sort adapters into a single priority order. Tiers (from highest to lowest): + /// + /// 1. ZED_DEVICE_ID match — explicit user override + /// 2. Compositor GPU match — the GPU the display server is rendering on + /// 3. Device type (Discrete > Integrated > Other > Virtual > Cpu). + /// "Other" ranks above "Virtual" because OpenGL seems to count as "Other". + /// 4. Backend — prefer Vulkan/Metal/Dx12 over GL/etc. + #[cfg(not(target_family = "wasm"))] + fn sort_adapters( + adapters: &mut [wgpu::Adapter], + device_id_filter: Option, + compositor_gpu: Option<&CompositorGpuHint>, + ) { + adapters.sort_by_key(|adapter| { + let info = adapter.get_info(); + // Backends like OpenGL report device=0 for all adapters, so + // device-based matching is only meaningful when non-zero. + let device_known = info.device != 0; + let user_override: u8 = match device_id_filter { + Some(id) if device_known && info.device == id => 0, + _ => 1, + }; + let compositor_match: u8 = match compositor_gpu { + Some(hint) + if device_known + && info.vendor == hint.vendor_id + && info.device == hint.device_id => + { + 0 + } + _ => 1, + }; + let type_priority: u8 = match info.device_type { + wgpu::DeviceType::DiscreteGpu => 0, + wgpu::DeviceType::IntegratedGpu => 1, + wgpu::DeviceType::Other => 2, + wgpu::DeviceType::VirtualGpu => 3, + wgpu::DeviceType::Cpu => 4, + }; + // Mesa 22 llvmpipe Vulkan can configure an X11 surface successfully + // yet present black frames. Prefer its working GL path for CPU-only + // Linux desktops; retain hardware and explicit-device priorities. + let software_backend_priority: u8 = if cfg!(target_os = "linux") + && info.device_type == wgpu::DeviceType::Cpu + && info.backend != wgpu::Backend::Gl + { + 1 + } else { + 0 + }; + let backend_priority: u8 = match info.backend { + wgpu::Backend::Vulkan | wgpu::Backend::Metal | wgpu::Backend::Dx12 => 0, + _ => 1, + }; + + ( + user_override, + compositor_match, + type_priority, + software_backend_priority, + backend_priority, + ) + }); + } + + /// Try to use an adapter with a surface by creating a device and testing configuration. + /// Returns the device and queue if successful, allowing them to be reused. + #[cfg(not(target_family = "wasm"))] + async fn try_adapter_with_surface( + adapter: &wgpu::Adapter, + surface: &wgpu::Surface<'_>, + ) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> { + let caps = surface.get_capabilities(adapter); + if caps.formats.is_empty() { + anyhow::bail!("no compatible surface formats"); + } + if caps.alpha_modes.is_empty() { + anyhow::bail!("no compatible alpha modes"); + } + + let (device, queue, dual_source_blending, color_atlas_texture_format) = + Self::create_device(adapter).await?; + let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + + let test_config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: caps.formats[0], + width: 64, + height: 64, + present_mode: wgpu::PresentMode::Fifo, + desired_maximum_frame_latency: 2, + alpha_mode: caps.alpha_modes[0], + view_formats: vec![], + }; + + surface.configure(&device, &test_config); + + let error = error_scope.pop().await; + if let Some(e) = error { + anyhow::bail!("surface configuration failed: {e}"); + } + + Ok(( + device, + queue, + dual_source_blending, + color_atlas_texture_format, + )) + } + + fn select_color_texture_format(adapter: &wgpu::Adapter) -> anyhow::Result { + let required_usages = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; + let bgra_features = adapter.get_texture_format_features(wgpu::TextureFormat::Bgra8Unorm); + let rgba_features = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba8Unorm); + #[cfg(target_family = "wasm")] + if adapter.get_info().backend == wgpu::Backend::Gl + && rgba_features.allowed_usages.contains(required_usages) + { + return Ok(wgpu::TextureFormat::Rgba8Unorm); + } + if bgra_features.allowed_usages.contains(required_usages) { + return Ok(wgpu::TextureFormat::Bgra8Unorm); + } + if rgba_features.allowed_usages.contains(required_usages) { + let info = adapter.get_info(); + log::warn!( + "Adapter {} ({:?}) does not support Bgra8Unorm atlas textures with usages {:?}; \ + falling back to Rgba8Unorm atlas textures.", + info.name, + info.backend, + required_usages, + ); + return Ok(wgpu::TextureFormat::Rgba8Unorm); + } + + let info = adapter.get_info(); + Err(anyhow::anyhow!( + "Adapter {} ({:?}, device={:#06x}) does not support a usable color atlas texture \ + format with usages {:?}. Bgra8Unorm allowed usages: {:?}; \ + Rgba8Unorm allowed usages: {:?}.", + info.name, + info.backend, + info.device, + required_usages, + bgra_features.allowed_usages, + rgba_features.allowed_usages, + )) + } + pub fn backend(&self) -> WgpuBackend { + self.backend + } + + pub fn uses_webgl_instance_data(&self) -> bool { + matches!(self.backend, WgpuBackend::Gl) && cfg!(target_family = "wasm") + } + + pub fn supports_dual_source_blending(&self) -> bool { + self.dual_source_blending + } + + pub fn color_texture_format(&self) -> wgpu::TextureFormat { + self.color_texture_format + } + + /// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume). + /// When this returns true, the context should be recreated. + pub fn device_lost(&self) -> bool { + self.errors.device_lost() + } + + /// The device-wide error state, shared with renderers on this device. + pub fn errors(&self) -> &Arc { + &self.errors + } +} + +#[cfg(not(target_family = "wasm"))] +fn parse_pci_id(id: &str) -> anyhow::Result { + let mut id = id.trim(); + + if id.starts_with("0x") || id.starts_with("0X") { + id = &id[2..]; + } + let is_hex_string = id.chars().all(|c| c.is_ascii_hexdigit()); + let is_4_chars = id.len() == 4; + anyhow::ensure!( + is_4_chars && is_hex_string, + "Expected a 4 digit PCI ID in hexadecimal format" + ); + + u32::from_str_radix(id, 16).context("parsing PCI ID as hex") +} + +#[cfg(test)] +mod tests { + use super::{DeviceErrorState, parse_pci_id}; + + #[test] + fn device_errors_are_observed_independently() { + let errors = DeviceErrorState::default(); + let mut first = 0; + let mut second = 0; + assert_eq!(errors.observe_error(&mut first), None); + errors.record("first".into()); + assert_eq!(errors.observe_error(&mut first).as_deref(), Some("first")); + assert_eq!(errors.observe_error(&mut first), None); + assert_eq!(errors.observe_error(&mut second).as_deref(), Some("first")); + assert_eq!(errors.observe_error(&mut second), None); + + errors.record("second".into()); + assert_eq!(errors.observe_error(&mut second).as_deref(), Some("second")); + assert_eq!(errors.observe_error(&mut first).as_deref(), Some("second")); + assert_eq!(errors.observe_error(&mut first), None); + assert_eq!(errors.observe_error(&mut second), None); + } + + #[test] + fn device_errors_coalesce_and_new_observers_see_latest() { + let errors = DeviceErrorState::default(); + errors.record("older".into()); + errors.record("latest".into()); + let mut generation = 0; + assert_eq!( + errors.observe_error(&mut generation).as_deref(), + Some("latest") + ); + assert_eq!(errors.observe_error(&mut generation), None); + + let replacement = DeviceErrorState::default(); + replacement.record("replacement".into()); + generation = 0; + assert_eq!( + replacement.observe_error(&mut generation).as_deref(), + Some("replacement") + ); + assert_eq!(replacement.observe_error(&mut generation), None); + } + + #[test] + fn test_parse_device_id() { + assert!(parse_pci_id("0xABCD").is_ok()); + assert!(parse_pci_id("ABCD").is_ok()); + assert!(parse_pci_id("abcd").is_ok()); + assert!(parse_pci_id("1234").is_ok()); + assert!(parse_pci_id("123").is_err()); + assert_eq!( + parse_pci_id(&format!("{:x}", 0x1234)).unwrap(), + parse_pci_id(&format!("{:X}", 0x1234)).unwrap(), + ); + + assert_eq!( + parse_pci_id(&format!("{:#x}", 0x1234)).unwrap(), + parse_pci_id(&format!("{:#X}", 0x1234)).unwrap(), + ); + } +} diff --git a/vendor/gpui-wgpu/src/wgpu_renderer.rs b/vendor/gpui-wgpu/src/wgpu_renderer.rs new file mode 100644 index 0000000..8387528 --- /dev/null +++ b/vendor/gpui-wgpu/src/wgpu_renderer.rs @@ -0,0 +1,2929 @@ +use crate::{CompositorGpuHint, DeviceErrorState, WgpuAtlas, WgpuContext}; +use anyhow::{Context as _, Result}; +use bytemuck::{Pod, Zeroable}; +use collections::FxHashMap; +use gpui::{ + AtlasTextureId, Background, Bounds, DevicePixels, GpuSpecs, Path, Point, PrimitiveBatch, + ScaledPixels, Scene, Size, get_gamma_correction_ratios, +}; +use log::warn; +#[cfg(not(target_family = "wasm"))] +use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; +use smallvec::SmallVec; +use std::cell::RefCell; +use std::num::NonZeroU64; +use std::ops::Range; +use std::rc::Rc; +use std::sync::Arc; + +const MAX_INSTANCE_BUFFER_SIZE: u64 = 256 * 1024 * 1024; + +const INSTANCE_TEXTURE_TEXEL_SIZE: u64 = 16; + +/// Shader variant for backends with storage buffer support: the shared shader +/// logic plus the storage-buffer instance transport. +const STORAGE_BUFFER_SHADERS: &str = concat!( + include_str!("shaders.wgsl"), + include_str!("shaders_storage.wgsl"), +); + +/// Shader variant for WebGL2, which has no storage buffers: the shared shader +/// logic plus the texture-based instance transport. +const WEBGL_SHADERS: &str = concat!( + include_str!("shaders.wgsl"), + include_str!("shaders_webgl.wgsl"), +); + +/// Subpixel text rendering requires dual-source blending, which WebGL2 lacks, so +/// this variant only ever runs with the storage-buffer transport. The `enable` +/// directive must precede all declarations. +const SUBPIXEL_SHADERS: &str = concat!( + "enable dual_source_blending;\n", + include_str!("shaders.wgsl"), + include_str!("shaders_storage.wgsl"), + include_str!("shaders_subpixel.wgsl"), +); + +fn least_common_multiple(left: u64, right: u64) -> u64 { + let mut first = left; + let mut second = right; + while second != 0 { + let remainder = first % second; + first = second; + second = remainder; + } + left / first * right +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct GlobalParams { + viewport_size: [f32; 2], + premultiplied_alpha: u32, + pad: u32, +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct PodBounds { + origin: [f32; 2], + size: [f32; 2], +} + +impl From> for PodBounds { + fn from(bounds: Bounds) -> Self { + Self { + origin: [bounds.origin.x.0, bounds.origin.y.0], + size: [bounds.size.width.0, bounds.size.height.0], + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct SurfaceParams { + bounds: PodBounds, + content_mask: PodBounds, +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct GammaParams { + gamma_ratios: [f32; 4], + grayscale_enhanced_contrast: f32, + subpixel_enhanced_contrast: f32, + is_bgr: u32, + _pad: u32, +} + +#[derive(Clone, Debug)] +#[repr(C)] +struct PathSprite { + bounds: Bounds, +} + +#[derive(Clone, Debug)] +#[repr(C)] +struct PathRasterizationVertex { + xy_position: Point, + st_position: Point, + color: Background, + bounds: Bounds, +} + +pub struct WgpuSurfaceConfig { + pub size: Size, + pub transparent: bool, + /// Preferred presentation mode. When `Some`, the renderer will use this + /// mode if supported by the surface, falling back to `Fifo`. + /// When `None`, defaults to `Fifo` (VSync). + /// + /// Mobile platforms may prefer `Mailbox` (triple-buffering) to avoid + /// blocking in `get_current_texture()` during lifecycle transitions. + pub preferred_present_mode: Option, +} + +struct WgpuPipelines { + quads: wgpu::RenderPipeline, + shadows: wgpu::RenderPipeline, + path_rasterization: wgpu::RenderPipeline, + paths: wgpu::RenderPipeline, + underlines: wgpu::RenderPipeline, + mono_sprites: wgpu::RenderPipeline, + subpixel_sprites: Option, + poly_sprites: wgpu::RenderPipeline, + #[allow(dead_code)] + surfaces: wgpu::RenderPipeline, +} + +/// One frame allocation of instance data, ready to bind. +struct InstanceBinding { + bind_group: wgpu::BindGroup, + /// Index of the allocation's first instance within the bound data. Always + /// zero on the storage-buffer path, where the binding offset already + /// positions the array; on the WebGL texture path the shader indexes the + /// shared instance texture absolutely, so draws must offset their + /// instance (or vertex) ranges by this value. + first_instance: u32, +} + +struct InstanceBindings { + quads: InstanceBinding, + shadows: InstanceBinding, + underlines: InstanceBinding, + monochrome_sprites: InstanceBinding, + subpixel_sprites: InstanceBinding, + polychrome_sprites: InstanceBinding, +} + +struct WgpuBindGroupLayouts { + globals: wgpu::BindGroupLayout, + instances: wgpu::BindGroupLayout, + texture: wgpu::BindGroupLayout, + surfaces: wgpu::BindGroupLayout, +} + +/// Shared GPU context reference, used to coordinate device recovery across multiple windows. +pub type GpuContext = Rc>>; + +enum InstanceData { + Storage(wgpu::Buffer), + // WebGL2 has no storage buffers. A uint texture keeps the records available to both shader + // stages while preserving integer and floating-point bit patterns exactly. + Texture { + texture: wgpu::Texture, + view: wgpu::TextureView, + width: u32, + height: u32, + }, +} + +/// GPU resources that must be dropped together during device recovery. +struct WgpuResources { + device: Arc, + queue: Arc, + pipelines: WgpuPipelines, + bind_group_layouts: WgpuBindGroupLayouts, + atlas_sampler: wgpu::Sampler, + atlas_texture_bind_groups: FxHashMap, + globals_buffer: wgpu::Buffer, + globals_bind_group: wgpu::BindGroup, + path_globals_bind_group: wgpu::BindGroup, + instance_data: InstanceData, + path_intermediate_texture: Option, + path_intermediate_view: Option, + path_msaa_texture: Option, + path_msaa_view: Option, +} + +struct CachedTextureBindGroup { + texture_generation: u64, + bind_group: wgpu::BindGroup, +} + +impl WgpuResources { + fn invalidate_intermediate_textures(&mut self) { + self.path_intermediate_texture = None; + self.path_intermediate_view = None; + self.path_msaa_texture = None; + self.path_msaa_view = None; + } +} + +struct WgpuRendererCore { + resources: WgpuResources, + atlas: Arc, + path_globals_offset: u64, + gamma_offset: u64, + instance_data_capacity: u64, + max_instance_data_size: u64, + instance_data_alignment: u64, + uses_webgl_instance_data: bool, + rendering_params: RenderingParameters, + is_bgr: bool, + dual_source_blending: bool, + adapter_info: wgpu::AdapterInfo, + target_format: wgpu::TextureFormat, + max_texture_size: u32, +} + +/// GPU resources of a windowed renderer. A surface is only ever configured against the +/// device that owns `core`, so it cannot outlive it: there is no surface-only state. +enum RendererState { + /// Frames can be drawn. + Ready { + surface: wgpu::Surface<'static>, + core: WgpuRendererCore, + }, + /// The native surface is gone (Android `TerminateWindow`, browser context loss) but + /// the device, pipelines, and atlas remain so `replace_surface` can resume without + /// re-uploading cached textures. + Unconfigured { core: WgpuRendererCore }, + /// Released by `destroy`, or dropped for a device recovery that has not succeeded yet. + Released, +} + +pub struct WgpuRenderer { + /// Shared GPU context for device recovery coordination (unused on WASM). + #[allow(dead_code)] + context: Option, + /// Compositor GPU hint for adapter selection (unused on WASM). + #[allow(dead_code)] + compositor_gpu: Option, + state: RendererState, + surface_config: wgpu::SurfaceConfiguration, + atlas: Arc, + transparent_alpha_mode: wgpu::CompositeAlphaMode, + opaque_alpha_mode: wgpu::CompositeAlphaMode, + max_texture_size: u32, + is_bgr: bool, + failed_frame_count: u32, + device_errors: Arc, + observed_error_generation: u64, + last_surface_error: Option, + needs_redraw: bool, +} + +impl WgpuRenderer { + fn core(&self) -> Option<&WgpuRendererCore> { + match &self.state { + RendererState::Ready { core, .. } | RendererState::Unconfigured { core } => Some(core), + RendererState::Released => None, + } + } + + fn core_mut(&mut self) -> Option<&mut WgpuRendererCore> { + match &mut self.state { + RendererState::Ready { core, .. } | RendererState::Unconfigured { core } => Some(core), + RendererState::Released => None, + } + } + + /// Creates a new WgpuRenderer from raw window handles. + /// + /// The `gpu_context` is a shared reference that coordinates GPU context across + /// multiple windows. The first window to create a renderer will initialize the + /// context; subsequent windows will share it. + /// + /// # Safety + /// The caller must ensure that the window handle remains valid for the lifetime + /// of the returned renderer. + #[cfg(not(target_family = "wasm"))] + pub fn new( + gpu_context: GpuContext, + window: &W, + config: WgpuSurfaceConfig, + compositor_gpu: Option, + ) -> anyhow::Result + where + W: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync + Clone + 'static, + { + let window_handle = window + .window_handle() + .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?; + + let target = wgpu::SurfaceTargetUnsafe::RawHandle { + // Fall back to the display handle already provided via InstanceDescriptor::display. + raw_display_handle: None, + raw_window_handle: window_handle.as_raw(), + }; + + // Use the existing context's instance if available, otherwise create a new one. + // The surface must be created with the same instance that will be used for + // adapter selection, otherwise wgpu will panic. + let instance = gpu_context + .borrow() + .as_ref() + .map(|ctx| ctx.instance.clone()) + .unwrap_or_else(|| WgpuContext::instance(Some(Box::new(window.clone())))); + + // Safety: The caller guarantees that the window handle is valid for the + // lifetime of this renderer. In practice, the RawWindow struct is created + // from the native window handles and the surface is dropped before the window. + let surface = unsafe { + instance + .create_surface_unsafe(target) + .map_err(|e| anyhow::anyhow!("Failed to create surface: {e}"))? + }; + + let mut ctx_ref = gpu_context.borrow_mut(); + let context = match ctx_ref.as_mut() { + Some(context) => { + context.check_compatible_with_surface(&surface)?; + context + } + None => ctx_ref.insert(WgpuContext::new(instance, &surface, compositor_gpu)?), + }; + + let atlas = Arc::new(WgpuAtlas::from_context(context)); + + Self::new_internal( + Some(Rc::clone(&gpu_context)), + context, + surface, + config, + compositor_gpu, + atlas, + ) + } + + #[cfg(target_family = "wasm")] + pub fn new_from_canvas( + context: &WgpuContext, + canvas: &web_sys::HtmlCanvasElement, + config: WgpuSurfaceConfig, + ) -> anyhow::Result { + let surface = context + .instance + .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone())) + .map_err(|e| anyhow::anyhow!("Failed to create surface: {e}"))?; + Self::new_from_surface(context, surface, config) + } + + #[cfg(target_family = "wasm")] + #[allow(clippy::arc_with_non_send_sync)] + pub fn new_from_surface( + context: &WgpuContext, + surface: wgpu::Surface<'static>, + config: WgpuSurfaceConfig, + ) -> anyhow::Result { + let atlas = Arc::new(WgpuAtlas::from_context(context)); + Self::new_internal(None, context, surface, config, None, atlas) + } + + fn new_internal( + gpu_context: Option, + context: &WgpuContext, + surface: wgpu::Surface<'static>, + config: WgpuSurfaceConfig, + compositor_gpu: Option, + atlas: Arc, + ) -> anyhow::Result { + let surface_caps = surface.get_capabilities(&context.adapter); + let preferred_formats = [ + wgpu::TextureFormat::Bgra8Unorm, + wgpu::TextureFormat::Rgba8Unorm, + ]; + let surface_format = preferred_formats + .iter() + .find(|f| surface_caps.formats.contains(f)) + .copied() + .or_else(|| surface_caps.formats.iter().find(|f| !f.is_srgb()).copied()) + .or_else(|| surface_caps.formats.first().copied()) + .ok_or_else(|| { + anyhow::anyhow!( + "Surface reports no supported texture formats for adapter {:?}", + context.adapter.get_info().name + ) + })?; + + let pick_alpha_mode = + |preferences: &[wgpu::CompositeAlphaMode]| -> anyhow::Result { + preferences + .iter() + .find(|p| surface_caps.alpha_modes.contains(p)) + .copied() + .or_else(|| surface_caps.alpha_modes.first().copied()) + .ok_or_else(|| { + anyhow::anyhow!( + "Surface reports no supported alpha modes for adapter {:?}", + context.adapter.get_info().name + ) + }) + }; + + let transparent_alpha_mode = pick_alpha_mode(&[ + wgpu::CompositeAlphaMode::PreMultiplied, + wgpu::CompositeAlphaMode::Inherit, + ])?; + + let opaque_alpha_mode = pick_alpha_mode(&[ + wgpu::CompositeAlphaMode::Opaque, + wgpu::CompositeAlphaMode::Inherit, + ])?; + + let alpha_mode = if config.transparent { + transparent_alpha_mode + } else { + opaque_alpha_mode + }; + + let device = Arc::clone(&context.device); + let max_texture_size = device.limits().max_texture_dimension_2d; + + let requested_width = config.size.width.0 as u32; + let requested_height = config.size.height.0 as u32; + let clamped_width = requested_width.min(max_texture_size); + let clamped_height = requested_height.min(max_texture_size); + + if clamped_width != requested_width || clamped_height != requested_height { + warn!( + "Requested surface size ({}, {}) exceeds maximum texture dimension {}. \ + Clamping to ({}, {}). Window content may not fill the entire window.", + requested_width, requested_height, max_texture_size, clamped_width, clamped_height + ); + } + + let surface_config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: surface_format, + width: clamped_width.max(1), + height: clamped_height.max(1), + present_mode: config + .preferred_present_mode + .filter(|mode| surface_caps.present_modes.contains(mode)) + .unwrap_or(wgpu::PresentMode::Fifo), + desired_maximum_frame_latency: 2, + alpha_mode, + view_formats: vec![], + }; + // Configure the surface immediately. The adapter selection process already validated + // that this adapter can successfully configure this surface. + surface.configure(&context.device, &surface_config); + + let core = WgpuRendererCore::new(context, atlas.clone(), surface_format, alpha_mode); + + Ok(Self { + context: gpu_context, + compositor_gpu, + state: RendererState::Ready { surface, core }, + surface_config, + atlas, + transparent_alpha_mode, + opaque_alpha_mode, + max_texture_size, + is_bgr: false, + failed_frame_count: 0, + device_errors: Arc::clone(context.errors()), + observed_error_generation: 0, + last_surface_error: None, + needs_redraw: false, + }) + } +} + +impl WgpuRendererCore { + fn create_bind_group_layouts( + device: &wgpu::Device, + uses_webgl_instance_data: bool, + ) -> WgpuBindGroupLayouts { + let globals = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("globals_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: NonZeroU64::new( + std::mem::size_of::() as u64 + ), + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: NonZeroU64::new( + std::mem::size_of::() as u64 + ), + }, + count: None, + }, + ], + }); + + let instance_data_entry = wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: if uses_webgl_instance_data { + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Uint, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + } + } else { + wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + } + }, + count: None, + }; + + let instances = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("instances_layout"), + entries: &[instance_data_entry], + }); + + let texture = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("texture_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + + let surfaces = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("surfaces_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: NonZeroU64::new( + std::mem::size_of::() as u64 + ), + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + + WgpuBindGroupLayouts { + globals, + instances, + texture, + surfaces, + } + } + + fn create_instance_texture( + device: &wgpu::Device, + requested_capacity: u64, + max_texture_dimension: u32, + ) -> (InstanceData, u64) { + let texel_count = requested_capacity.div_ceil(INSTANCE_TEXTURE_TEXEL_SIZE); + let width = texel_count.min(u64::from(max_texture_dimension)).max(1) as u32; + let height = texel_count + .div_ceil(u64::from(width)) + .min(u64::from(max_texture_dimension)) + .max(1) as u32; + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("instance_texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba32Uint, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let capacity = u64::from(width) * u64::from(height) * INSTANCE_TEXTURE_TEXEL_SIZE; + ( + InstanceData::Texture { + texture, + view, + width, + height, + }, + capacity, + ) + } + + fn create_pipelines( + device: &wgpu::Device, + layouts: &WgpuBindGroupLayouts, + surface_format: wgpu::TextureFormat, + alpha_mode: wgpu::CompositeAlphaMode, + path_sample_count: u32, + dual_source_blending: bool, + uses_webgl_instance_data: bool, + ) -> WgpuPipelines { + // Diagnostic guard: verify the device actually has + // DUAL_SOURCE_BLENDING. We have a crash report (ZED-5G1) where a + // feature mismatch caused a wgpu-hal abort, but we haven't + // identified the code path that produces the mismatch. This + // guard prevents the crash and logs more evidence. + // Remove this check once: + // a) We find and fix the root cause, or + // b) There are no reports of this warning appearing for some time. + let device_has_feature = device + .features() + .contains(wgpu::Features::DUAL_SOURCE_BLENDING); + if dual_source_blending && !device_has_feature { + log::error!( + "BUG: dual_source_blending flag is true but device does not \ + have DUAL_SOURCE_BLENDING enabled (device features: {:?}). \ + Falling back to mono text rendering. Please report this at \ + https://github.com/zed-industries/zed/issues", + device.features(), + ); + } + let dual_source_blending = + dual_source_blending && device_has_feature && !uses_webgl_instance_data; + + let shader_source = if uses_webgl_instance_data { + WEBGL_SHADERS + } else { + STORAGE_BUFFER_SHADERS + }; + let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("gpui_shaders"), + source: wgpu::ShaderSource::Wgsl(shader_source.into()), + }); + + let subpixel_shader_module = if dual_source_blending { + Some(device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("gpui_subpixel_shaders"), + source: wgpu::ShaderSource::Wgsl(SUBPIXEL_SHADERS.into()), + })) + } else { + None + }; + + let blend_mode = match alpha_mode { + wgpu::CompositeAlphaMode::PreMultiplied => { + wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING + } + _ => wgpu::BlendState::ALPHA_BLENDING, + }; + + let color_target = wgpu::ColorTargetState { + format: surface_format, + blend: Some(blend_mode), + write_mask: wgpu::ColorWrites::ALL, + }; + + let create_pipeline = |name: &str, + vs_entry: &str, + fs_entry: &str, + globals_layout: &wgpu::BindGroupLayout, + data_layout: &wgpu::BindGroupLayout, + texture_layout: Option<&wgpu::BindGroupLayout>, + topology: wgpu::PrimitiveTopology, + color_targets: &[Option], + sample_count: u32, + module: &wgpu::ShaderModule| { + let mut bind_group_layouts = vec![Some(globals_layout), Some(data_layout)]; + bind_group_layouts.extend(texture_layout.map(Some)); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some(&format!("{name}_layout")), + bind_group_layouts: &bind_group_layouts, + immediate_size: 0, + }); + + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(name), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module, + entry_point: Some(vs_entry), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(fs_entry), + targets: color_targets, + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: None, + polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, + conservative: false, + }, + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: sample_count, + mask: !0, + alpha_to_coverage_enabled: false, + }, + multiview_mask: None, + cache: None, + }) + }; + + let quads = create_pipeline( + "quads", + "vs_quad", + "fs_quad", + &layouts.globals, + &layouts.instances, + None, + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(color_target.clone())], + 1, + &shader_module, + ); + + let shadows = create_pipeline( + "shadows", + "vs_shadow", + "fs_shadow", + &layouts.globals, + &layouts.instances, + None, + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(color_target.clone())], + 1, + &shader_module, + ); + + let path_rasterization = create_pipeline( + "path_rasterization", + "vs_path_rasterization", + "fs_path_rasterization", + &layouts.globals, + &layouts.instances, + None, + wgpu::PrimitiveTopology::TriangleList, + &[Some(wgpu::ColorTargetState { + format: surface_format, + blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + path_sample_count, + &shader_module, + ); + + let paths_blend = wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }; + + let paths = create_pipeline( + "paths", + "vs_path", + "fs_path", + &layouts.globals, + &layouts.instances, + Some(&layouts.texture), + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(wgpu::ColorTargetState { + format: surface_format, + blend: Some(paths_blend), + write_mask: wgpu::ColorWrites::ALL, + })], + 1, + &shader_module, + ); + + let underlines = create_pipeline( + "underlines", + "vs_underline", + "fs_underline", + &layouts.globals, + &layouts.instances, + None, + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(color_target.clone())], + 1, + &shader_module, + ); + + let mono_sprites = create_pipeline( + "mono_sprites", + "vs_mono_sprite", + "fs_mono_sprite", + &layouts.globals, + &layouts.instances, + Some(&layouts.texture), + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(color_target.clone())], + 1, + &shader_module, + ); + + let subpixel_sprites = if let Some(subpixel_module) = &subpixel_shader_module { + let subpixel_blend = wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Src1, + dst_factor: wgpu::BlendFactor::OneMinusSrc1, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + }; + + Some(create_pipeline( + "subpixel_sprites", + "vs_subpixel_sprite", + "fs_subpixel_sprite", + &layouts.globals, + &layouts.instances, + Some(&layouts.texture), + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(wgpu::ColorTargetState { + format: surface_format, + blend: Some(subpixel_blend), + write_mask: wgpu::ColorWrites::COLOR, + })], + 1, + subpixel_module, + )) + } else { + None + }; + + let poly_sprites = create_pipeline( + "poly_sprites", + "vs_poly_sprite", + "fs_poly_sprite", + &layouts.globals, + &layouts.instances, + Some(&layouts.texture), + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(color_target.clone())], + 1, + &shader_module, + ); + + let surfaces = create_pipeline( + "surfaces", + "vs_surface", + "fs_surface", + &layouts.globals, + &layouts.surfaces, + None, + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(color_target)], + 1, + &shader_module, + ); + + WgpuPipelines { + quads, + shadows, + path_rasterization, + paths, + underlines, + mono_sprites, + subpixel_sprites, + poly_sprites, + surfaces, + } + } + + fn create_path_intermediate( + device: &wgpu::Device, + format: wgpu::TextureFormat, + width: u32, + height: u32, + ) -> (wgpu::Texture, wgpu::TextureView) { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("path_intermediate"), + size: wgpu::Extent3d { + width: width.max(1), + height: height.max(1), + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + (texture, view) + } + + fn create_msaa_if_needed( + device: &wgpu::Device, + format: wgpu::TextureFormat, + width: u32, + height: u32, + sample_count: u32, + ) -> Option<(wgpu::Texture, wgpu::TextureView)> { + if sample_count <= 1 { + return None; + } + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("path_msaa"), + size: wgpu::Extent3d { + width: width.max(1), + height: height.max(1), + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + Some((texture, view)) + } +} + +impl WgpuRenderer { + /// Records the new drawable size and reconfigures the surface when one is present. + /// The size is kept even without GPU resources so that recovery restores it. + pub fn update_drawable_size(&mut self, size: Size) { + let width = size.width.0 as u32; + let height = size.height.0 as u32; + + if width == self.surface_config.width && height == self.surface_config.height { + return; + } + + let clamped_width = width.min(self.max_texture_size); + let clamped_height = height.min(self.max_texture_size); + if clamped_width != width || clamped_height != height { + warn!( + "Requested surface size ({}, {}) exceeds maximum texture dimension {}. \ + Clamping to ({}, {}). Window content may not fill the entire window.", + width, height, self.max_texture_size, clamped_width, clamped_height + ); + } + self.surface_config.width = clamped_width.max(1); + self.surface_config.height = clamped_height.max(1); + + let Some(core) = self.core_mut() else { + return; + }; + let resources = &mut core.resources; + + // Wait for any in-flight GPU work to complete before destroying textures + if let Err(e) = resources.device.poll(wgpu::PollType::Wait { + submission_index: None, + timeout: None, + }) { + warn!("Failed to poll device during resize: {e:?}"); + } + + // Destroy old textures before allocating new ones to avoid GPU memory spikes + if let Some(ref texture) = resources.path_intermediate_texture { + texture.destroy(); + } + if let Some(ref texture) = resources.path_msaa_texture { + texture.destroy(); + } + + // Invalidate intermediate textures - they will be lazily recreated + // in draw() after we confirm the surface is healthy. This avoids + // panics when the device/surface is in an invalid state during resize. + resources.invalidate_intermediate_textures(); + + if let RendererState::Ready { surface, core } = &self.state { + surface.configure(&core.resources.device, &self.surface_config); + } + } + + pub fn set_subpixel_layout(&mut self, is_bgr: bool) { + self.is_bgr = is_bgr; + if let Some(core) = self.core_mut() { + core.is_bgr = is_bgr; + } + } + + pub fn update_transparency(&mut self, transparent: bool) { + let new_alpha_mode = if transparent { + self.transparent_alpha_mode + } else { + self.opaque_alpha_mode + }; + if new_alpha_mode == self.surface_config.alpha_mode { + return; + } + self.surface_config.alpha_mode = new_alpha_mode; + let format = self.surface_config.format; + + let Some(core) = self.core_mut() else { + return; + }; + let resources = &mut core.resources; + resources.pipelines = WgpuRendererCore::create_pipelines( + &resources.device, + &resources.bind_group_layouts, + format, + new_alpha_mode, + core.rendering_params.path_sample_count, + core.dual_source_blending, + core.uses_webgl_instance_data, + ); + + if let RendererState::Ready { surface, core } = &self.state { + surface.configure(&core.resources.device, &self.surface_config); + } + } + + #[allow(dead_code)] + pub fn viewport_size(&self) -> Size { + Size { + width: DevicePixels(self.surface_config.width as i32), + height: DevicePixels(self.surface_config.height as i32), + } + } + + pub fn sprite_atlas(&self) -> &Arc { + &self.atlas + } + + pub fn supports_dual_source_blending(&self) -> bool { + self.core().is_some_and(|core| core.dual_source_blending) + } + + /// Returns `None` once GPU resources have been released by `destroy` or a pending + /// device recovery. + pub fn gpu_specs(&self) -> Option { + let adapter_info = &self.core()?.adapter_info; + Some(GpuSpecs { + is_software_emulated: adapter_info.device_type == wgpu::DeviceType::Cpu, + device_name: adapter_info.name.clone(), + driver_name: adapter_info.driver.clone(), + driver_info: adapter_info.driver_info.clone(), + }) + } + + pub fn max_texture_size(&self) -> u32 { + self.max_texture_size + } + + pub fn draw(&mut self, scene: &Scene) -> bool { + #[cfg(target_family = "wasm")] + if self.device_lost() { + if matches!(self.state, RendererState::Ready { .. }) { + log::error!( + "Browser graphics context was lost; rendering has stopped. Reload the page to recover." + ); + self.unconfigure_surface(); + } + return false; + } + + // Bail out early if the surface has been unconfigured (e.g. during + // Android background/rotation transitions). Attempting to acquire + // a texture from an unconfigured surface can block indefinitely on + // some drivers (Adreno). + let RendererState::Ready { surface, core } = &mut self.state else { + return false; + }; + + if let Some(error) = self.last_surface_error.take().or_else(|| { + self.device_errors + .observe_error(&mut self.observed_error_generation) + }) { + self.failed_frame_count += 1; + log::error!( + "GPU error during frame (failure {} of 10): {error}", + self.failed_frame_count + ); + + // TBD. Does retrying more actually help? + if self.failed_frame_count > 10 { + panic!("Too many consecutive GPU errors. Last error: {error}"); + } else if self.failed_frame_count > 5 { + core.resources.invalidate_intermediate_textures(); + self.atlas.clear(); + self.needs_redraw = true; + self.failed_frame_count = 0; + return false; + } + } else { + self.failed_frame_count = 0; + } + + let frame = match surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(frame) => frame, + wgpu::CurrentSurfaceTexture::Suboptimal(frame) => { + // Textures must be destroyed before the surface can be reconfigured. + drop(frame); + surface.configure(&core.resources.device, &self.surface_config); + return false; + } + wgpu::CurrentSurfaceTexture::Lost | wgpu::CurrentSurfaceTexture::Outdated => { + surface.configure(&core.resources.device, &self.surface_config); + return false; + } + wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => { + return false; + } + wgpu::CurrentSurfaceTexture::Validation => { + self.last_surface_error = Some("Surface texture validation error".to_string()); + return false; + } + }; + + // The acquired texture is the authority on frame dimensions; the surface + // configuration is only a request. + let size = Size { + width: DevicePixels(frame.texture.width() as i32), + height: DevicePixels(frame.texture.height() as i32), + }; + let frame_view = frame + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + let premultiplied_alpha = + self.surface_config.alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied; + if let Err(error) = core.render_frame( + scene, + &frame_view, + size, + premultiplied_alpha, + wgpu::Color::TRANSPARENT, + ) { + log::error!("{error:#}"); + return false; + } + + frame.present(); + true + } +} + +impl WgpuRendererCore { + fn new( + context: &WgpuContext, + atlas: Arc, + target_format: wgpu::TextureFormat, + alpha_mode: wgpu::CompositeAlphaMode, + ) -> Self { + let device = Arc::clone(&context.device); + let queue = Arc::clone(&context.queue); + let rendering_params = RenderingParameters::new(&context.adapter, target_format); + let uses_webgl_instance_data = context.uses_webgl_instance_data(); + let dual_source_blending = + context.supports_dual_source_blending() && !uses_webgl_instance_data; + let bind_group_layouts = Self::create_bind_group_layouts(&device, uses_webgl_instance_data); + let pipelines = Self::create_pipelines( + &device, + &bind_group_layouts, + target_format, + alpha_mode, + rendering_params.path_sample_count, + dual_source_blending, + uses_webgl_instance_data, + ); + let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("atlas_sampler"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as u64; + let globals_size = std::mem::size_of::() as u64; + let gamma_size = std::mem::size_of::() as u64; + let path_globals_offset = globals_size.next_multiple_of(uniform_alignment); + let gamma_offset = (path_globals_offset + globals_size).next_multiple_of(uniform_alignment); + let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("globals_buffer"), + size: gamma_offset + gamma_size, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let ( + instance_data, + instance_data_capacity, + max_instance_data_size, + instance_data_alignment, + ) = if uses_webgl_instance_data { + let max_texture_dimension = device.limits().max_texture_dimension_2d; + let max_instance_data_size = (u64::from(max_texture_dimension).pow(2) + * INSTANCE_TEXTURE_TEXEL_SIZE) + .min(MAX_INSTANCE_BUFFER_SIZE); + let initial_capacity = (2 * 1024 * 1024).min(max_instance_data_size); + let (instance_data, capacity) = + Self::create_instance_texture(&device, initial_capacity, max_texture_dimension); + ( + instance_data, + capacity, + max_instance_data_size, + INSTANCE_TEXTURE_TEXEL_SIZE, + ) + } else { + let max_buffer_size = device + .limits() + .max_buffer_size + .min(device.limits().max_storage_buffer_binding_size) + .min(MAX_INSTANCE_BUFFER_SIZE); + let initial_capacity = (2 * 1024 * 1024).min(max_buffer_size); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("instance_buffer"), + size: initial_capacity, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + ( + InstanceData::Storage(buffer), + initial_capacity, + max_buffer_size, + device.limits().min_storage_buffer_offset_alignment as u64, + ) + }; + let globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("globals_bind_group"), + layout: &bind_group_layouts.globals, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &globals_buffer, + offset: 0, + size: NonZeroU64::new(globals_size), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &globals_buffer, + offset: gamma_offset, + size: NonZeroU64::new(gamma_size), + }), + }, + ], + }); + let path_globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("path_globals_bind_group"), + layout: &bind_group_layouts.globals, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &globals_buffer, + offset: path_globals_offset, + size: NonZeroU64::new(globals_size), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &globals_buffer, + offset: gamma_offset, + size: NonZeroU64::new(gamma_size), + }), + }, + ], + }); + let max_texture_size = device.limits().max_texture_dimension_2d; + + Self { + resources: WgpuResources { + device, + queue, + pipelines, + bind_group_layouts, + atlas_sampler, + atlas_texture_bind_groups: FxHashMap::default(), + globals_buffer, + globals_bind_group, + path_globals_bind_group, + instance_data, + path_intermediate_texture: None, + path_intermediate_view: None, + path_msaa_texture: None, + path_msaa_view: None, + }, + atlas, + path_globals_offset, + gamma_offset, + instance_data_capacity, + max_instance_data_size, + instance_data_alignment, + uses_webgl_instance_data, + rendering_params, + is_bgr: false, + dual_source_blending, + adapter_info: context.adapter.get_info(), + target_format, + max_texture_size, + } + } + + fn resources(&self) -> &WgpuResources { + &self.resources + } + + fn resources_mut(&mut self) -> &mut WgpuResources { + &mut self.resources + } + + /// Path rendering goes through an intermediate texture that must match the frame + /// target's dimensions, so the textures are keyed by size and rebuilt on mismatch. + fn ensure_intermediate_textures(&mut self, size: Size) { + let width = size.width.0 as u32; + let height = size.height.0 as u32; + if self + .resources + .path_intermediate_texture + .as_ref() + .is_some_and(|texture| texture.width() == width && texture.height() == height) + { + return; + } + + let format = self.target_format; + let path_sample_count = self.rendering_params.path_sample_count; + let resources = &mut self.resources; + + let (texture, view) = + Self::create_path_intermediate(&resources.device, format, width, height); + resources.path_intermediate_texture = Some(texture); + resources.path_intermediate_view = Some(view); + + let (path_msaa_texture, path_msaa_view) = Self::create_msaa_if_needed( + &resources.device, + format, + width, + height, + path_sample_count, + ) + .map(|(texture, view)| (Some(texture), Some(view))) + .unwrap_or((None, None)); + resources.path_msaa_texture = path_msaa_texture; + resources.path_msaa_view = path_msaa_view; + } + + fn render_frame( + &mut self, + scene: &Scene, + target_view: &wgpu::TextureView, + size: Size, + premultiplied_alpha: bool, + clear_color: wgpu::Color, + ) -> Result { + anyhow::ensure!( + size.width.0 > 0 && size.height.0 > 0, + "invalid render target size: {size:?}" + ); + anyhow::ensure!( + size.width.0 as u32 <= self.max_texture_size + && size.height.0 as u32 <= self.max_texture_size, + "render target size {size:?} exceeds maximum texture dimension {}", + self.max_texture_size + ); + + self.atlas.before_frame(); + self.ensure_intermediate_textures(size); + + let gamma_params = GammaParams { + gamma_ratios: self.rendering_params.gamma_ratios, + grayscale_enhanced_contrast: self.rendering_params.grayscale_enhanced_contrast, + subpixel_enhanced_contrast: self.rendering_params.subpixel_enhanced_contrast, + is_bgr: self.is_bgr as u32, + _pad: 0, + }; + let globals = GlobalParams { + viewport_size: [size.width.0 as f32, size.height.0 as f32], + premultiplied_alpha: premultiplied_alpha as u32, + pad: 0, + }; + let path_globals = GlobalParams { + premultiplied_alpha: 0, + ..globals + }; + self.resources.queue.write_buffer( + &self.resources.globals_buffer, + 0, + bytemuck::bytes_of(&globals), + ); + self.resources.queue.write_buffer( + &self.resources.globals_buffer, + self.path_globals_offset, + bytemuck::bytes_of(&path_globals), + ); + self.resources.queue.write_buffer( + &self.resources.globals_buffer, + self.gamma_offset, + bytemuck::bytes_of(&gamma_params), + ); + + self.record_frame(scene, target_view, clear_color) + .inspect_err(|_| { + // Queue writes are staged before encoding; flush them even if the frame fails. + self.resources.queue.submit(std::iter::empty()); + }) + } + + fn record_frame( + &mut self, + scene: &Scene, + frame_view: &wgpu::TextureView, + clear_color: wgpu::Color, + ) -> Result { + let mut instance_offset = 0; + let instance_bindings = self + .write_instances(scene, &mut instance_offset) + .with_context(|| { + format!( + "scene too large: {} paths, {} shadows, {} quads, {} underlines, {} monochrome sprites, {} subpixel sprites, {} polychrome sprites", + scene.paths.len(), + scene.shadows.len(), + scene.quads.len(), + scene.underlines.len(), + scene.monochrome_sprites.len(), + scene.subpixel_sprites.len(), + scene.polychrome_sprites.len(), + ) + })?; + self.prepare_texture_bind_groups(scene); + + let mut encoder = + self.resources() + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("main_encoder"), + }); + + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("main_pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: frame_view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(clear_color), + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + ..Default::default() + }); + + for batch in scene.batches() { + match batch { + PrimitiveBatch::Quads(range) => self.draw_instances( + &instance_bindings.quads, + &self.resources().pipelines.quads, + instance_range(range), + &mut pass, + ), + PrimitiveBatch::Shadows(range) => self.draw_instances( + &instance_bindings.shadows, + &self.resources().pipelines.shadows, + instance_range(range), + &mut pass, + ), + PrimitiveBatch::Paths(range) => { + let paths = &scene.paths[range]; + if paths.is_empty() { + continue; + } + + drop(pass); + let rasterized = self.draw_paths_to_intermediate( + &mut encoder, + paths, + &mut instance_offset, + )?; + + pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("main_pass_continued"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: frame_view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + ..Default::default() + }); + + if rasterized { + self.draw_paths_from_intermediate( + paths, + &mut instance_offset, + &mut pass, + )?; + } + } + PrimitiveBatch::Underlines(range) => self.draw_instances( + &instance_bindings.underlines, + &self.resources().pipelines.underlines, + instance_range(range), + &mut pass, + ), + PrimitiveBatch::MonochromeSprites { texture_id, range } => { + self.draw_sprites( + &instance_bindings.monochrome_sprites, + texture_id, + &self.resources().pipelines.mono_sprites, + instance_range(range), + &mut pass, + )?; + } + PrimitiveBatch::SubpixelSprites { texture_id, range } => { + let resources = self.resources(); + self.draw_sprites( + &instance_bindings.subpixel_sprites, + texture_id, + resources + .pipelines + .subpixel_sprites + .as_ref() + .unwrap_or(&resources.pipelines.mono_sprites), + instance_range(range), + &mut pass, + )?; + } + PrimitiveBatch::PolychromeSprites { texture_id, range } => { + self.draw_sprites( + &instance_bindings.polychrome_sprites, + texture_id, + &self.resources().pipelines.poly_sprites, + instance_range(range), + &mut pass, + )?; + } + // Surfaces are macOS-only for video playback and are not + // implemented by the WGPU renderer. + PrimitiveBatch::Surfaces(_surfaces) => {} + } + } + } + + let submission = self + .resources() + .queue + .submit(std::iter::once(encoder.finish())); + Ok(submission) + } + + fn write_instances( + &mut self, + scene: &Scene, + instance_offset: &mut u64, + ) -> Result { + Ok(InstanceBindings { + quads: self.write_instance_binding( + "quads_bind_group", + instance_offset, + &scene.quads, + )?, + shadows: self.write_instance_binding( + "shadows_bind_group", + instance_offset, + &scene.shadows, + )?, + underlines: self.write_instance_binding( + "underlines_bind_group", + instance_offset, + &scene.underlines, + )?, + monochrome_sprites: self.write_instance_binding( + "monochrome_sprites_bind_group", + instance_offset, + &scene.monochrome_sprites, + )?, + subpixel_sprites: self.write_instance_binding( + "subpixel_sprites_bind_group", + instance_offset, + &scene.subpixel_sprites, + )?, + polychrome_sprites: self.write_instance_binding( + "polychrome_sprites_bind_group", + instance_offset, + &scene.polychrome_sprites, + )?, + }) + } + + fn create_texture_bind_group( + &self, + label: &str, + texture_view: &wgpu::TextureView, + ) -> wgpu::BindGroup { + let resources = self.resources(); + resources + .device + .create_bind_group(&wgpu::BindGroupDescriptor { + label: Some(label), + layout: &resources.bind_group_layouts.texture, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(texture_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&resources.atlas_sampler), + }, + ], + }) + } + + fn prepare_texture_bind_groups(&mut self, scene: &Scene) { + let mut texture_ids = SmallVec::<[AtlasTextureId; 8]>::new(); + for batch in scene.batches() { + let texture_id = match batch { + PrimitiveBatch::MonochromeSprites { texture_id, .. } + | PrimitiveBatch::SubpixelSprites { texture_id, .. } + | PrimitiveBatch::PolychromeSprites { texture_id, .. } => texture_id, + _ => continue, + }; + if !texture_ids.contains(&texture_id) { + texture_ids.push(texture_id); + } + } + + self.resources_mut() + .atlas_texture_bind_groups + .retain(|texture_id, _| texture_ids.contains(texture_id)); + + for texture_id in texture_ids { + let Some(texture_info) = self.atlas.get_texture_info(texture_id) else { + self.resources_mut() + .atlas_texture_bind_groups + .remove(&texture_id); + continue; + }; + let is_current = self + .resources() + .atlas_texture_bind_groups + .get(&texture_id) + .is_some_and(|cached| cached.texture_generation == texture_info.generation); + if is_current { + continue; + } + + let bind_group = + self.create_texture_bind_group("atlas_texture_bind_group", &texture_info.view); + self.resources_mut().atlas_texture_bind_groups.insert( + texture_id, + CachedTextureBindGroup { + texture_generation: texture_info.generation, + bind_group, + }, + ); + } + } + + fn draw_instances( + &self, + instances: &InstanceBinding, + pipeline: &wgpu::RenderPipeline, + range: Range, + pass: &mut wgpu::RenderPass<'_>, + ) { + if range.is_empty() { + return; + } + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &self.resources().globals_bind_group, &[]); + pass.set_bind_group(1, &instances.bind_group, &[]); + pass.draw( + 0..4, + instances.first_instance + range.start..instances.first_instance + range.end, + ); + } + + fn draw_sprites( + &self, + sprite_instances: &InstanceBinding, + texture_id: AtlasTextureId, + pipeline: &wgpu::RenderPipeline, + range: Range, + pass: &mut wgpu::RenderPass<'_>, + ) -> Result<()> { + if range.is_empty() { + return Ok(()); + } + let resources = self.resources(); + // The atlas has released this texture; the batch belongs to a stale + // paint that will be replaced once its view re-renders. + let Some(texture) = resources.atlas_texture_bind_groups.get(&texture_id) else { + return Ok(()); + }; + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &resources.globals_bind_group, &[]); + pass.set_bind_group(1, &sprite_instances.bind_group, &[]); + pass.set_bind_group(2, &texture.bind_group, &[]); + pass.draw( + 0..4, + sprite_instances.first_instance + range.start + ..sprite_instances.first_instance + range.end, + ); + Ok(()) + } + + unsafe fn instance_bytes(instances: &[T]) -> &[u8] { + unsafe { + std::slice::from_raw_parts( + instances.as_ptr() as *const u8, + std::mem::size_of_val(instances), + ) + } + } + + fn draw_paths_from_intermediate( + &mut self, + paths: &[Path], + instance_offset: &mut u64, + pass: &mut wgpu::RenderPass<'_>, + ) -> Result<()> { + let first_path = &paths[0]; + let sprites: Vec = if paths.last().map(|p| &p.order) == Some(&first_path.order) + { + paths + .iter() + .map(|p| PathSprite { + bounds: p.clipped_bounds(), + }) + .collect() + } else { + let mut bounds = first_path.clipped_bounds(); + for path in paths.iter().skip(1) { + bounds = bounds.union(&path.clipped_bounds()); + } + vec![PathSprite { bounds }] + }; + + let Some(path_intermediate_view) = self.resources().path_intermediate_view.clone() else { + return Ok(()); + }; + let instances = + self.write_instance_binding("path_sprites_bind_group", instance_offset, &sprites)?; + let texture = self.create_texture_bind_group( + "path_intermediate_texture_bind_group", + &path_intermediate_view, + ); + let resources = self.resources(); + pass.set_pipeline(&resources.pipelines.paths); + pass.set_bind_group(0, &resources.globals_bind_group, &[]); + pass.set_bind_group(1, &instances.bind_group, &[]); + pass.set_bind_group(2, &texture, &[]); + pass.draw( + 0..4, + instances.first_instance..instances.first_instance + sprites.len() as u32, + ); + Ok(()) + } + + fn draw_paths_to_intermediate( + &mut self, + encoder: &mut wgpu::CommandEncoder, + paths: &[Path], + instance_offset: &mut u64, + ) -> Result { + let mut vertices = Vec::new(); + for path in paths { + let bounds = path.clipped_bounds(); + vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex { + xy_position: v.xy_position, + st_position: v.st_position, + color: path.color, + bounds, + })); + } + + if vertices.is_empty() { + return Ok(false); + } + + let vertex_binding = self.write_instance_binding( + "path_rasterization_bind_group", + instance_offset, + &vertices, + )?; + + let resources = self.resources(); + let Some(path_intermediate_view) = resources.path_intermediate_view.as_ref() else { + return Ok(false); + }; + + let (target_view, resolve_target) = if let Some(ref msaa_view) = resources.path_msaa_view { + (msaa_view, Some(path_intermediate_view)) + } else { + (path_intermediate_view, None) + }; + + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("path_rasterization_pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target_view, + resolve_target, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + ..Default::default() + }); + + pass.set_pipeline(&resources.pipelines.path_rasterization); + pass.set_bind_group(0, &resources.path_globals_bind_group, &[]); + pass.set_bind_group(1, &vertex_binding.bind_group, &[]); + // The path rasterization shader loads records by vertex index + // rather than instance index, so the allocation's base shifts the + // vertex range here. + pass.draw( + vertex_binding.first_instance + ..vertex_binding.first_instance + vertices.len() as u32, + 0..1, + ); + } + + Ok(true) + } + + fn write_instance_binding( + &mut self, + label: &str, + instance_offset: &mut u64, + instances: &[T], + ) -> Result { + let data = unsafe { Self::instance_bytes(instances) }; + // wgpu rejects zero-sized bindings, so empty primitive arrays still + // reserve the 16-byte minimum. + let size = (data.len() as u64).max(16); + let stride = (std::mem::size_of::() as u64).max(1); + let (alignment, allocation_size) = if self.uses_webgl_instance_data { + // The texture transport has no binding offset: the shader indexes + // the instance texture absolutely, so each allocation must start on + // a whole instance (a stride multiple) and a whole texel, and must + // end on a texel boundary so the zero padding of its final partial + // texel cannot overlap the next allocation. + ( + least_common_multiple(self.instance_data_alignment, stride), + size.next_multiple_of(INSTANCE_TEXTURE_TEXEL_SIZE), + ) + } else { + (self.instance_data_alignment.max(1), size) + }; + let mut offset = (*instance_offset).next_multiple_of(alignment); + if offset + allocation_size > self.instance_data_capacity { + self.grow_instance_data(allocation_size)?; + offset = 0; + } + *instance_offset = offset + allocation_size; + + let first_instance = if self.uses_webgl_instance_data { + u32::try_from(offset / stride).context("instance index exceeds u32 range")? + } else { + 0 + }; + + let resources = self.resources(); + if !data.is_empty() { + match &resources.instance_data { + InstanceData::Storage(buffer) => resources.queue.write_buffer(buffer, offset, data), + InstanceData::Texture { .. } => { + Self::write_instance_texture(resources, offset, data) + } + } + } + let bind_group = resources + .device + .create_bind_group(&wgpu::BindGroupDescriptor { + label: Some(label), + layout: &resources.bind_group_layouts.instances, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: match &resources.instance_data { + InstanceData::Storage(buffer) => { + wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer, + offset, + size: NonZeroU64::new(size), + }) + } + InstanceData::Texture { view, .. } => { + wgpu::BindingResource::TextureView(view) + } + }, + }], + }); + Ok(InstanceBinding { + bind_group, + first_instance, + }) + } + + fn write_instance_texture(resources: &WgpuResources, offset: u64, data: &[u8]) { + let InstanceData::Texture { + texture, + width, + height, + .. + } = &resources.instance_data + else { + return; + }; + let mut byte_offset = 0usize; + let mut texel_offset = offset / INSTANCE_TEXTURE_TEXEL_SIZE; + while byte_offset < data.len() { + let x = (texel_offset % u64::from(*width)) as u32; + let y = (texel_offset / u64::from(*width)) as u32; + if y >= *height { + // The capacity check in write_instance_binding should make this + // unreachable. Truncating silently would leave stale bytes in the + // texture and draw garbage for the remaining instances. + debug_assert!( + false, + "instance texture write out of bounds: row {y} >= height {}", + *height + ); + log::error!( + "instance texture write out of bounds; dropping {} bytes of instance data", + data.len() - byte_offset + ); + return; + } + let available_texels = u64::from(*width - x); + let remaining_bytes = data.len() - byte_offset; + let complete_texels = remaining_bytes as u64 / INSTANCE_TEXTURE_TEXEL_SIZE; + let texels = complete_texels.min(available_texels); + if texels > 0 { + let byte_count = (texels * INSTANCE_TEXTURE_TEXEL_SIZE) as usize; + resources.queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d { x, y, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + &data[byte_offset..byte_offset + byte_count], + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(byte_count as u32), + rows_per_image: None, + }, + wgpu::Extent3d { + width: texels as u32, + height: 1, + depth_or_array_layers: 1, + }, + ); + byte_offset += byte_count; + texel_offset += texels; + continue; + } + + let mut final_texel = [0; INSTANCE_TEXTURE_TEXEL_SIZE as usize]; + final_texel[..remaining_bytes].copy_from_slice(&data[byte_offset..]); + resources.queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d { x, y, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + &final_texel, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(INSTANCE_TEXTURE_TEXEL_SIZE as u32), + rows_per_image: None, + }, + wgpu::Extent3d { + width: 1, + height: 1, + depth_or_array_layers: 1, + }, + ); + break; + } + } + + fn grow_instance_data(&mut self, required: u64) -> Result<()> { + let capacity = (self.instance_data_capacity * 2) + .max(required.next_power_of_two()) + .min(self.max_instance_data_size); + anyhow::ensure!( + capacity >= required, + "instance data needs {required} bytes, above the maximum of {}", + self.max_instance_data_size + ); + anyhow::ensure!( + capacity > self.instance_data_capacity, + "frame instance data exceeds the {}-byte maximum", + self.max_instance_data_size + ); + log::debug!( + "instance data grown from {} to {capacity}", + self.instance_data_capacity + ); + // Bind groups created earlier in the frame keep the previous buffer or + // texture alive, so allocations written before the grow remain valid; + // only subsequent writes land in the new allocation. + let uses_webgl_instance_data = self.uses_webgl_instance_data; + let resources = self.resources_mut(); + if uses_webgl_instance_data { + let max_texture_dimension = resources.device.limits().max_texture_dimension_2d; + let (instance_data, actual_capacity) = + Self::create_instance_texture(&resources.device, capacity, max_texture_dimension); + resources.instance_data = instance_data; + self.instance_data_capacity = actual_capacity; + } else { + resources.instance_data = + InstanceData::Storage(resources.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("instance_buffer"), + size: capacity, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + self.instance_data_capacity = capacity; + } + Ok(()) + } +} + +impl WgpuRenderer { + /// Mark the surface as unconfigured so rendering is skipped until a new + /// surface is provided via [`replace_surface`](Self::replace_surface). + /// + /// This does **not** drop the renderer — the device, queue, atlas, and + /// pipelines stay alive. Use this when the native window is destroyed + /// (e.g. Android `TerminateWindow`) but you intend to re-create the + /// surface later without losing cached atlas textures. + pub fn unconfigure_surface(&mut self) { + self.state = match std::mem::replace(&mut self.state, RendererState::Released) { + RendererState::Ready { core, surface } => { + drop(surface); + RendererState::Unconfigured { core } + } + state @ (RendererState::Unconfigured { .. } | RendererState::Released) => state, + }; + // Drop intermediate textures since they reference the old surface size. + if let Some(core) = self.core_mut() { + core.resources.invalidate_intermediate_textures(); + } + } + + /// Replace the wgpu surface with a new one (e.g. after Android destroys + /// and recreates the native window). Keeps the device, queue, atlas, and + /// all pipelines intact so cached `AtlasTextureId`s remain valid. + /// + /// The `instance` **must** be the same [`wgpu::Instance`] that was used to + /// create the adapter and device (i.e. from the [`WgpuContext`]). Using a + /// different instance will cause a "Device does not exist" panic because + /// the wgpu device is bound to its originating instance. + #[cfg(not(target_family = "wasm"))] + pub fn replace_surface( + &mut self, + window: &W, + config: WgpuSurfaceConfig, + instance: &wgpu::Instance, + ) -> anyhow::Result<()> { + let window_handle = window + .window_handle() + .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?; + + let surface = create_surface(instance, window_handle.as_raw())?; + + let width = (config.size.width.0 as u32).max(1); + let height = (config.size.height.0 as u32).max(1); + + let alpha_mode = if config.transparent { + self.transparent_alpha_mode + } else { + self.opaque_alpha_mode + }; + + self.surface_config.width = width; + self.surface_config.height = height; + self.surface_config.alpha_mode = alpha_mode; + if let Some(mode) = config.preferred_present_mode { + self.surface_config.present_mode = mode; + } + + let mut core = match std::mem::replace(&mut self.state, RendererState::Released) { + RendererState::Ready { + core, + surface: old_surface, + } => { + drop(old_surface); + core + } + RendererState::Unconfigured { core } => core, + RendererState::Released => { + anyhow::bail!("Cannot replace the surface: GPU resources have been released") + } + }; + surface.configure(&core.resources.device, &self.surface_config); + core.resources.invalidate_intermediate_textures(); + self.state = RendererState::Ready { surface, core }; + + Ok(()) + } + + pub fn destroy(&mut self) { + // Release surface-bound GPU resources eagerly so the underlying native + // window can be destroyed before the renderer itself is dropped. + self.state = RendererState::Released; + } + + /// Returns true if the GPU device was lost and recovery is needed. + pub fn device_lost(&self) -> bool { + self.device_errors.device_lost() + } + + /// Returns true if a redraw is needed because GPU state was cleared. + /// Calling this method clears the flag. + pub fn needs_redraw(&mut self) -> bool { + std::mem::take(&mut self.needs_redraw) + } + + /// Recovers from a lost GPU device by recreating the renderer with a new context. + /// + /// Call this after detecting `device_lost()` returns true. + /// + /// This method coordinates recovery across multiple windows: + /// - The first window to call this will recreate the shared context + /// - Subsequent windows will adopt the already-recovered context + #[cfg(not(target_family = "wasm"))] + pub fn recover(&mut self, window: &W) -> anyhow::Result<()> + where + W: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync + Clone + 'static, + { + let gpu_context = self.context.as_ref().expect("recover requires gpu_context"); + + // Check if another window already recovered the context + let needs_new_context = gpu_context + .borrow() + .as_ref() + .is_none_or(|ctx| ctx.device_lost()); + + let window_handle = window + .window_handle() + .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?; + + let surface = if needs_new_context { + log::warn!("GPU device lost, recreating context..."); + + // Drop old resources to release Arc/Arc and GPU resources + self.state = RendererState::Released; + *gpu_context.borrow_mut() = None; + + // Wait briefly for the GPU driver to stabilize, then try to + // recreate the context without software renderers. If this fails + // the caller should request another frame and retry — the real GPU + // may need more time to come back (e.g. after suspend/resume). + std::thread::sleep(std::time::Duration::from_millis(350)); + + let instance = WgpuContext::instance(Some(Box::new(window.clone()))); + let surface = create_surface(&instance, window_handle.as_raw())?; + let new_context = + WgpuContext::new_rejecting_software(instance, &surface, self.compositor_gpu)?; + *gpu_context.borrow_mut() = Some(new_context); + surface + } else { + let ctx_ref = gpu_context.borrow(); + let instance = &ctx_ref.as_ref().unwrap().instance; + create_surface(instance, window_handle.as_raw())? + }; + + let config = WgpuSurfaceConfig { + size: gpui::Size { + width: gpui::DevicePixels(self.surface_config.width as i32), + height: gpui::DevicePixels(self.surface_config.height as i32), + }, + transparent: self.surface_config.alpha_mode != wgpu::CompositeAlphaMode::Opaque, + preferred_present_mode: Some(self.surface_config.present_mode), + }; + let gpu_context = Rc::clone(gpu_context); + let ctx_ref = gpu_context.borrow(); + let context = ctx_ref.as_ref().expect("context should exist"); + + self.state = RendererState::Released; + self.atlas.handle_device_lost(context); + + let is_bgr = self.is_bgr; + *self = Self::new_internal( + Some(gpu_context.clone()), + context, + surface, + config, + self.compositor_gpu, + self.atlas.clone(), + )?; + self.set_subpixel_layout(is_bgr); + + log::info!("GPU recovery complete"); + Ok(()) + } +} + +#[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") +))] +struct HeadlessRenderTarget { + texture: wgpu::Texture, + view: wgpu::TextureView, +} + +#[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") +))] +impl HeadlessRenderTarget { + fn size(&self) -> Size { + Size { + width: DevicePixels(self.texture.width() as i32), + height: DevicePixels(self.texture.height() as i32), + } + } +} + +#[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") +))] +pub struct WgpuHeadlessRenderer { + context: WgpuContext, + core: WgpuRendererCore, + render_target: Option, + observed_error_generation: u64, +} + +#[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") +))] +impl WgpuHeadlessRenderer { + pub fn new() -> anyhow::Result { + let (context, target_format) = WgpuContext::new_headless()?; + // The device may be shared with earlier renderers; observe only errors raised from + // here on, including any while this renderer builds its pipelines. + let observed_error_generation = context.errors().current_generation(); + let atlas = Arc::new(WgpuAtlas::from_context(&context)); + let core = WgpuRendererCore::new( + &context, + atlas, + target_format, + wgpu::CompositeAlphaMode::Opaque, + ); + + Ok(Self { + context, + core, + render_target: None, + observed_error_generation, + }) + } + + fn ensure_render_target(&mut self, size: Size) -> anyhow::Result<()> { + anyhow::ensure!( + size.width.0 > 0 && size.height.0 > 0, + "invalid headless render target size: {size:?}" + ); + anyhow::ensure!( + size.width.0 as u32 <= self.core.max_texture_size + && size.height.0 as u32 <= self.core.max_texture_size, + "headless render target size {size:?} exceeds maximum texture dimension {}", + self.core.max_texture_size + ); + if self + .render_target + .as_ref() + .is_some_and(|target| target.size() == size) + { + return Ok(()); + } + + let texture = self + .core + .resources + .device + .create_texture(&wgpu::TextureDescriptor { + label: Some("headless_render_target"), + size: wgpu::Extent3d { + width: size.width.0 as u32, + height: size.height.0 as u32, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.core.target_format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + self.render_target = Some(HeadlessRenderTarget { texture, view }); + Ok(()) + } + + fn check_gpu_errors(&mut self) -> anyhow::Result<()> { + anyhow::ensure!( + !self.context.device_lost(), + "GPU device was lost during headless rendering" + ); + if let Some(error) = self + .context + .errors() + .observe_error(&mut self.observed_error_generation) + { + anyhow::bail!("GPU error during headless rendering: {error}"); + } + Ok(()) + } + + fn render(&mut self, scene: &Scene, size: Size) -> anyhow::Result<()> { + self.check_gpu_errors()?; + self.ensure_render_target(size)?; + let view = self + .render_target + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))? + .view + .clone(); + self.core + .render_frame(scene, &view, size, false, wgpu::Color::BLACK)?; + Ok(()) + } + + /// Copies the current render target back to the CPU. Dimensions come from the + /// target texture itself, so the copy can never disagree with what was rendered. + fn read_image(&mut self) -> anyhow::Result { + let target = self + .render_target + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))?; + let width = target.texture.width(); + let height = target.texture.height(); + let bytes_per_row = width + .checked_mul(4) + .ok_or_else(|| anyhow::anyhow!("Headless render target row size overflowed"))?; + let padded_bytes_per_row = bytes_per_row + .checked_next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) + .ok_or_else(|| anyhow::anyhow!("Headless padded row size overflowed"))?; + let buffer_size = u64::from(padded_bytes_per_row) + .checked_mul(u64::from(height)) + .ok_or_else(|| anyhow::anyhow!("Headless readback buffer size overflowed"))?; + anyhow::ensure!( + buffer_size <= self.core.resources.device.limits().max_buffer_size, + "Headless readback buffer size {buffer_size} exceeds maximum buffer size {}", + self.core.resources.device.limits().max_buffer_size + ); + let readback_buffer = self + .core + .resources + .device + .create_buffer(&wgpu::BufferDescriptor { + label: Some("headless_readback_buffer"), + size: buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = + self.core + .resources + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("headless_readback_encoder"), + }); + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture: &target.texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &readback_buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bytes_per_row), + rows_per_image: Some(height), + }, + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + let submission = self + .core + .resources + .queue + .submit(std::iter::once(encoder.finish())); + let (sender, receiver) = std::sync::mpsc::channel(); + readback_buffer + .slice(..) + .map_async(wgpu::MapMode::Read, move |result| { + if sender.send(result).is_err() { + log::error!("Headless readback receiver was dropped before mapping completed"); + } + }); + self.core + .resources + .device + .poll(wgpu::PollType::Wait { + submission_index: Some(submission), + timeout: Some(std::time::Duration::from_secs(30)), + }) + .map_err(|error| anyhow::anyhow!("Failed to wait for headless rendering: {error}"))?; + receiver + .recv_timeout(std::time::Duration::from_secs(30)) + .map_err(|error| anyhow::anyhow!("Failed to receive headless mapping result: {error}"))? + .map_err(|error| anyhow::anyhow!("Failed to map headless readback buffer: {error}"))?; + self.check_gpu_errors()?; + + let mapped_data = readback_buffer.slice(..).get_mapped_range(); + let pixel_capacity = usize::try_from(u64::from(bytes_per_row) * u64::from(height)) + .map_err(|_| anyhow::anyhow!("Headless image size exceeds addressable memory"))?; + let mut pixels = Vec::with_capacity(pixel_capacity); + for row in mapped_data + .chunks_exact(padded_bytes_per_row as usize) + .take(height as usize) + { + pixels.extend_from_slice(&row[..bytes_per_row as usize]); + } + drop(mapped_data); + readback_buffer.unmap(); + + if self.core.target_format == wgpu::TextureFormat::Bgra8Unorm { + for pixel in pixels.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + } + + image::RgbaImage::from_raw(width, height, pixels) + .ok_or_else(|| anyhow::anyhow!("Failed to create image from headless pixel data")) + } +} + +#[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") +))] +impl gpui::PlatformHeadlessRenderer for WgpuHeadlessRenderer { + fn render_scene_to_image( + &mut self, + scene: &Scene, + size: Size, + ) -> anyhow::Result { + self.render(scene, size)?; + self.read_image() + } + + fn render_scene(&mut self, scene: &Scene, size: Size) -> anyhow::Result<()> { + self.render(scene, size) + } + + fn sprite_atlas(&self) -> Arc { + self.core.atlas.clone() + } +} + +fn instance_range(range: Range) -> Range { + range.start as u32..range.end as u32 +} + +#[cfg(not(target_family = "wasm"))] +fn create_surface( + instance: &wgpu::Instance, + raw_window_handle: raw_window_handle::RawWindowHandle, +) -> anyhow::Result> { + unsafe { + instance + .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle { + // Fall back to the display handle already provided via InstanceDescriptor::display. + raw_display_handle: None, + raw_window_handle, + }) + .map_err(|e| anyhow::anyhow!("{e}")) + } +} + +struct RenderingParameters { + path_sample_count: u32, + gamma_ratios: [f32; 4], + grayscale_enhanced_contrast: f32, + subpixel_enhanced_contrast: f32, +} + +impl RenderingParameters { + fn new(adapter: &wgpu::Adapter, surface_format: wgpu::TextureFormat) -> Self { + use std::env; + + let format_features = adapter.get_texture_format_features(surface_format); + let path_sample_count = [4, 2, 1] + .into_iter() + .find(|&n| format_features.flags.sample_count_supported(n)) + .unwrap_or(1); + + let gamma = env::var("ZED_FONTS_GAMMA") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1.8_f32) + .clamp(1.0, 2.2); + let gamma_ratios = get_gamma_correction_ratios(gamma); + + let grayscale_enhanced_contrast = env::var("ZED_FONTS_GRAYSCALE_ENHANCED_CONTRAST") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1.0_f32) + .max(0.0); + + let subpixel_enhanced_contrast = env::var("ZED_FONTS_SUBPIXEL_ENHANCED_CONTRAST") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0.5_f32) + .max(0.0); + + Self { + path_sample_count, + gamma_ratios, + grayscale_enhanced_contrast, + subpixel_enhanced_contrast, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{ + BorderStyle, ColorSpace, ContentMask, Corners, Edges, Hsla, MonochromeSprite, + PolychromeSprite, Quad, Shadow, Size, SubpixelSprite, Underline, linear_color_stop, + linear_gradient, + }; + #[cfg(target_os = "linux")] + use gpui::{DevicePixels, PlatformHeadlessRenderer, Scene}; + + #[cfg(target_os = "linux")] + fn device_size(width: i32, height: i32) -> Size { + Size { + width: DevicePixels(width), + height: DevicePixels(height), + } + } + + #[cfg(target_os = "linux")] + fn solid_quad(x: f32, y: f32, width: f32, height: f32, color: Hsla) -> Quad { + let bounds = Bounds { + origin: Point { + x: x.into(), + y: y.into(), + }, + size: Size { + width: width.into(), + height: height.into(), + }, + }; + Quad { + order: 0, + border_style: BorderStyle::Solid, + bounds, + content_mask: ContentMask { bounds }, + background: color.into(), + border_color: color, + corner_radii: Corners::default(), + border_widths: Edges::default(), + } + } + + /// Channels are compared with a small tolerance so the assertions hold across + /// drivers without pinning exact rasterizer output. + #[cfg(target_os = "linux")] + fn assert_pixel(image: &image::RgbaImage, x: u32, y: u32, expected: [u8; 4]) { + let actual = image.get_pixel(x, y).0; + assert!( + actual + .iter() + .zip(expected) + .all(|(actual, expected)| actual.abs_diff(expected) <= 3), + "pixel ({x}, {y}) was {actual:?}, expected {expected:?}" + ); + } + + #[cfg(target_os = "linux")] + const RED: [u8; 4] = [255, 0, 0, 255]; + #[cfg(target_os = "linux")] + const BLUE: [u8; 4] = [0, 0, 255, 255]; + #[cfg(target_os = "linux")] + const BLACK: [u8; 4] = [0, 0, 0, 255]; + + #[cfg(target_os = "linux")] + #[test] + fn headless_renderer_draws_quads_with_distinct_colors() -> anyhow::Result<()> { + let mut renderer = WgpuHeadlessRenderer::new()?; + let mut scene = Scene::default(); + scene.insert_primitive(solid_quad(0.0, 0.0, 32.0, 32.0, gpui::red())); + scene.insert_primitive(solid_quad(32.0, 0.0, 32.0, 32.0, gpui::blue())); + scene.finish(); + + let image = renderer.render_scene_to_image(&scene, device_size(64, 32))?; + assert_eq!(image.dimensions(), (64, 32)); + assert_pixel(&image, 8, 16, RED); + assert_pixel(&image, 24, 16, RED); + assert_pixel(&image, 40, 16, BLUE); + assert_pixel(&image, 56, 16, BLUE); + Ok(()) + } + + #[cfg(target_os = "linux")] + #[test] + fn headless_renderer_captures_each_requested_size() -> anyhow::Result<()> { + let mut renderer = WgpuHeadlessRenderer::new()?; + let mut scene = Scene::default(); + scene.insert_primitive(solid_quad(2.0, 2.0, 4.0, 3.0, gpui::red())); + scene.finish(); + + // 13 px rows are 52 bytes, forcing readback to strip copy-row padding. + let image = renderer.render_scene_to_image(&scene, device_size(13, 7))?; + assert_eq!(image.dimensions(), (13, 7)); + assert_pixel(&image, 0, 0, BLACK); + assert_pixel(&image, 3, 3, RED); + assert_pixel(&image, 12, 6, BLACK); + + let image = renderer.render_scene_to_image(&scene, device_size(17, 9))?; + assert_eq!(image.dimensions(), (17, 9)); + assert_pixel(&image, 3, 3, RED); + assert_pixel(&image, 16, 8, BLACK); + + let image = renderer.render_scene_to_image(&Scene::default(), device_size(13, 7))?; + assert_eq!(image.dimensions(), (13, 7)); + assert!(image.pixels().all(|pixel| pixel.0 == BLACK)); + Ok(()) + } + + #[cfg(target_os = "linux")] + #[test] + fn headless_renderer_reuses_target_for_same_size() -> anyhow::Result<()> { + let mut renderer = WgpuHeadlessRenderer::new()?; + let target_texture = |renderer: &WgpuHeadlessRenderer| { + renderer + .render_target + .as_ref() + .map(|target| target.texture.clone()) + }; + + renderer.render_scene(&Scene::default(), device_size(16, 16))?; + let first = target_texture(&renderer); + assert!(first.is_some()); + + renderer.render_scene(&Scene::default(), device_size(16, 16))?; + assert_eq!(target_texture(&renderer), first); + + renderer.render_scene(&Scene::default(), device_size(16, 17))?; + assert_ne!(target_texture(&renderer), first); + Ok(()) + } + + #[cfg(target_os = "linux")] + #[test] + fn headless_renderer_rejects_invalid_sizes() -> anyhow::Result<()> { + let mut renderer = WgpuHeadlessRenderer::new()?; + let too_large = renderer.core.max_texture_size as i32 + 1; + + for size in [ + device_size(0, 8), + device_size(8, 0), + device_size(-1, 8), + device_size(too_large, 8), + ] { + assert!( + renderer.render_scene(&Scene::default(), size).is_err(), + "{size:?} should be rejected" + ); + assert!( + renderer + .render_scene_to_image(&Scene::default(), size) + .is_err(), + "{size:?} should be rejected" + ); + } + + // Rejection must leave the renderer usable. + let image = renderer.render_scene_to_image(&Scene::default(), device_size(4, 4))?; + assert_eq!(image.dimensions(), (4, 4)); + Ok(()) + } + + #[test] + fn webgl_shader_is_valid_wgsl_without_storage_buffers() { + assert!(!WEBGL_SHADERS.contains("var(), 40 * 4); + assert_eq!(std::mem::size_of::(), 28 * 4); + assert_eq!(std::mem::size_of::(), 26 * 4); + assert_eq!(std::mem::size_of::(), 4 * 4); + assert_eq!(std::mem::size_of::(), 16 * 4); + assert_eq!(std::mem::size_of::(), 28 * 4); + assert_eq!(std::mem::size_of::(), 28 * 4); + assert_eq!(std::mem::size_of::(), 24 * 4); + } + + #[test] + fn webgl_quad_layout_matches_fixed_decoder() { + let quad = Quad { + order: 41, + border_style: BorderStyle::Dashed, + bounds: Bounds { + origin: Point { + x: 1.0.into(), + y: 2.0.into(), + }, + size: Size { + width: 3.0.into(), + height: 4.0.into(), + }, + }, + content_mask: ContentMask { + bounds: Bounds { + origin: Point { + x: 5.0.into(), + y: 6.0.into(), + }, + size: Size { + width: 7.0.into(), + height: 8.0.into(), + }, + }, + }, + background: linear_gradient( + 11.0, + linear_color_stop( + Hsla { + h: 12.0, + s: 13.0, + l: 14.0, + a: 15.0, + }, + 16.0, + ), + linear_color_stop( + Hsla { + h: 17.0, + s: 18.0, + l: 19.0, + a: 20.0, + }, + 21.0, + ), + ) + .color_space(ColorSpace::Oklab), + border_color: Hsla { + h: 22.0, + s: 23.0, + l: 24.0, + a: 25.0, + }, + corner_radii: Corners { + top_left: 26.0.into(), + top_right: 27.0.into(), + bottom_right: 28.0.into(), + bottom_left: 29.0.into(), + }, + border_widths: Edges { + top: 30.0.into(), + right: 31.0.into(), + bottom: 32.0.into(), + left: 33.0.into(), + }, + }; + + let bytes = unsafe { WgpuRendererCore::instance_bytes(std::slice::from_ref(&quad)) }; + let words: &[u32] = bytemuck::cast_slice(bytes); + assert_eq!( + words, + &[ + 41, + 1, + 1.0_f32.to_bits(), + 2.0_f32.to_bits(), + 3.0_f32.to_bits(), + 4.0_f32.to_bits(), + 5.0_f32.to_bits(), + 6.0_f32.to_bits(), + 7.0_f32.to_bits(), + 8.0_f32.to_bits(), + 1, + 1, + 0, + 0, + 0, + 0, + 11.0_f32.to_bits(), + 12.0_f32.to_bits(), + 13.0_f32.to_bits(), + 14.0_f32.to_bits(), + 15.0_f32.to_bits(), + 16.0_f32.to_bits(), + 17.0_f32.to_bits(), + 18.0_f32.to_bits(), + 19.0_f32.to_bits(), + 20.0_f32.to_bits(), + 21.0_f32.to_bits(), + 0, + 22.0_f32.to_bits(), + 23.0_f32.to_bits(), + 24.0_f32.to_bits(), + 25.0_f32.to_bits(), + 26.0_f32.to_bits(), + 27.0_f32.to_bits(), + 28.0_f32.to_bits(), + 29.0_f32.to_bits(), + 30.0_f32.to_bits(), + 31.0_f32.to_bits(), + 32.0_f32.to_bits(), + 33.0_f32.to_bits(), + ] + ); + } +}